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 |
|---|---|---|---|---|---|
Building a Remotely Stoppable Connector Server
By daniel on Jan 09, 2008.
Starting an agent on demand
In some of my previous posts I have outlined how to use a
premain agent in order to create a custom
JMX RMI Connector Server. In this post, we're going to
reuse much of the concepts explained
before.
However, we will add the ability to dynamically
upload the JMX agent in the running application by
creating an
Agent-Main class. In fact, an
Agent-Main class
is nothing more than a class which has a method:
public static void agentmain(String agentArgs);
Our
agentmain method will create and start a
Remotely Stoppable JMX RMI Connector Server. Later on,
when we're done with monitoring our application, we will
be able to stop the JMX Connector Server that was created
by our
agentmain, thus leaving the application in its
original state (or close to it).
Custom agents started on demand cannot be stopped
The problem with custom agents created on demand is that they
can't be stopped: you can't stop them at the end of the
agentmain() or
premain() method, because
it's precisely at this point that you will start using them.
And the problem with running custom agents is that
they usually hold some non daemon threads alive (e.g. RMI DGC...)
and thus prevent the application in which they run from
exiting when all its non-daemon threads have
finished working.
This behaviour is a much desirable feature in a standalone JMX
application, where you can control when to start and stop
your JMX Connector Server - but it leads to awkward situations
in the case of JMX Agents started from
premain()
or
agentmain().
In a previous post I have suggested a work around which consisted
on creating a
CleanThread daemon,
which would daemon would simply stop the
JMXConnectorServer, which would make it possible for the
RMI Reaper thread to terminate and for the application to
exit normally.
This trick however presents several limitations:
-.
In this post, we will show how to:
- Dynamically load and start a Remotely Stoppable JMX RMI Connector Server - using an
Agent-Mainclass
- Perform some remote monitoring action through this connector - e.g. using JConsole from a remote machine.
- Then remotely stop the JMX RMI Connector Server, leaving the application running in a clean state.
If needed, the JMX Connector Server can also be re-created and re-started later on. To make things less easy, we will do all of this with a secure firewall-friendly (one single port) RMI Connector Server.
Making a Remotely Stoppable JMX Connector Server
Project Sources
The code source that does all of this comprises the following classes:
- StoppableAgent.java: our Agent-Main class. Can also be used as a premain agent.
- ForwardingInterceptor.java: our configurable
MBeanServerForwarder, implemented as a java.lang.reflect.Proxy.
- InvokeOperationInterceptor.java a default
InvokeOperationInterceptorwhich acts as a pass-through.
- Stopper.java: creates and configure a
ForwardingInterceptorthat can stop its connector server. Can also send a stop request through a given
JMXConnector
- Attach.java: a command line tool. The RMI port and secret name are passed through system properties:
start <pid>: uses the Attach API to dynamically start a
StoppableAgentin the target process.
status: creates a JMXConnector and checks whether the remote server that was started in a previous call is still alive (useful for tests).
list: list running java processes
stop: creates a JMXConnector to connect to the
StoppableAgentand invoke stop on the "fake" MBean.
help: prints a crude help message
You can see the example sources here in the form of a NetBeans 6 project.
Building the StoppableAgent jar
Once you have compiled all the classes, you can create an agent
jar by invoking an ant target like this one in your
build.xml
(already done in the provided NetBeans 6 project):
If you're using the provided NetBeans 6 project simply clean & build
the StoppableAgent project: the agent jar (
dist/jagent.jar)
will be automatically generated.
The
StoppableAgent class creates a secure
JMX RMI Connector Server. This means that the target application
in which the agent will be loaded must have
an appropriate truststore and keystore. The Attach class
provided in this example will forward its own default
SSL configuration to the target application if the
example.rmi.agent.ssl.config.send System property
is set to
true. In the general case, this is a
very bad idea as it is profundly unsecure - and this is why the
default is
example.rmi.agent.ssl.config.send=false.
A much better idea would be to configure SSL
properly when starting the target application.
If you don't have a target application to play with, you could use this one:
public class Test { public static void main(String[] args) throws Exception { System.out.println("Strike Enter to exit:"); System.in.read(); } }
Compile it and start it as follow:
java -classpath . \\ -Djavax.net.ssl.keyStore=<keystore> \\ -Djavax.net.ssl.keyStorePassword=<password> \\ -Djavax.net.ssl.trustStore=<truststore> \\ -Djavax.net.ssl.trustStorePassword=<trustword> \\ Test
Note: If you haven't already a keystore and trustore to play with, the Monitoring and Management guide has a section that explains how to create them.
To start the stoppable agent in a target application use start <pid>
To check that the StoppableAgent was correctly started run status
Connecting from remote
To connect with JConsole, start it with the following command line:.
Stopping the agent
To stop the agent, you now only need to invoke stop
Some additional considerations
The 'start' command can only be invoked from the local machine where the application is running. This is because we use the Attach API to upload the stoppable agent.
However, once done, the agent can be accessed from remote in a secure way. Since 'status' and 'stop' use a regular JMX connection with the stoppable agent, they could also be invoked from a remote machine.
Cheers,
-- daniel
Your solutions, while innovative, are basically just tricks to get around the horrible application architecture of what is supposedly an enterprise management/monitoring framework. By your own admission the cons are pretty serious:
\*.
Is there any move on Sun's part to create a REAL solution to these challenges? I can't imagine my company is the only one in the world that has a default deny policy on their firewall. My security guys will only give me a port or two, not access to 65,535 ports on the server.
Frustrated by JMX,
ErikC
Posted by ErikC on April 17, 2008 at 07:00 PM CEST #
Hi Erick,
In retrospect, it was certainly a mistake to have the default agent use two port numbers, instead of a single one.
Bear in mind however that having the possibility to start a connector on demand through the attach API is quite an advance feature of the Sun JVM.
All these problems that I cite arise when you try to use this attach on demand feature:
The regular use case for managing an application is to start and stop the JMXConnector server in the main() of your application, where none of these problems arise since you have full control over the connector configuration, and over when to start it and stop it.
Note also that the remotely stoppable connector trick shown above precisely works with all kind of connectors, JRMP, IIOP, or whatever.
What didn't work with the IIOP connector was the CleanThread daemon - which indeed was a horrible trick, but if you use a remotely stoppable connector like above you won't need that trick.
For some time now we've been working on a WebService connector for JMX (this is JSR 262) - and this will certainly help to get through firewall.
I do believe that these issues around the JMX RMI connector and firewalls is something we do need to address in the next version of the API for JDK 7.
I am sorry to hear your frustration. I wrote these articles in the hope it could help quickly getting around firewall issues.
Did you get to try my remotely stoppable JMXConnectorServer above?
Best regards, and let me know if I can help.
-- daniel
Posted by daniel on April 18, 2008 at 02:23 AM CEST #
Thanks for the comment, and I apologize for sounding so harsh. My fellow coworkers pointed out that I sounded overly frustrated...but it was with JMX not you! :-)
See the problem is we're trying to monitor Tomcat via JMX and we'd rather not branch the code base modify the main() for ourselves as to make upgrades easier.
Oh well, we'll keep looking for a compromise that works between SEC & DEV.
Cheers,
ErikC
Posted by ErikC on April 21, 2008 at 05:50 PM CEST # | https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector | CC-MAIN-2016-07 | refinedweb | 1,458 | 59.64 |
Least squares polynomial fitting in PythonJanuary 24, 2009 | categories: python, mathematics, estimation | View Comments
A few weeks ago at work, in the course of reverse engineering a dissolved oxygen sensor calibration routine, Jon needed to fit a curve to measured data so he could calculate calibration values from sensor readings, or something like that. I don’t know how he did the fitting, but it got me thinking about least squares and mathematical modeling.
The tools I’ve used for modeling (Matlab, Excel and the like) and the programming languages I’ve used for embedded systems (C and Python, mostly) are disjoint sets. Who wants to use Matlab for network programming, when you could use Python instead? Who wants to use C for calculating eigenvalues, when you could use Matlab instead? Generally, nobody.
Unfortunately, sometimes you need to do both in the same system. I’m not sure that I’m making a wise investment, but I think that Python’s numerical libraries have matured enough that Python can straddle the divide.
So, here’s what I’ve figured out about least squares in Python. My apologies to most of you regular readers, as you will find this boring as hell. This one’s for me and the internet.
Least squares estimation
Generally, least squares estimation is useful when you have a set of unknown parameters in a mathematical model. You want to estimate parameters that minimize the errors between the model and your data. The canonical form is:
Ax=y where:
* A is an M \times N full rank matrix with M > N (skinny) * x is a vector of length N * y is a vector of length M
As matrices, this looks like
You want to minimize the L2-norm, ||Ax-y||. To be explicit, this means that if you define the residuals r = Ax - y, you want to choose the
that minimizes sqrt{r_1^2 + ... r_M^2}. This is where the “least squares” name comes from– you’re going to choose the
that results in the squares of r being least.
Once you know A and y, actually finding the best x (assuming you have a computer at your disposal) is quick. The derivation sets the gradient of ||r||^2 with respect to x to zero and then solves for x. Mathematicians call the solution the Moore-Penrose pseudo-inverse. I call it “what the least squares function returned.” In any case, here it is:
Fortunately, one need not know the correct name and derivation of a thing for it to be useful.
So now, how do you go about using this technique to fit a polynomial to some data?
Polynomial fitting
In the case of polynomial fitting, let’s say you have a series of data points, (t_i, y_i) that you got from an experiment. The t_i are the times at which you made your observations. Each y_i is the reading from your sensor that you noted at the time with the same i.
Now you want to find a polynomial y = f(t) that approximates your data as closely as possible. The final output will look something like
where you have cleverly chosen the x_i for the best fit to your data. You’ll be able to plug in whatever value of t you want and get an estimate of y in return.
In the conventional form, we are trying to find an approximate solution to Ax=y
In this case, A is called the Vandermonde matrix; it takes the form:
(This presumes that you want to use powers of t as your basis functions– not a good idea for all modeling tasks, but this blog post is about polynomial fitting. Another popular choice is sinusoidal functions; perhaps Google can tell you more on that topic.)
(Also, the Vandermonde matrix is sometimes defined with the powers ascending from left to right, rather than descending. Descending works better with Python because of the coefficient order that numpy.poly1d() expects, but mathematically either way works.)
(Back to polynomial fitting.)
Each observation in your experiment corresponds to a row of A; A_i * x = y_i. Presumably, since every experiment has some noise in it, there is no x that fits every observation exactly. You know all the t_i, so you know A.
As a reminder, our model looks like this:
You can check that A makes sense by imagining the matrix multiplication of each row of A with x to equal the corresponding entry in y. For the second row of A, we have y_2 = x_Nt_2 + . . . + x_2t_2^2 + x_1t_2^1 + x_0
which is just the polynomial we’re looking to fit to the data.
Now, how can we actually do this in Python?
Python code
Let’s suppose that we have some data that looks like a noisy parabola, and we want to fit a polynomial of degree 5 to it. (I chose 5 randomly; it’s a stupid choice. More on selection of polynomial degree in another post.)
import numpy as np import scipy as sp import matplotlib.pyplot as plt
degree = 5
# generate a noisy parabola t = np.linspace(0,100,200) parabola = t2 noise = np.random.normal(0,300,200) y = parabola + noise
So now we have some fake data– an array of times and an array of noisy sensor readings. Next, we form the Vandermonde matrix and find an approximate solution for x. Note that numpy.linalg.lstsq() returns a tuple; we’re really only interested in the first element, which is the array of coefficients.
# form the Vandermonde matrix A = np.vander(t, degree) # find the x that minimizes the norm of Ax-y (coeffs, residuals, rank, sing_vals) = np.linalg.lstsq(A, y) # create a polynomial using coefficients f = np.poly1d(coeffs)
Three lines of code later, we have a solution!
I could have also used numpy.polyfit() in place of numpy.linalg.lstsq(), but then I wouldn’t be able to write a blog post about regularized least squares later.
Now we’ll plot the data and the fitted curve to see if the function actually works!
# for plot, estimate y for each observation time y_est = f(t) # create plot plt.plot(t, y, '.', label = 'original data', markersize=5) plt.plot(t, y_est, 'o-', label = 'estimate', markersize=1) plt.xlabel('time') plt.ylabel('sensor readings') plt.title('least squares fit of degree 5') plt.savefig('sample.png')
This post took two-thirds of eternity to write. Feel free to ask questions or point out how confused I am below.
Next: regularized least squares! Or maybe selection of polynomial degree! Or maybe forgetting the blog and melting brain with TV! | http://pingswept.org/2009/01/24/least-squares-polynomial-fitting-in-python/ | CC-MAIN-2017-04 | refinedweb | 1,105 | 64.51 |
Advertisement
Excellency
All the tutorials and examples are so interesting and easy to learn.But i request you to show all the related and methods of a particulsr class being used in example.Hence,i'll try myself with them.
Thank you so much...........
excellent
good examples, good way of explanation. very fine very use full. give no of examples which occur at real life. each line of the each example put comment lines which explain that line. give information about methods of basic interfaces and class. i th
Java - Opening a URL from an Applet
Java - Opening a URL from an Applet
This is the example of opening a url in same... used for
opening url from an applet. This program is using two functions
Java - Opening a url in new window from an applet
Java - Opening a url in new window from an applet
This is the example of opening a url from an applet. This program shows that
how a url is opened in a new document or browser
Opening a URL from an Applet
Opening a URL from an Applet
Introduction
This is the example of opening a url in same... used for
opening url from an applet. This program is using two functions in which
Java - Opening a url in new window from an applet
Java - Opening a url in new window from an applet
... how to open a new window from an applet. You can use the code given in this program to open any url by replacing the value of url.
In this example our applet
Applet
Applet Write a Java applet that drwas a line between 2 points. The co-ordinates of 2 points should be passed as parametrs from html file. The color of the line should be red running but no display - Applet
from a client, the page appears with a blank applet part (just whitescreen... strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String...applet running but no display Hai,
Thanks for the post. I have
applet servlet communication - Applet
extends Applet{
URL url = null;
URLConnection servletConnection = null;
public...();
}
}
}
3)Call this applet with the html file.
Java Applet Demo...applet servlet communication Can anybody tell me applet - servlet
applet - Applet
information,visit the following link:
Thanks...*;
import java.awt.*;
public class CreateTextBox extends Applet implements | http://roseindia.net/tutorialhelp/allcomments/182 | CC-MAIN-2015-32 | refinedweb | 388 | 65.73 |
I.
Whilst events work, and no doubt better than a MessageBox, I don't think they should be used for debugging. You may use them for genuine Information reasons , but it would be a temptation to leave the extra debug events in your code. That wouldn’t be a good idea as they are quite expensive to fire, especially row by row. For debug purposes I prefer using the System.Diagnostics.Debug.WriteLine method. Use the DebugView tool from Sysinternals to capture the messages when you are actively debugging, but without a listener they are passive and less overhead than events.
Hi Ben,
If you want to use the messagebox.show method at design time simlpy add the line:
using System.Windows.Forms;
to the top of the script. The dll reference is already in the project by default when created by BIDS. | https://blogs.msdn.microsoft.com/benjones/2010/10/04/debugging-parameters-in-the-ssis-data-flow-script-component/ | CC-MAIN-2017-09 | refinedweb | 143 | 64.71 |
Nonlinear measures for dynamical systems (based on one-dimensional time series)
Nolds is a small numpy-based library that provides an implementation and a learning resource for nonlinear measures for dynamical systems based on one-dimensional time series. Currently the following measures are implemented:
import nolds import numpy as np rwalk = np.cumsum(np.random.random(1000)) h = nolds.dfa(rwalk)
Nolds supports Python 2 (>= 2.7) and 3 (>= 3.4) from one code source. It requires the package numpy.
If you want to use the RANSAC algorithm for line fitting, you will also need the package sklearn.
Nolds is available through PyPI and can be installed using pip:
pip install nolds
You can test your installation by running some sample code with:
python -m nolds.examples all
Nolds is designed as a learning resource for the measures mentioned above. Therefore the corresponding functions feature extensive documentation that not only explains the interface but also the algorithm used and points the user to additional reference code and papers. The documentation can be found in the code, but it is also available as HTML-Version.
All relevant code can be found in the file nolds/measures.py.
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/nolds/ | CC-MAIN-2017-26 | refinedweb | 215 | 58.08 |
Many mobile applications use external databases that are located remotely on the Internet. In the following tutorial, we will create a simple database, connect to it, and receive or send data from this source. To do this we will use a Windows Phone 7 Silverlight based application and a NuSOAP web service. Let's begin!
1. Install the Software
Before we start we need to install the following programs:
- Windows Phone 7.5 SDK
- Silverlight 5 Toolkit
- PHP Library to run the web service (NuSOAP)
Obviously, we will also need some sort of web hosting where we can create a database. Most of the free hosting options will be enough for us, but they may have some limitations which I will discuss later on in this tutorial.
We also need an FTP client. In this tutorial I will use a FireFTP add-on to Mozilla Firefox. But you can use anything you want.
When all the programs are installed, we can continue.
2. Creating an External Database
Step 1
To begin, check that the hosting uses phpMyAdmin because I use it in the examples. But if you choose to use something else all the commands should be similar.
First we need to create a simple database, in our case it will contain only one table and three attributes:
- ID - this value identifies the record. It must be set as an autoincrement field.
The table name is MyUsers.
To do this just click "create table":
Step 2
After that, fill in the cells as shown in this screenshot:
The table structure should now look like this:
Step 3
At this step we must note a few important points:
- Host address
As I wrote earlier, free hostings have limits, one of these is to possibly connect only from localhost, remember that!
- Database user
Our username to log into the database:
- Database password
- Database name
3. NuSOAP Server - Starting Web Service
Step 1
Starting our web service is very simple:
First, we must copy some files to the ftp server. I recommend a ftp server because it is directly connected to our hosting because of the localhost issue.
Once we're connected, we need to copy the nusoap.php file which was downloaded earlier. We also require a file that will contain specific functions written by us that is necessary for our application; I called it MyService.php.
Step 2
After we copy the files, our FTP root directory should look like the image below:
Now open the MyService.php file and write into it:
<?php // Pull in the NuSOAP code require_once('nusoap.php'); // Create the server instance $server = new soap_server(); // Initialize WSDL support (MyService is name of our service) $server----->configureWSDL('MyService', 'urn:MyService'); // Character encoding $server->soap_defencoding = 'utf-8'; //------------------------------------------------- //Registrations of our functions //------------------------------------------------- //Our web service functions will be here. //------------------------------------------------- $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $server->service($HTTP_RAW_POST_DATA); ?>
The most important points are explained in the upper comments to code.
Step 3
From now on our service should work. We can check this by typing in the web browser:
If all went well you should see something like this:
After we successfully started the web service, we can go to the next step.
4. Writing Web Service Functions
In our service we need two functions:
- The first function adds data to the online database.
- The second function receives data from it.
Step 1
Let's open MyService.php. We need to register the new function, to do this we should type:
$server->register( 'InsertData', //Name of function array('FirstName' => 'xsd:string', 'LastName' => 'xsd:string'), //Input Values array('return' =>'xsd:boolean'), //Output Values 'urn:MyServicewsdl', //Namespace 'urn:MyServicewsdl#InsertData', //SoapAction 'rpc', //style 'literal', //can be encoded but it doesn't work with silverlight 'Some_comments_about_function' );
Remember that it needs to be placed before the body function and after the server directives.
Here is some code explanation:
'FirstName' => 'xsd:string'
"FirstName" is the name of variable, "string" is the type of variable (i.e. it can be int, longint, boolean, etc.).
When the function registers, we need to write the body of it. Below is the code and explanation:
function InsertData($FirstName, $LastName) { $connect = mysql_pconnect("Host","UserName","UserPassword")); if ($connect) { if(mysql_select_db("DatabaseName", $connect)) { mysql_query("INSERT INTO MyUser SET FirstName='$FirstName', LastName='$LastName'"); return true; } } return false; }
InsertData($FirstName, $LastName)
Here's the name of the function and its attributes. They must be the same as in the registration section.
$connect = mysql_pconnect("Host","UserName","UserPassword");
Here we can insert the data we noticed when we created the database.
if(mysql_select_db("DatabaseName", $connect)) {
And also here.
After that it is a simple MySQL query that adds data to our database:
mysql_query("INSERT INTO MyUser SET FistName='$FirstName', LastName='$LastName'");
Step 2
Now it's time to write the second function. The structure will be similar to the first.
Here is the code of method registration:
$server->register( 'GetData', array('ID' => 'xsd:int'), array('return' =>'xsd:string'), 'urn:MyServicewsdl', 'urn:MyServicewsdl#GetData', 'rpc', 'literal', 'Some comments about function 2' );
The main differences are in the Input/Output values section (changed types of variables).
Here's the body function code:; }
Here is a little code explanation:
return $result['FirstName']."-".$result['LastName'];
This line states what must return to the Windows Phone application.
Step 3
After writing all the functions the MyService.php file should look like this:
<?php // Pull in the NuSOAP code require_once('nusoap.php'); // Create the server instance $server = new soap_server(); // Initialize WSDL support configureWSDL('MyService', 'urn:MyService'); // Character encoding $server->soap_defencoding = 'utf-8'; //------------------------------------------------- //Register InsertData function $server->register( 'InsertData', array('FirstName' => 'xsd:string', 'LastName' => 'xsd:string'), array('return' =>'xsd:boolean'), 'urn:MyServicewsdl', 'urn:MyServicewsdl#InsertData', 'rpc', 'literal', 'Some comments about function' ); //Register GetData function $server->register( 'GetData', array('ID' => 'xsd:int'), array('return' =>'xsd:string'), 'urn:MyServicewsdl', 'urn:MyServicewsdl#GetData', 'rpc', 'literal', 'Some comments about function 2' ); //------------------------------------------------- //Body InsterData function function InsertData($FirstName, $LastName) { $connect = mysql_pconnect("Host","UserName","UserPassword"); if ($connect) { if(mysql_select_db("DatabaseName", $connect)) { mysql_query("INSERT INTO MyUser SET FirstName='$FirstName', LastName='$LastName'"); return true; } } return false; } //Body GetData function; } //------------------------------------------------- $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $server->service($HTTP_RAW_POST_DATA); ?>
To validate the functions we can again type in the browser. Now the site should look a little bit different, but similar to this:
Now we're ready to go to next step.
5. Creating a Simple Layout for a Windows Phone Application
Step 1
Firstly, we must create a Windows Phone app. Let's run Microsoft Visual Studio for Windows Phone 2010. After Visual Studio starts, click "File" then "New Project". You should see a dialog window like in the screenshot below:
Our app will use Silverlight, so we must check this template. We can also change the project name, like localisations, etc. In my case, the project name is "MyApplication". After you have done this, click the OK button.
Step 2
At this point we must note what we need in our app. We need:
- Two text boxes for sending data to the database (First Name, Last Name)
- One text box to receive the data (ID)
- Two buttons to approve our actions
Adding objects (such as buttons) to our application is easy, just drag it from "ToolBox" and drop it onto preview of the app. Keep in mind that you have a free hand in setting your own layout.
This is how it looks on my app:
Another important aspect is the names of the elements used in Visual Studio (they're used later in code).
To change it, just click on element. Then in properties you can see text like "Textbox1", click on it, and change it to something that you can remember, that is crucial. I used these names for my elements:
- "FirstNameBox", "LastNameBox", and "IdBox" for text boxes
- "SendBTN" and "ReadBTN" for buttons
That's all we need to do in this step, we can move on.
6. Connecting to Service
To connect to the web service we must right click on "Reference" in "Solution Explorer" dialog and select "Add Service Reference..."
Here how this looks:
After that a new window will appear. In it we must write the address of our web service and the name of namespace.
In our case an address will be created, like on this scheme:.
After entering an address and clicking "Go" you should see something like this:
If you see the operations called "GetData" and "InsertData" that means the connection was successfully created! Remember to type namespace, in my case it is "MyService". Now click OK.
7. Writing Windows Phone Functions
We're almost at the end of this tutorial; we only need to write two simple functions.
Step 1
The first function will be behind the "Send" button, so double click it. Now we must add at the top of the file a "using" directive of our service:
using MyApplication.MyService;
Let's look at the send function behind the "Send" button, now it is empty:
private void SendBTN_Click(object sender, RoutedEventArgs e) { }
Our complete function should look like this:
private void SendBTN_Click(object sender, RoutedEventArgs e) { //Creating new proxy object of our service MyServicePortTypeClient send = new MyServicePortTypeClient(); send.InsertDataCompleted += new EventHandler<InsertDataCompletedEventArgs>(send_InsertDataCompleted); //Calling method, as a parameters we type text contained in FirstNameBox and LastNameBox //This data will be sent to web service and later to database send.InsertDataAsync(FirstNameBox.Text, LastNameBox.Text); } void send_InsertDataCompleted(object sender, InsertDataCompletedEventArgs e) { //If our server return true, that means we're added data to database... if (e.Result) MessageBox.Show("Successfully added!"); //...if return false we aren't. else MessageBox.Show("Some problems occured!"); }
The most important points are explained in the code comments, but we must be aware of the following:
Method "send_InsertDataCompleted" executes when we get an answer from the server. Also this function is not in the "SendBTN" object, it is outside.
Now it's time to test our work! Start to debug and fill out the boxes with some data. Here I have entered John as a first name and Doe as a last name, then I clicked Send:
Let's see how the database looks now:
Yes, the new record with ID = 1 has appeared and everything is going well.
Step 2
Now we've reached the final function for receiving. It is similar to the previous method. Double click on the "Read" button and copy the code:
private void ReadBTN_Click(object sender, RoutedEventArgs e) { //Creating new proxy object of our service MyServicePortTypeClient read = new MyServicePortTypeClient(); read.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(read_GetDataCompleted); //Calling method, as a parameters we type text contained in IdTextBox //but we must change text type of string to integer (ID in web service have integer type) read.GetDataAsync(Convert.ToInt32(IdBox.Text)); } void read_GetDataCompleted(object sender, GetDataCompletedEventArgs e) { MessageBox.Show(e.Result); }
This is the same process as before, "read_GetDataCompleted" executes after getting data from the database. In this method we'll use a message box to show our result, i.e. first and last name. There is one more step to do; we need to change the type of text in IdBox from string to integer because the variable called ID in the web service has an integer type. To do this I used a function called "Convert.ToIn32()"
8. Testing
Now we can see if this works. Enter ID into "IdTextBox". I entered "1", then clicked the "Read" button.
Everything is working! Our application is now complete!
Conclusion
In this tutorial we created a database using a Windows Phone 7 Silverlight based application and NuSOAP web service. This database is helpful to receive or send data. External databases are important because they are used by many mobile<< | https://code.tutsplus.com/tutorials/connecting-to-an-external-database-with-nusoap--mobile-15832 | CC-MAIN-2021-04 | refinedweb | 1,933 | 53.81 |
Configure multiple dhcp bindings
I have a problem configuring a dhcp pool on a 3750 switch.
I would like to input on the dhcp scope address reservations for 20 ip phones, so that the phones get always the same ip address.
The problem is that it only let me input only one address binding.
Example of the configuration:
Ip dhcp pool test
network 192.168.10.0 255.255.255.0
import all
option 150 ip:x.x.x.x
host 192.169.10.1
hardware-address 11aa.22bb.33cc
If I input a second host and the mac-address of that host, the first one is deleted.
I do not want to create 20 dhcp different scopes for 20 phones.
Can you please advice...
Thank you in advance...
| https://supportforums.cisco.com/discussion/10752566/configure-multiple-dhcp-bindings | CC-MAIN-2017-22 | refinedweb | 129 | 78.04 |
ustat — get filesystem statistics
Synopsis
#include <sys/types.h> #include <unistd.h> /* libc[45] */ #include <ustat.h> /* glibc2 */ int ustat(dev_t dev, struct ustat *ubuf);
Description
ustat() filesystem.
- ENOSYS
The mounted filesystem referenced by dev does not support this operation, or any version of Linux before 1.3.16.
Versions
Since version 2.28, glibc no longer provides a wrapper for this system call.
Conforming to
SVr4.
Notes filesystem 5.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
Referenced By
syscalls(2). | https://dashdash.io/2/ustat | CC-MAIN-2022-05 | refinedweb | 101 | 63.96 |
Following code segments shows how to display a message dialog in Java Swing:
import javax.swing.JOptionPane; JOptionPane.showMessageDialog(mainFrame, “Data processing has been completed”);
where, mainFrame = the parent frame in which the dialog should be displayed. mainFrame can also be replaced with null.
If you notice error that the Gradle home path is incorrect, when building your Android Project in Android Studio, select and set the gradle path to correct one. To do so, select File -> Settings. Click on Build, Execution, Deployment -> Build Tools -> Gradle.
After I updated Android Studio from 1.4 to 1.5, all went well and the patch got applied. However, when starting the project, I got an error that read something like this. Error Junit:Junit:4.12 not found or missing
This error occurred due to gradle not getting updated / synced properly. Apparently, to speed up Android Studio, . . . → Read More: Error Junit:Junit:4.12 not found or missing after Android Studio 1.4 to 1.5 update
I earlier had Oracle Java 7 installed on my Linux box. I upgraded to Oracle Java 8 as follows (below commands to be typed in a terminal window): $ sudo apt-get purge oracle-java7-installer <enter> $ sudo apt-get install oracle-java8-installer <enter>
However, when Oracle Java 8 was downloaded and installed, I saw a message like this: . . . → Read More: How to resolve update-binfmts: warning: current package is oracle-java8, but binary format already installed by openjdk-7 | http://www.askmeaboutlinux.com/?cat=27&paged=2 | CC-MAIN-2019-13 | refinedweb | 245 | 50.53 |
Goswin von Brederlow wrote:
I made a quick port of the "HR-MIB cache" for net-snmp of rpm, so that it can be used with the dpkg packaging system as well.
...
PS. It can also be used for doing bash-completion of packages. There are patches for this available elsewhere on the net.A few points: 1) If the $package.list file already contains all that information for the current packages in its timestamp then what exactly is the use of this? Seems more like a log than a cache.
I wanted it to be the same as for rpm, as it would simplify handling: agent/mibgroup/host/hr_swinst.c
@@ -183,6 +185,9 @@ #define _PATH_HRSW_directory "/var/db/pkg" #endif +#undef _PATH_HRSW_directory +#define _PATH_HRSW_directory "/var/cache/hrmib" + void init_hr_swinst(void) { I think bash-completion currently uses a grep command like: grep-status -P -e "^$1" -a -FStatus 'install ok installed' -n -s Package When using the cache, this instead becomes something like: ls -1 /var/cache/hrmib | sed -ne '/^'$1'/p' Checking the .list files was the best workaround I could come up with, as it seemed like "${Installtime}" was not a valid dpkg-query field ? It's only used for the initial population (if ever), when activated in dpkg the cache directory is supposed to take care of it itself...
2) If versions are taken without epochs then versions can collide and they won't work well.
Is it normal to have more than one package of the same name installed ? I thought it would error on the versions already, let alone the epochs. But if you do have the same name-version installed more than once thenit would only show up once and removing one might delete the file, right.
3) Each new version creates a new file. Who cleans up obsolete files? Or is the "cache" supposed to grow and grow and grow?
If you remove the package, the file is supposed to get deleted too... (the files are 0 bytes in size, so it doesn't grow by all that much) It's of course easy enough to just delete the entire directory and recreate it from the current dpkg package list if anything goes wrong.
4) /var/log/dpkg seems to also alraedy have the info.
It was missing for some packages, and old log files were rotated away ? But it wasn't a log, more of a exported information directory (cache) Grepping through the log output is probably worse than grepping status, which is already twice as slow for bash-completion than checking a file. --anders | https://lists.debian.org/debian-dpkg/2009/10/msg00047.html | CC-MAIN-2016-44 | refinedweb | 433 | 69.82 |
HLSL Support¶
- Introduction
- Project Goals
- Guiding Principles
- Architectural Direction
- HLSL Language
Introduction¶
HLSL Support is under active development in the Clang codebase. This document describes the high level goals of the project, the guiding principles, as well as some idiosyncrasies of the HLSL language and how we intend to support them in Clang.
Project Goals¶
The long term goal of this project is to enable Clang to function as a replacement for the DirectXShaderCompiler (DXC) in all its supported use cases. Accomplishing that goal will require Clang to be able to process most existing HLSL programs with a high degree of source compatibility.
Guiding Principles¶
This document lacks details for architectural decisions that are not yet finalized. Our top priorities are quality, maintainability, and flexibility. In accordance with community standards we are expecting a high level of test coverage, and we will engineer our solutions with long term maintenance in mind. We are also working to limit modifications to the Clang C++ code paths and share as much functionality as possible.
Architectural Direction¶
HLSL support in Clang is expressed as C++ minus unsupported C and C++ features. This is different from how other Clang languages are implemented. Most languages in Clang are additive on top of C.
HLSL is not a formally or fully specified language, and while our goals require a high level of source compatibility, implementations can vary and we have some flexibility to be more or less permissive in some cases. For modern HLSL DXC is the reference implementation.
The HLSL effort prioritizes following similar patterns for other languages, drivers, runtimes and targets. Specifically, We will maintain separation between HSLS-specific code and the rest of Clang as much as possible following patterns in use in Clang code today (i.e. ParseHLSL.cpp, SemaHLSL.cpp, CGHLSL*.cpp…). We will use inline checks on language options where the code is simple and isolated, and prefer HLSL-specific implementation files for any code of reasonable complexity.
In places where the HLSL language is in conflict with C and C++, we will seek to make minimally invasive changes guarded under the HLSL language options. We will seek to make HLSL language support as minimal a maintenance burden as possible.
DXC Driver¶
A DXC driver mode will provide command-line compatibility with DXC, supporting DXC’s options and flags. The DXC driver is HLSL-specific and will create an HLSLToolchain which will provide the basis to support targeting both DirectX and Vulkan.
Parser¶
Following the examples of other parser extensions HLSL will add a ParseHLSL.cpp file to contain the implementations of HLSL-specific extensions to the Clang parser. The HLSL grammar shares most of its structure with C and C++, so we will use the existing C/C++ parsing code paths.
Sema¶
HLSL’s Sema implementation will also provide an
ExternalSemaSource. In DXC,
an
ExternalSemaSource is used to provide definitions for HLSL built-in data
types and built-in templates. Clang is already designed to allow an attached
ExternalSemaSource to lazily complete data types, which is a huge
performance win for HLSL.
CodeGen¶
Like OpenCL, HLSL relies on capturing a lot of information into IR metadata. hand wave hand wave hand wave As a design principle here we want our IR to be idiomatic Clang IR as much as possible. We will use IR attributes wherever we can, and use metadata as sparingly as possible. One example of a difference from DXC already implemented in Clang is the use of target triples to communicate shader model versions and shader stages.
Our HLSL CodeGen implementation should also have an eye toward generating IR that will map directly to targets other than DXIL. While IR itself is generally not re-targetable, we want to share the Clang CodeGen implementation for HLSL with other GPU graphics targets like SPIR-V and possibly other GPU and even CPU targets.
HLSL Language¶
The HLSL language is insufficiently documented, and not formally specified. Documentation is available on Microsoft’s website. The language syntax is similar enough to C and C++ that carefully written C and C++ code is valid HLSL. HLSL has some key differences from C & C++ which we will need to handle in Clang.
HLSL is not a conforming or valid extension or superset of C or C++. The language has key incompatibilities with C and C++, both syntactically and semantically.
An Aside on GPU Languages¶
Due to HLSL being a GPU targeted language HLSL is a Single Program Multiple Data (SPMD) language relying on the implicit parallelism provided by GPU hardware. Some language features in HLSL enable programmers to take advantage of the parallel nature of GPUs in a hardware abstracted language.
HLSL also prohibits some features of C and C++ which can have catastrophic performance or are not widely supportable on GPU hardware or drivers. As an example, register spilling is often excessively expensive on GPUs, so HLSL requires all functions to be inlined during code generation, and does not support a runtime calling convention.
Pointers & References¶
HLSL does not support referring to values by address. Semantically all variables
are value-types and behave as such. HLSL disallows the pointer dereference
operators (unary
*, and
->), as well as the address of operator (unary
&). While HLSL disallows pointers and references in the syntax, HLSL does use
reference types in the AST, and we intend to use pointer decay in the AST in
the Clang implementation.
HLSL
this Keyword¶
HLSL does support member functions, and (in HLSL 2021) limited operator
overloading. With member function support, HLSL also has a
this keyword. The
this keyword is an example of one of the places where HLSL relies on
references in the AST, because
this is a reference.
Bitshifts¶
In deviation from C, HLSL bitshifts are defined to mask the shift count by the size of the type. In DXC, the semantics of LLVM IR were altered to accommodate this, in Clang we intend to generate the mask explicitly in the IR. In cases where the shift value is constant, this will be constant folded appropriately, in other cases we can clean it up in the DXIL target.
Non-short Circuiting Logical Operators¶
In HLSL 2018 and earlier, HLSL supported logical operators (and the ternary
operator) on vector types. This behavior required that operators not short
circuit. The non-short circuiting behavior applies to all data types until HLSL
2021. In HLSL 2021, logical and ternary operators do not support vector types
instead builtin functions
and,
or and
select are available, and
operators short circuit matching C behavior.
Precise Qualifier¶
HLSL has a
precise qualifier that behaves unlike anything else in the C
language. The support for this qualifier in DXC is buggy, so our bar for
compatibility is low.
The
precise qualifier applies in the inverse direction from normal
qualifiers. Rather than signifying that the declaration containing
precise
qualifier be precise, it signifies that the operations contributing to the
declaration’s value be
precise. Additionally,
precise is a misnomer:
values attributed as
precise comply with IEEE-754 floating point semantics,
and are prevented from optimizations which could decrease or increase
precision.
Differences in Templates¶
HLSL uses templates to define builtin types and methods, but disallowed user-defined templates until HLSL 2021. HLSL also allows omitting empty template parameter lists when all template parameters are defaulted. This is an ambiguous syntax in C++, but Clang detects the case and issues a diagnostic. This makes supporting the case in Clang minimally invasive.
Vector Extensions¶
HLSL uses the OpenCL vector extensions, and also provides C++-style constructors for vectors that are not supported by Clang.
Standard Library¶
HLSL does not support the C or C++ standard libraries. Like OpenCL, HLSL describes its own library of built in types, complex data types, and functions.
Unsupported C & C++ Features¶
HLSL does not support all features of C and C++. In implementing HLSL in Clang use of some C and C++ features will produce diagnostics under HLSL, and others will be supported as language extensions. In general, any C or C++ feature that can be supported by the DXIL and SPIR-V code generation targets could be treated as a clang HLSL extension. Features that cannot be lowered to DXIL or SPIR-V, must be diagnosed as errors.
HLSL does not support the following C features:
- Pointers
- References
gotoor labels
- Variable Length Arrays
_Complexand
_Imaginary
- C Threads or Atomics (or Obj-C blocks)
uniontypes (in progress for HLSL 202x)
- Most features C11 and later
HLSL does not support the following C++ features:
- RTTI
- Exceptions
- Multiple inheritance
- Access specifiers
- Anonymous or inline namespaces
new&
deleteoperators in all of their forms (array, placement, etc)
- Constructors and destructors
- Any use of the
virtualkeyword
- Most features C++11 and later | https://clang.llvm.org/docs/HLSL/HLSLSupport.html | CC-MAIN-2022-40 | refinedweb | 1,453 | 51.68 |
Programming in Clojure. Part 3: Syntax and REPL
What Will I Learn?
In this part of the tutorial you will learn:
- What are the benefits Clojure's LISP-like syntax
- How to use REPL to run and debug your code
- How to develop your own REPL for Clojure
Requirements
To follow this part of the tutorial it might be beneficial to have:
- Experience in any other programming languages, especially in those designed for functional programming. Ideally Lisp dialects.
- Experience with functional programming.
- Experience working in command line.
Difficulty
- Intermediate
Tutorial Contents
This part of a tutorial will demonstrate a simple model for thinking about evaluation of Clojure programs. It will also describe how to take advantage from powerful Clojure REPL. Practical task of this tutorial will consist of developing our own REPL, which is surprisingly simple thanks to Clojure's syntax.
Curriculum
- Part 1: Why Clojure?
- Part 2: Functional Programming
- Part 3: Syntax and REPL
- Part 4: Data structures
- Part 5: Advanced data structures
- And maybe more...
Abstract Syntax Tree
Being a LISP dialect, Syntax of Clojure is famous for being quite exotic compared to most modern lanugages. Latter opt-in to use expression and statements which look similar to mathematic notation:
1 + 2 * y is immidiately understandable even for middle schoolers. Identical expression in any LISP would look like
(+ 1 (* 2 y)), which many people find confusing, especially when they just start learning programming. However, there are compelling evidence to use latter, which you will know by the end of this article.
Almost all programming languages are executed in sequence of following phases:
- Preprocessing: manipulating the source code of the program in one way or another. LISPs has macros for this, C has preprocessor, other languages might have different techniques.
- Lexical analysis: breaking down source code into it's constutuent elements. In a sense, that's when compiler/interpreted "understands" the meaning of the smallest pieces of source code.
- Syntax analysis: organizing tokens received from Lexical analysis stage into an abstract syntax tree, according to syntactic rules of a language.
- Semantic analysis: handling type checking, declaring variables and binding them to values, and ensuring semantic correctness of a program.
- Analysis and optimization: advanced techniques for manipulating program structure in such a way as to make it run faster. One particular example might be elimination of "dead code" (code which will never run, like
if (false) { <dead code> }.
- Code generation: creating a machine code (or code in some other language in case of transpiling).
Let's take previously mentioned expression
1 + 2 * y as an example, and see what compiler or interpreter needs to do on Lexical and Semantic analysis phases to process it:
- Lexical analysis: will output tokens similar to the following: <Literal, 1>, <Operator, +>, <Literal 2>, <Operator, *>, (of course it's not persice, since exact format of changes from language to language and even between compiler/interpreter versions).
- Semantic analysis: will need to form an abstract syntax tree from those tokens. It needs to scan the whole thing to find an operation with highest preference, which is <Operator, *> in our case, then it needs to find tokens to which this operator is applied, which are <Literal, 2> and <Variable, y>. Now it needs to figure out that resulting value must be appled on <Operator, +> together with <Literal, 2>. As you can see, there are many back-an-forth lookups performed, even in this simple example:
However, the process is much more strightforward with LISP syntax, because LISP expression is already a tree. Each LISP expression represents a list, where first element is a function to apply, and the rest are it's arguments. In fact, with LISP Lexical and Semantic analysis can be performed at the same time. Again, let's follow steps performed by compiler or interpreter, but now given the LISP expression
(+ 1 (* 2 y)) as an input:
- First element of a top level list expression is
+, so create
<Function, +>token.
- Second element of a top level list expression is
1, so create
<Literal, 1>token as an argument to
Function, +.
- Third element of a top level list expression is
(* 2 y), so take the first element of it
<Function, *>and put it as an argument to
<Function, +>.
- Second element of second level list is
<Literal, 2>, so put it as an argument to
<Function, +>.
- Third element of second level list is
<Variable, y>, so put it as a second argument to
<Function, +>.
As a result, we get exactly the same tree, built in one pass, which exactly mirrors the initial syntax.
In effect, this means that LISP source code already represents abstract syntax tree, and it describes internal structure on a program much better than traditional syntax. This gives developer power to modify abstract syntax tree by simply modifying the source code programmaticaly, instead of using complicated introspection tools. Since source code is basically a structure consisting of nested lists, it is relatively easy to work with. With traditional syntax, source code is just an array of strings, with evaluation rules way too complicated to allow for efficient preprocessing without compiler support.
Another benefit of LISP-based syntax is that basic evaluation rules can be modelled as two stage process of recursively reducing the program to it's simpler version:
Given a list, it's evaluation can be performed in following way:
- Evaluate the tail of the list.
- Apply the head of the list to the tail of the list.
If we try to apply this process to our initial expression, this is how it will be evaluated:
(+ 1 (* 2 y))- initial list. For this example, let's say that value of
yis
5in current namespace.
- Evaluate it's tail:
- Evaluate
1. Literals, obviously, evaluate to their own value, so the result of this step is
1.
- Evaluate
(* 2 y).
- Evaluate it's tail:
- Evaluate
2. Returns
2.
- Evaluate
y. Returns it's value
5.
- Apply
*to
2and
5. Returns
10.
- Apply
+to
1and
10, Returns
11
1. (+ 1 (* 2 y)) 2. (+ 1 (* 2 5)) 3. (+ 1 10) 4. 11
Keep in mind that while this model gives a convenient way of thinking about the source code evaluation, it does not always match what really happens in a real application. In many situation Clojure needs to alter the argument evaluation rules for one reason or another. Still, we need to understand eval/apply execution model to use as a base for understanding those exceptional cases.
Read Eval Print Loop
Many modern languages, especially interpreted ones, have a built-in read-eval-print-loop, or REPL: : Python, Ruby, Scala, JavaScript to name a few. In many cases having access to REPL is very convinient, since it allows working with code in more interactive manner. Developer can try out different features of a language and receive immidiate feedback from the language. It might also be used as a very powerfull debugging tool.
LISP was one of the first languages to implement REPL. Event the name itself has it roots in following LISP expression (not valid in Clojure due to differences in syntax):
(loop (print (eval (read))))
Thanks to the newly-obtained knowledge of the LISP evaluation model, we can see why that expression seems to be written backwards (arguments are always evaluated first). Here's how this simples REPL works:
readan input as a string
evalan input as a Clojure source code
loopto repeat the process from the start
You can start Clojure's REPL with Leiningen by running
lein repl. If you run this command from the project directory, you will have an access to project's namespace and all variables there. Here's how we can use REPL to change the list of messages for the program we've developed in the previous part of the tutorial:
Writing REPL
We can create similar kind of REPL on our own with without too much effort. All we need to modify initial
(loop (print (eval (read)))) construct to match closure's syntax, and add some niceties like idicator of waiting for the user's input.
Create new Leiningen project, as usual with
lein new app laxam-clojure-tutorial-part3-repl. Open file
./src/laxam_clojure_tutorial_part3_repl/core.clj in your favourite editor and let's get to work.
First, we need to change
loop expression. In Clojure,
loop is very similar to recursion. It accepts a vector of bindings (just like a function with it's arguments), and requires user to trigger next loop iteration by calling
recur. Values of
recur's arguments will be used for bindings. So, the first draft of our
-main function looks like this:
(defn -main [& args] (loop [_ nil] (recur (println (eval (read))))))
Now, let's extend this small program with user interaction promit. I will use
>>> symbol as an indicator that REPL is ready to accept user's input:
(defn -main [& args] (loop [_ nil] (recur (println (do (print ">>>") (flush) (eval (read)))))))
This works almost perfectly. It evaluates expressions correctly and even looks up varaibles in current namespace:
There's just one problem with this code so far. Once we encounter an error, exception will bubble up all the way to the top, closing our REPL process. That's not what we expect from REPL, so let's catch that exception, print the error message and stop the process from exiting:
(defn -main [& args] (loop [_ nil] (recur (println (do (print ">>> ") (flush) (try (eval (read)) (catch Exception e (println "Exception: " (.getMessage e)))))))))
That's much better. We used Clojure's version of
try-catch expression, which works quite similar to ideantical expression in Java.
.getMessage is an example of interoperability between Java and clojure: it is actually a method bound to exception object, and not a Clojure function. If "function name" starts with
., Clojure will try to look up corresponding method in a second element of a list expression (first function argument).
One last problem with this code is that when we want to exit REPL with CTRL+D, JVM generates runtime exception "End of file while reading", which will be caught in
try-catch block and ignored. Next
(read) will still contain
EOF symbol, so our repl will get into endless loop. To handle it, we need to handle EOF manually. Fortunately,
read expression in Clojure can be instructed to return special symbol when encountering
EOF, instead of throwing an error. We will use it to safely exit the process when user sends
EOF combination to standard input channel:
(defn -main [& args] (loop [_ nil] (recur (println (do (print ">>> ") (flush) (try (eval (let [expr (read *in* false :end)] (if (= expr :end) (System/exit 0) expr))) (catch Exception e (println "Exception: " (.getMessage e)))))))))
As you can see,
read was modified by instructing it to not throw an exception (
false flag) and to replace it with
:end value instead. We store incomming expression into
expr variable and, if it equals
:end, we call
System/exit 0 to stop the process cleanly. Finally, our REPL application is complete, and works correctly even when exceptions occur:
The complete source code for this project can be found, as usual, in a GitHub repostory.
Summary
Clojure's exotic syntax has many benefits which are not visible from the first glance. It is very easy to reason about the program execution with simple set of rules in mind. We developed a REPL application, which despite a simple source code is complete and functional.
I hope you have enjoyed this tutorial.
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been reviewed.
Need help? Write a ticket on.
Chat with us on Discord.
[utopian-moderator]
Hey @laxam I am @utopian-io. I have just upvoted you!
Achievements
Utopian Witness!
Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord | https://steemit.com/utopian-io/@laxam/programming-in-clojure-part-3-syntax-and-repl | CC-MAIN-2022-05 | refinedweb | 1,975 | 53.61 |
A signed Django form
Project description
A small library that provides a form class that signs a configurable set of hidden fields using django.core.signing.
The most common use case for such a form is when the view that handles the post differs from the view that sets up the form, but you need to pass some information from one view to the other, without evil hackers tampering with your precious data.
Usage
Subclass SignedForm, and define which fields should be signed:
from signedforms.forms import SignedForm class MyForm(SignedForm): signed_fields = ['redirect_url',] redirect_url = forms.CharField(required=False, widget=forms.HiddenInput)
In the form that sets up the view, provide the data to be signed in the initial dictionary:
my_form = MyForm(initial={'redirect_url': self.request.path_info})
and in the view that handles the posted form:
def form_valid(self, form): # do some work return HttpResponseRedirect(form.cleaned_data['redirect_url'])
Note
If the user tampered with the hidden data, the form will not validate.
Warning
Only fields that contain JSON-serializable data can be signed. This includes all fields that are represented as text in the database, but not datetimes and other more “complex” types.
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/django-signedforms/ | CC-MAIN-2021-10 | refinedweb | 221 | 52.8 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
On 26/09/2013 at 06:34, xxxxxxxx wrote:
User Information:
Cinema 4D Version: 13.061
Platform: Windows ;
Language(s) : C++ ;
---------
Hello,
I like to copy some objects from one c4d project into another project. I open a second project with LoadDocument(...) and now I can scan all objects. I'm create new objects in my project and use the CopyTo(..) function to copy all data (BaseContainer and tags) to my object in my project. That's working.
But in some BaseContainers are LINKs inside with references to other objects. The CopyTo(..) function can not copy this links simple. I'm reading something about the AliasTrans parameter, but I don't understand how this is working. Or what I have to implement it. How convert C4D the links into my project?
regards
Markus
On 26/09/2013 at 09:34, xxxxxxxx wrote:
Allocate (AutoAlloc will work) an AliasTrans and include it in the CopyTo. This class is then tasked by the call to 'fix' the links. The docs for AliasTrans provide an example:
AutoAlloc<AliasTrans> aliastrans;
if (!aliastrans || !aliastrans->Init(document)) return FALSE;
dup = op->GetClone(COPYFLAGS_0, aliastrans);
if (!dup) return FALSE;
aliastrans->Translate(TRUE);
On 26/09/2013 at 22:29, xxxxxxxx wrote:
Does it means, I have to implement the Translate() function itself?
Because if I added this code, nothing happend with the links. All links in BaseContainer are empty.
I add a part of my code: (it's only a clip)
...
BaseDocument* pXrefDoc = LoadDocument(file, SCENEFILTER_OBJECTS | SCENEFILTER_MATERIALS, NULL);
BaseObject *pobj = pxrefdoc->GetFirstObject();
AutoAlloc<AliasTrans> aliastrans;
if (!aliastrans || !aliastrans->Init(pdoc)) return;
while ( pXrefobj ) {
C4DAtom * atom;
BaseObject* poNew;
//if (!pXrefobj->CopyTo( poNew, COPYFLAGS_0, aliastrans )) return; // copy base container data and tags, but no links
atom = pXrefobj->GetClone( COPYFLAGS_0, aliastrans );
if (!atom) return;
aliastrans->Translate( TRUE );
poNew = (BaseObject* )atom;
poNew->SetName( "My::"+ pXrefobj->GetName()); // set name with namespace
pdoc->InsertObject( poNew, NULL, ppred );
pXrefobj = pXrefobj->GetNext();
}
...
On 27/09/2013 at 00:26, xxxxxxxx wrote:
You probably need to postpone the aliastrans->Translate() call until after the loop so that all of the objects that are linked exist in (have been inserted into) the document for translation. If one AliasTrans fails, you might need an array of them (one for each clone). | https://plugincafe.maxon.net/topic/7461/9283_c4datomcopyto-and-aliastrans/1 | CC-MAIN-2021-31 | refinedweb | 416 | 66.33 |
Mentioned 106've heard that, in C++, the
static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
See Effective C++ Introduction:
From what I saw in this post I decided to start reading the book Effective C++.
But now that there are many new features because of C++11 and that a few of the good practices changed, I'm not sure whether or not it is actually a good idea. Has the advent of C++11 deprecated any of the advice contained in Effective C++? If so, which topics should I avoid?
This what Scott Meyers himself had to say about it on his own blog.
UPDATE: the new title Effective Modern C++ has been for sale since November 2014 from O'Reilly and Amazon (and many others that you can google for).
int main( const int argc , const char[] const argv)
As Effective C++ Item#3 states "Use const whenever possible", I start thinking "why not make these 'constant' parameters
const"?.
Is there any scenario in which the value of
argc is modified in a program?
In this case, history is a factor. C defined these inputs as "not constant", and compatibility with (a good portion of) existing C code was an early goal of C++.
Some UNIX APIs, such as
getopt, actually do manipulate
argv[], so it can't be made
const for that reason also.
(Aside: Interestingly, although
getopt's prototype suggests it won't modify
argv[] but may modify the strings pointed to, the Linux man page indicates that
getopt permutes its arguments, and it appears they know they're being naughty. The man page at the Open Group does not mention this permutation.)
Putting
const on
argc and
argv wouldn't buy much, and it would invalidate some old-school programming practices, such as:
// print out all the arguments: while (--argc) std::cout << *++argv << std::endl;
I've written such programs in C, and I know I'm not alone. I copied the example from somewhere.
I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools.
Are there any other common pitfalls to avoid in C++?
Some must have C++ books that will help you avoid common C++ pitfalls:
Effective C++
More Effective C++
Effective STL
The Effective STL book explains the vector of bools issue :)
I've already mentioned it a few times, but Scott Meyers' books Effective C++ and Effective STL are really worth their weight in gold for helping with C++.
Come to think of it, Steven Dewhurst's C++ Gotchas is also an excellent "from the trenches" resource. His item on rolling your own exceptions and how they should be constructed really helped me in one project.
Read the book C++ Gotchas: Avoiding Common Problems in Coding and Design.
I); }
When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the
-Wall -Wextra options) I suddenly got a bunch of errors of the form
warning: type qualifiers ignored on function return type.
Consider
temp.cpp:
class Something { public: const int getConstThing() const { return _cMyInt; } const int getNonconstThing() const { return _myInt; } const int& getConstReference() const { return _myInt; } int& getNonconstReference() { return _myInt; } void setInt(const int newValue) { _myInt = newValue; } Something() : _cMyInt( 3 ) { _myInt = 2; } private: const int _cMyInt; int _myInt; };
Running
g++ temp.cpp -Wextra -c -o blah.o:
temp.cpp:4: warning: type qualifiers ignored on function return type temp.cpp:7: warning: type qualifiers ignored on function return type
Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading
const is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const?
Scott Meyers pointed out that there's pretty good reason why someone would want to return
const values. Here's an example:
int some_calculation(int a, int b) { int res = 0; /* ... */ return res; } /* Test if the result of the calculation equals 40.*/ if (some_calculation(3,20) = 40) { }
Do you see what I did wrong? This code is absolutely correct and should compile. The problem is that the compiler didn't understand that you intended tocompare instead of assign the value
40.
With a
const return value the above example won't compile. Well, at least if the compiler doesn't discard the
const keyword.
I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)
Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider
iterator_traits, which provides typedefs (e.g.
value_type) for iterators.
Using them, you can write
iterator_traits<vector<int>::iterator>::value_type x; iterator_traits<int*>::value_type y; // `x` and `y` have type int.
But to make this work, there is actually an explicit definition somewhere in the
<iterator> header, which reads something like this:
template <typename T> struct iterator_traits<T*> { typedef T value_type; // … };
This is a partial specialization of the
iterator_traits type for types of the form
T*, i.e. pointers of some generic type.
In the same vein,
iterator_traits are specialized for other iterators, e.g.
typename vector<T>::iterator.
Could someone point me to an article, or write some tips right here about some c++ programming habits that are generally valid (no real drawbacks) and improves performance? I do not mean programming patterns and algorithm complexity - I need small things like how you define your functions, things to do/to avoid in loops, what to allocate on the stack, what on the heap, and so on.
It's not about making a particular software faster, also it's not about how to create a clean software design, but rather programming habits that - if you always apply them, you will make your code rather a little bit faster than a little bit slower.
Thanks :)
I took the habit to prefer writing
++i rather than
i++ not that it brings any performance boost when
i is an
int but things are different when
i is an
iterator which might have a complex implementation.
Then let's say you come from the C programming language, lose your habit to declare all your variables at the beginning on the function: declare your variables when they are needed in the function flow since the function might contain early
return statements before some variables that were initialized at the beginning are effectively used.
Apart from that, another resource is C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter (him again) and Alexei Alexandrescu.
There is also a more recent edition of Scott Meyers' Effective C++: Effective C++: 55 specific ways to improve your programs and designs.
Finally, I would like to mention Tony Albrecht's Pitfalls of Object Oriented Programming presentation: not that it contains rules of thumb you can follow blindly but it's a very interesting read.
A number of the tips in Effective C++, More Effective C++, Effective STL and C++ Coding Standards are along this line.
A simple example of such a tip: use preincrement (++i) rather than postincrement (i++) when possible. This is especially important with iterators, as postincrement involves copying the iterator. You optimizer may be able to undo this, but it isn't any extra work to write preincrement instead, so why take the risk?
Every so often, I'll have to switch between languages for the majority of the code I write (whether for work or for play). I find that C++ is one of those languages that requires a lot of mental cache space, so if I take a long break from it, then I forget a lot of the details. Even things like adding items to an STL container or using the
static storage keyword in various contexts get all jumbled up ("is it
add,
append,
push...oh, it's
push_back").
So what essential tidbits do you like to have loaded into your brain when you're writing C++?
Edit: I should say, I'd like to be able to bookmark this page and use it as my cheatsheet :)
Since I work in C++ all the time I keep most of the syntax in my head. For library reference I use sgi and Josuttis' book. When I haven't done C++ for a while and really want a refresher I go back to Effective C++.
When I need to ansewer a deeper question I'll refer to the standard or Stroustrup's book.
When all else fails, google and stackoverflow are great tools.:
Are there some drawbacks of such implementation of copy-constructor?
Foo::Foo(const Foo& i_foo) { *this = i_foo; }
As I remember, it was recommend in some book to call copy constructor from assignment operator and use well-known swap trick, but I don't remember, why...
You're looking for Scott Meyers' Effective C++ Item 12: Copy all parts of an object.
I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials.
Does any one have any nice links to teach me RAII?
The reference that I personally have found most helpful on the topic of RAII is the book Exceptional C++ by Herb Sutter.
Many of the topics covered in that book are touched on in the Guru of the Week articles by Sutter. Those articles are available at.
Item 13 of "Effective C+" is also pretty useful
Just would like some thoughts of what you think about my strategy to learn C++. While I understand that it takes years to master a programming language, I simply want to get to the point where I can be considered competent as quickly as possible. Why quickly? Well when I say quickly I'm really saying I'm committed, and that I don't want it to take forever where forever is never. If it takes five years to become competent, it takes five years. I'm not expecting 24 hours or 30 days.
About me: I don't have a CS degree, I have an anthropology degree and a Masters in library science. Learning the CS fundamentals such as Big O notation, and basics such as binary trees and linked lists, sort algorithms has been a challenge. Probably nothing substitutes a good CS degree. :( I do have many years programming experience, starting with PHP in 2001, ActionScript, 2003, JavaScript soon after. I have been writing programs in Python for about two years now and I have learned C (by reading the K&R book and writing some programs), but I'm probably not going to get hired for a C job. Also recently learned Objective C. I work as a JavaScript & Python, & CSS developer at a website at the moment.
Anyhow, this is my strategy: Read the Stroustrup book (I just started on Part I) and at the same time start a simple C++ project, while also doing many of the Stroustrup exercises.
Thoughts?
Also be sure to check out How Not to Program in C++
Bjarne's book is fantastic, especially for C++ syntax, but the one book that will really make you a competent C++ programmer is Meyers' Effective C++. Get it. Read it.
I as well do not have a CS degree, but I work for a silicon valley startup. It is possible, you just have to be aware of what's out there and never stop learning. Many students who graduate with a computer science degree end up working in a language they didn't study, so be sure to hit the fundamentals. If you hear something that's unfamiliar to you, be sure to find a good book and a coffee shop and get to it. The C++ will come in time - with Stroustrup and Meyers, you've got 90% of what it takes to be good at C++
If you have a strong handle on C, then C++ is not a huge leap once you have a good handle on the OOP concepts....which hopefully you have from becoming proficient in Python. Coming from C, the biggest thing to learn in C++ is really getting familiar with the Standard Template Library (STL) and all the subtle things come along with using it.
Personally, I think the Stroustrup book is not all that great for learning the language, it's more of a reference. I would recommend C++ Primer Plus as a better book and the Effective C++ books by Meyers for really learning to use the language coherently.
I don't htink the Stroustrop book is a good place to start. It's more of an advanced/reference book. I would start with Thinking in C++ (Volume 1) (and Volume 2. And write lots of code. Once you've got a basic handle on the code I would get the Scott Meyer Effective C++ books and definitely the Stroustrop book.
I'm trying to find a least-resistance path from C# to C++, and while I feel I handle C# pretty well after two solid years, I'm still not sure I've gotten the "groove" of C++, despite numerous attempts.
Are there any particular books or websites that might be suitable for this transition?
About two years ago, I made the switch from C# to C++ (after 10 years of writing java). The most useful book for me was Bruce Eckel's Thinking in C++ [AMZN]. You can also read the book online at Eckel's website. It's a well-written book--the kind you can read in bed--that's also useful as a keyboard-side reference. It assumes a significant level of comfort with OO and general programming concepts.
Stroustrup [AMZN] is invaluable as a reference, but basically impenetrable unless you're trying to answer a very specific question--and even then, it's a struggle. I haven't cracked my K&R [AMZN] in a few years. I don't think it's got much value as a C++ reference. Myers' Effective C++ [AMZN] (and, once you get there, Effective STL [AMZN]) are fantastic books. They're very specific, though (e.g., "36. Design functor classes for pass-by-value"), and hence not as useful as Eckel for making the transition.
My experience writing C++ after many years writing managed languages has been great. C++ is a hundred times more expressive than C#, and extremely satisfying to write--where it's warranted. On the other hand, on the rare occasions when I still get to write C#, I'm always amazed by how quickly and succinctly I can get things done.
Anyway, Eckel's Effective C++ can help you make the transition. There's a second volume that's good, but not as good. Stick with the original.
Good luck!
You should read one of the other books posted, but then also The Design & Evolution of C++. It helps you to get inside the head of what the language is trying to do.
recently I've been reading through Scott Meyers's excellent Effective C++ book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost.
However, there was one that I definitely did NOT recognize: tr1::reference_wrapper.
How and when would I use tr1::reference_wrapper?
It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.
For example (using boost syntax):
void Increment( int& iValue ) { iValue++; } int iVariable = 0; boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable )); fIncrementMyVariable();
This Dr. Dobbs article has some info.
Hope this is right, and helpful. :)
What is the difference between these two terms, and why do I need
mutable?
Scott Meyers, Effective C++, Item 3:
Use
const whenever possible
has an excellent discussion (with examples) on this topic. Its hard to write better than Scott!
Note also that physical-constness is also known as bitwise-constness.
In several introductory texts on Object-oriented programming, I've come across the above statement.
From wikipedia, "In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects and can be viewed as an independent 'machine' with a distinct role or responsibility."
What exactly does the statement mean in code?
class A { methodA() { } } class B { methodB() { } } class C{ main() { A a=new A(); B b=new B(); a.methodA(); // does this mean msgs passing?? b.methodB(); // or does this?? I may be completely off-track here.. } }
If we are talking about OOP than the term "message passing" comes from Smalltalk. In a few words the Smalltalk basic principles are:
If you are interested in Smalltalk take a look at Pharo or Squeak.
Java/C#/C++ and many other languages use slightly different approach probably derived from Simula. You invoke a method instead of pass a message.
I think this terms are more or less equivalent. May be the only interesting difference is that message passing (at least in Smalltalk) always rely on dynamic dispatch and late binding while in the case of method invocation one can use static dispatch and early binding too. For example, C++ (AFAIK) does early binding by default until "virtual" keyword appears somewhere...
Anyway, regardless of which formalism do your programming language use for communication between two objects (message passing or method invocation) it's always considered a good OOP style to forbid direct access to instance variables in Smalltalk terminology or data members in C++ terminology or whatever term is used in your programming language.
Smalltalk directly prohibits access to instance variables at the syntax level. As I mentioned above objects in Smalltalk program can interact only by passing/receiving messages. Many other languages allow access to instance variables at the syntax level but it's considered a bad practice. For example, the famous Effective C++ book contains the corresponding recommendation: Item 22: Declare data members private.
The reasons are:
The last one is the most important. It's the essence of encapsulation - information hiding on the class level..
(с) Scott Meyers, Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)
I occasionally have classes with private static data members. I'm currently debating if I should replace these with static variables in an unnamed namespace in the implementation file. Other that not being able to use these variables in inline methods, are there any other drawbacks? The advantage that I see is that is hides them completely from the users of the class.
I disagree with the other answers. Keep as much out of the class definition as possible.
In Scott Meyers' Effective C++ 3rd edition he recommends preferring non-friend functions to class methods. In this way the class definition is as small as possible, the private data is accessed in as few places as possible (encapsulated).
Following this principle further leads to the pimpl idiom. However, balance is needed. Make sure your code is maintainable. Blindly, following this rule would lead you to make all your private methods file local and just pass in the needed members as parameters. This would improve encapsulation, but destroy maintainability.
All that said, file local objects are very hard to unit test. With some clever hacking you can access private members during unit tests. Accessing file local objects is a bit more involved.
I've been extensively using smart pointers (boost::shared_ptr to be exact) in my projects for the last two years. I understand and appreciate their benefits and I generally like them a lot. But the more I use them, the more I miss the deterministic behavior of C++ with regarding to memory management and RAII that I seem to like in a programming language. Smart pointers simplify the process of memory management and provide automatic garbage collection among other things, but the problem is that using automatic garbage collection in general and smart pointer specifically introduces some degree of indeterminisim in the order of (de)initializations. This indeterminism takes the control away from the programmers and, as I've come to realize lately, makes the job of designing and developing APIs, the usage of which is not completely known in advance at the time of development, annoyingly time-consuming because all usage patterns and corner cases must be well thought of.
To elaborate more, I'm currently developing an API. Parts of this API requires certain objects to be initialized before or destroyed after other objects. Put another way, the order of (de)initialization is important at times. To give you a simple example, let's say we have a class called System. A System provides some basic functionality (logging in our example) and holds a number of Subsystems via smart pointers.
class System { public: boost::shared_ptr< Subsystem > GetSubsystem( unsigned int index ) { assert( index < mSubsystems.size() ); return mSubsystems[ index ]; } void LogMessage( const std::string& message ) { std::cout << message << std::endl; } private: typedef std::vector< boost::shared_ptr< Subsystem > > SubsystemList; SubsystemList mSubsystems; }; class Subsystem { public: Subsystem( System* pParentSystem ) : mpParentSystem( pParentSystem ) { } ~Subsystem() { pParentSubsystem->LogMessage( "Destroying..." ); // Destroy this subsystem: deallocate memory, release resource, etc. } /* Other stuff here */ private: System * pParentSystem; // raw pointer to avoid cycles - can also use weak_ptrs };
As you can already tell, a Subsystem is only meaningful in the context of a System. But a Subsystem in such a design can easily outlive its parent System.
int main() { { boost::shared_ptr< Subsystem > pSomeSubsystem; { boost::shared_ptr< System > pSystem( new System ); pSomeSubsystem = pSystem->GetSubsystem( /* some index */ ); } // Our System would go out of scope and be destroyed here, but the Subsystem that pSomeSubsystem points to will not be destroyed. } // pSomeSubsystem would go out of scope here but wait a second, how are we going to log messages in Subsystem's destructor?! Its parent System is destroyed after all. BOOM! return 0; }
If we had used raw pointers to hold subsystems, we would have destroyed subsystems when our system had gone down, of course then, pSomeSubsystem would be a dangling pointer.
Although, it's not the job of an API designer to protect the client programmers from themselves, it's a good idea to make the API easy to use correctly and hard to use incorrectly. So I'm asking you guys. What do you think? How should I alleviate this problem? How would you design such a system?
Thanks in advance, Josh
There are two competing concerns in this question.
Subsystems, allowing their removal at the right time.
Subsystems need to know that the
Subsystemthey are using is valid.
System owns the
Subsystems and should manage their life-cycle with it's own scope. Using
shared_ptrs for this is particularly useful as it simplifies destruction, but you should not be handing them out because then you loose the determinism you are seeking with regard to their deallocation.
This is the more intersting concern to address. Describing the problem in more detail, you need clients to receive an object which behaves like a
Subsystem while that
Subsystem (and it's parent
System) exists, but behaves appropriately after a
Subsystem is destroyed.
This is easily solved by a combination of the Proxy Pattern, the State Pattern and the Null Object Pattern. While this may seem to be a bit complex of a solution, 'There is a simplicity only to be had on the other side of complexity.' As Library/API developers, we must go the extra mile to make our systems robust. Further, we want our systems to behave intuitively as a user expects, and to decay gracefully when they attempt to misuse them. There are many solutions to this problem, however, this one should get you to that all important point where, as you and Scott Meyers say, it is "easy to use correctly and hard to use incorrectly.'
Now, I am assuming that in reality,
System deals in some base class of
Subsystems, from which you derive various different
Subsystems. I've introduced it below as
SubsystemBase. You need to introduce a Proxy object,
SubsystemProxy below, which implements the interface of
SubsystemBase by forwarding requests to the object it is proxying. (In this sense, it is very much like a special purpose application of the Decorator Pattern.) Each
Subsystem creates one of these objects, which it holds via a
shared_ptr, and returns when requested via
GetProxy(), which is called by the parent
System object when
GetSubsystem() is called.
When a
System goes out of scope, each of it's
Subsystem objects gets destructed. In their destructor, they call
mProxy->Nullify(), which causes their Proxy objects to change their State. They do this by changing to point to a Null Object, which implements the
SubsystemBase interface, but does so by doing nothing.
Using the State Pattern here has allowed the client application to be completely oblivious to whether or not a particular
Subsystem exists. Moreover, it does not need to check pointers or keep around instances that should have been destroyed.
The Proxy Pattern allows the client to be dependent on a light weight object that completely wraps up the details of the API's inner workings, and maintains a constant, uniform interface.
The Null Object Pattern allows the Proxy to function after the original
Subsystem has been removed.
I had placed a rough pseudo-code quality example here, but I wasn't satisfied with it. I've rewritten it to be a precise, compiling (I used g++) example of what I have described above. To get it to work, I had to introduce a few other classes, but their uses should be clear from their names. I employed the Singleton Pattern for the
NullSubsystem class, as it makes sense that you wouldn't need more than one.
ProxyableSubsystemBase completely abstracts the Proxying behavior away from the
Subsystem, allowing it to be ignorant of this behavior. Here is the UML Diagram of the classes:
#include <iostream> #include <string> #include <vector> #include <boost/shared_ptr.hpp> // Forward Declarations to allow friending class System; class ProxyableSubsystemBase; // Base defining the interface for Subsystems class SubsystemBase { public: // pure virtual functions virtual void DoSomething(void) = 0; virtual int GetSize(void) = 0; virtual ~SubsystemBase() {} // virtual destructor for base class }; // Null Object Pattern: an object which implements the interface to do nothing. class NullSubsystem : public SubsystemBase { public: // implements pure virtual functions from SubsystemBase to do nothing. void DoSomething(void) { } int GetSize(void) { return -1; } // Singleton Pattern: We only ever need one NullSubsystem, so we'll enforce that static NullSubsystem *instance() { static NullSubsystem singletonInstance; return &singletonInstance; } private: NullSubsystem() {} // private constructor to inforce Singleton Pattern }; // Proxy Pattern: An object that takes the place of another to provide better // control over the uses of that object class SubsystemProxy : public SubsystemBase { friend class ProxyableSubsystemBase; public: SubsystemProxy(SubsystemBase *ProxiedSubsystem) : mProxied(ProxiedSubsystem) { } // implements pure virtual functions from SubsystemBase to forward to mProxied void DoSomething(void) { mProxied->DoSomething(); } int GetSize(void) { return mProxied->GetSize(); } protected: // State Pattern: the initial state of the SubsystemProxy is to point to a // valid SubsytemBase, which is passed into the constructor. Calling Nullify() // causes a change in the internal state to point to a NullSubsystem, which allows // the proxy to still perform correctly, despite the Subsystem going out of scope. void Nullify() { mProxied=NullSubsystem::instance(); } private: SubsystemBase *mProxied; }; // A Base for real Subsystems to add the Proxying behavior class ProxyableSubsystemBase : public SubsystemBase { friend class System; // Allow system to call our GetProxy() method. public: ProxyableSubsystemBase() : mProxy(new SubsystemProxy(this)) // create our proxy object { } ~ProxyableSubsystemBase() { mProxy->Nullify(); // inform our proxy object we are going away } protected: boost::shared_ptr<SubsystemProxy> GetProxy() { return mProxy; } private: boost::shared_ptr<SubsystemProxy> mProxy; }; // the managing system class System { public: typedef boost::shared_ptr< SubsystemProxy > SubsystemHandle; typedef boost::shared_ptr< ProxyableSubsystemBase > SubsystemPtr; SubsystemHandle GetSubsystem( unsigned int index ) { assert( index < mSubsystems.size() ); return mSubsystems[ index ]->GetProxy(); } void LogMessage( const std::string& message ) { std::cout << " <System>: " << message << std::endl; } int AddSubsystem( ProxyableSubsystemBase *pSubsystem ) { LogMessage("Adding Subsystem:"); mSubsystems.push_back(SubsystemPtr(pSubsystem)); return mSubsystems.size()-1; } System() { LogMessage("System is constructing."); } ~System() { LogMessage("System is going out of scope."); } private: // have to hold base pointers typedef std::vector< boost::shared_ptr<ProxyableSubsystemBase> > SubsystemList; SubsystemList mSubsystems; }; // the actual Subsystem class Subsystem : public ProxyableSubsystemBase { public: Subsystem( System* pParentSystem, const std::string ID ) : mParentSystem( pParentSystem ) , mID(ID) { mParentSystem->LogMessage( "Creating... "+mID ); } ~Subsystem() { mParentSystem->LogMessage( "Destroying... "+mID ); } // implements pure virtual functions from SubsystemBase void DoSomething(void) { mParentSystem->LogMessage( mID + " is DoingSomething (tm)."); } int GetSize(void) { return sizeof(Subsystem); } private: System * mParentSystem; // raw pointer to avoid cycles - can also use weak_ptrs std::string mID; }; ////////////////////////////////////////////////////////////////// // Actual Use Example int main(int argc, char* argv[]) { std::cout << "main(): Creating Handles H1 and H2 for Subsystems. " << std::endl; System::SubsystemHandle H1; System::SubsystemHandle H2; std::cout << "-------------------------------------------" << std::endl; { std::cout << " main(): Begin scope for System." << std::endl; System mySystem; int FrankIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Frank")); int ErnestIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Ernest")); std::cout << " main(): Assigning Subsystems to H1 and H2." << std::endl; H1=mySystem.GetSubsystem(FrankIndex); H2=mySystem.GetSubsystem(ErnestIndex); std::cout << " main(): Doing something on H1 and H2." << std::endl; H1->DoSomething(); H2->DoSomething(); std::cout << " main(): Leaving scope for System." << std::endl; } std::cout << "-------------------------------------------" << std::endl; std::cout << "main(): Doing something on H1 and H2. (outside System Scope.) " << std::endl; H1->DoSomething(); H2->DoSomething(); std::cout << "main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object." << std::endl; return 0; }
main(): Creating Handles H1 and H2 for Subsystems. ------------------------------------------- main(): Begin scope for System. <System>: System is constructing. <System>: Creating... Frank <System>: Adding Subsystem: <System>: Creating... Ernest <System>: Adding Subsystem: main(): Assigning Subsystems to H1 and H2. main(): Doing something on H1 and H2. <System>: Frank is DoingSomething (tm). <System>: Ernest is DoingSomething (tm). main(): Leaving scope for System. <System>: System is going out of scope. <System>: Destroying... Frank <System>: Destroying... Ernest ------------------------------------------- main(): Doing something on H1 and H2. (outside System Scope.) main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object.
An interesting article I read in one of the Game Programming Gems books talks about using Null Objects for debugging and development. They were specifically talking about using Null Graphics Models and Textures, such as a checkerboard texture to make missing models really stand out. The same could be applied here by changing out the
NullSubsystem for a
ReportingSubsystem which would log the call and possibly the callstack whenever it is accessed. This would allow you or your library's clients to track down where they are depending on something that has gone out of scope, but without the need to cause a crash.
I mentioned in a comment @Arkadiy that the circular dependency he brought up between
System and
Subsystem is a bit unpleasant. It can easily be remedied by having
System derive from an interface on which
Subsystem depends, an application of Robert C Martin's Dependency Inversion Principle. Better still would be to isolate the functionality that
Subsystems need from their parent, write an interface for that, then hold onto an implementor of that interface in
System and pass it to the
Subsystems, which would hold it via a
shared_ptr. For example, you might have
LoggerInterface, which your
Subsystem uses to write to the log, then you could derive
CoutLogger or
FileLogger from it, and keep an instance of such in
System..
I've got about 2/3 years C++ experience but I've spent most of my career doing Java. I'm about to go for an interview for a C++ programming role and I've been thinking about the best way to brush up my C++ to make sure I don't get caught out by any awkward questions. What would you recommend? was wondering whether a design pattern or idiom exists to automatically register a class type. Or simpler, can I force a method to get called on a class by simply extending a base class?
For example, say I have a base class
Animal and extending classes
Tiger and
Dog, and I have a helper function that prints out all classes that extend
Animal.
So I could have something like:
struct AnimalManager { static std::vector<std::string> names; static void registerAnimal(std::string name) { //if not already registered names.push_back(name); } }; struct Animal { virtual std::string name() = 0; void registerAnimal() { AnimalManager::registerAnimal(name()); } }; struct Tiger : Animal { virtual std::string name() { return "Tiger"; } };
So basically I would do:
Tiger t; t.registerAnimal();
This could be worked into a
static function as well. Is there any pattern (like a curiously recursive template) or something like that that can help me achieve this without explicitly having to call the
registerAnimal method.
I want my
class Animal to be extendible in the future and others might forget to call
register, I'm looking for ways to prevent that besides documenting this (which I will anyway).
PS This is just an example, I'm not actually implementing animals.
This is a typical example where you want to do some sort of bookkeeping when an object is constructed. Item 9 in Scott Meyers "Effective C++" gives an example of this.
Basically you move all the bookkeeping stuff to base class. Derived class explicitly constructs base class and passes the information that is required for Base class construction. For example:
struct Animal { Animal(std::string animal_type) { AnimalManager::registerAnimal(animal_type); }; }; struct Dog : public Animal { Dog() : Animal(animal_type()) {}; private: static std::string animal_type() { return "Dog"; }; };
As I've understand, when overloading operator=, the return value should should be a non-const reference.
A& A::operator=( const A& ) { // check for self-assignment, do assignment return *this; }
It is non-const to allow non-const member functions to be called in cases like:
( a = b ).f();
But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?
It's assumed that copy constructor is implemented correctly.
This is Item 10 of Scott Meyers' excellent book, Effective C++. Returning a reference from
operator= is only a convention, but it's a good one.
This is only a convention; code that doesn't follow it will compile. However, the convention is followed by all the built-in types as well as by all the types in the standard library. Unless you have a good reason for doing things differently, don't.)
This is a very general question. I'm a self taught 'programmer' who programs in C#. A project I would like to work on would be made a whole lot easier (in the grand scheme of things) if I knew C++. How easy is it to move from C# to C++? Any pitfalls I should watch out for? And if I am using VS2010, can I program (not in the same class, but same project) something in both C# and C++?
I came the other way from c++ to c#. In many ways that was a relief. C++ has a lot more rules than c# particularly around memory allocation. The syntax can also be challenging and it is easy to wander off into out of bounds memory. C++ is however much more suitable for system level programming but with great power comes great responsibility.
I recommend first grabbing a copy of Scott Meyer's Effective C++ and read it cover to cover. This is the best resource I know of for getting the basics correct and without question improved the quality of the code I was producing, even as an "experienced" c++ developer. Then grab a unit test framework and take a look at a c++ kata (in this case an xcode project but should still be useful). And get familiar with the Standard Template Library which contains a lot of useful/efficient code/classes for containers, algorithms, etc.
Lastly, best of luck. Learning a new language is always a challenge and can be daunting but the payoff is generally worth it. If nothing else you will see your c# code with new eyes.
For illustrative purposes, let's say I want to implement a generic integer comparing function. I can think of a few approaches for the definition/invocation of the function.
(A) Function Template + functors
template <class Compare> void compare_int (int a, int b, const std::string& msg, Compare cmp_func) { if (cmp_func(a, b)) std::cout << "a is " << msg << " b" << std::endl; else std::cout << "a is not " << msg << " b" << std::endl; } struct MyFunctor_LT { bool operator() (int a, int b) { return a<b; } };
And this would be a couple of calls to this function:
MyFunctor_LT mflt; MyFunctor_GT mfgt; //not necessary to show the implementation compare_int (3, 5, "less than", mflt); compare_int (3, 5, "greater than", mflt);
(B) Function template + lambdas
We would call
compare_int like this:
compare_int (3, 5, "less than", [](int a, int b) {return a<b;}); compare_int (3, 5, "greater than", [](int a, int b) {return a>b;});
(C) Function template + std::function
Same template implementation, invocation:
std::function<bool(int,int)> func_lt = [](int a, int b) {return a<b;}; //or a functor/function std::function<bool(int,int)> func_gt = [](int a, int b) {return a>b;}; compare_int (3, 5, "less than", func_lt); compare_int (3, 5, "greater than", func_gt);
(D) Raw "C-style" pointers
Implementation:
void compare_int (int a, int b, const std::string& msg, bool (*cmp_func) (int a, int b)) { ... } bool lt_func (int a, int b) { return a<b; }
Invocation:
compare_int (10, 5, "less than", lt_func); compare_int (10, 5, "greater than", gt_func);
With those scenarios laid out, we have in each case:
(A) Two template instances (two different parameters) will be compiled and allocated in memory.
(B) I would say also two template instances would be compiled. Each lambda is a different class. Correct me if I'm wrong, please.
(C) Only one template instance would be compiled, since template parameter is always te same:
std::function<bool(int,int)>.
(D) Obviously we only have one instance.
Needless to day, it doesn't make a difference for such a naive example. But when working with dozens (or hundreds) of templates, and numerous functors, the compilation times and memory usage difference can be substantial.
Can we say that in many circumstances (i.e., when using too many functors with the same signature)
std::function (or even function pointers) must be preferred over templates+raw functors/lambdas? Wrapping your functor or lambda with
std::function may be very convenient.
I am aware that
std::function (function pointer too) introduces an overhead. Is it worth it?
EDIT. I did a very simple benchmark using the following macros and a very common standard library function template (std::sort):
#define TEST(X) std::function<bool(int,int)> f##X = [] (int a, int b) {return (a^X)<(b+X);}; \ std::sort (v.begin(), v.end(), f##X); #define TEST2(X) auto f##X = [] (int a, int b) {return (a^X)<(b^X);}; \ std::sort (v.begin(), v.end(), f##X); #define TEST3(X) bool(*f##X)(int, int) = [] (int a, int b) {return (a^X)<(b^X);}; \ std::sort (v.begin(), v.end(), f##X);
Results are the following regarding size of the generated binaries (GCC at -O3):
Even if I showed the numbers, it is a more qualitative than quantitative benchmark. As we were expecting, function templates based on the
std::function parameter or function pointer scale better (in terms of size), as not so many instances are created. I did not measure runtime memory usage though.
As for the performance results (vector size is 1000000 of elements):
It is a notable difference, and we must not neglect the overhead introduced by
std::function (at least if our algorithms consist of millions of iterations).
As others have already pointed out, lambdas and function objects are likely to be inlined, especially if the body of the function is not too long. As a consequence, they are likely to be better in terms of speed and memory usage than the
std::function approach. The compiler can optimize your code more aggressively if the function can be inlined. Shockingly better.
std::function would be my last resort for this reason, among other things.
But when working with dozens (or hundreds) of templates, and numerous functors, the compilation times and memory usage difference can be substantial.
As for the compilation times, I wouldn't worry too much about it as long as you are using simple templates like the one shown. (If you are doing template metaprogramming, yeah, then you can start worrying.)
Now, the memory usage: By the compiler during compilation or by the generated executable at run time? For the former, same holds as for the compilation time. For the latter: Inlined lamdas and function objects are the winners.
Can we say that in many circumstances
std::function(or even function pointers) must be preferred over templates+raw functors/lambdas? I.e. wrapping your functor or lambda with
std::functionmay be very convenient.
I am not quite sure how to answer to that one. I cannot define "many circumstances".
However, one thing I can say for sure is that type erasure is a way to avoid / reduce code bloat due to templates, see Item 44: Factor parameter-independent code out of templates in Effective C++. By the way,
std::function uses type erasure internally. So yes, code bloat is an issue.
I am aware that std::function (function pointer too) introduces an overhead. Is it worth it?
"Want speed? Measure." (Howard Hinnant)
One more thing: function calls through function pointers can be inlined (even across compilation units!). Here is a proof:
#include <cstdio> bool lt_func(int a, int b) { return a<b; } void compare_int(int a, int b, const char* msg, bool (*cmp_func) (int a, int b)) { if (cmp_func(a, b)) printf("a is %s b\n", msg); else printf("a is not %s b\n", msg); } void f() { compare_int (10, 5, "less than", lt_func); }
This is a slightly modified version of your code. I removed all the iostream stuff because it makes the generated assembly cluttered. Here is the assembly of
f():
.LC1: .string "a is not %s b\n" [...] .LC2: .string "less than" [...] f(): .LFB33: .cfi_startproc movl $.LC2, %edx movl $.LC1, %esi movl $1, %edi xorl %eax, %eax jmp __printf_chk .cfi_endproc
Which means, that gcc 4.7.2 inlined
lt_func at
-O3. In fact, the generated assembly code is optimal.
I have also checked: I moved the implementation of
lt_func into a separate source file and enabled link time optimization (
-flto). GCC still happily inlined the call through the function pointer! It is nontrivial and you need a quality compiler to do that.
Just for the record, and that you can actually feel the overhead of the
std::function approach:
This code:
#include <cstdio> #include <functional> template <class Compare> void compare_int(int a, int b, const char* msg, Compare cmp_func) { if (cmp_func(a, b)) printf("a is %s b\n", msg); else printf("a is not %s b\n", msg); } void f() { std::function<bool(int,int)> func_lt = [](int a, int b) {return a<b;}; compare_int (10, 5, "less than", func_lt); }
yields this assembly at
-O3 (approx. 140 lines):
f(): .LFB498: .cfi_startproc .cfi_personality 0x3,__gxx_personality_v0 .cfi_lsda 0x3,.LLSDA498 pushq %rbx .cfi_def_cfa_offset 16 .cfi_offset 3, -16 movl $1, %edi subq $80, %rsp .cfi_def_cfa_offset 96 movq %fs:40, %rax movq %rax, 72(%rsp) xorl %eax, %eax movq std::_Function_handler<bool (int, int), f()::{lambda(int, int)#1}>::_M_invoke(std::_Any_data const&, int, int), 24(%rsp) movq std::_Function_base::_Base_manager<f()::{lambda(int, int)#1}>::_M_manager(std::_Any_data&, std::_Function_base::_Base_manager<f()::{lambda(int, int)#1}> const&, std::_Manager_operation), 16(%rsp) .LEHB0: call operator new(unsigned long) .LEHE0: movq %rax, (%rsp) movq 16(%rsp), %rax movq $0, 48(%rsp) testq %rax, %rax je .L14 movq 24(%rsp), %rdx movq %rax, 48(%rsp) movq %rsp, %rsi leaq 32(%rsp), %rdi movq %rdx, 56(%rsp) movl $2, %edx .LEHB1: call *%rax .LEHE1: cmpq $0, 48(%rsp) je .L14 movl $5, %edx movl $10, %esi leaq 32(%rsp), %rdi .LEHB2: call *56(%rsp) testb %al, %al movl $.LC0, %edx jne .L49 movl $.LC2, %esi movl $1, %edi xorl %eax, %eax call __printf_chk .LEHE2: .L24: movq 48(%rsp), %rax testq %rax, %rax je .L23 leaq 32(%rsp), %rsi movl $3, %edx movq %rsi, %rdi .LEHB3: call *%rax .LEHE3: .L23: movq 16(%rsp), %rax testq %rax, %rax je .L12 movl $3, %edx movq %rsp, %rsi movq %rsp, %rdi .LEHB4: call *%rax .LEHE4: .L12: movq 72(%rsp), %rax xorq %fs:40, %rax jne .L50 addq $80, %rsp .cfi_remember_state .cfi_def_cfa_offset 16 popq %rbx .cfi_def_cfa_offset 8 ret .p2align 4,,10 .p2align 3 .L49: .cfi_restore_state movl $.LC1, %esi movl $1, %edi xorl %eax, %eax .LEHB5: call __printf_chk jmp .L24 .L14: call std::__throw_bad_function_call() .LEHE5: .L32: movq 48(%rsp), %rcx movq %rax, %rbx testq %rcx, %rcx je .L20 leaq 32(%rsp), %rsi movl $3, %edx movq %rsi, %rdi call *%rcx .L20: movq 16(%rsp), %rax testq %rax, %rax je .L29 movl $3, %edx movq %rsp, %rsi movq %rsp, %rdi call *%rax .L29: movq %rbx, %rdi .LEHB6: call _Unwind_Resume .LEHE6: .L50: call __stack_chk_fail .L34: movq 48(%rsp), %rcx movq %rax, %rbx testq %rcx, %rcx je .L20 leaq 32(%rsp), %rsi movl $3, %edx movq %rsi, %rdi call *%rcx jmp .L20 .L31: movq %rax, %rbx jmp .L20 .L33: movq 16(%rsp), %rcx movq %rax, %rbx testq %rcx, %rcx je .L29 movl $3, %edx movq %rsp, %rsi movq %rsp, %rdi call *%rcx jmp .L29 .cfi_endproc
Which approach would you like to choose when it comes to performance?( m_nNumber, nNumber ); } private: int m_nNumber; };
Am I on the right track? Should all private methods be moved to non-member non-friend functions? What should be rules that would tell you otherwise?
Not all private methods should be moved to non-member non-friend function, but those that do not need access to your private data members should be. You should give access to as little function as you can, to encapsulate your classes as mush a possible.
I strongly recommend reading Effective C++ from Scott Meyers which explain why you should do this and when it is appropriate.
Edit : I would like to add that this is less true for private method then for public ones, although still valid. As encapsulation is proportionnal to the amount of code you would break by modifying your method, having a private member-function , even though it does not requires access to data members. That is because modifying that code would break little code and only code that you have control over. wrote a Stack and Queue implementation (Linked List based). There is one stack (
bigStack). For example, I separate
bigStack (example:
stackA and
stackB). I
pop() a node from
bigStack, I
push() in
stackA. In the same way, I
push() in
stackB. I want
bigStack to not change. Therefore I want to clone the
bigStack object. How do I clone objects in C++? Or is there another solution to my problem?
class Stack : public List { public: Stack() {} Stack(const Stack& rhs) {} Stack& operator=(const Stack& rhs) {}; ~Stack() {} int Top() { if (head == NULL) { cout << "Error: The stack is empty." << endl; return -1; } else { return head->nosu; } } void Push(int nosu, string adi, string soyadi, string bolumu) { InsertNode(0, nosu, adi, soyadi, bolumu); } int Pop() { if (head == NULL) { cout << "Error: The stack is empty." << endl; return -1; } else { int val = head->nosu; DeleteNode(val); return val; } } void DisplayStack(void); };
then...
Stack copyStack = veriYapilariDersi; copyStack.DisplayStack();
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
I'm implementing a CORBA like server. Each class has remotely callable methods and a dispatch method with two possible input, a string identifying the method or an integer which would be the index of the method in a table. A mapping of the string to the corresponding integer would be implemented by a map.
The caller would send the string on the first call and get back the integer with the response so that it simply has to send the integer on subsequent calls. It is just a small optimization. The integer may be assigned dynamically on demand by the server object. The server class may be derived from another class with overridden virtual methods.
What could be a simple and general way to define the method binding and the dispatch method ?
Edit: The methods have all the same signature (no overloading). The methods have no parameters and return a boolean. They may be static, virtual or not, overriding a base class method or not. The binding must correctly handle method overriding.
The string is class hierarchy bound. If we have A::foo() identified by the string "A.foo", and a class B inherits A and override the method A::foo(), it will still be identified as "A.foo", but the dispatcher will call A::foo if the server is an A object and B::foo if it is a B object.
Edit (6 apr): In other words, I need to implement my own virtual method table (vftable) with a dynamic dispatch method using a string key to identify the method to call. The vftable should be shared among objects of the same class and behave as expected for polymorphism (inherited method override).
Edit (28 apr): See my own answer below and the edit at the end.
You might like to rephrase the question slightly as static and dynamic binding actually have a specific meaning in C++.
For example, default values for parameters are determined at compile time so if I have a virtual method in a base class that declares default values for its parameters then those values are set at compile time.
Any new default values for these parameters that are declared in a derived class will be ignored at run time with the result being that the default parameter values in the base class will be used, even though you called the member function in the derived class.
The default parameter values are said to be statically bound.
Scott Meyers discusses this in an item in his excellent book "Effective C++".
HTH
It took me a long time to realize how important and subtle having variables that:
1) exist on the stack
2) have their destructors called when they fall out of scope
are.
These two things allow things like:
A) RAII
B) refcounted GC
Interesting enough, (1) & (2) are not available in "lower" languages like C/Assembly; nor in "higher" languages like Ruby/Python/Java (since GC prevents predictable destruction of objects).
I'm curious -- what other techniques do you know of that are very C++ specific, due to language design choices.
Thanks!
Edit: If your answer is "this works in C++ & this other langauge", that's okay too. The things I want to learn about are similar to:
By choosing to not have certain features (like GC), we gain other features (like RAII + predicable destructing of objects). In what areas of C++, by choosing to NOT have features that other "higher level" langauges have, C++ manages to get patterns that those higher level langauges can't express.
There's the pImpl idiom. It work similar to the Bridge pattern.
And the Expression Template, which delays C++'s expression evaluations.
These two works also explore this question: More C++ Idioms and Effective C++ (Scott Meyers, 2005)
As we have so many design patterns in java, like wise do we have any in c++.Or can we use the same sort of patterns in c++.
Design patterns are language agnostic. Language specific patterns are called idioms - these are solutions to recurring problems in a certain language.
For C++ there are good books like Effective C++, that introduce you to the basic ones. The wikibook More C++ idioms is also worth a look. have a good understanding of OO from java and C# and I'm lucky in my engineering courses to have been exposed to the evils of both assembler and C (pointers are my playground :D ).
However, I've tried looking into C++ and the thing that gets me is the library code. There are so many nice examples of how to perform the bread and butter tasks in java and C#, but I've not been able to find a good explanation of how to do these things in C++.
I'd love to expand my knowledge into C++ to add to my skillset but I've not had a chance to be exposed to people and communities that are keen on these things.
Could anyone here recommend some good open source projects or tutorials which are useful. Bonus marks if they involve coming from java or C# into this environment.
Assuming you already have some knowledge of the C++ syntax, and have good Object Oriented experience I'd go for Effective c++ series.
It's a collection of "tips and tricks" explaining how c++ works under the hood. Which are the common misunderstandings from people coming from other languages and why c++ works this way.
I read that destructors need to be defined when we have pointer members and when we define a base class, but I am not sure if I completely understand. One of the things I am not sure about is whether or not defining a default constructor is useless or not, since we are always given a default constructor by default. Also, I am not sure if we need to define default constructor to implement the RAII principle (do we just need to put resource allocation in a constructor and not define any destructor?).
class A { public: ~Account() { delete [] brandname; delete b; //do we need to define it? }; something(){} =0; //virtual function (reason #1: base class) private: char *brandname; //c-style string, which is a pointer member (reason #2: has a pointer member) B* b; //instance of class B, which is a pointer member (reason #2) vector<B*> vec; //what about this? } class B: public A { public something() { cout << "nothing" << endl; } //in all other cases we don't need to define the destructor, nor declare it? }
As @nonsensickle points out, the questions is too broad... so I'm gonna try to tackle it with everything I know...
The first reason to re define the destructor would be in The Rule of Three which is on part the item 6 in Scott Meyers Effective C++ but not entirely. The rule of three says that if you re defined the destructor, copy constructor, or copy assignment operations then that means you should rewrite all three of them. The reason is that if you had to rewrite your own version for one, then the compiler defaults will no longer be valid for the rest.
Another example would be the one pointed out by Scott Meyers in Effective C++
When you try to delete a derived class object through a base class pointer and the base class has a non virtual destructor, the results are undefined.
And then he continues
If a class does not contain any virtual functions, that is often an indication that it is not meant to be used as a base class. When a class is not intended to be used as a base class, making the destructor virtual is usually a bad idea.
His conclusion on destructors for virtual is.
And if it is not a Rule Of three case, then maybe you have a pointer member inside your object, and maybe you allocated memory to it inside your object, then, you need to manage that memory in the destructor, this is item 6 on his.
A developer in a team I'm supervising prefers declaring variables as constants in his tests, e.g.
const int someValue = 1; (rather than just
int someValue = 1;).
When I saw this I found it a bit odd and questioned what he'd done. His argument is that this is sensible for the purposes of this test - because the value he's assigned never changes.
I've always thought of constants as something that should be declared at a class level. However I do see this developer's point of view.
What's your opinion? And, tests aside, would you declare constants in normal methods? If 'yes', why?
From Effective C++ by Scott Meyers (chapter 3):
Use
constwhenever possible.
The wonderful thing about
const.
How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?
The class with the constructor (used in all three examples):
class Foo { public: Foo(int a) { b = a; } private: int b; };
And here are my attempts at calling this constructor:
Foo global_foo(3); // works, but I can't control when the constructor is called. int main() { // ... }
int main() { // Array on stack Foo array_of_foos[30](3); // doesn't work // Array on heap Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work }
There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements.
class Bar { Foo foo(3); // doesn't work }; int main() { Bar bar; }
The Konrad reply is OK, just a puntualization about the arrays.... There is a way to create an array of items(not pointers) and here it follows:
//allocate raw memory for our array void *rawMemory = operator new[](30 * sizeof(Foo)) // point array_of_foos to this memory so we can use it as an array of Foo Foo *array_of_foos = static_cast<Foo *>(rawMemory); // and now we can create the array of objects(NOT pointers to the objects) // using the buffered new operator for (int i = 0; i < 30; i++) new(array_of_foos[i])Foo(3);
This approach is described here:
What is the difference between the index overloaded operator and the insert method call for std::map?
ie:
some_map["x"] = 500;
vs.
some_map.insert(pair<std::string, int>("x", 500));
In addition to the fact that
map::operator[] will replace an existing value is that
operator[] map::will create and add to the map a default existing value to replace before the replacement occurs (the
map::operator[]() call has to return a reference to something). For items that are expensive to create this could be a performance issue.
See "Item 24: Choose carefully between
map::operator[] and
map::insert when efficiency is important" in Scott Meyers' Effective STL.
In an attempt to write a
wrapper type for another type
T, I encountered a rather obnoxious problem: I would like to define some binary operators (such as
+) that forward any operation on
wrapper to the underlying type, but I need these operators accept any of the potential combinations that involve
wrapper:
wrapper() + wrapper() wrapper() + T() T() + wrapper()
The naive approach involves writing all the potential overloads directly.
But I don't like writing duplicated code and wanted a bit more challenge, so I chose to implement it using a very generic template and restrict the potential types with an
enable_if.
My attempt is shown at the bottom of the question (sorry, this is as minimal as I can think of). The problem is that it will run into an infinite recursion error:
test() + test(), the compile looks at all potential overloads.
enable_ifclause, which is supposed to prevent it from being a valid overload, but the compiler just ignores that and tries to compute the
decltypefirst, which requires ...
operator+(test, test).
And we're back where we started. GCC is nice enough to spit an error; Clang just segfaults.
What would be a good, clean solution for this? (Keep in mind that there are also other operators that need to follow the same pattern.)
template<class T> struct wrapper { T t; }; // Checks if the type is instantiated from the wrapper template<class> struct is_wrapper : false_type {}; template<class T> struct is_wrapper<wrapper<T> > : true_type {}; // Returns the underlying object template<class T> const T& base(const T& t) { return t; } template<class T> const T& base(const wrapper<T>& w) { return w.t; } // Operator template<class W, class X> typename enable_if< is_wrapper<W>::value || is_wrapper<X>::value, decltype(base(declval<W>()) + base(declval<X>())) >::type operator+(const W& i, const X& j); // Test case struct test {}; int main() { test() + test(); return 0; }
Here's rather clunky solution that I would rather not use unless I have to:
// Force the evaluation to occur as a 2-step process template<class W, class X, class = void> struct plus_ret; template<class W, class X> struct plus_ret<W, X, typename enable_if< is_wrapper<W>::value || is_wrapper<X>::value>::type> { typedef decltype(base(declval<W>()) + base(declval<X>())) type; }; // Operator template<class W, class X> typename plus_ret<W, X>::type operator+(const W& i, const X& j);
The most straightforward way to write mixed-mode arithmetic is to follow Scott Meyers's Item 24 in Effective C++
template<class T> class wrapper1 { public: wrapper1(T const& t): t_(t) {} // yes, no explicit here friend wrapper1 operator+(wrapper1 const& lhs, wrapper1 const& rhs) { return wrapper1{ lhs.t_ + rhs.t_ }; } std::ostream& print(std::ostream& os) const { return os << t_; } private: T t_; }; template<class T> std::ostream& operator<<(std::ostream& os, wrapper1<T> const& rhs) { return rhs.print(os); }
Note that you would still need to write
operator+= in order to provide a consistent interface ("do as the ints do"). If you also want to avoid that boilerplate, take a look at Boost.Operators
template<class T> class wrapper2 : boost::addable< wrapper2<T> > { public: wrapper2(T const& t): t_(t) {} // operator+ provided by boost::addable wrapper2& operator+=(wrapper2 const& rhs) { t_ += rhs.t_; return *this; } std::ostream& print(std::ostream& os) const { return os << t_; } private: T t_; }; template<class T> std::ostream& operator<<(std::ostream& os, wrapper2<T> const& rhs) { return rhs.print(os); }
In either case, you can then write
int main() { wrapper1<int> v{1}; wrapper1<int> w{2}; std::cout << (v + w) << "\n"; std::cout << (1 + w) << "\n"; std::cout << (v + 2) << "\n"; wrapper2<int> x{1}; wrapper2<int> y{2}; std::cout << (x + y) << "\n"; std::cout << (1 + y) << "\n"; std::cout << (x + 2) << "\n"; }
which will print 3 in all cases. Live example. The Boost approach is very general, e.g. you can derive from
boost::arithmetic to also provide
operator* from your definition of
operator*=.
NOTE: this code relies on implicit conversions of
T to
wrapper<T>. But to quote Scott Meyers:
Classes supporting implicit type conversions are generally a bad idea. Of course, there are exceptions to this rule, and one of the most common is when creating numerical types. learn C++ via some web tutorials. I don't have a compiler available to me, otherwise I would try this out. I'm not sure what is meant by a const pointer. Does that just mean it always points to the same memory address? Why would you ever want to do that? Would the following code be legal?
... int * const aPointer = new int; ... //do something with aPointer delete aPointer; ... //do something else, including possibly more 'new' statements aPointer = new int; ...
G'day,
To remember this easily you can use the trick that Scott Meyers describes in his excellent book "Effective C++" (sanitised Amazon link)
You draw a line through the declaration where the asterisk is located.
BTW That book is excellent, and while not for a beginner, is definitely a way of taking your C++ knowledge to the next level! Highly recommended.
HTH
cheers,
I am very interested in c++ and want to master this language. I have read a lot of books about c++. I want to read some library source code to improve my skill, but when I read the boost library source code, I find it is very difficulty.
Can anyone give me some advice about how to read boost source code and before I can understand it what kind of books about c++ should I read?
If you're starting out in C++, the boost source code is probably not the best place. It's where the wizards hang out and they deal in template magic. I think a better starting point are Scott Myers and Herb Sutters books (in that order).
Some versions of Scott's book can be a bit out dated but they are still strong in the fundamentals. Herb's books are worth reading many many times and are an invaluable tool. Once you've gotten through both of those authors, then would be a good time to tackle the boost source code.
I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.
.\src\Scene\SceneAnimationData.cpp(23) : error C2662: 'SceneTrackerData::getRect' : cannot convert 'this' pointer from 'const SceneTrackerData' to 'SceneTrackerData &'
#include "SceneTrackerData.h" void SceneAnimationData::SetupData(const SceneTrackerData &initialData) { // getRect(), points() and links() all return const pointers CloneRect(initialData.getRect()); ClonePoints(initialData.points()->values()); CloneLinks(initialData.links()->values()); } void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect) { if (initialRect != NULL) { QPointF position = initialRect->scenePos(); QRectF rect = initialRect->rect(); initialRect = new QGraphicsRectItem(rect); initialRect->setPos(position); } } void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links) { links_ = new QList<QGraphicsLineItem*>(*links); } void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points) { points_ = new QList<QGraphicsEllipseItem*>(*points); }
I'm not sure as I am no expert C++ programmer, but are your functions getRect() and so on declared const? If not but you know the way you use them is const, you can still use a const_cast to remove the const from your initialData reference.
See for example here:
Or Scott Meyers excellent C++-Books Effective C++ and More Effective C++. At least one of them has an item about constness.
I port a middle-sized application from C to C++. It doesn't deal anywhere with exceptions, and that shouldn't change.
My (wrong!) understanding of C++ was (until I learned it the hard way yesterday) that the (default) new operator returns a NULL pointer in case of an allocation problem. However, that was only true until 1993 (or so). Nowadays, it throws a std::bad_alloc exception.
Is it possible to return to the old behavior without rewriting everything to using std::nothrow on every single call?
Sorry, but as for my opinion you should NOT do this and return to old new behavior. This is because you simply can't avoid exceptions anyway.
WHY?
Consider about new call which should allocate class with constructor calling some initialization code which needs to construct anything temporary which is dynamic. Alas, you are going to have exception. No matter if you use std::nothrow. This is only one scenario among number of them.
In Scott Meyers book Effective C++ it was discussed in details as far as I remember. But I'm not sure if all the cases are reviewed (but I suggest enough of them).
I saw what looks like an inconsistency in the std::lower_bound() and std::upper_bound() syntaxes (well, type-conversion, really) and was wondering if anyone could elucidate please? Per the comments, line 2 will not compile despite its obvious similarity to line 1; you need to use the form shown on line 3 (on gcc 4.7.3 / ubuntu 64-bit at least - that's all I've got to play with)
#include <set> #include <algorithm> using namespace std; class MyInt { private: int val; public: MyInt(int _val): val(_val) {} bool operator<(const MyInt& other) const {return val < other.val;} }; int main() { set<MyInt> s; s.insert(1); // demonstrate implicit conversion works s.insert(MyInt(2)); s.insert(3); // one last one for the road set<MyInt>::iterator itL = lower_bound(s.begin(), s.end(), 2); //LINE 1 // the line below will NOT compile set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), 2); //LINE 2 // the line below WILL compile set<MyInt>::iterator itU2 = upper_bound(s.begin(), s.end(), MyInt(2)); // LINE 3 return 0; }
I don't think it's a bug. If you look at the (possible) implementation of
std::upper_bound, the comparison is done like
if (!(value < *it)) { ... } // upper_bound, implicit conversion `MyInt`->`int` doesn't work
And because
operator< is a member function of
MyInt (and not of
int, which is not a class type), the code doesn't compile, since there is no conversion from
MyInt to
int. On the other hand, in
std::lower_bound,
*it appears on the lhs of the comparison, and
value (of type
int) can be implicitly converted to
MyInt when passed to
MyInt::operator<.
if (*it < value) { ... } // lower_bound, implicit conversion `int`->`MyInt` works
This is the reason why it's better to implement comparison operators as non-members, so you don't have this asymmetry. This is also mentioned in Scott Meyers' Effective C++ book: Item 24: Declare non-member functions when type conversions should apply to all parameters.
Quick and dirty fix: define an . (EDIT: doesn't really work, ambiguity). What works is removing the need for implicit conversion
MyInt::operator int(){return val;} for implicit conversion
MyInt to
int
set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), MyInt(2));
instead.
I spent over 2 hours finding this memory leak:
class Parent{ ... } class Child:public Parent{ std::string str; ... } int main(){ Parent *ptr=new Child(); delete ptr; }
I fixed it by moving the string into the parent class. Why did this memory leak happen? Shouldn't the child's members be deleted as well?
This can happen because
Parent may not have a virtual destructor. Since you are creating a
Parent* (the base class) to a dynamically allocated derived class
Child, deleting the
Parent* which has no virtual destructor will cause undefined behaviour, but typically will result in the derived class not being destroyed.
From Scott Myers - Effective C++ Third Edition:
....
class Parent{ }; class Child:public Parent{ public: Child() : str("Child") {} ~Child() { std::cout << str << std::endl;}; std::string str; }; int main(){ Parent *ptr=new Child(); delete ptr; // undefined behaviour: deleting a Base* to a Derived object where the Base has no virtual destructor }
Parent's destructor
virtual:
class Parent{ public: virtual ~Parent() {} // Will call derived classes destructors now as well }; class Child:public Parent{ public: Child() : str("Child") {} ~Child() { std::cout << str << std::endl;}; std::string str; }; int main(){ Parent *ptr=new Child(); delete ptr; // Child::~Child() has now been called. }
See When to use virtual destructors? which probably explains it better than I did
Edit: Thank you to the @aschepler (in the question's comments), commenters below, and the answer to the linked question, I have updated the answer to better reflect that this is undefined behaviour. In my haste I didn't mention it, and only mentioned the typical behaviour++
Our project uses a macro to make logging easy and simple in one-line statements, like so:
DEBUG_LOG(TRACE_LOG_LEVEL, "The X value = " << x << ", pointer = " << *x);
The macro translates the 2nd parameter into stringstream arguments, and sends it off to a regular C++ logger. This works great in practice, as it makes multi-parameter logging statements very concise. However, Scott Meyers has said, in Effective C++ 3rd Edition, "You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using a template for an inline function" (Item 2). I know there are many issues with macro usage in C++ related to predictable behavior, so I'm trying to eliminate as many macros as possible in our code base.
My logging macro is defined similar to:
#define DEBUG_LOG(aLogLevel, aWhat) { \ if (isEnabled(aLogLevel)) { \ std::stringstream outStr; \ outStr<< __FILE__ << "(" << __LINE__ << ") [" << getpid() << "] : " << aWhat; \ logger::log(aLogLevel, outStr.str()); \ }
I've tried several times to rewrite this into something that doesn't use macros, including:
inline void DEBUG_LOG(LogLevel aLogLevel, const std::stringstream& aWhat) { ... }
And...
template<typename WhatT> inline void DEBUG_LOG(LogLevel aLogLevel, WhatT aWhat) { ... }
To no avail (neither of the above 2 rewrites will compile against our logging code in the 1st example). Any other ideas? Can this be done? Or is it best to just leave it as a macro?
Logging remains one of the few places were you can't completely do away with macros, as you need call-site information (
__LINE__,
__FILE__, ...) that isn't available otherwise. See also this question.
You can, however, move the logging logic into a seperate function (or object) and provide just the call-site information through a macro. You don't even need a template function for this.
#define DEBUG_LOG(Level, What) \ isEnabled(Level) && scoped_logger(Level, __FILE__, __LINE__).stream() << What
With this, the usage remains the same, which might be a good idea so you don't have to change a load of code. With the
&&, you get the same short-curcuit behaviour as you do with your
if clause.
Now, the
scoped_logger will be a RAII object that will actually log what it gets when it's destroyed, aka in the destructor.
struct scoped_logger { scoped_logger(LogLevel level, char const* file, unsigned line) : _level(level) { _ss << file << "(" << line << ") [" << getpid() << "] : "; } std::stringstream& stream(){ return _ss; } ~scoped_logger(){ logger::log(_level, _ss.str()); } private: std::stringstream _ss; LogLevel _level; };
Exposing the underlying
std::stringstream object saves us the trouble of having to write our own
operator<< overloads (which would be silly). The need to actually expose it through a function is important; if the
scoped_logger object is a temporary (an rvalue), so is the
std::stringstream member and only member overloads of
operator<< will be found if we don't somehow transform it to an lvalue (reference). You can read more about this problem here (note that this problem has been fixed in C++11 with rvalue stream inserters). This "transformation" is done by calling a member function that simply returns a normal reference to the stream.
Small live example on Ideone....
I am trying to implement factory pattern by registering the function pointers of the derived class to the factory in a static map(member of the factory)and creating objects by looking up the map. But I am getting a segmentation fault in doing this.
Code Snippet:
factory.cpp
typedef Shape* (*Funcptr)(); std::map<int,Funcptr> Factory::funcmap; int Factory::registerCreator(int ShapeID, Shape *(*CFuncptr)()) { Factory::funcmap[ShapeID] = CFuncptr; return 1; } Shape* Factory::CreateObject(int ShapeID) { std::map<int,Funcptr>::iterator iter; iter = funcmap.find(ShapeID); if(iter != funcmap.end()){ return iter->second(); } return NULL; }
factory.h
class Factory { public: Factory(); virtual ~Factory(); static int registerCreator(int, Shape *(*CFuncptr)()); Shape* CreateObject(int); private: static std::map<int,Funcptr> funcmap; };
Square.cpp
static Shape *SquareCreator() { return new Square; } static int SquareAutoRegHook = Factory::registerCreator(1,SquareCreator);
On creating the object for Factory in the main file a segmentation fault occurs. Can you please suggest if I am doing something wrong. I am using CppUTest for TDD and not sure how to debug this.
There is no guarantee about the order of creation of static objects that are defined in different translations uints* so you have a 50/50 shot as to which would happen first, the initializtion of
Factory::funcmap or
Factory::registerCreator(1,SquareCreator) and Undefined Behavior Russian Roulette is not a good game to play.
A common approach to deal with this, and one that described in Item 4 of the third edition of Scott Meyer's Effective C++ is to use local static objects instead of global static objects. In this case it means changing
Factory to look like this:
class Factory { public: Factory(); virtual ~Factory(); static int registerCreator(int, Shape *(*CFuncptr)()); Shape* CreateObject(int); private: static std::map<int,Funcptr> & GetFactoryMap() { static std::map<int,Funcptr> funcmap; return funcmap; } };
and changing
Factory::registerCreator to this:
int Factory::registerCreator(int ShapeID, Shape *(*CFuncptr)()) { GetFactoryMap()[ShapeID] = CFuncptr; return 1; }
This way funcmap will be initialized the first time registerCreator is called and will never be used uninitialized.
*Or, roughly speaking, different .cpp files if you are not familar with the term translation unit
I just don't get it. Tried on VC++ 2008 and G++ 4.3.2
#include <map> class A : public std::multimap<int, bool> { public: size_type erase(int k, bool v) { return erase(k); // <- this fails; had to change to __super::erase(k) } }; int main() { A a; a.erase(0, false); a.erase(0); // <- fails. can't find base class' function?! return 0; }
Others have answered how to resolve the syntax problem and why it can be dangerous to derive from standard classes, but it's also worth pointing out:
Prefer composition to inheritance.
I doubt you mean for 'A' to explicitly have the "is-a" relationship to multimap< int, bool >. C++ Coding Standards by Sutter/Alexandrescu has entire chapter on this (#34), and Google points to many good references on the subject.
It appears there is a SO thread on the topic as well.
For those that use Effective C++ as a C++ programming reference, this issue is covered in Item 33 (Avoid hiding inherited names.) in the book.
Possible Duplicate:
The Definitive C++ Book Guide and List
I was developing for quite long time already on C/C++ (mostly C, which makes style poorer). So, I know how to use it. However, quite often I stuck with style decisions like: - should I return error code here, throw exceptions, return error through a parameter - should I have all this stuff in constructor or should I create separate init function for that. and so on.
Any solutions WILL work. However, each of them has cons and pros, which I know and most importantly which I don't know.
It would be very nice to read something regarding overall C++ development style, coding practices and so forth. What do you recommend?
I've been recommended this by many people and I have a copy. Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)
I am a student, and new to c++. I am searching for a standard c++ api that is as comprehensive as the java api. I have been using cplusplus.com, and cppreference.com. Please any help would be greatly appreciated.
C++ has a standard library.
You can try The C++ Standard Library: Tutorial and Reference. While I don't own it myself, it's on our book list (which I recommend you check out), so it shouldn't be bad.
Note C++ isn't Java, so the libraries don't necessarily have the same functionality. Another resource you'll want to look at is Boost, which serves as a source for well-written C++ libraries for things the standard library lacks.
If you mean the c++ standard library I'd look at. It covers the current standards. After familiarizing yourself with that, you could try looking at boost.
There are a number of changes in the upcoming c++0x standard. Wikipedia has info on a number of these as does SO.
The number one book, IMO, for c++ is Effective C++ by Scott Meyers.
I am trying to develop abstract design pattern code for one of my project as below.. But, I am not able to compile the code ..giving some compile errors(like "unresolved external symbol "public: virtual void __thiscall Xsecs::draw_lines(double,double)" (?draw_lines@Xsecs@@UAEXNN@Z)" ).. Can any one please help me out in this...
#include "stdafx.h" #include <iostream> #include <vector> #include "Xsecs.h" using namespace std; //Product class class Xsecs { public: virtual void draw_lines(double pt1, double pt2); virtual void draw_curves(double pt1, double rad); }; class polyline: public Xsecs { public: virtual void draw_lines(double pt1,double pt2) { cout<<"draw_line in polygon"<<endl; } virtual void draw_curves(double pt1, double rad) { cout<<"Draw_curve in circle"<<endl; } /*void create_polygons() { cout<<"create_polygon_thru_draw_lines"<<endl; }*/ }; class circle: public Xsecs { public: virtual void draw_lines(double pt1,double pt2) { cout<<"draw_line in polygon"<<endl; } virtual void draw_curves(double pt1, double rad) { cout<<"Draw_curve in circle"<<endl; } /*void create_circles() { cout<<"Create circle"<<endl; }*/ }; //Factory class class Factory { public: virtual polyline* create_polyline()=0; virtual circle* create_circle()=0; }; class Factory1: public Factory { public: polyline* create_polyline() { return new polyline(); } circle* create_circle() { return new circle(); } }; class Factory2: public Factory { public: circle* create_circle() { return new circle(); } polyline* create_polyline() { return new polyline(); } }; int _tmain(int argc, _TCHAR* argv[]) { Factory1 f1; Factory * fp=&f1; return 0; }
You should inherit publicly from
A, like
class ProductA1 : public ProductA { ...
Without the
public keyword, this relationship is private inheritance, which is not an is-a relationship, therefore you can't simply cast from
ProductA1 to
ProductA.
Scott Meyers explains this in Effective C++, Third Ed., Item 39:
[...] compilers, when given a hierarchy in which a class
Studentpublicly inherits from a class
Person, implicitly convert Students to Persons when that is necessary for a function call to succeed.
[...] the first rule governing private inheritance you've just seen in action: in contrast to public inheritance, compilers will generally not convert a derived class object (such as
Student) into a base class object (such as
Person) if the inheritance relationship between the classes is private. [...] The second rule is that members inherited from a private base class become private members of the derived class, even if they were protected or public in the base class.
Private inheritance means is-implemented-in-terms-of. If you make a class
Dprivately inherit from a class
B, you do so because you are interested in taking advantage of some of the features available in class
B, not because there is any conceptual relationship between objects of types
Band
D. As such, private inheritance is purely an implementation technique.
Update for the 2nd version of the post: if you want pure virtual functions, you should declare them so:
virtual void draw_lines(double pt1, double pt2) = 0; virtual void draw_curves(double pt1, double rad) = 0;
Otherwise the linker will miss their definition.
I'm wondering if you can overload an operator and use it without changing the object's original values.
Edited code example:
class Rational{ public: Rational(double n, double d):numerator_(n), denominator_(d){}; Rational(){}; // default constructor double numerator() const { return numerator_; } // accessor double denominator() const { return denominator_; } // accessor private: double numerator_; double denominator_; }; const Rational operator+(const Rational& a, const Rational& b) { Rational tmp; tmp.denominator_ = (a.denominator() * b.denominator()); tmp.numerator_ = (a.numerator() * b.denominator()); tmp.numerator_ += (b.numerator() * a.denominator()); return tmp; }
I made the accessors const methods, but I'm still getting a privacy error for every tmp.denominator_ / numerator_.
Since your class already provides accessors to the numerator and denominator, and it has a public constructor, there is no need to use any
friends. You can overload
operator+ as follows:
const Rational operator+(const Rational& rhs, const Rational& lhs) { double newNumerator = rhs.numerator() * lhs.denominator() + rhs.denominator() * lhs.numerator(); return Rational(newNumerator, rhs.denominator() * lhs.denominator()); }
In response to some of the other answers:
Everything about this question is exactly answered by
Item 24 of Effective C++ (Third Edition). In this item, Scott Meyers shows that, in cases dealing with numerical types where you want to support implicit conversion in an intuitive manner, it is best to use a non-member non-friend function.
Say your
Rational class had the following constructor:
Rational::Rational(double numerator = 0, double denominator = 1);
In this case, if
operator+ were a member function, trying to do mixed mode arithmetic would work only half the time:
Rational oneHalf(1, 2); oneHalf + 2; // works 2 + oneHalf; // error!
In the second example,
operator+ for integers is called. The way to fix this is to make
operator+ for
Rationals a non-member function as shown above.
If you have access to Effective C++, you should also check out
Item 23: Prefer non-member non-friend functions to member functions.
I'm writing this question with reference to this one which I wrote yesterday. After a little documentation, it seems clear to me that what I wanted to do (and what I believed to be possible) is nearly impossible if not impossible at all. There are several ways to implement it, and since I'm not an experienced programmer, I ask you which choice would you take. I explain again my problem, but now I have some solutions to explore.
What I need
I have a Matrix class, and I want to implement multiplication between matrices so that the class usage is very intuitive:
Matrix a(5,2); a(4,1) = 6 ; a(3,1) = 9.4 ; ... // And so on ... Matrix b(2,9); b(0,2) = 3; ... // And so on ... // After a while Matrix i = a * b;
What I had yesterday
At the moment I overloaded the two operators
operator* and
operator= and until yesterday night the were defined in this way:
Matrix& operator*(Matrix& m); Matrix& operator=(Matrix& m);
The operator* instantiates a new Matrix object (
Matrix return = new Matrix(...)) on the heap, set the values and then just:
return *result;
What I have today
After the discussion I decided to implement it in a "different way" to avoid the user to be bothered bother by pointers of any type and to keep the usage unchanged. The "different way" is to pass the returning value of operator* by value:
Matrix operator*(Matrix& m); Matrix& operator=(Matrix& m);
The operator* instantiates
return on the stack, set the values and then return the object.
There is a problem with this approach: it doesn't work. The operator= expects a Matrix& and operator* returns a Matrix. Moreover this approach doesn't look so good to me for another reason: I'm dealing with matrices, that can be very large and the aims of this library were to be 1) good enough for my project 2) fast, so probably passing by value should not be an option.
Which solutions I have explored
Well, following the suggestions in the previous discussion I read some stuff about smart pointers, they look great but I can't still figure out how to solve my problem with them. They deal with memory freeing and pointer copying, but I'm basicly using references, so they don't look the right choice for me. But I may be wrong.
Maybe the only solution is to pass by value, maybe I can't get both efficiency and a good interface. But again, you're the expert, and I would like to know your opinion.
You should really read Effective C++ by Scott Meyers, it has great topics on that.
As already said, the best signatures for
operator= and
operator* are
Matrix& operator=(Matrix const& m); Matrix operator*(Matrix const& m) const;
but I have to say you should implement multiplication code in
Matrix& operator*=(Matrix const& m);
and just reuse it in
operator*
Matrix operator*(Matrix const &m) const { return Matrix(*this) *= m; }
that way user could multiply without creating new matrices when she wants to. Of course for this code to work you also should have copy constructor :)).
right now i am learning C++, and now I know the basic concept of template, which act just like a generic type, and i found almost every c++ program used template, So i really want to know when are we supposed to use template ? Can someone conclude your experience for me about c++ template ? When will you consider to use template ?
Supplement: if we defined such function
template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b); }
but we want to pass a object(self-defined class) for comparison, how can we implement ?
Supplement2: in the answer below, someone have wrote this sample code
template <class myType> const myType& GetMax (const myType& a, const myType& b) { return (a<b?b:a); } template <class myType, class Compare> const myType& GetMax (const myType& a, const myType& b, Compare compare) { return (compare(a,b)?b:a); }
is this correct ? can we just pass a function name as a parameter of class myType ?
G'day,
Simple answer is when you want the behaviour to remain the same independent of the type being used to instantiate the class.
So a stack of ints will behave in the same way as a stack of floats will behave as a stack of MyClass objects.
Inheritance and base classes are used when you want to allow specialisation of the behaviour.
So say you have a base class called Animal and it has a member function called makeSound(). You have no idea which sound every animal will make so you make the makeSound member function a virtual function. In fact, because there is no default sound for all animals you have no idea what to have as default behaviour so you would declare this member function as a pure virtual function.
This then tells anyone making an instance of a derived class, for example a Lion class, that they must provide an implementation the makeSound member function which will provide a roar in some way.
Edit: I forgot to add that this is one of the articles in Scott Meyers's excellent book "Effective C++" (sanitised Amazon link) which I highly recommend.
HTH
cheers,
When implementing reference counting in objects the "release and possibly delete object" primitive is usually implemented like this:
void CObject::Release() { --referenceCount; if( referenceCount == 0 ) { delete this; } }
First of all,
delete this looks scary. But since the member function returns immediately and doesn't try to access any member variables the stuff still works allright. At least that's how it is explained usually. The member function might even call some global function to write to a log that it deleted the object.
Does the C++ standard guarantee that a member function can call
delete this and then do anything that will not require access to member variables and calling member functions and this will be defined normal behaviour?
This problem has a number on implications, covered best in Item 27 (10 pages) of Scott Meyers book:
More Effective C++: 35 New Ways to Improve Your Programs and Designs
If you dont have this book, buy it as well as its predecessor
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
They are no "how to" Programming learning books, but rather give clear and straight (and explained) advice what to do and what not to do.
EDIT:
Very briefly the item covers:
Paragraphs are titled:
One of the Problems is, that you must not delete a object thats created on the stack (local objects created not using
new) - this is a illegal case and will lead to a crash. But there are more implications about this items.
I can only repeat myself: Every C++ Programmer should know these books. They won't cost you too much time.
The following code block appears in Scott Meyers' famous book "Effective C++" Item 3:
class TextBlock { public: ... const char& operator[](std::size_t position) const { ... // do bounds checking ... // log access data ... // verify data integrity return text[position]; } char& operator[](std::size_t position) { ... // do bounds checking ... // log access data ... // verify data integrity return text[position]; } ... private: std::string text; };
The author states that in the above implementation, the contents of the
const and the non-
const overloads are essentially the same. In order to avoid code duplication, it could be simplified like this:
class TextBlock { public: ... const char& operator[](std::size_t position) const // the same as before { ... ... ... return text[position]; } char& operator[](std::size_t position) // now just calls const op[] { return // cast away const on const_cast<char&>( // op[]'s return type; static_cast<const TextBlock&>(*this) // add const to *this's type; [position] // call const version of op[] ); } ... private: std::string text; };
My questions are:
When shall we need an overload for
const T& and another for
T&&? (Here,
T may be a template parameter or a class type, so
T&& may or may not mean a universal reference) I can see that in the standard library, many classes provide both overloads. Examples are constructors of
std::pair and
std::tuple, there are tons of overloads. (Okay, I know that among the functions, one of them is the copy constructor and one of them is the move constructor.)
Is there a similar trick to share the implementations for the
const T& and
T&& overloads? I mean, if the
const T&& overload returns an object that is copy-constructed, and the
T&& overload returns something that is move-constructed, after sharing the implementation, this property must still hold. (Just like the above trick:
const returns
const and non-
const returns non-
const, both before and after implementation sharing)
Thanks!
The two overloads I'm referring to should look like:
Gadget f(Widget const& w); Gadget f(Widget&& w);
It is nothing related to returning by rvalue references, that is:
Widget&& g(/* ... */);
(By the way, that question was addressed in my previous post)
In
f() above, if
Gadget is both copy-constructible and move-constructible, there's no way (except from reading the implementation) to tell whether the return value is copy-constructed or move-constructed. It is nothing to deal with Return Value Optimization (RVO) / Named Return Value Optimization (NRVO). (See my previous post)
When is it a good time to return by rvalue references?
I have a lot of experience with Java/OO. There are tons of C++ tutorials/references out there, but I was wondering if there are a few key ones that a Java programmer might find useful when making the transition.
I will be moving from server-side J2EE to Windows Visual C++ desktop programming.
I have googled and found tons of resources, but am overwhelmed and don't know where to best spend my time. I have only a few days to get a good start.
Is Visual Studio Express / Microsoft Visual C++ the best IDE for me to start with?
Also, any words of wisdom from others who know and work with both languages?
Visual C++ is a good way to go, you can get the express version for free from here
As far as books It really depends what you want to do. I like the Horton book as far as learning Visual C++, GUI, CLR and Database programming. The Lippman book is a very good tutorial on C++, but it only covers the basic language, which is large.
Once you get past the basics then look at the Meyers books, as stated in other answers.
Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)
There are a couple of others from this author, they are real good but have not been updated in a long time.
A real good online C++ FAQ is here.
If you put a comment stating what you plan to do with C++, we could give you narrower guidance to point you in the direction you want to go in
The widely recommended books here are Scott Meyers Effective series. "Effective C++", "More Effective C++" and "Effective STL".
I would also recommend the C++ FAQ Lite and The C++ Programming Language.
I have been developing using c# now since the first release of .NET. I have never really spent time on C or C++ and thought it would be a good idea to get a little more awareness. Does anyone have any recommendations for sites that would provide a good learning/tutorial for someone that has c# experience to venture into C++ a little?
Thanks
Warning: C++ is not C and the following is related only with C++.
If you are already a c# developer I think you should work in three different directions:
1) copy semantic, memory management and const keyword, these are the main differences between c# and c++. Make yourself familiar with copy constructor, destructor and assignment operator. Learn how to use RAII idiom. Study the differences between passing a variable by: value, reference and pointer.
I will suggest Effective C++ also guru of the week it is a great source.
In More Effective C++ there is a nice chapter on the difference between pointer and reference.
2) you need to make yourself familiar with the standard library, in my opinion this is a really good book
3) the standard library is great but not enough, you will soon need boost.
I am reading this book at the moment
I haven't finished it yet, but it looks good so far.
Keep practise, you are going to love coding in c++.
I'm going to create a class to hold a long list of parameters that will be passed to a function. Let's use this shorter example:
class ParamList{ public: ParamList(string& a_string); string& getString(); //returns my_string private: string& my_string; }
My question is this: my_string is private, yet I'm returning the reference to it. Isn't that called something like private pointer leaking in C++? Is this not good programming practice? I want callers of getString to be able to get the reference and also modify it.
Please let me know.
Thanks, jbu
edit1: callers will use getString() and modify the string that was returned.
Returing a private reference is perfectly okay so long as:
A. That is a
const reference, and you have documented when that reference can be invalidated or
B. That reference is intended to be modified (i.e.
std::vector<T>::operator[])
While there are useful cases for returning a non-const reference you should usually avoid it. This is covered in Scott Meyers' Effective C++ (3rd Edition, Item 28): Avoid returning "handles" to object internals, if you'd like to take a look.
In brief, my question is about member variables as pointers in unmanaged C++.
In java or c#, we have "advanced pointer". In fact, we can't aware the "pointer" in them. We usually initialize the member of a class like this:
member = new Member();
or
member = null;
But in c++, it becomes more confusing. I have seen many styles: using
new, or leave the member variable in stack.
In my point of view, using
boost::shared_ptr seems friendly, but in boost itself source code there are
news everywhere. It's the matter of efficiency,isn't it?
Is there a guildline like "try your best to avoid
new" or something?
EDIT
I realize it's not proper to say "leave them in stack", here's a more proper way to say: when i need an
object to be my member variable, should i prefer a
object than a
object*?
The guide to the language by Stroustrup:
Scott Meyers's triple are quite useful: Effective C++, More Effective C++, and Effective STL.
Also see these questions:
-
- Java FAQ equivalent of C++ FAQ lite?
- C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
- What C++ pitfalls should I avoid?
- New to C++. Question about constant pointers
Is there any good list of techniques + descriptions for C++ newbies. I was thinking of a list describing RAII, RVO, Lvalues... This would be for newbies that don't currently understand those techniques or come from other languages where those are not applicable.
Something short & sweet would be preferred :-)
Yes, they're in two very great books authored by the same person.
Effective C++
More Effective C++
Since I'm still learning c++ (and with still I mean since 5 years :-) ) I thought, what better way to learn the hidden details than asking for it.
So, I'm not looking for the question with the most votes, but I would like to know, if you have ever read an article here, you think every intermediate c++ programmer should read to gain a bettter understanding of the craft.
I cant suggest you an article but I can advice you two amazing books by Scott Meyers ( I hope they help you). I never seen anything better.
More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
Since the book Effective C++ seems to be still worth reading and the best to start with from the Effective C++ series, I wonder which suggested solutions/implementations I need not understand in detail/memorize because there are better solutions in C++11 or later. So:
Which Effective C++ Items can be implemented much simpler or better via C++11 or later? How can they be implemented now, and in which way is it better?
Details:
Since there are many C++ idioms deprecated in C++11, I guess this also influences the solutions in the Effective C++ book. For example, looking at its table of contents, I guess (since I have not yet read the book) that
=delete
make_shared(and C++14's
make_unique)
Correct? Any more? How are these Items implemented in modern C++?
This question is from a C# guy asking the C++ people. (I know a fair bit of C but only have some general knowledge of C++).
Allot of C++ developers that come to C# say they miss const correctness, which seems rather strange to me. In .Net in order to disallow changing of things you need to create immutable objects or objects with read only properties/fields, or to pass copies of objects (by default structs are copied).
Is C++ const correctness, a mechanism to create immutable/readonly objects, or is there more to it? If the purpose is to create immutable/readonly objects, the same thing can be done in an environment like .Net.
Excellent Scott Meyer's book Effective C++ has dedicated an item to this issue:
ITEM 3: Use const whenever possible.
It really enlightens you :-)
What makes smartpointers better than normal pointers?
Fewer memory leaks. Maybe Scott Meyers can make it clearer for you:
Possible Duplicate: What is the difference between const int*, const int * const, and int const *?
What is the difference between the following?
char const *p; const char *p; char *const p;
And is there a good site where I can relearn C and C++? It seems that I forgot it and job interviews are doing me an hard time...
As an added bonus, read Effective STL to use the STL properly.
Possible Duplicate:
C++ blogs that you regularly follow?
where can we find some good c++ programming articles by experts programmers. I want to read their experience, pitfalls, do's n donts etc.
Get and read Scott Meyers' Effective C++ and More Effective C++. Quickly!
so what is difference between local and global static variable?
When we have to use local static variable and global static variable?
Other answers have told you the differences between a local static object (local to a function) and a non-local static object (static objects declared global or in a namespace); however, you should also understand the importance of using one over the other.
The information I use here comes from Effective C++ Third Edition by Scott Myers (a recommended and excellent read)
A static object is one that exists from the time it's constructed until the end of the program.
As others have mentioned, a non-local static object is constructed before
main whereas a local static object is constructed the first time the function is called.
But what if you had two static objects and one relied on the other. How could you be sure that one would be constructed before the other? You can't: The relative order of initialisation of non-local static objects defined in different translation units is undefined
Scott Myers definition of a translation unit (from aforementioned book):
A translation unit is the source code giving rise to a single object file. It's basically a single source file, plus all of the #include files.
So imagine you have these two non-local static objects in separate source files, you couldn't guarantee one would be constructed before the other. This is where a local static object prevails!
Consider Scott Myers' example of a
FileSystem class and a
Directory class, where the
Directory relies on the
FileSystem:
class FileSystem { public: size_t numDisks() const; }; extern FileSystem tfs;
and
class Directory { public: Directory() { size_t disks = tfs.numDisks(); ... } };
If
Directory gets constructed before
FileSystem, then you are going to be using an uninitialised class! Fortunately, you can get around this by using local static objects!
class FileSystem { public: size_t numDisks() const; }; FileSystem& tfs() { static FileSystem fs; return fs; }
Now when
Directory is constructed, even if it's constructed before
FileSystem is,
FileSystem is guaranteed to be constructed before it's used!
Could you let me know about books that explains the ideas of smart pointer very clearly (beginner, intermediate and advanced level)?
Thank you.
Scott Meyers has an a few items on it. You might not need a whole book.
Scott Meyers books : a fairly capable Ruby scripter/programmer, but have been feeling pressure to branch out into C++. I haven't been able to find any sites along the lines of "C++ for Ruby Programmers". This site exists for Python (which is quite similar, I know). Does anyone know of a guide that can help me translate my Ruby 'thoughts' into C++?
If you want to learn C++, start here. Once you have learned the fundamentals, you should also look into these: Effective C++, More Effective C++, Effective STL, and Exceptional C++
I am trying to wrap my head around something I've been wondering for quite some time now.
Assume I have a class
Base
class Base { public: virtual ~Base(){} virtual bool operator== ( const Base & rhs ) const; };
Now, another class inherits from it. It has two equality operators:
class A : public Base { public: bool operator== ( const A & rhs ) const; bool operator== ( const Base & rhs ) const; private: int index__; };
And yet another class which also inherits from Base, and which also has two equality operators:
class B : public Base { public: bool operator== ( const B & rhs ) const; bool operator== ( const Base & rhs ) const; private: int index__; };
This is what I understand (which is not necessarily correct). I can use the first operator only to check if same class objects are equal. Yet, I can use the second operator to check if they are the same type of class, and then if they are equal. Now, yet another class exists, which wraps around pointers of Base, which are however, polymorphic types A, or B.
class Z { public: bool operator== ( const Z & rhs ) const; private: std::shared_ptr<Base> ptr__; };
First things first, I've found out, that I can't have two operator== overloaded. I get no errors from the compiler, but when I try to run it, it just hangs. I am guessing it has something to do with rtti, which is beyond me.
What I have been using, and is quite ugly, is attempting to downcast, and if I can, then try to compare instances, within class Z:
bool Z::operator== ( const Z & rhs ) const { if ( const auto a1 = std::dynamic_pointer_cast<A>( this->ptr__ ) ) if ( const auto a2 = std::dynamic_pointer_cast<A>( rhs.ptr__ ) ) return *a1 == *a2; else if ( const auto b1 = std::dynamic_pointer_cast<B>( this->ptr__ ) ) if ( const auto b2 = std::dynamic_pointer_cast<B>( rhs.ptr__ ) ) return *b1 == *b2; return false; }
This is quite ugly, and it assumes that your class A and B, have an equality operator which takes as parameter the same type class.
So I tried to come up with a way, which would use the second type of operator, more agnostic, more elegant if you will. And failed. This would require to use it in both classes A and B, thus moving it away from class Z.
bool A::operator== ( const Base & rhs ) const { return ( typeid( *this ) == typeid( rhs ) ) && ( *this == rhs ); }
Same for class B. This doesn't seem to work (app hangs without any errors). Furthermore, it uses some kind of default operator, or does it use the base class operator? Ideally, it should use both the Base::operator== and compare class types.
If however, I want a more elaborate comparison, based upon a member of class A, or B, such as
index__ then I obviously have to friend each class, because when I try this, it won't compile (unless of course I add a getter or make it somehow visible):
bool A::operator== ( const Base & rhs ) const { return ( typeid( *this ) == typeid( rhs ) ) && (*this == *rhs ) && (this->index__ == rhs.index__ ); }
Is there an elegant, simple solution to this? Am I confined to downcasting and trying, or is there some other way to achieve what I want?
In general, in a hierarchy, one should have a common interface, and imo the
operator== should be only implemented in the
Base class using (virtual) getters from the interface. Otherwise it's like re-defining functions (without using
virtual) down the hierarchy, which is almost always a bad idea. So you may want to think about your design, having more than one
operator== seems fishy.
Very simple example:
#include <iostream> class A { int _x; public: A(int x):_x(x){} virtual int getx() const { return _x; } // runtime bool operator==(const A& other){return getx() == other.getx();} // one implementation }; class B: public A { using A::A; int getx() const override // Make all B's equal, runtime { return 0; // so always 0, all B's are equal } }; int main() { A a1(10), a2(20); B b1(10), b2(20); std::cout << std::boolalpha << (a1==a2) << std::endl; // false std::cout << std::boolalpha << (b1==b2) << std::endl; // always true }
This pattern is usually called the non-virtual interface idiom and is a manifestation of the so called template method (has nothing to do with templates, just an unfortunate name), in which you have clients (along the hierarchy) call virtual functions indirectly through public non-virtual member functions. Item 55 of Scott Meyers' Effective C++ has an excellent discussion about this issue.
I have a pointer which is pointing to an integer variable. Then I assign this pointer to a reference variable. Now when I change my pointer to point some other integer variable, the value of the reference variable doesn't change. Can anyone explain why?
int rats = 101; int * pt = &rats; int & rodents = *pt; // outputs cout << "rats = " << rats; // 101 cout << ", *pt = " << *pt; // 101 cout << ", rodents = " << rodents << endl; // 101 cout << "rats address = " << &rats; // 0027f940 cout << ", rodents address = " << &rodents << endl; // 0027f940 int bunnies = 50; pt = &bunnies; cout << "bunnies = " << bunnies; // 50 cout << ", rats = " << rats; // 101 cout << ", *pt = " << *pt; // 50 cout << ", rodents = " << rodents << endl; // 101 cout << "bunnies address = " << &bunnies; // 0027f91c cout << ", rodents address = " << &rodents << endl; // 0027f940
We assigned pt to bunnies, but the value of rodents is still 101. Please explain why.
The line
int & rodents = *pt;
is creating a reference to what
pt is pointing to (i.e.
rats). It's not a reference to the pointer
pt.
Later, when you assign
pt to point to
bunnies, you would not expect the
rodents reference to change.
EDIT: To illustrate @Als point, consider the following code:
int value1 = 10; int value2 = 20; int& reference = value1; cout << reference << endl; // Prints 10 reference = value2; // Doesn't do what you might think cout << reference << endl; // Prints 20 cout << value1 << endl; // Also prints 20
The second
reference assignment does not change the reference ltself. Instead, it applies the assignment operator (
=) to the thing referred to, which is
value1.
reference will always refer to
value1 and cannot be changed.
It's a little tricky to get your head around at first, so I recommend you take a look at Scott Meyer's excellent books Effective C++ and More Effective C++. He explains all this much better than I can.
I'm learning C++ from "C++ for Programmers" book. In "templates" section, there is a code like that:
template<typename T> void printArray(const T * const array, int size) { for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; }
My question is, the constants of first parameter in function. I have never seen two constants in one parameter. I tried to realize but I could not. Thanks for helps.
In your example, you have a
const pointer to a
const object of type
T. This means you can't change where the pointer is pointing or the object to which it points.
You can actually have const in even more places in a single line. Take this declaration for example:
class MyClass { public: const std::string& get_name(const int * const id) const; };
In this case, the function
get_name is constant, and can't modify the instance of
MyClass. It takes in a constant pointer to a constant integer, and returns a constant reference to a string.
If you'd like to learn more about best practices while using
const (and other parts of C++), I highly recommend Bruce Eckel's book Effective C++: 55 Specific Ways to Improve Your Programs and Designs.
Item 25 in Effective c++ third edition, Scott Meyers suggests to implement swap in the same namespace as the class, and then when swapping to employ the using std::swap, and there the author says :
For example, if you were to write the call to swap this way:
std::swap(obj1,obj2); // the wrong way to call swap
you'd force the compiler to consider only the swap in std, thus eliminating the possibility of getting a more appropriate T-specific version defined elsewhere. Alas, some misguided programmers do qualify calls to swap in this way, and that is why it's important to totally specialize std::swap for your classes.
The author recommends to always swap objects this way :
#include <iostream> #include <utility> #define CUSTOM_SWAP namespace aaa{ struct A { }; #ifdef CUSTOM_SWAP void swap( A&, A& ) { std::cout<<"not std::swap"<<std::endl; } #endif } int main() { using std::swap; // add std::swap to a list of possible resolutions aaa::A a1; aaa::A a2; swap(a1,a2); }
Why isn't
std::swap in global namespace? That way, it would be simpler to add custom swap functions.
Probably because the standard says so, 17.6.1.1/2:
All library entities except macros, operator new and operator delete are defined within the namespace std or namespaces nested within namespace std.
And you would still need to put
using ::swap sometimes, so it would introduce even more special cases. Here I use
func instead of
swap - :
#include <iostream> using namespace std; template <class T> auto func(T) -> void { cout << "::f" << endl; } namespace my_ns { struct my_struct {}; auto func(my_struct) -> void { cout << "my_ns::func" << endl; } auto another_func() -> void { // won't compile without `using ::func;` func(123); } } auto main() -> int {}
fails with
prog.cpp: In function ‘void my_ns::another_func()’: prog.cpp:21:17: error: could not convert ‘123’ from ‘int’ to ‘my_ns::my_struct’ func(123);
The code is as follows:
template <int __inst> void* __malloc_alloc_template<__inst>::_S_oom_malloc(size_t __n) { void (* __my_malloc_handler)(); void* __result; for (;;) { __my_malloc_handler = __malloc_alloc_oom_handler; if (0 == __my_malloc_handler) { __THROW_BAD_ALLOC; } (*__my_malloc_handler)(); __result = malloc(__n); if (__result) return(__result); } }
I have two questions. 1. why does _S_oom_malloc use infinite loop? 2. as we known, _S_oom_malloc will be called when malloc fails in __malloc_alloc_template::allocate function. And why does it use malloc to allocate space?
Anyone can help me? Thanks a lot.
First, the loop is not truly infinite. There are two exits: by throwing a
BAD_ALLOC exception an by allocating the requested amount of memory. The exception will be thrown when the current new-handler is a null pointer.
To understand how that can happen, consult e.g. Item 49 from Effective C++. Essentially any new-handler can either
set_new_handler
abortor
exit
Second, the reason that it uses the C library's
malloc to allocate space is that
malloc on most systems is a well-tested and efficiently implemented function. The Standard Library's
new functions are "simply" exception-safe and type-safe wrappers around it (which you as a user can also override, should you want that).
This is the base class:
template <class T> class DataLogger { // ... public: void AddData(T Data); // ... }
And this is the derived class:
#include "DataLogger.h" #include <utility> class Plotter : public DataLogger<std::pair<long double, long double>> { // ... public: void AddData(long double x, long double y); // ... } // This method is supposed to wrap the original AddData() method // which was defined in the base class void Plotter::AddData(long double x, long double y) { AddData(std::make_pair(x, y)); // LINE #29 }
The given error is:
LINE 29: IntelliSense: no suitable conversion function from "std::pair" to "long double" exists
LINE 29: IntelliSense: too few arguments in function call
Apparently, the problem is that I can not access to the method in base class from derived class, even though it is defined public.
How do I make this code work?
(My IDE is Visual Studio 2010.)
Your
AddData in derived class hides the function
AddData in the base class, so all you need to do is, unhide the latter using
using directive:
class Plotter : public DataLogger<std::pair<long double, long double>> { public: //unhiding : bringing base class function into scope! using DataLogger<std::pair<long double, long double>>::AddData; };
Read Item 33: Avoid hiding inherited names from Effective C++ by Scott Meyers.
This should be a simple 100-level question, but I'm seeing something I don't expect in my project, and web searches have failed me, so I thought I'd ask here. Suppose I have the following C++ code:
class BaseClass { public: BaseClass() { this->Initialize(); } int foo() { return this->foo_; } protected: virtual int GetInitialValue() { return 1; } private: void Initialize() { this->foo_ = this->GetInitialValue(); } int foo_; }; class DerivedClass : public BaseClass { public: DerivedClass() : BaseClass() { } protected: virtual int GetInitialValue() { return 2; } };
What should be the return value of
DerivedClass::foo()? Will
BaseClass::GetInitialValue() ever get called, or will it always be
DerivedClass::GetInitialValue() that gets called? Where should I have searched, and what search terms should I have used to find the answer?
GetInitialValue() isn't virtual so there isn't dynamic dispatch anyway.
In your situation, the expected value of
foo() would be
1, as the value of
_foo is set in the
BaseClass constructor. The derived class's version isn't called as the
BaseClass constructor is called first, and the
DerivedClass members haven't been initialized yet.
This is also item #9 in Effective C++, and that snippet is in this page from artima:
The summary from that article is:
Things to Remember
Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor
#include <iostream> class Base { public: Base() { this->initialize(); } void initialize() { this->_foo = this->getInitial(); } virtual int getInitial() { return 1; } int _foo; }; class Derived : public Base { public: Derived() : Base() {} virtual int getInitial() { return 2;} }; int main() { Base* dp = new Derived(); std::cout << dp->_foo << std::endl; }
This code outputs
1.
What I want to do is that I have a list
std::list<Displayable> display_queue
Displayable being defined in
Displayable.h as:
class Displayable { public: int x, y; Displayable() : x(0), y(0) {} Displayable(int x, int y) : x(x), y(y) {} };
and
DifferentDisplayable as:
class DifferentDisplayable : public Displayable { public: std::string id; DifferentDisplayable() : Displayable(), id("") {} DifferentDisplayable(int x, int y) : Displayable(x, y), id("") {} DifferentDisplayable(int x, int y, std::string id) : Displayable(x, y), id(id) {} };
The items added to the list is:
Displayable disp_one; DifferentDisplayable disp_two(10, 10, "the id"); display_queue.push_back(disp); display_queue.push_back(disp_two);
Since
DifferentDisplayable is derived from
Displayable it is able to be stored in the list but what I can't figure out is how can I or can I even access
std::string id in
DifferentDisplayable when iterating through the list (display_queue) like so:
for (std::list<Displayable>::iterator i = display_queue.begin(); i != display_queue.end(); i++) { // insert code here }
Thanks in advance for any answers
If 'id' isn't needed for all derived classes, then instead of trying to access it directly from your loop, add a base class method that uses it. For example:
class Displayable { public: virtual void Display(); ... };
(Even better would be to make 'class Displayable' an abstract base class, with Display() as a pure virtual function. See the links below.)
Then the implementations can vary independently:
void Displayable::Display() { // Do something here with 'x' and 'y' } void DifferentDisplayable::Display() { // Do something here with 'x', 'y', and 'id' }
Then allocate your objects on the heap to avoid the slicing problem:
Displayable* disp_one = new Displayable(); DifferentDisplayable* disp_two = new DifferentDisplayable(10, 10, "the id"); display_queue.push_back(disp); display_queue.push_back(disp_two);
Then your loop becomes:
for (std::list<Displayable>::iterator i = display_queue.begin(); i != display_queue.end(); ++i) { (*i)->Display(); }
Remember to 'delete' the pointers when you're done with them.
This strategy is discussed in the Open-Closed Principle and in Item 34 "Differentiate between inheritance of interface and inheritance of implementation" in Effective C++ 3rd Edition by Scott Meyers.
I am new to Stack Overflow, and new to programming. I am learning how to program in C++.
My question is not related to specific code, but is about research and learning the language. What I have learned so far relates to narrow examples of syntax and simple programs which use variables, functions, arrays, etc.
I am wondering if people have or can link to example programs so I can study them.
I'm looking for console programs which:
and is basically a useful program.
Through Google, I have mostly only been able to find C++ tutorial pages (cplusplus, cprogramming, etc) which deal with each of the above separately, usually in a bare-bones way to show the syntax. I'm looking for something more complex (but not overly so) so I can learn how to combine these things in a meaningful way with the intent of eventually writing programs of my own at the same level.
I've already coded a calculator (though not one that has all of these features; namely it was missing file i/o and I was able to make a basic one which didn't need objects), so I'm looking for something different. I understand console programs are text based and lend themselves well to these kind of programs, so it can be a calculator of another type, as long as it isn't a basic arithmetic one.
cplusplus.com has a few examples.
As @GMan said, you'd be better off reading a book.
Possibly Effective C++ by Scott Meyers, or maybe one in the
Beginner\Introductory section.
The best way to improve is to give yourself a task and code it. Use different techniques/paradigms (OOP, modular, etc). Instead of studying programs, try to create them yourself - you'll learn a lot better this way.
The book can guide you, but you must make the journey.
Here are some exercises. You can try solving puzzles, too. CodeGolf.SE is good if you want to have some fun.
I have a huge C++ solution.
When I change one class and compile In some cases compilation (and linkage) takes little time (less than a second) But in some cases it takes ages (more that 30 seconds)
I do not understand why this happens. The huge difference in performance suggests that something can be done in order to maximize the number of times the compiler is fast.
Any ideas?
Say you have a class
A and you add a new data member to it in the header file. Then
A has to be recompiled. If
B contains
A as a member then
B has to be recompiled as well. If
C has a member
B then
C also has to be recompiled and so on. A change in
A can have a domino effect. A seemingly tiny change (adding a new data member to a class) can result in recompiling the entire project.
On the other hand, if you make substantial changes to implementation of a member function of
A in the implementation source file (
*.cpp) then, chances are, only
A has to be recompiled but nothing else. This is likely to be very fast.
If you wish to understand what triggers the domino effect and what doesn't, I suggest you read Item 31: Minimize compilation dependecies between files in Effective C++ and Items 26-30 on Minimizing Compile-time Dependencies in Exceptional C++.
There is no magic setting of the compiler that will make the compilation fast. Only your understanding and careful coding can help.
I have a vector of structs declared in a class. My question is do I have to explicitly free the memory allocated by the vector in the class destructor or is that done automatically when I destroy the instance. As in, do I have to include code in the class destructor to free the memory of the vector.
If you are allocating the structs yourself using
new then you need to deallocate them using
delete when you are finished with them.
std::vector won't do that for you.
Item 13 in the book Effective C++ (highly recommended) says to use objects to manage resources. This helps you avoid problems like having to worry about your resource de-allocation code not getting called because, for example, an exception was thrown. If you are using C++11 you can look into shared_ptr or just create your own resource management class.
Update: As jogojapan pointed out, std::auto_ptr is unsuitable for STL containers.
I'm interested in improving my understanding of how to avoid writing a C++ class that causes problems when copied.
In particular, I've written a class named
Policy that I intend to copy. I have not defined a non-default destructor, copy constructor, or copy assignment operator. The only operator I've overloaded is the following:
friend bool operator== (const Policy& p1, const Policy& p2) { for(int i=0; i<p1.x.size(); i++) { if(p1.x[i] != p2.x[i]) return false; } return true; }
The class's members are either standard data types such as
int,
double,
bool,
std::string,
std::vector<double>,
std::vector<int>,
std::vector<string>, or one of a few small (and thus not overly complex) classes I defined that are definitely copyable without any problem. Now, there is a member of
Policy that is an instance of the
NRRan class, which is a class I built as a wrapper around a non-copyable third-party data type;
NRRan is as follows:
class NRRan { public: double doub() { return stream->doub(); } int intInterval(const int& LB, const int& UB) { return LB+int64()%(UB-LB+1); } void setNewSeed(const long& seed) { delete stream; stream = new Ranq1(seed); } NRRan() { stream = new Ranq1(12345); } ~NRRan() { delete stream; } NRRan(const NRRan& nrran) { stream = new Ranq1(12345); *stream = *(nrran.stream); } NRRan& operator= (const NRRan& nrran) { if(this == &nrran) return *this; delete stream; stream = new Ranq1(12345); *stream = *(nrran.stream); return *this; } private: Ranq1* stream; // underlying C-struct Ullong int64() { return stream->int64(); } };
But the whole point of the
NRRan class is to make
Ranq1 copyable. So, given the
Policy class as I've described it (sorry, I am unable to post a large part of the code), is there any thing that might cause a problem when I copy
Policy? My expectation is that copying will create a perfect value-for-value copy.
A more general way of asking my question is the following: Generally speaking, what types of things can possibly cause problems when copying a class? Is there anything in addition to the "Rule of Three" (or "Rule of Five") to be concerned about when making a class copyable?
You should take a look at the book "Effective C++", especially Chapter 2.
Chapter 2: Constructors, Destructors, and Assignment Operators
In Chapter 9 of Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers, it has a section entitled Item 53: Pay Attention to compiler warnings. Meyers says that the following program should give a warning:
class B { public: virtual void f() const; }; class D: public B { public: virtual void f(); };
And says:
The idea is for
D::fto redefine the virtual function
B::f, but there’s a mistake: in B, f is a const member function, but in D it’s not declared const. One compiler I know says this about that:
warning: D::f() hides virtual B::f()
Too many inexperienced programmers respond to this message by saying to themselves, "Of course
D::fhides
B::f— that’s what it’s supposed to do!" Wrong. This compiler is trying to tell you that the f declared in B has not been redeclared in D; instead, it’s been hidden entirely (see Item 33 for a description of why this is so). Ignoring this compiler warning will almost certainly lead to erroneous program behavior, followed by a lot of debugging to discover something this compiler detected in the first place.
But my compiler doesn't give any warning, even with with
-Wall. Why doesn't my compiler (GCC) give a warning?
I've studied C++ as a college course. And I have been working on it for last three years. So I kinda have a fairly good idea what is it about. But I believe to know a language is quite different from using it to full potential. My current job doesn't allow me to explore much.
I have seen you guys suggest studying a open source project and perhaps contributing to one too. So my question is, can you suggest one(of both?) to start with that is simple and doesn't overwhelm a starter.
I was in the same situation 12 years ago when I got my first programming job out of college. I didn't do any open source but I managed to gain a lot of practical and advanced C++ knowledge by reading books (the dead tree kind).
In particular, there was an excellent series by Scott Meyers which I feel helped the most in turning me from newbie to professional:
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library
The topics in these books range from beginner to advanced. It took me about 2 years working in C++ to understand every chapter in these books, so don't be disheartened if it goes over your head at some point... just try reading it again later :)
I want to know more about the casting (like static cast, dynamic cast, const cast and reinterpret cast) and when do we REALLY need that (real life scenario)? Any references/links/books will be appreciated.
Thanks.
Chapter 5 of Scott Meyers' Effective C++ Third Edition has a discussion about casting in C++.
Say I have a class
Foo that has a member function which returns a non-const reference, that itself runs a member function that uses a const
this pointer:
class Foo{ public: Foo& display(std::ostream& os) { do_display(os); return *this; } private: void do_display(std::ostream& os) const { os << contents; } std::string contents; }
When
display runs
do_display, the
this pointer gets implicitly converted to a pointer to const. Why is it, then, that when
do_display terminates,
display is still able to change the object it was called on? As far as I know, it's not possible to assign a pointer to const to a pointer to non-const normally. Any insight is appreciated.
In C++
const access is often only a compile-time attribute [1] that is introduced to ease the control of the object's state. [2]
The method
do_display() does not change anything of
this but it restricts the access to read-only in its scope. After the call of the
do_display() method returned, the access is read-write as before in the scope of the
display() method.
[1] that's the reason for the option to cast const away, which can be considered safe if the constness is only a declarative one.
[2] see Item #3 in Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition): Scott Meyers or for example Const Correctness - C++ Tutorials - Cprogramming.com
While trying to formulate a C macro to ease the writing of non-const member functions calling const member functions with exact same logic (see Chapter 1, Item 3, "Avoiding Duplication in const and Non-const Member Functions" in Effective C++), I believe I came across a
decltype() bug in VS2013 Update 1.
I wanted to use
decltype(*this) to build a
static_cast<decltype(*this) const&>(*this) expression in the aforementioned macro to avoid having the macro call site pass any explicit type information. However, that latter expression doesn't appear to properly add const in some cases in VS2013.
Here's a small block of code I was able to make repo the bug:
#include <stdio.h> template<typename DatumT> struct DynamicArray { DatumT* elements; unsigned element_size; int count; inline const DatumT* operator [](int index) const { if (index < 0 || index >= count) return nullptr; return &elements[index]; } inline DatumT* operator [](int index) { #if defined(MAKE_THIS_CODE_WORK) DynamicArray const& _this = static_cast<decltype(*this) const&>(*this); return const_cast<DatumT*>(_this[index]); #else // warning C4717: 'DynamicArray<int>::operator[]' : recursive on all control paths, function will cause runtime stack overflow return const_cast<DatumT*>( static_cast<decltype(*this) const>(*this) [index] ); #endif } }; int _tmain(int argc, _TCHAR* argv[]) { DynamicArray<int> array = { new int[5], sizeof(int), 5 }; printf_s("%d", *array[0]); delete array.elements; return 0; }
(may the first one to blab about not using std::vector be smitten)
You can either compile the above code and see the warning yourself, or refer to my lone comment to see what VC++ would spew at you. You can then ! the
defined(MAKE_THIS_CODE_WORK) expression to have VC++ compile the code as how I'm excepting the
#else code to work.
I don't have my trusty clang setup on this machine, but I was able to use GCC Explorer to see if clang complains (click to see/compile code). Which it doesn't. However, g++ 4.8 will give you an
‘const’ qualifiers cannot be applied to ‘DynamicArray&’ error message using that same code. So perhaps g++ also has a bug?
Referring to the decltype and auto standards paper (albeit, it's almost 11 years old), the very bottom of page 6 says that
decltype(*this) in a non-const member function should be
T&, so I'm pretty sure this should be legal...
So am I wrong in trying to use decltype() on *this plus adding const to it? Or is this a bug in VS2013? And apparently g++ 4.8, but in a different manner.
edit: Thanks to Ben Voigt's response I was able to figure out how to craft a standalone C macro for what I'm desire to do.
// Cast [this] to a 'const this&' so that a const member function can be invoked // [ret_type] is the return type of the member function. Usually there's a const return type, so we need to cast it to non-const too. // [...] the code that represents the member function (or operator) call #define CAST_THIS_NONCONST_MEMBER_FUNC(ret_type, ...) \ const_cast<ret_type>( \ static_cast< \ std::add_reference< \ std::add_const< \ std::remove_reference< \ decltype(*this) \ >::type \ >::type \ >::type \ >(*this) \ __VA_ARGS__ \ ) // We can now implement that operator[] like so: return CAST_THIS_NONCONST_MEMBER_FUNC(DatumT*, [index]);
The original desire was to hide this all in a macro, which is why I wasn't wanting to worry about creating typedefs or
this aliases. It is still curious that clang in GCC Explorer didn't output a warning...though the output assembly does appear fishy.
You said yourself,
decltype (*this) is
T&.
decltype (*this) const & tries to form a reference to a reference (
T& const &).
decltype triggers the reference collapsing rule 8.3.2p6. But it doesn't collapse the way you'd like.
You could say
decltype(this) const&, but that would be
T* const& -- a reference to a const pointer, not a pointer to a const object. For the same reason,
decltype (*this) const and
const decltype (*this) don't form
const T&, but
(T&) const. And top-level
const on a reference is useless, since references already forbid rebinding.
Perhaps you are looking for something more like
const typename remove_reference<decltype(*this)>::type &
But note that you don't need the cast at all when adding
const. Instead of
DynamicArray const& _this = static_cast<decltype(*this) const&>(*this);
just say
DynamicArray const& _this = *this;
These combine to
const typename std::remove_reference<decltype(*this)>::type & this_ = *this;
Still, this is a stupid amount of code for a very simple and pervasive problem. Just say:
const auto& this_ = *this;
FYI here's the text of the reference collapsing rule:
If a typedef-name (7.1.3, 14.1) or a decltype-specifier (7.1.6.2) denotes a type
TRthat is a reference to a type
T, an attempt to create the type "lvalue reference to cv
TR" creates the type "lvalue reference to
T", while an attempt to create the type "rvalue reference to cv
TR" creates the type
TR.
decltype(*this) is our decltype-specifier which denotes
TR, which is
DynamicArray<DatumT>&. Here,
T is
DynamicArray<DatumT>. The attempt
TR const& is the first case, attempt to create lvalue reference to (const)
TR, and therefore the final result is
T&, not
const T&. The cv-qualification is outside the innermost reference.
I'm starting C++ programming in my first job. I'm a CS student and I have learn programming in Java. What advice would you tell me to watch out so I don't cause trouble in my new job?
Would you have any advice or references would be appreciated.
(example: I know C++ is more likely to have memory problem than Java)
Thank you very much!
Two things:
I'm using c++ and i'm in a really deeply nested set of functions and a special case has occurred and I would like to exit to the top level.
Now I hear c++ exceptions are deprecated now so what should I use instead in this case?
So what i'm really asking is, are
setjmp() and
longjmp() OK in c++ code?
If possible I would avoid using
setjmp/longjmp, as most C stuff, in C++ code. For what concerns C++ exceptions, as far as I know, they are not deprecated. Indeed, I think it would be very hard to deprecate such a pervasive feature without severely hindering backwards compatibility. It's possible that you have heard that (some form of) exception specifications,
a feature of the recent C++11 standard that was not present in the previous version of the language, has been deprecated during the approval process (see, e.g., this post on Herb Sutter's blog).
This said, exceptions in C++ are not easy to use well. C++ has lots of features, and sometimes they interplay in very complex ways. Some necessary (but not sufficient) advices are:
std::exception;
But the best advice is: understand exactly how exceptions work - precanned advices do not work well. At the purpose, you might read this, this, this and this about how to use exceptions and RAII. Especially "More Effective C++" has a whole chapter dedicated to exceptions, exposing some intricate consequences of apparently simple snippets of code. It raises your overall awareness of the language.
Should I always add
public keyword when inheriting a class? When doing this code:
class Derived : public Base { }
I think this the right thing to do in 99% cases. Right?
It depends on what model you are looking for.
From Scott Myers - Effective C++ Third Edition (a recommended read, btw):
publicinheritance means "is-a". If you write that class
D("Derived") publicly inherits from
class B("Base"), you are telling C++ compilers (as well as human readers of your code) that every object of type
Dis also an object of type
B, but not vice versa
And
privateinheritance means "is-implemented-in-terms-of"
I have been learning programing, mainly JavaScript and C++, but all the programs I have been writing are simple and in note pad like applications.
What would I need to make a simple calculator that takes user input and dose calculations with it.
What would I use to get the GUI on the screen, how would I compile it, and what IDE should I use.
Develop deep understanding of c++ concepts. Study more and good books including it's standard. Start with normal applications & go towards advanced programming. for GUI, try
QT - it's good of go for MFC Application. Write Code yourself and work on different projects, alogirithms. For book suggestion, i suggest you getting Scott Mayers Effective c++
For Compiler, i suggest using Visual Studio on widnows - it's awesome IDE.
.netallocatorargcarticleassignment-operatorbase-classbindingboostcc#c++c++-faqc++11c++14castingclasscoding-stylecompilationconstconst-correctnessconstantsconstructorcopy-constructordata-structuresdecltypedeprecatedderived-classdesigndesign-patternsdesktop-applicationdestructoreffective-c++equalityexceptionfunctionfunctorgarbage-collectiongccgcc-warninghashmapidiomaticidiomsimplicit-conversioninheritanceiteratorjavajavascriptlambdalanguage-agnosticlinkerlistlogiclower-boundmacrosmainmapmemory-leaksmemory-managementmethod-overloadingmethodsnamespacesnoncopyableobject-lifetimeoopoperator-overloadingpass-by-rvalue-referencepointerspolymorphismprogramming-languagesqueueraiirefactoringreferenceresourcesreturnrubyrvaluervalue-referencescopesfinaesgishared-ptrsmart-pointersstackstaticstatic-membersstlstringswaptemplate-meta-programmingtemplatesthistr1traitsupperboundvariablesvectorvisual-c++visual-studiovisual-studio-2008visual-studio-2013 | http://www.dev-books.com/book/book?isbn=0321334876&name=Effective-C%2B%2B | CC-MAIN-2019-09 | refinedweb | 23,706 | 60.95 |
User talk:Thelonesoldier
Leave a message after the beep.
**combine soldier death tone**
Contents
Why are you deleting compile errors?
How else are we going to know what's wrong on compile time, if not through checking the wiki? I'm desputing all of those tags. (So far I've found two.) --MossyBucket (formerly Andreasen) 16:57, 19 February 2011 (UTC)
- Also, I think I recall that inserting delete tags needs to be major edits, so if you've inserted them as minor edits, they might not register. --MossyBucket (formerly Andreasen) 17:30, 19 February 2011 (UTC)
- The ones I marked for deletion were generally useless articles, "you did something wrong" or "I don't know what causes this problem". If you want to make them useful instead of deleting them, that's fine, I said that in one of my edit summaries. My profile defaults to haviing the minor edit checkbox checked, and if I insert a template with an external link the captcha won't function if I uncheck the checkbox. Thelonesoldier 00:00, 20 February 2011 (UTC)
Changes to the templates are causing some issues
For example: —Unsigned comment added by ThaiGrocer (talk • contribs). Please use four tildes (
~~~~) to sign your username.
- Ah, what a stupid problem. Thanks for pointing it out, I'm fixing the issues now. Thelonesoldier 21:57, 1 March 2011 (UTC)
Template categories
Special:AllPages can be filtered by namespace you know... --TomEdwards 22:43, 1 March 2011 (UTC)
- It appears Jeff Lane created the actual template category for some reason, probably because it's more intuitive to search for - I dunno. I added the link to view all the templates within that category. --MossyBucket (formerly Andreasen) 03:13, 14 March 2011 (UTC)
Template documentation
If you got Template:Documentation/end box2 and Template:Documentation/start box2 to work somehow, could you provide a documentation for them? If they don't work, you should mark them for deletion instead. --MossyBucket (formerly Andreasen) 03:13, 14 March 2011 (UTC)
- Done. Thelonesoldier 03:34, 14 March 2011 (UTC)
Award!
Thelonesoldier 01:43, 20 March 2011 (UTC)
Reverting song reference
Hi, could you please explain your motivation reverting the link I added to Dr. Wallace Breen. Thanks --Phaeilo 16:27, 9 April 2011 (UTC)
- As your first contribution to the wiki that edit may look like advertising to some. Also if we were going to start adding links to music videos that have a reference to any game of valve to the wiki it will become a mess. I would assume you could get away with creating a new article for the sole purpose of mentioning valve references in songs, seen as there are other articles here that don't exactly have anything to do with development. --Biohazard 17:00, 9 April 2011 (UTC)
- Thank you for clearing that up. --Phaeilo 17:07, 9 April 2011 (UTC)
- Exactly as Biohazard has stated (thanks!). I guess I wouldn't be opposed to a new article with a comprehensive list. I've always been curious what Valve's stance on using audio samples from their games in music is; I doubt we'll ever get an official answer. Thelonesoldier 11:35, 10 April 2011 (UTC) | https://developer.valvesoftware.com/w/index.php?title=User_talk:Thelonesoldier&%3Bdiff=prev&%3Boldid=146442&printable=yes | CC-MAIN-2019-26 | refinedweb | 537 | 62.38 |
TLDR; Learning to hack JavaScript will develop the skill of automating using the browser dev tools console.
For the last 6 months or so, I have, on and off, been learning to code JavaScript. That process has mainly involved:
- writing some simple games
- hacking other games to see how they were written
To do all of that now, JavaScript and the Browser Dev tools are perfect companions.
Learn How to Hack GamesI watched Philip Hödtke's talk from JS Unconf 2016 yesterday "Hacking Games and Why You Should Do It." and added a few new techniques into my ‘cheating/hacking’ repertoire.
I encourage you to watch Philip’s talk.
After watching Philip at work I realised:
- I haven’t been using the find functionality in the source part of the browser dev tools
- I had an over-reliance on adding breakpoints and don’t need to
- I had not been using
setIntervalfrom the console
But I test things, why should I care?Well:
- imagine that instead of having to use an automated tool to put the application into a certain state, or having to manually click around a do a lot of work.
- imagine that you could just write a few lines of code into the browser console and automate there.
- imagine that you could write a single line of code that would execute every second and ‘do stuff’ like click on a link, or close a dialog, or <insert something in here that you regularly have to do when you use an app>.
Back to Cookie ClickerAnd I did quite well.
I used a slightly different approach than Philip used and found that
forloops worked better for me than
setIntervalwhen manipulating as I explored, in this game.
Go beyond the for loopI went off to find games where
setIntervalwas a better fit for me.
- First The World’s Biggest Pac-man where
setIntervalwas a great way to provide infinite lives, restoring a new life each time one was lost.
I had a few false starts with other games that looked promising but which either:
- had such obfuscated code I could make no headway
- contained game crashing bugs
Automating ZType from the consoleAnd then I went back to that old favourite zty.pe.
I’ve played zty.pe before. I really like it.
I suspect I might end up playing z-type quite a lot just to improve my typing you understand.— Alan Richardson (@eviltester) July 21, 2016
- I periodically still play “Typing of the Dead” on the Dreamcast. Yup. I have a Dreamcast with a keyboard.
- I periodically still play “R-type” - primarily from “R-Types” on the Playstation One (Yup, I still have a PS1)
If you can’t trigger keyboard events, how could you play ZType?Yes, I know what you’re thinking.
“But if I encountered the ‘how do I trigger keyboard events’ stumbling block, how do I automate zty.pe, which is all about keyboard events.”Well, zty.pe is pretty well designed. It's almost as though it was built to be tested and automated.
- rather than add the ‘shoot’ functionality in the keyboard event hook, so that the only way to trigger it, is by issuing a keyboard event.
- the keyboard event calls a method, so the method can be called outside the keyboard event
Human vs BotI only managed to reach level 15, but my automated ‘bot’ reached level 93. You can see the results of my automating here on youtube.
I’m not going to explain exactly what I did since that would ruin the fun. And the video doesn’t show you how either.
Unfortunately, and you can see this in the video. The bot is highly inefficient. The bzzzz noise from the bot is when it is firing, but missing. And it misses a lot, given its 1% efficiency rating. So I'll investigate how to make it more efficient as a training exercise for myself later.
Tips on Hacking JavaScript GamesBut I’ll give some additional tips, some you might see in action in Philip’s video:
- pretty print the source
- use ‘find’ to search for classes and variable you find in the source
- if you type something into the console and it comes back with ‘function’ then you need to find where the class is instantiated in the code
- use ‘find’ to search for ‘new’ instantiations of the classes
- you can do a lot of exploration and manipulation with ‘for’ loops
- for bots you’ll need to use
setInterval
- I assign the result of
setIntervalto a bot e.g.
ztypebot = setInterval(...)so that I can shut the bot down later with a
clearInterval(ztypebot)
- find some ‘quick hacks’ that you can use early in your investigation to give you more room to find a better hack e.g. when automating ztype I started with a bot that had infinite emps and triggered an emp every 2 seconds, and when that was working it gave me time to experiment with the objects and source to figure out how to make a bot that could shoot properly
- keep notes as you go about what you tried, and how you found the objects
- sometimes I start by working through the code and look for hints as Philip demonstrates
- sometimes I start by looking to see what code is triggered by the Event Listeners in the browser dev tools
- sometimes I breakpoint code that I think is interesting
- they key (and Philip demonstrates this well) is to find the big ‘namespace’ type objects as early as possible
Testing SummaryWhen you hack/cheat at JavaScript games in this way, you are developing skills that will transfer to your testing:
- understand JavaScript
- learn how to use the browser dev tools
- interacting with a running application
- exploring the internal object state of an application
- putting a running application into a specific state for testing automatically
- writing very small amounts of code to automate an application state
Related Notes:
You can play Z-Type at
That's such a great idea! I've been delaying my learning of JavaScript, but hacking games might be a great excuse to start it. Also, even at 1% efficiency, you're Z-Type bot is impressive at level 80.
Thanks. I reached 100% efficiency and a higher level over here
To improve my skills in Java programming, I had put a lot of effort into it.
There are many techniques but I like java foreach since this method has excellent structured information. The list of textbooks, that you can find on the site, designed specifically for easy memorization. Of course, I spent more than half a year on a full course, but it really helped me to expand my experience in programming, I learned many topics without it my future career would be impossible.
Hey, i know this is old but I played around with ZType a bit as well because of ur post. By just calling the parent.entityenemy.prototype.kill(); function (function name is from memory, but its somewhere there) just once, the enemys didnt spawn, only the words. I had endless time to enter everything. Using that and ur bot will be endless points :D
Cool. Glad to hear you dug into the code and found a different way to manipulate it. And thanks for sharing :) | http://blog.eviltester.com/2016/09/hacking-javascript-games-to-improve.html | CC-MAIN-2017-51 | refinedweb | 1,220 | 65.35 |
Understanding and Replacing Microsoft Exchange
February 1st, 2003 by Tom Adelstein in.
First, we observed that Outlook did around 95% of the work in the Microsoft Exchange model. Exchange, as its name implies, transfers data between or among Outlook users. Even so, Exchange controlled the transport protocol and that presented a problem. People use the term MAPI to describe the Exchange protocol for transferring data among Outlook users. I don't see MAPI as being the appropriate term.
When intercepting Outlook messages, we discovered large arrays of binary data instead of text. I recognized the data but didn't realize where I had seen it before.
Outlook runs in two different modes: Corporate Workgroup mode and Internet Mail Only mode. In the Corporate Workgroup mode, Microsoft turns on all of Outlook's highly regarded features. In the Internet Mail Only mode, Microsoft uses a completely different and undocumented application program interface (API) with a limited feature set. Without an Exchange server, Outlook doesn't function in the Corporate Workgroup mode at all and has a limited set of features.
In Outlook's Workgroup mode, or when connected to an Exchange server, its data moves around in binary form. That binary data becomes impossible to recognize by an uninformed observer.
While researching, I found a developers' site on SourceForge.net that was porting Open DCE to Linux. I e-mailed one of the developers who wrote back and mentioned that the Open Group contributed the code.
I went to the Open Group's web site, searched the archives and found an old article mentioning that Microsoft had licensed DCE. We downloaded the Open DCE code and, using the engine, shook hands with Outlook and then Exchange. We knew more about the transport protocol as a result. We also understood the presence of binary data streams.
What we discovered is Microsoft uses the distributed computing environment (DCE) as its transport when using Exchange and Outlook in the Corporate Workgroup mode. Microsoft provides a programming interface on top of DCE, which it calls MAPI. Still, underneath MAPI exists an open standards-based protocol (DCE), which Microsoft bought from the Open Group and modified.
One of the default functions in DCE automatically translates ASCII text into binary objects. Microsoft leaves the binary object undocumented. So most of the MAPI properties programmers tag wind up as binary code they would not recognize. To make matters a little more complex, Microsoft embeds the binary property code in a large array of null binary data, thus hiding it.
We began to understand the transport, but we realized that Outlook sent MIME attachments to other Outlook clients. Those attachments did not transform themselves into binary data. We concluded that Outlook also used encapsulation to pass attachments around, which led us to the TNEF object.
Microsoft Exchange uses a number of programs it calls “service providers” that Linux users might call dæmons. Exchange service providers handle objects, which have state and behavior.
Transport neutral encapsulation format (TNEF) is a method to pass ASCII text, other files and objects, along with binary message data. The binary message data makes up the bulk of each TNEF object. TNEF encapsulates MAPI properties into a binary stream that accompanies a message through transports and gateways. Outlook can decode the encapsulation to retrieve all the properties of the original message. The TNEF object hides in MIME as an attachment.
When we found the properties, which created calendar events, we built a TNEF encoder and soon began sending calendar events to and from Outlook clients with SMTP. We immediately recognized that we could use internet transport protocols and turn on Microsoft's Corporate Workgroup mode without MAPI. We knew we had arrived when we saw Microsoft Knowledge Base Article Q197204, which says that Microsoft does not support our transport protocol in the Workgroup mode.
With our primary goal being server-side calendaring, we needed to create a message store to hold our Outlook client objects. As we used an IMAP server, we needed IMAP support, which Microsoft did not provide in the Workgroup mode. So we had to find a way to add IMAP client support to Outlook. The facilitator for adding functionality to an existing Outlook client involved what most people think of as a plugin.
When Microsoft first released Exchange, Outlook didn't exist. Instead, Microsoft provided a set of Exchange messaging clients for its different Windows operating systems. Microsoft also provided an extensible architecture for those Exchange messaging clients. Client extensions provided developers with a way to change the default behavior of the Exchange client. When Microsoft released Outlook, it continued providing support for the Exchange client extension architecture for compatibility with existing client extension DLLs.
Client extensions allow one to alter the default behavior of the client. Microsoft saw the advantages of an extension as a convenient way to integrate customized features and new behavior directly into the client, instead of having to write a separate MAPI application. We, however, saw extensions as a way to add IMAP client services to Outlook in the Workgroup mode. Using this architecture, we added commands to Outlook menus, custom buttons to the toolbars and the ability to preprocess outgoing and incoming messages with IMAP client services.
Luckily, we had already written client libraries for IMAP when we built our Linux client the previous year. We simply needed to port them to Windows. Our familiarity with the function calls, headers and protocols reduced our overall effort.
Once we built a Microsoft DLL for the client functions, we added it as an Outlook extension. Luckily, it worked the first time we tried it. By choosing the rich text format (RTF) for mail and meeting invitations, our TNEF objects attached themselves to the messages. Because Outlook created the TNEF objects, it exchanged them without any problems.
At this point, we uploaded our messages to our IMAP folders using the Microsoft .pst file as store and swap space. Staying connected to Exchange and using our server for message stores, we noticed compatibility between the two systems. We dragged and dropped objects from the Exchange folders into our IMAP folders. By doing this we discovered that tasks, journal entries, calendar events and so on, all showed up in Outlook as if they arrived from Exchange. The calendar also worked perfectly.
When you look at Exchange and study its components, you find they number only four. The first is an information store or message store. The store holds individual user messages and has an access control list (ACL) engine associated with them. Similar to RFC-compliant IMAP servers, namespace differs according to whether the stores belong to individual users or whether the folders are public. Microsoft uses an Access database for storing message stores. The limitation of Microsoft's Jet Engine technology and the Access MDB file prevents vertical scalability.
Secondly, Exchange has a directory. Microsoft structured their Exchange directory with object classes and attributes. The Exchange directory structure resembles the RFC-compliant LDAP protocol. However, Microsoft added Object Classes and changed the attribute names within those and other classes.
Next, Exchange has a mail transfer agent or MTA. Microsoft's MTA appears similar to the MTA used in an earlier product called Microsoft Mail 3.5. The Microsoft Mail MTA requires connectors or gateways, which rewrite their proprietary mail headers to those that comply with foreign systems, such as Lotus Notes, X-400 and RFC 822 internet mail standards. Unlike sendmail and similar internet MTAs, Exchange's MTA lacks configuration options.
Finally, Exchange has a component called a system attendant. The attendant handles every action taken within Exchange, from sending and receiving e-mail to filling requests for addresses from the Exchange directory. In many ways the system attendant resembles an attempt to provide interprocess communication (IPC), which Microsoft's operating systems lack.
Our Linux server-side solution included similar components to those found in Exchange. The first is the Cyrus IMAP message store. Cyrus stores hold individual user messages and have an ACL engine associated with them. Namespace differs according to whether the stores belong to individual users or whether the folders are public. Cyrus uses the Berkeley Database from Sleepycat Software. Where Microsoft's Jet Engine and Access database technology prevents scaling, Berkeley DB's high performance and scalability support thousands of simultaneous users working on databases as large as 256 terabytes.
Secondly, Linux has a directory. While Microsoft structured their Exchange directory to resemble the Lightweight Directory Access Protocol (LDAP), the Linux solution uses OpenLDAP software, an open-source implementation of LDAP. To accommodate Outlook clients, we added the Exchange object classes and their noncompliant attribute names. We indexed the Microsoft-based distinguished names and created a high-performance global address list.
Like Exchange, the Linux solution has an MTA that can be managed and configured internally and doesn't need external connectors. The University of Cambridge developed the Linux MTA we use, called Exim. Exim has numerous configuration options, including file lookups, local delivery and regular expression support. In the context of the Linux MTA, users provide regular expressions to filter content coming in and going out.
In the “Exchange Replacement HOWTO”, Johnson and Mead leave the tasks of adding server-side messaging and the administrative console to the next generation of Linux developers. In this article, we explain how one could transform Exchange transports and message stores. We accomplish this in two steps. First, we capture Outlook messages and decode their TNEF objects. Secondly, we use the Exchange client extension architecture to add IMAP functionality to Outlook in its Corporate Workgroup mode..
Highly scalable Linux components, such as Cyrus IMAP, OpenLDAP and Exim, can replace dozens of Exchange servers on a single Intel platform. The layers of interfaces and outdated DCE components used by Exchange do not hinder Linux. With Linux on the zSeries mainframe, we can replace hundreds of Exchange servers.
If you're looking for a graphical administrative console, projects such as PHP Cyrus tools, cyrus_imap-sql, Webmin and Replex can make administration of the server a simple task.
In general, few people would consider replacing Exchange with Linux an easy task. In spite of that, our development team proved that it could be done. Hopefully, we have taken much of the mystery and intimidation out of the Exchange article,thn
On July 14th, 2008 greymarkus (not verified) says:????
On July 13th, 2007 Wong Seoul (not verified) says:
On May 26th, 2009 Jairo (not verified) says:
On March 10th, 2007 Anonymous (not verified) says:
On August 28th, 2006 Anonymous (not verified) says:
Awesome work. Thanks for saving the world. You're definitely earned your success and money.
I am a windows developer and
On June 13th, 2006 Anonymous (not verified) says:!
On November 24th, 2005 Anonymous (not verified) says:
On July 1st, 2005 Outlook Express repair (not verified) says:
I must admit to being more impressed for it. I've even recommended it to all my friends.
what a waste of time... So
On March 24th, 2008 Anonymous (not verified) says:"
On June 11th, 2008 Anonymous (not verified) says:
There's nothing "cheap" about Exchange!
Post new comment | http://www.linuxjournal.com/article/6368 | crawl-002 | refinedweb | 1,856 | 55.95 |
Last week @mariobehling opened up an issue to implement voice search in Susper. Google Chrome provides an API to integrate Speech recognition feature with any website. More about API can be read here:
The explanation might be in Javascript but it has been written following syntax of Angular 4 and Typescript. So, I created a speech-service including files:
- speech-service.ts
- speech-service.spec.ts
Code for speech-service.ts: This is the code which will control the working of voice search.
import { Observable } from ‘rxjs/Rx’;
interface IWindow extends Window {
webkitSpeechRecognition: any;
}
export class SpeechService {
constructor(private zone: NgZone) { }
record(lang: string): Observable<string> {
return Observable.create(observe => {
const { webkitSpeechRecognition }: IWindow = <IWindow>window;
const recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onresult = take => this.zone.run(() => observe.next(take.results.item(take.results.length – 1).item(0).transcript)
);
recognition.onerror = err =>observe.error(err);
recognition.onend = () => observe.complete();
recognition.lang = lang;
recognition.start();
});
}
}
You can find more details about API following the link which I have provided above in starting. Here recognition.onend() => observe.complete() works as an important role here. Many developers forget to use it when working on voice search feature. It works like: whenever a user stops speaking, it will automatically understand that voice action has now been completed and the search can be attempted. And for this:
this.speech.record(‘en_US’).subscribe(voice => this.onquery(voice));
}
We have used speechRecognition() function. onquery() function is called when a query is entered in a search bar.
Default language has been set up as ‘en_US’ i.e English. We also created an interface to link it with the API which Google Chrome provides for adding voice search feature on any website.
I have also used a separate module by name NgZone. Now, what is NgZone? It is used as an injectable service for executing working inside or outside of the Angular zone. I won’t go into detail about this module much here. More about it can be found on angular-docs website.
We have also, implemented a microphone icon on search bar similar to Google. This is how Susper’s homepage looks like now:
This feature only works in Google Chrome browser and for Firefox it doesn’t. So, for Firefox browser there was no need to show ‘microphone’ icon since voice search does not work Firefox. What we did simply use CSS code like this:
.microphone {
display: none;
}
}
@-moz-document url-prefix() is used to target elements for Firefox browser only. Hence using, this feature we made it possible to hide microphone icon from Firefox and make it appear in Chrome.
For first time users: To use voice search feature click on the microphone feature which will trigger speechRecognition() function and will ask you permission to allow your laptop/desktop microphone to detect your voice. Once allowing it, we’re done! Now the user can easily, use voice search feature on Susper to search for a random thing. | https://blog.fossasia.org/implementing-voice-search-in-susper-in-chrome-only/ | CC-MAIN-2022-21 | refinedweb | 496 | 58.99 |
Well, I think this is mainly a syntax problem, but I just can't figure out how to get this thing to do what I want it to.
I have a program that needs to run with an open command prompt window so that when the user closes the window the program goes away. To do that, I created this short program (it's one line of code; it's more like a script than a program) to access cmd.exe and do it so that I could have an executable JARfile to make running the program simple for the end user (rather than them having to type at the command prompt).
Here is my code. If I run it, it seems like it only gets as far as the cd C:\HearingAid bit, completely ignoring the fact that it goes FURTHER into the ProgramData folder, and of course not even coming within a mile of making a call to Java.exe:
Code :
import java.io.IOException; public class HearingAid { public static void main(String[] args) throws IOException { Runtime.getRuntime().exec(new String[] { "cmd.exe", "/C", "start;", "cd C:/HearingAid/ProgramData", "&", "java AudioTransfer"}); } }
What have I written wrong, folks?
-summit45
--- Update ---
I feel kind of stupid now, but I just saw someone on StackOverflow suggest to someone else for a very slightly similar issue to just use a shell script for this. The irony is I was using those earlier to simplify compiling and didn't think of that. Lol.
Either way, someone feel free to answer the question if you want to. Can always learn something.
-summit45 | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/31129-how-get-command-line-function-java-code-printingthethread.html | CC-MAIN-2014-10 | refinedweb | 268 | 78.59 |
Packages are special directories that can contain class directories, functions, and other packages. Packages define a scope (sometimes called a namespace) for the contents of the package directory. This means function and class names need to be unique only within the package. Using a package provides a means to organize classes and functions and to select names for these components that can be reused in other packages.
Package directories always begin with the + character. For example,
+mypack +mypack/pkfcn.m % a package function +mypack/@myClass % class in a package
The package directory's parent directory must be on the MATLAB path.:
mpack.myClass.stMethod(arg)
Back to Top
Because functions, classes, and other packages contained in a package are scoped to that package, to reference any of the package members, you must:
obj = mypack.myfirstclass; obj.MyProp = some_value;
Back to Top
You cannot add package directories to the MATLAB path, but you must add the package's parent directory to the path. Even if a package directory is the current directory, its parent directory must still be on the MATLAB path or the package members are not accessible.
Package members remain scoped to the package even if the package directory is the current directory. You must, therefore, always refer to the package members using the package name.
Package directories do not shadow other package directories that are positioned later on the path, unlike classes, which do shadow other classes.
Suppose a package and a class have the same name. For example:
dir1/+foo dir2/@foo/foo.m
A call to which foo returns the path to the executable class constructor:
>> which foo dir:
dir1/+foo/bar.m % bar is a function in package foo dir2/@foo/bar.m % bar is a static method of class foo
A call to which foo.bar returns the path to the static method:
>> which foo.bar dir2/@foo/bar.m
In cases where a path directory contains both package and class directories with the same name, the class static method takes precedence over the package method:
dir1/@foo/bar.m % bar is a static method of class foo dir1/+foo/bar.m % bar is a function in package foo
A call to which foo.bar returns the path to the static method:
>> which foo.bar dir1/@foo/bar.m
Back to Top
Get MATLAB trial software
Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts. | http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brfynt_-1.html | crawl-002 | refinedweb | 407 | 55.84 |
GAL is a collection of widgets and utility routines that were taken
from Evolution and Gnumeric.
The upcoming version of Evolution and Gnumeric will both require
GAL, as the code has been moved to this new module.
The API is not frozen and might change at any time. Larger class
renaming might happen at any point without notice. Use this library
at your own risk.
WWW:
NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered.
This port is required by:
No installation instructions: this port has been deleted.
The package name of this deleted port was: gal
gal
No options to configure
Number of commits found: 76
Developement ceased, and nothing in the ports tree uses it anymore
Approved by: gnome (kwm)
Feature safe: yes
Deprecate this old gnome1 library, development as ceased and last user in the
ports tree (guppi) is now deprecated), set the same expiration date as guppi
Approved by: gnome (kvm)
-40 after objformat removal
Reported by: pointyhat
portlint:
-Use DOCSDIR in pl_REINPLACE need be defined only when REINPLACE_CMD is used.
Remove REINPLACE commands that were rolled into gnomehack.
Remove USE_GNOMENG.
Update to 0.24.
Clear moonlight beckons.
Requiem mors pacem pkg-comment,
And be calm ports tree.
E Nomini Patri, E Fili, E Spiritu Sancti.
Update to 0.23.
Update to 0.22.
Protect targets with .if target(...) ... .endif for targets that are
redefined in slave ports. Slave port maintainers need to check that
they aren't actually relying on the master port target to be executed.
Update to 0.21..19.3.
- Move misc documentation into share/doc where it belongs;
- use USE_LIBTOOL while I here;
- make gnome-hint from gnomecore actually working;
- bump PORTREVISIONs.
Update to 0.19.2.
Update to 0.19.1.
Iconv cleanup, stage 2b: remove regex hacks that change iconv.h to giconv.h and
-liconv to -lgiconv..
Update to 0.19.
Update to 0.18.1.
Update to 0.18.
Another day, another gal update...
Update to 0.13.
Update to 0.12.
Update to 0.11.2.
Update to 0.11.1.
Add missed converters/libiconv dependency.
Update to 0.10.
Update to 0.9.1.
Update to 0.9
Fold gtkhtml (and, by association, gal) into dependencies for x11/gnomecore
(adding some extra functionality).
Update to 0}
Allow CATEGORIES to be overridable by the japanese/gal slave port
Update to 0.5 converters/libiconv (1.5.1 - committed today) is now a
requirement
Update to 0.4.1.2nd-cup-of-coffee
Update to 0.4
Update to 0.3
Chase new print/gnomeprint shlib version
Update to 0.2.2
Update to 0.2.1
Update to 0.2
Remove extra directory
Convert category x11-toolkits to new layout.
GAL is a collection of widgets and utility routines that were taken from GNOME
Evolution and Gnumeric - upcoming releases of these two pieces of software,
and others, will require this library.
Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD
7 vulnerabilities affecting 28 ports have been reported in the past 14 days
* - modified, not new
All vulnerabilities | http://www.freshports.org/x11-toolkits/gal/ | CC-MAIN-2014-42 | refinedweb | 519 | 62.04 |
How to install Ubuntu 12.04 Precise, Xubuntu-desktop and Open JDK-7 on Beagleboard Rev. C2
My aim was to install Ubuntu 12.04, Xubuntu-desktop graphical user interface and Java virtual machine (Open JDK-7) on my beagleboard so that I could run my java application on the monitor connected to the BB. I encountered several problems and solved them one by one. Following is how I've done it..
I had all the accesorries for the beagleboard (usb hub, dvi-to-hdmi cable, usb-ethernet converter, usb keyboard, usb mouse and a hdmi enabled monitor).
My host PC also has a Ubuntu 12.04 installed and it was connected to the internet through my smart phone's wireless access point during the installation..
You need a 4GB or 8GB blank SD card to install the three. I do not recommend 2GB SD card since there will be almost no place in the SD card after installing the three.
1) Connect your Beagleboard to your PC via a serial cable
2) Run a terminal and start minicom to access your Beagleboard
root@tayyar:~# minicom -s
Make sure you set the serial communication parameters correctly as 115200, 8N1, No HW Flow Control.
3) Open another terminal to configure your host PC during the installation
4) Get all the required packages for Step 6 & Step 7. If you already have all of these installed you can skip this.
root@tayyar:~# sudo apt-get install wget xz-utils uboot-mkimage pv dosfstools btrfs-tools parted git
5) Instert the SD card in your computer.
6) Get the processor flashing script.
root@tayyar:~# git clone git://github.com/RobertCNelson/flash-omap.git
root@tayyar:~# cd flash-omap
7) Get the location of your sd card.
root@tayyar:flash-omap# sudo ./mk_mmc.sh --probe-mmc
You will see something like:
Are you sure? I Don't see [/dev/idontknow], here is what I do see...
fdisk -l:
Disk /dev/sda: 160.0 GB, 160041885696 bytes
Disk /dev/sdb: 3957 MB, 3957325824 bytes
mount:
/dev/sda1 on / type ext4 (rw,errors=remount-ro,commit=0)
/dev/sdb is my SD card. Your’s might have a different name and size. Notice that /dev/sda is 160.0GB, that’s my hardrive, do not accidentally format yours!
8) Download Ubuntu 12.04 and unpack it,
a) download
wget
mirrors (will take some time to update):
wget
b) verify the package
root@tayyar:~# md5sum ubuntu-12.04-r3-minimal-armhf.tar.xz ecda26197d3f5279b8db0a74a486008c ubuntu-12.04-r3-minimal-armhf.tar.xz
c) unpack the prebuilt image,
root@tayyar:~# tar xJf ubuntu-12.04-r3-minimal-armhf.tar.xz root@tayyar:~# cd ubuntu-12.04-r3-minimal-armhf
9) Create the SD card content
root@tayyar:ubuntu-12.04-r3-minimal-armhf# sudo ./setup_sdcard.sh --mmc /dev/sdb --uboot "beagle_cx"
Notice that my SD card is /dev/sdb.. yours could be different.. You should know this from Step 7.
10) Remove the SD card from your PC and insert it into Beagleboard.
11) Pushing on the "User" button, reset the beagleboard.
12) As the u-boot console is counting down from a number "10..9..8..7.. ...".. press "Enter"..
You should see the Beagleboard u-boot console,
OMAP3 beagleboard.org #
13) Check the content of the SD card by using "fatls" command
OMAP3 beagleboard.org # mmc rescan
OMAP3 beagleboard.org # fatls mmc 0:1
45876 mlo
337932 u-boot.img
3000856 zimage
3061227 initrd.img
919 uenv.txt
tools/
0 uenv.txt~
6 file(s), 1 dir(s)
14) Once you see the files listed above in the SD card, you could now write the image files into the flash memory (NAND). Type the following commands to do so.
mmc rescan
fatload mmc 0:1 0x80200000 mlo
nand erase 0 80000
nand write 0x80200000 0 20000
nand write 0x80200000 20000 20000
nand write 0x80200000 40000 20000
nand write 0x80200000 60000 20000
fatload mmc 0:1 0x80300000 u-boot.img
nand erase 80000 160000
nand write 0x80300000 80000 160000
nand erase 260000 20000
15) Reboot the Beagleboard and wait until it the login screen comes. Use the following username and password to login,
Ubuntu 12.04 LTS omap ttyO2
omap login: ubuntu
Password: temppwd
Last login: Wed Dec 31 18:04:25 CST 1969 on tty02
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.19-x13 armv7l)
* Documentation:
ubuntu@omap:~$
I recommend you to become "root" to proceed so that you don't encounter permission problems during the installations..
ubuntu@omap:~$ sudo -s
enter "temppwd" as your password.. now you should see the root console..
root@omap:~#
It is time to configure our network and access internet to proceed the installation of XFCE4 and Open JDK.
In my case, my internet source was my wireless AP in my room and I connected my ethernet cable to a hub to communicate with Beagleboard via network. Finally, my Beagleboard will acces the internet through my wired ethernet. Since there is no physical connection between my beagleboard and wireless adapter on my host PC, I needed to share my ethernet with both wireless and beagleboard ethernet interfaces. Following describes how you can do it.
16) On your host Linux (Ubuntu 12.04 Precise), set your wired eth0 IP address as the following
-> go to System Settings->Network->Wired->Options->IPV4 Settings->set the Method to "Shared to other computers"
17) Check your wired IP address using "ifconfig" on your host PC
18) set the target IP on the Beagleboard accordingly,
root@omap:~# ifconfig eth0 10.42.0.2 netmask 255.255.255.0 up
you should set this IP according to your host IP address so that they exist in the same network.
19) set the Gateway IP on Beagleboard
root@omap:~# route add default gw 10.42.0.1 eth0
Notice that you set the host Linux eth0 IP address as the gateway on your beagleboard.
20) Configure your nameserver (DNS) by editing resolv.conf
root@omap:~# vi /etc/resolv.conf
add the following lines anywhere in the file,
nameserver 208.67.220.220
nameserver 8.8.8.8
21) you should be able to ping to any IP on the internet
root@omap:~# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=43 time=493 ms
64 bytes from 8.8.8.8: icmp_req=2 ttl=42 time=1293 ms
64 bytes from 8.8.8.8: icmp_req=3 ttl=42 time=868 ms
64 bytes from 8.8.8.8: icmp_req=4 ttl=42 time=688 ms
^C
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4006ms
rtt min/avg/max/mdev = 493.835/836.044/1293.606/295.547 ms, pipe 2
root@omap:~#
22) Now it is time to install Xubuntu-desktop on the Beagleboard.
root@omap:~# sudo apt-get update
root@omap:~# sudo apt-get install gdm xubuntu-desktop
root@omap:~# sudo apt-get install xfce4 xserver-xorg-video-omap3 network-manager
Once the Xubuntu installation is done, reboot your Beagleboard..
Bad news is, Xubuntu won't successfully start..
Now it is time to fix the problem..
a) Remove the SD card from your Beagleboard and insert it into your host PC.
b) Edit "uEnv.txt"
c) Add the line "console=tty0" under the line where it is written "optargs=console=tty0"
d) Change the "dvimode=1280x720MR-16@60" to "dvimode=1024x768MR-16@60"
Once you're done editing uEnv.txt, remove the SD card from the host PC and insert it into the BB again and reboot the beagleboard.
Another problem is, XFCE4 won't allow you to login due to permission and ownership problems of the default user account..
23) You need to add a new user and give it the root rights and change the ownership..
a) create the user,
root@omap:~# adduser genius
b) set a password for the user,
root@omap:~# passwd genius
c) Edit the /etc/passwd file using "vi" to make the user root.
change the line from
genius:x:1001:1004:Genius User,207,,:/home/genius:/bin/bash
to
genius:x:0:0:Genius User,207,,:/home/genius:/bin/bash
d) Reboot the beagleboard and login with your new username ("genius" in my case)
add the following line to your .bashrc
root@omap:~# chown genius:genius .ICEauthority
root@omap:~# chmod 644 /home/genius .ICEauthority
reboot the beagleboard.. Once the login screen comes, you should now be able to login with the new user..
24) A known problem of Beagleboard is that once the Ubuntu is installed on the BB, the sound does not properly work.. To try this out, do the following..
a) record your voice
root@omap:~# arecord -t wav -c 2 -r 44100 -f S16_LE deneme.wav
b) listen the same file "deneme.wav"
root@omap:~# aplay -t wav -c 2 -r 44100 -f S16_LE deneme.wav
It won't give any errors but you won't be hearing any sound.. To fix this, type the following to get into ALSA Mixer configuration software..
root@omap:~# alsamixer
unmute 'HeadsetL Mixer AudioL2', and 'HeadsetR Mixer AudioR2'then volume can be controlled through 'DAC2 Analog' and 'Headset' volume controls.
Now you should be able hear the record..
25) Now we are ready to install the Open JDK-7. This is fairly easy compared to Ubuntu and X-ubuntu Desktop installation..
Do the following,
26) apt-get install openjdk-7-jre
27) apt-get install librxtx-java
28) cp /usr/lib/jni/librxtx* to /usr/lib/jvm/java-7-openjdk-armhf/jre/lib/arm to make the libraries work at all. This is not done by the install rxtx above.
Reboot your beagleboard..
29) Create a file on your host PC using Gedit or any other text editor, type in the following lines and save the file as "HelloWorld.java"
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
or
Find the "HelloWorld.class" from internet and download it to your host PC..
You could send one of these files to your beagleboard to test your Java installation..
30) Copy the HelloWorld.class or HelloWorld.java to beagleboard over the network as the following
root@tayyar:~# scp HelloWorld.class genius@10.42.0.2:/home/genius
31) test the Java VM..
root@omap:~# java HelloWorld
Hello, World
root@omap:~#
I was also able to run my Java application on the monitor and control my IP camera using the beagleboard.
Previous post by Dr. Tayyar GUZEL:
Ideas to develop Embedded Devices for Smart Grid
Next post by Dr. Tayyar GUZEL:
Best Firmware Architecture Attributes
- Write a CommentSelect to add a comment
very nice tutorial for me. i am using BB-XM rev C. same steps can help me? as i am new to this area please guide me
I have used all these steps given in above. I dont want to have Open JDK . Still I am not getting sound correctly. I am unable to hear/record any song...I have tried using different speakers, different files formats of .mp3,.wav also
So please can you tell me whats wrong I am doing and how can I fix the sound problem.
Thanks in advance
I am following the same steps. But at the 6th step , when I am trying get the processor flashing script using the command "git clone git://github.com/RobertCNelson/flash-omap.git" . Then I a error as follows:
--------------------------------------------------
Cloning into flash-omap...
fatal: remote error:
Repository not found.
---------------------------------------
Please help. | https://www.embeddedrelated.com/showarticle/138.php | CC-MAIN-2017-13 | refinedweb | 1,939 | 67.45 |
Python Program to Compute Quotient and Remainder
Grammarly
In this tutorial, you will learn how to compute the quotient and the reminder using the input function, format function, print function, the double division and modulus operator of the python programming language.
How to Compute the Quotient and Reminder in Python?
Let’s take a look at the first source code , here the values are assigned in the code, the double division and modulus operator carry out the function.
# Python program to compute the quotient and the reminder def find(n, m): # for quotient q = n//m print("The quotient is:", q) # for remainder r = n%m print("The remainder is:", r) # Driver Code find(14, 5) find(69, 9)
OUTPUT:
The quotient is: 2 The remainder is: 4 The quotient is: 7 The remainder is: 6
- At the start, we use
def find(n, m)where the
defkeyword is used to define a function and the
findfunction is used to find the first occurrence of the specified value.
- Declare the formula to compute the quotient as
q = n//m, where the double division operator is used to compute and return the quotient. The value is displayed with the statement
("The quotient is:", q)using the
q.
- Similarly, declare the formula to compute the reminder as
r = n%m, where the modulus operator is used to compute and return the reminder. The value is displayed with the statement
("The reminder is:", r)using the
r.
- The input values
(n, m)are entered in the code within the
findfunction.
Let’s take a look at the second source code , here the values are assigned in the code and we use the divmod function to compute the quotient and reminder.
# Python program to find the quotient and remainder using divmod() q, r = divmod(14, 5) print("Quotient: ", q) print("Remainder: ", r) q, r = divmod(69, 9) print("Quotient: ", q) print("Remainder: ", r)
OUTPUT:
Quotient: 2 Remainder: 4 Quotient: 7 Remainder: 6
- At the start, we declare the variables
q, rwith the function
divmodalong with the input values
(14, 5). We display the statements with the
qand
r.
- Similarly in the second part of the code, the same steps are followed with different input values
(69, 9)with the statements displayed with the
- The
divmod()function takes two numbers and returns a pair of numbers consisting of their quotient and remainder. To explain with an example – The
divmod()function takes two parameters x and y, where x is treated as numerator and y is treated as the denominator. The function calculates both x / y and x % y and returns both the values.
Let’s take a look at the third source code , here the values are given as input by the user in the code, the double division and modulus operator carries out the function.
#Program to compute the quotient and the reminder n =int(input("Enter the dividend: ")) d =int(input("\nEnter the divisor: ")) #To compute the quotient and reminder quotient=n // d; remainder=n % d; #To display the values print("\nQuotient is: ",quotient) print("remainder is: ",remainder)
INPUT:
50 3
OUTPUT:
Enter the dividend: Enter the divisor: Quotient is: 16 remainder is: 2
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction which is declared with the variable the variables
nand
dfor the dividend and the divisor.
- We use
int()function before the input function which converts the specified value into an integer number.
- In the STDIN section of the code editor the input values are entered.
- We declare the operators
//and
%with the variables
nand
dwhich computes the quotient and the reminder of the input values. The values are saved in the variables
Quotientand
Reminder
- Then we display the output value using the
Quotientand
Reminder.
NOTE:
- The double division operator (//) is used to compute the quotient and the modulus operator (%) is used to compute the reminder.
- The int() function is used to convert the specified value into an integer number and evaluates the input and accordingly appropriate data type is returned.
- The divmod() method in python takes two numbers and returns a pair of numbers consisting of their quotient and remainder.
- The print statement/string to be displayed in enclosed in double quotes.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string. | https://developerpublish.com/academy/courses/python-examples/lessons/python-program-to-compute-quotient-and-remainder/ | CC-MAIN-2021-49 | refinedweb | 745 | 53.24 |
SwiftUI is a very interesting library introduced at WWDC 2019. It brings iOS developer community a novel way to develop UIs for iOS and MacOS apps.
SwiftUI is also the first Swift binary framework that Apple introduced despite Swift was born in 2014 and been very popular.
To integrate SwiftUI, simply importing it, right?
import SwiftUI
First of all, SwiftUI is only available on iOS 13 and later. It's likely that your app or team's app has to support iOS 12, 11. So adding
@available is needed.
@available(iOS 13, *) struct ContentView: View { var body: some View { Text("Hello World") } }
Next, to make sure your app doesn't crash at launch on iOS less than 13, you need to add SwiftUI as
-weak-framework, the same for Combine, which was also introduced last WWDC.
or
But then lowering your deployment target to iOS 10 or lower and compiling to Generic iOS Device or archiving, this happens:
the reason for this is because SwiftUI wasn't compiled for 32 bit architectures. So adding 64-bit compiler flag to every SwiftUI code is required.
#if (arch(x86_64) || arch(arm64)) @available(iOS 13.0, *) struct HelloWorld : View { var body: some View { //... } } #endif
canImport(SwiftUI) won't help you solve the problem above.
Finally, SwiftUI uses many new Swift 5.1 features, like
some keyword of opaque return types and property wrappers. So if you, at some point, wants your code to compiles to Xcode before 11, you needs to add:
#if compiler(>=5.1) //... #endif
compiler flag actually represents Xcode 11, because changing
SWIFT_VERSION in Xcode project still can get SwiftUI fully functional. So adding
#if swift(>=5.1) is not the correct way.
Discussion | https://dev.to/quangdecember/compiling-swiftui-codes-4jjk | CC-MAIN-2020-45 | refinedweb | 284 | 65.83 |
Read Roberts <rroberts at adobe.com> wrote in message news:<mailman.302.1073927909.12720.python-list at python.org>... [Returning a string/tuple to a C function] > In fact, I did try all combinations of > > in the Python call-back function : > return myString > return (myString) > > and, in the C calling function, > > PyArg_ParseTuple(pyStringResult, "s", myString) > PyArg_ParseTuple(pyStringResult, "(s)", myString) I'm guessing here but, if you want to pass tuples around, have you tried using the second form of each of the above with the following correction to the Python code? return (myString,) > Also, the Python documentation (and other working code examples I > have) indicate that 'PyArg_ParseTuple', unlike BuildValues, always > assumes the arguments are supplied in a argument tuple, even if there > is only one argumen. Maybe. I haven't really thought about it. > I speculate that an argument list object, as required by > PyArg_ParseTuple, is not in fact a simple tuple., and that > PyArg_ParseTuple cannot be used to parse a regular tuple. Any idea if > this is correct? I think that there's been a misunderstanding. Since your original message, and some unavailable reply were quoted below your last message, I think I can see where it happened. > >In comp.lang.python, you wrote: > > > >> Why does PyArg_ParseTuple fail to parse a return value which is a > >> tuple? > >> > >> However, the following does not work: > >> from Python callback function: return (myString) > >> in calling C function: > >> if (!PyArg_ParseTuple(pyStringResult, "s", name)) { > >> dbprintf(4, "c: failed to parse return value\n"); > >> PyErr_Clear(); > >> } > >> PyArg_ParseTuple fails, and returns NULL. How come? By the > >> documentation, I would think that PyArg_ParseTuple would parse any > >> Python tuple object. I don't know whether it does or not, but you have returned a string! This happened because you need to use a trailing comma within the brackets. This tells the interpreter that the return value is not simply a string enclosed in brackets. You can see this from the following output from an interactive session in Python: >>> "string" 'string' >>> ("string") 'string' >>> ("string",) ('string',) In your original example, you returned a string and converted it successfully to a char pointer. Presumably, you wanted a more general solution in order to catch any non-string objects returned and turned to PyArg_ParseTuple. Maybe you could put the returned object in a tuple and call PyArg_ParseTuple on the result, but there's surely an easier way to check the validity of the return value. Hope this helps, David | https://mail.python.org/pipermail/python-list/2004-January/285095.html | CC-MAIN-2014-15 | refinedweb | 405 | 62.27 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Last Updated 17 Oct 2000
This
It really does come with answers
Yes, this is a long document (around 35 pages), if you cannot see the answers then you have not got the entire document, try reloading it untill you can see the answer to Question 60 and the words "End of document". The answers contain references to approximately which objective the question relates to. If you have a query about any of these questions, please, please include the full answer with the question.
Why not discuss this exam with other people ?
You can post a message on the discussion forum at (scroll down the messages to find the create new conversation button). You could also send me your question but I get heaps of email and my answer is likely to be slow and terse.
How does this compare with the real thing?
As of 5 Oct 200 the question format has changed very slightly. You will now get more questions that include snippets (though the ratio may be similar to this mock exam). Each question will also tell you how many of the options you need to pick. You can read more about these revisions at. You should assume that the real thing will be harder though many people have told me that they get similar marks in the real thing to my exams..
Where can you find other Mock Exams?
Check out my FAQ at for links to other mock exams You will find links to many good mock exams that add up to hundreds of questions. You can check out my second mock exam that contains 60 question at
If you think you have found an error:Please include which exam you are referring to, ie 1 or 2 (and maybe soon 3)
Read the questions carefully
I have tried to make the questions unambiguous (the meaning should be obvious), but make sure you have read what I have written now what you think I might have written. Thus if it says "Classes can be declared with the private modifier ", it means It is possible to declare a class with the private modifier and not that all classes in all situations can be declared as private. Each question may have one or more correct Answers.
Questions
Question 1)
Which of the following lines will compile without warning or error. 1) float f=1.3; 2) char c="a"; 3) byte b=257; 4) boolean b=null; 5) int i=10; Answer to Question 1
Question 2)
What will happen if you try to compile and run the following code public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(arguments[1]); } } 1) error Can't make static reference to void amethod. 2) error method main not correct 3) error array must include parameter 4) amethod must be declared with String Answer to Question 2
Question 3)
Which of the following will compile without error 1) import java.awt.*; package Mypackage; class Myclass {} 2) package MyPackage; import java.awt.*; class MyClass{} 3) /*This is a comment */ package MyPackage; import java.awt.*; class MyClass{}
Answer to Question 3
Question 4)
A byte can be of what size 1) -128 to 127 2) (-2 power 8 )-1 to 2 power 8 3) -255 to 256 4)depends on the particular implementation of the Java Virtual machine Answer to Question 4
Question 5)
What will be printed out if this code is run with the following command line? java myprog good morning public class myprog{ public static void main(String argv[]) { System.out.println(argv[2]) } } 1) myprog 2) good 3) morning 4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2" Answer to Question 5
Question 6)
Which of the following are keywords or reserved words in Java? 1) if 2) then 3) goto 4) while 5) case Answer to Question 6
Question 7)
Which of the following are legal identifiers 1) 2variable 2) variable2 3) _whatavariable 4) _3_ 5) $anothervar 6) #myvar Answer to Question 7
Question 8)
What will happen when you compile and run the following code? public class MyClass{ static int i; public static void main(String argv[]){ System.out.println(i);
} } 1) Error Variable i may not have been initialized 2) null 3) 1 4) 0 Answer to Question 8
Question 9)
What will happen if you try to compile and run the following code? public class Q { public static void main(String argv[]){ int anar[]=new int[]{1,2,3}; System.out.println(anar[1]); } } 1) 1 2) Error anar is referenced before it is initialized 3) 2 4) Error: size of array must be defined Answer to Question 9
Question 10)
What will happen if you try to compile and run the following code? public class Q { public static void main(String argv[]){ int anar[]=new int[5]; System.out.println(anar[0]); } } 1) Error: anar is referenced before it is initialized 2) null 3) 0 4) 5 Answer to Question 10
Question 11) 2) Error: ar is used before it is initialized 3) Error Mine must be declared abstract 4) IndexOutOfBoundes Error Answer to Question 11
Question 12)
What will be printed out if you attempt to compile and run the following code ? int i=1; switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); case 2: System.out.println("two"); default: System.out.println("default"); } 1) one 2) one, default 3) one, two, default 4) default Answer to Question 12
Question 13)
What will be printed out if you attempt to compile and run the following code? int i=9; switch (i) { default: System.out.println("default");
case 0: System.out.println("zero"); break; case 1: System.out.println("one"); case 2: System.out.println("two"); } 1) default 2) default, zero 3) error default clause not defined 4) no output displayed Answer to Question 13
Question 14)
Which of the following lines of code will compile without error 1) int i=0; if(i) { System.out.println("Hello"); } 2) boolean b=true; boolean b2=true; if(b==b2) { System.out.println("So true"); } 3) int i=1; int j=2; if(i==1|| j==2) 4) int i=1; int j=2; if(i==1 &| j==2) System.out.println("OK"); Answer to Question 14 System.out.println("OK");
Question 15)
What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?. 2 No such file found ,-1 3) No such file found, Doing finally, -1 4) 0 Answer to Question 15
Question 16)
Which of the following statements are true? 1) Methods cannot be overriden to be more private 2) Static methods cannot be overloaded 3) Private methods cannot be overloaded 4) An overloaded method cannot throw exceptions not checked in the base class Answer to Question 16
Question 17); } } Answer to Question 17
Question 18)
Which of the following statements are true?
Question 19)
You are browsing the Java HTML documentation for information on the java.awt.TextField component. You want to create Listener code to respond to focus events. The only Listener method listed is addActionListener. How do you go about finding out about Listener methods?
Question 20) 1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right 2) One button occupying the entire frame saying Hello 3) One button occupying the entire frame saying Bye 4) Two buttons at the top of the frame one saying Hello the other saying Bye Answer to Question 20
Question 21) 2) Value for i=2 value for j=1 3) Value for i=2 value for j=2 4) Value for i=3 value for j=1 Answer to Question 21
Question 22)
If g is a graphics instance what will the following code draw on the screen?. g.fillArc(45,90,50,50,90,180); 1) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise.
Question 23)
Which of the following methods can be legally inserted in place of the comment //Method Here ? class Base{ public void amethod(int i) { } public class Scope extends Base{ public static void main(String argv[]){ } //Method Here } 1) void amethod(int i) throws Exception {} 2) void amethod(long i)throws Exception {} 3) void amethod(long i){} 4) public void amethod(int i) throws Exception {} Answer to Question 23 }
Question 24)
Which of the following will output -4.0 1) System.out.println(Math.floor(-4.7)); 2) System.out.println(Math.round(-4.7)); 3) System.out.println(Math.ceil(-4.7)); 4) System.out.println(Math.min(-4.7)); Answer to Question 24
Question 25)
What will happen if you attempt to compile and run the following code? Integer ten=new Integer(10); Long nine=new Long (9); System.out.println(ten + nine); int i=1; System.out.println(i + ten); 1) 19 followed by 20 2) 19 followed by 11 3) Error: Can't convert java lang Integer 4) 10 followed by 1 Answer to Question 25
Question 26)
If you run the code below, what gets printed out? String s=new String("Bicycle");
int iBegin=1; char iEnd=3; System.out.println(s.substring(iBegin,iEnd)); 1) Bic 2) ic 3) icy 4) error: no method matching substring(int,char) Answer to Question 26
Question 27)
If you wanted to find out where the position of the letter v (ie return 2) in the string s containing "Java", which of the following could you use? 1) mid(2,s); 2) charAt(2); 3) s.indexOf('v'); 4) indexOf(s,'v'); Answer to Question 27
Question 28)
Given the following declarations
Question 29)
What is the result of the following operation? System.out.println(4 | 3); 1) 6 2) 0 3) 1 4) 7 Answer to Question 29
Question 30)
public class MyClass1 { public static void main(String argv[]){ } /*Modifier at XX */ class MyInner {} } What modifiers would be legal at XX in the above code? 1) public 2) private 3) static 4) friend Answer to Question 30
Question 31)
Question 32)
An Applet has its Layout Manager set to the default of FlowLayout. What code would be correct to change to another Layout Manager. 1) setLayoutManager(new GridLayout()); 2) setLayout(new GridLayout(2,2)); 3) setGridLayout(2,2); 4) setBorderLayout(); Answer to Question 32
Question 33)
Question 34)
You have created an applet that draws lines. You have overriden the paint operation and used the graphics drawLine method, and increase one of its parameters to multiple lines across the screen. When you first test the applet you find that the news lines are redrawn, but the old lines are erased. How can you modify your code to allow the old lines to stay on the screen instead of being cleared.
Question 35)" 2) Compilation and output the string "ello" 3) Compilation and output the string elloH 4) Compile time error Answer to Question 35
Question 36)
Given the following code, what test would you need to put in place of the comment line? /) 2) if(s.equals(s2) 3) if(s.equalsIgnoreCase(s2)) 4)if(s.noCaseMatch(s2)) Answer to Question 36
Question 37)
Given the following code
Question 38)
Question 39)
If you create a TextField with a constructor to set it to occupy 5 columns, what difference will it make if you use it with a proportional font (ie Times Roman) or a fixed pitch typewriter style font (Courier).
Question 40)); 2) On the line After //One put super(10); 3) On the line After //Two put super(10); 4) On the line After //Three put super(10); Answer to Question 40
Question 41)
Given the following code what will be output? 2) 20 and 40 3) 10 and 40 4) 10, and 20 Answer to Question 41
Question 42)++) 2) for (int i=0; i< ia.length(); i++) 3) for(int i=1; i < 4; i++) 4) for(int i=0; i< ia.length;i++) Answer to Question 42
Question 43) 2) 200 3) 100 followed by 200 4) 100 Answer to Question 43
Question 44)
What will the following code print out? public class Oct{ public static void main(String argv[]){ Oct o = new Oct(); o.amethod(); } public void amethod(){ int oi= 012;
System.out.println(oi); } } 1)12 2)012 3)10 4)10.0 Answer to Question 44
Question 45
What will happen when you try compiling and running this code? 2) An output of 99 3) An output of 198 4) An error at runtime Answer to Question 45
Question 46)
You need to create a class that will store a unique object elements. You do not need to sort these elements but they must be unique. What interface might be most suitable to meet this need? 1)Set 2)List 3)Map 4)Vector Answer to Question 46
Question 47)
Which of the following will successfully create an instance of the Vector class and add an element?
1) Vector v=new Vector(99); v[1]=99; 2) Vector v=new Vector(); v.addElement(99); 3) Vector v=new Vector(); v.add(99); 4 Vector v=new Vector(100); v.addElement("99"); Answer to Question 47
Question 48)
You have created a simple Frame and overridden the paint method as follows
Question 49)
What will be the result when you attempt to compile this program? public class Rand{ public static void main(String argv[]){ int iRand; iRand = Math.random(); System.out.println(iRand); } } 1) Compile time error referring to a cast problem 2) A random number between 1 and 10 3) A random number between 0 and 1 4) A compile time error about random being an unrecognised method Answer to Question 49
Question 50)
Given the following code
Question 51)
What will happen when you compile and run the following code? public class Scope{ private int i; public static void main(String argv[]){ Scope s = new Scope(); s.amethod(); }//End of main public static void amethod(){ System.out.println(i);
}//end of amethod }//End of class 1) A value of 0 will be printed out 2) Nothing will be printed out 3) A compile time error 4) A compile time error complaining of the scope of the variable i Answer to Question 51
Question
Question 53)
Which of the following can you perform using the File class? 1) Change the current directory 2) Return the name of the parent directory 3) Delete a file 4) Find if a file contains text or binary information Answer to Question 53
Question 54)
Which of the following code fragments will compile without error
Question 55)
You are concerned that your program may attempt to use more memory than is available. To avoid this situation you want to ensure that the Java Virtual Machine will run its garbage collection just before you start a complex routine. What can you do to be certain that garbage collection will run when you want .
Question 56)
You are using the GridBagLayout manager to place a series of buttons on a Frame. You want to make the size of one of the buttons bigger than the text it contains. Which of the following will allow you to do that?
Question 57)
Which of the following most closely describes a bitset collection?
Question1 1) Compile Error: Methods in Base not found 2) Compile Error: Unable to access protected method in base class 3) Compilation followed by the output "amethod" 4)Compile error: Superclass Class1.Base of class Class1.Class1 not found Answer to Question 58
Question 59)
What will happen when you attempt to compile and run the following code 2) Runtime error complaining that Base.amethod is private 3) Output of "Base.amethod" 4) Output of "Over.amethod" Answer to Question 59
Question 60)
You are creating an applet with a Frame that contains buttons. You are using the GridBagLayout manager and you have added Four buttons. At the moment the buttons appear in the centre of the frame from left to right. You want them to appear one on top of the other going down the screen. What is the most appropriate way to do this..
Answers
Answer 1)
Back to question 1) Objective 4.5).
Answer 2)
Back to question 2).
Answer 3)
back to Question 3) Objective 4.1) 2 and 3 will compile without error. 1 will not compile because any package declaration must come before any other code. Comments may appear anywhere.
Answer 4)
Back to question 4) Objective 4.5) 1) A byte is a signed 8 bit integer.
Answer 5)
Back to question 5) Objective 4.2).
Answer 6)
Back to question 6) Objective 1.5) 1) if 3) goto 4) while 5) case then is not a Java keyword, though if you are from a VB background you might think it was. Goto is a reserved word in Java.
Answer 7)
Back to Question 7) Objective 1.10).
Answer 8)
Back to Question 8) Objective 1.6) type of error.
Answer 9)
Back to Question 9) Objective 1.7,3.4).
Answer 10)
Back to question 10) Objective 1.7) 3) 0 Arrays are always initialised when they are created. As this is an array of ints it will be initalised with zeros.
Answer 11)
Back to Question 11) Objective 3.6 3) Error Mine must be declared abstract A class that contains an abstract method must itself be declared as abstract. It may however contain non abstract methods. Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.
Answer 12)
Back to Question 12) Objective 4.1) 3) one, two, default Code will continue to fall through a case statement until it encounters a break.
Answer 13)
Back to Question 13) Objective 4.1).
Answer 14)
Back to Question 14) Objective 4.2, 2,3 Example 1 will not compile because if must always test a boolean. This can catch out C/C++ programmers who expect the test to be for either 0 or not 0.
Answer 15)
Back to Question 15) Objective 4.5) 3) No such file found, doing finally, -1 The no such file found message is to be expected, however you can get caught out if you are not aware that the finally clause is almost always executed, even if there is a return statement.
Answer 16)
Answer 17)
Back to Question 17) Objective 5.8 (sort of)).
Answer 18)
Back to question 18) Objective 5 System.out.println( -1 System.out.println( 2 } } Java does not have a <<< operator. The operation 1 << 2 would output 4 Because of the way twos complement number representation works the unsigned right shift operation means a small shift in a negative number can return a very large value so the output of option 1 will be much larger than 10. The unsigned right shift places no significance on the leading bit that indicates the sign. For this shift the value 1 of the bit sign is replaced with a zero turning the result into a positive number for option 2. >>> 2); >>> 2); >> 1);
Answer 19)
Back to Question 19) Objective 1.1).
Answer 20)
Back to Question 20) Objective 10.4)
Answer 21)
Back to Question 21) Objective 4.4) 1,2 Value for i=1 Value for j=1 Value for i=2 Value for j=1 The statement continue outer causes the code to jump to the label outer and the for loop increments to the next number.
Answer 22)
Back to Question 22) Objective 9.5).
Answer 23)
Back to Question 23) Objective 4.7) 2,3 Options 1, & 4 will not compile as they attempt to throw Exceptions not declared in the base class. Because options 2 and 4 take a parameter of type long they represent overloading not overriding and there is no such limitations on overloaded methods.
Answer 24)
Back to Question 24) Objective 8.1) 3) System.out.println(Math.ceil(-4.7)); Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2 parameters.
Answer 25)
Back to Question 25 Objective 2.2.
Answer 26)
Back to Question 26) Objective 8".
Answer 27)
Back to Question 27) Objective 8.2) 3) s.indexOf('v'); charAt returns the letter at the position rather than searching for a letter and returning the position, MID is just to confuse the Basic Programmers, indexOf(s,'v'); is how some future VB/J++ nightmare hybrid, might perform such a calculation.
Answer 28)
Objective 2.2 Back to Question 28 1) s3=s1 + s2; Java does not allow operator overloading as in C++, but for the sake of convenience the + operator is overridden for strings.
Answer 29)
Back to Question 29) Objective 2.5).
Answer 30)
Back to Question 30 Objective 3.7) 1,2,3 public, private, static are all legal access modifiers for this inner class.
Answer 31)
Back to Question 31 Objective 9.6)");
Answer 32)
Back to Question 32) Objective 1.3).
Answer 33)
Back to Question 33) Objective 7();
Answer 34)
Back to Question 34) Objective 11.1).
Answer 35)
Back to Question 35 Objective 2.2 4) Compile time error The only operator overloading offered by java is the + sign for the String class. A char is a 16 bit integer and cannot be concatenated to a string with the + operator.
Answer 36)
Back to Question 36 Objective 8.2).
Answer 37)
Back to Question 37 Objective 9.1) 1) s.setBackground(Color.pink); For speakers of the more British spelt English note that there is no letter u in Color. Also the constants for colors are in lower case.
Answer 38)
Back to Question 38) Objective 13.1).
Answer 39)
Back to Question 39) Objective 9.2).
Answer 40)
Back to Question 40) Objective 5.8 3) On the line After //Two put super(10); Constructors can only be invoked from within constructors.
Answer 41)
Back to Question 41) Objective 2.8) 3) 10 and 40 when a parameter is passed to a method the method receives a copy of the value. The method can modify its value without affecting the original copy. Thus in this example when the value is printed out the method has not changed the value.
Answer 42)
Back to Question 42 Objective 3.3.
Answer 43)
Back to Question 43) Objective 3.6 (maybe).
Answer 44)
Back to Question 44 Objective 1.11).
Answer 45)
Back to Question 45 Objective 3.5) 1) Error at compile time The variable i is created at the level of amethod and will not be available inside the method multi.
Answer 46)
Back to Question 46 Java2 Objective 10.1).
Answer 47)
Back to Question 47 Java2 Objective 10.
Answer 48)
Objective 9.5) Back to Question 48.
Answer 49)
Back to Question 49) Objective 8.
Answer 50)
Objective 4.6) Back to question 50.
Answer 51)
Objective 3.10) Back to Question 51)
Answer 52)
Java2 Objective 8.2) Back to Question 52).
Answer 53)
Objective 13.1) Back to Question 53) 2) Return the name of the parent directory 3) Delete a file It is surprising that you can't change the current directory. It is not so surprising that you can't tell if a file contains text or binary information.
Answer 54)
Objective 9.5) Back to Question 54)).
Answer 55)
Objective 6.1) Back to Question 55).
Answer 56)
Java2 Objective 8.2) Back to Question 56).
Answer 57)
Java2 Objective 10.1) Back to Question 57).
Answer 58)
Back to Question 58) Objective 3.10).
Answer 59)
Back to Question 59) Objective 5.3) 4) Output of Over.amethod() The names of parameters to an overridden method are not important.
Answer 60)
Java2 Objective 8.2) Back to Question 60) | https://www.scribd.com/document/7234358/Mock-Exam-Jchq-Scjp-Exam-1 | CC-MAIN-2018-13 | refinedweb | 4,045 | 63.9 |
disable/enable tool without deleting/installing extensions?
- RafaŁ Buchner last edited by gferreira
As in the topic:
Is it possible to enable/disable the tool by code without deleting/installing the extension? Is there a list of available tools that are waiting to be activated or deactivated?
It would be wonderful for me :D
hello @RafaŁ-Buchner,
have a look at the
MyToolActivatorexample here.
does this solve your problem?
cheers!
- RafaŁ Buchner last edited by
delayed Thanks!
Btw: is it possible to load the list of tool objects, that are appearing in glyph window toolbar without opening glyph window?
right now in order to get those tools, I'm creating an observer for glyphWindowDidOpen event. So the list
self.toolsis created when the glyph window is opened for the first time. I'm doing it because I don't know the other way of getting tool objects than
getActiveEventTool.
def glyphWindowDidOpenCallback(self, info): toolNames = getToolOrder() currentToolName = getActiveEventTool().__class__.__name__ # populating self.tools list for toolName in toolNames: setActiveEventTool(toolName) toolObj = getActiveEventTool() self.tools += [toolObj] # Resetting the tool, to the one that was active before th loop setActiveEventTool(currTool) removeObserver(self, 'glyphWindowDidOpen')
Why do you need those tool objects? Im trying to understand your question ;) | https://forum.robofont.com/topic/665/disable-enable-tool-without-deleting-installing-extensions/1 | CC-MAIN-2019-35 | refinedweb | 204 | 51.14 |
CppSharp / Maintenance & Improvement tasks (Mohit Mohta)
Author: Mohit Mohta
About Me
Hello everyone, I’m Mohit Mohta, a junior year computer science undergraduate from IIT Indore, India. I got the opportunity to work with CppSharp project of Mono organisation under Google Summer of Code 2017 and hereby, I present my overall work experience and work accomplished this summer. Happy reading.
Summary
Google Summer of Code 2017 is about to end now, finally! Oh, what better could I’ve asked for this summer. Contributing to CppSharp project, as a student, taught me so many things which I could’ve learnt no where else at this pace. My project was to fix as many bugs and add as many enhancements as possible during the summer and I, with the help and guidance from my mentors, tried my best to do so!
The day it began
May 4th. I was overwhelmed to see that I’m selected as a student in the prestigious GSoC programme. But, there was a feeling of nervousness that was triggering some fears into me. CppSharp was actually the hardest of all the projects which I applied for. The codebase for CppSharp was large and it took me a while to get a hold of it. As soon as I got to know about my selection, I shared the news with my mentors, and also the feeling of nervousness. And my mentor assured me that there is nothing to worry about for they’ll be helping me throughout. I was little relieved to hear it and I planned of making full use of the month of May and start working straighway to make an early lead, and avoid any shortcomings in the time to follow.
Once I was done with setting up the basics, like generating solution and running tests etc, I started working on a beginner-level issue. I had been using Git from long but I never used it so extensively ever before. So, in the process, I started using TortoiseGit (Thanks to my mentor for introducing me to this) and now I could do things which I didn’t even know existed.
The daily chore
Eat, sleep code repeat. That was something I had heard a lot before from the routine of seniors, but never ever practiced. But now, my day started between 10-11 am in the morning and work would be in action till midnight 12, untill I felt sleepy, in the initial days. Ghosh, and even after giving so much time, output initially wasn’t much impressive, I remember. There was a time then when I started feeling demotivated about my capabilities and doubting myself but it was just this “never say die” kinda feeling which kept me up. But, with the ongoing efforts, with time, results started reflecting. Every Merge gave a sense of happiness that is tough to explain in words!
I remember being extremely silly at times, but thanks to my mentors, who took the pain of explaining things to me whenever I was stuck. My mentors used to assign me an issue to work upon and I’d to try it then. If I get stuck, they’d help me and if not, they’ll motivate me to maintain the flow. Those were good days, ofcourse with a set routine!
With time, the speed with which I could handle issues improved significantly. I could do more work in lesser time, but I simultaneously wasn’t getting myself proper sleep, and when my mentor came to know about it, he like a guardian adviced me to improve my schedule. I had the kind of discussions that one would have from his care-takers! Like he adviced me to take proper breaks, he even got an “eye-relax” software installed on my machine (which I use it even today) and curated my schedule, relived me from eye-strain. Not only me, many of my friends use these techniques now. Credits to my mentor.
All in all it was fun working this way.
Let me now begin with a description of the accomplished work during the summer.
Accomplished Tasks
All of my accepted PR’s can be easily viewed here
CppSharp has a huge codebase, and my work is like a small brick in this huge building. Besides, the list of the PRs at the link above, I would also like to present some of the outlines of my work here :
Added support for std::string
This was something that was long due to be added as one of the features of CppSharp. In order to achieve this, we divided it in the following sub-tasks : Firstly, we added a new project for C++ standard library symbols alongwith the required dependencies by adding the code for that in Lua. Then, we enabled export of those symbols in the code generator like,
var exporting = Context.ParserOptions.IsMicrosoftAbi ? "__declspec(dllexport) " : string.Empty; WriteLine($"template {exporting}{method.Visit(cppTypePrinter)};");
I also had to enable generation of the destructor in C++ standard library class
basic_string, like
case "basic_string": foreach (var method in @class.Methods.Where(m => !m.IsDestructor && m.OriginalName != "c_str")) method.ExplicitlyIgnore(); foreach (var specialization in @class.Specializations.Where(s => !s.Ignore)) { foreach (var method in specialization.Methods.Where(m => !m.IsDestructor && m.OriginalName != "c_str")) method.ExplicitlyIgnore(); ... ... } break;
then I updated CppSharp’s Clang parser code as previously it relied on C macros to convert
std::string to C strings, but now I could remove these macros and use C++ strings directly to take advantage of this support for
std::string, here.
And, lastly we just enabled the tests, and woo-hoo, support was ready!
This way CppSharp was ready for a new release. Felt so good - a release with my work in. :)
Fixed stack mismatch when bool param passed from C++ to C#
This initially seemed quite complicated to me because I always found delegates confusing and it had to do something with them. But, as I spent time on this, we broke it into simpler and even simpler code! Before we were doing manual marshaling of bool types to byte when needed, but I changed it to take the advantage of P/Invoke
MarshalAs(UnmanagedType.I1) attribute and in
VisitTypeDefNameDecl, I simply added,
if (functionType.ReturnType.Type.Desugar().IsPrimitiveType(PrimitiveType.Bool)) WriteLine("[return: MarshalAs(UnmanagedType.I1)]");
with which we could now fix the bug. See more about this here.
Added passage of VS Version selected at config time to build
Well, it was really important and was a cause of a few bugs that our users reported. Basically it was an issue when users had multiple VS versions installed and we did not know which one to use. In order to fix this, I just added the generation of a new file in Premake like,
buildconfig = io.open("../BuildConfig.cs", "w+") io.output(buildconfig) io.write("namespace CppSharp.Parser", "\n{\n ") io.write("public static class BuildConfig", "\n {\n ") io.write("public const string Choice = \"" .. action .. "\";\n") io.write(" }\n}") io.close(buildconfig)
And, then used this
buildConfig.Choice in
SetupMSVC, while setting parser options. This way we could now pass the VS version selected at config time to the build.
Added some switches / options in ParserOptions
Simple, but very important. Previously we hard-coded some of the language flags in the Clang native parser code instead of in managed code as options. This caused an issue when users needed to switch certain flags like RTTI or language version.
So, I moved processing of Clang arguments to managed code (
ParserOptions.cs) where they can be more easily changed.
For eg,
parserOptions.LanguageVersion = LanguageVersion.GNUPlusPlus11; and
parserOptions.EnableRtti = true;
Fixed code generation for functions with Typedef function pointers as parameters
Before, we never supported code generation for functions with typedef function pointers as parameters, for instance something like,
typedef int (typedefedFuncPtr)(Foo *a, Bar b); int DLL_API funcWithTypedefedFuncPtrAsParam(typedefedFuncPtr *func);
So, I had to change the dictionary for delegates from a function to a declaration and then create a method that would do the tasks of adding the delegates to the dictionary, mapping the respective decl (be it a method or a parameter) with its delegate definition. And, this way we finally could replace generic delegates with generated delegates as params (wherever needed) in the bindings. For more details one may refer this.
Unified code for handling named and anonymous delegates
This work served many objectives all together. For instance, we got rid of the anonymous delegate names, also merging common code for delegate generation meant delegate pass could now work for C++/CLI as well. Issues related to access specifiers and calling conventions were also addressed. We also got rid of delegate dictionary as a simple list could do the job now. My mentor Joao and Dimitar helped a lot with this work. Many thanks to them for this. One can see source for this here.
Fixed the generated C# when setting a field which is an array of complex objects
Users had reported issues with generated code for the same, for instance something like this,
struct ComplexArrayElement { bool BoolField; uint32_t IntField; float FloatField; }; #define ARRAY_LENGTH_MACRO 10 struct HasComplexArray { ComplexArrayElement complexArray[ARRAY_LENGTH_MACRO]; };
I can recall this was what I attempted in the initial days. And, it involved a lot of debugging and understanding. Though the final solution was sleek, just a change of a line.
Just added the following in
VisitArrayType,
if (@class != null && @class.IsRefType) { supportBefore.WriteLineIndent( "*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};", Context.ReturnVarName, array.Type, Helpers.InternalStruct, Context.ArgName, Helpers.InstanceIdentifier); }
Well, those were some glimpses of the accomplished work. However, I’d be glad if you see my accepted work here for the complete overview.
Future Work
I also tried my hands on a few tasks which I couldn’t accomplish. For example,
- A user was getting expection with boost::signals2 here. I tried fixing this but with little luck. So, finally I just compiled all my efforts for this issue in a doc and left it as a comment there on the issue. I would like to work on this again in future.
- Publishing the Linux and macOS binaries from Travis to GitHub : I gave this a try in my initial days and this is almost done. Just there were some issues with macOS dylibs which needs to be resolved before I can get this working. But, since this wasn’t much high on the priority list then, so I left it for later. And, would try to do it later on.
- Bind delegates with higher-level managed types : I attempted this one for a while, but then wasn’t confident enough about my knowledge of delegates so I left it and moved on to solve other issues. But, now I since I’ve already solved few issues that concern delegates, I feel much more confident. I’d love to give this a shot again after the summer. I just hope I get it right this time.
- I’d love to ask the maintainers for more work that I could do and keep learning this way, whenever I get enough time.
I wish, I had enough words to show my gratitude, but I’ll make an attempt anyways
Well, this might sound an extravaganza. But, let me acknowledge this fact that I was once very nervous about this project and now finally I’ve played my part in a better way than I anticipated. This would have never been possible if I wasn’t having my super cool mentor Joao Matos and the extremely helpful, Dimitar Dobrev (he is an active contributer to CppSharp) to help me out. And, of course thank you Kimon (he was working on CppSharp this summer as a fellow student). Kimon helped me with loads of motivation throughout and we became good friends with discussions varying from CppSharp’s code to Greek and Indian culture. So, birth to a cross-border friendship.
In the end, I’d like to thank Mono organisation and Google for letting me this opportunity to learn and providing me such a good platform to facilitate the process.
All of it, from top to bottom was a really amazing experience and I’m very happy to be a part of a project as great as CppSharp. What I did for CppSharp, is just a single brick in the huge building but still enough for a beginner like me to cherish!! :) | https://www.mono-project.com/community/google-summer-of-code/reports/2017/cppsharp-mohit-mohta/ | CC-MAIN-2020-50 | refinedweb | 2,077 | 62.27 |
mastablasta,if you want
hey mastablasta, if you want to add new voice commands you have to use for example this :
ear.addCommand("open hand", "python", "handopen")
i'll explain how is this composed :
"open hand" is the voice command you want to add, so after adding it MyRobotLab will "Listen" for that command too
then you need to add an action to do when that command is heard :
"hand open" : you are saying you want to execute "handopen" function when the "open hand" command is heard and "python" means that the "hand open" function is in python...
In fact the action you want to do, will look in this way in python :
def handopen():
put here what you want to do
In your case you did it in
In your case you did it in the right way !
Now you just have to create the "shakehand" function in python
ear.addCommand("shake hand", "python", "shakehand")
def shakehand():
print 'hey i'm using a new function !'
working!
Hello Allesandruino.
First of all thank you.
I did not expect it to be that simple. It´s working already (modified minimal.py), next I will try to make him answer new phrases.
So this way I just need to feed the script with whatever I want to say to him and what I want him to do/answer.
I enjoy MRL more and more!
Update: Listens and speaks as well!
markus got a very good
markus got a very good script, when you say something too many times, it react on that, might be usefull for U, gael put it in his inmoov2full3 script
script
I guess you mean the part with the "howdoyoudo" for example. Yeah really great! One day I will attach the paintball gun so he can start shooting around if I drive him nuts ;-)
Now things make more sense to me. I will try to do a small script myself these days. Just purchased a webcam so I will try the tracking today.
Do you have pics of your bot?
Do you have pics of your bot?
Pics
That´s all I have so far:
Next is the biceps but I don´t know about the servos, the 805 is very expensive over here. I was wondering if I can use this one as well:...
Only the size should be
Only the size should be fixed, the rest, it will work. | http://myrobotlab.org/content/vocabulary-solved | CC-MAIN-2021-10 | refinedweb | 403 | 87.25 |
Most discussion is on Typelevel Discord:
@Avasil Here are my notes! Again, massive credit to @rossabaker for doing all the real legwork on figuring this stuff out and benchmarking it. I basically just distilled and came up with some requirements.
So the raw mechanics of how you get the trace boils down to
new Throwable().getStackTrace(), which will give you an
Array[StackTraceElement]. That's where the easy part ends. Doing this is very expensive, and you need to do it eagerly inside the definition of
flatMap,
map,
delay, and
async (at a minimum). Naively implemented, this would result in a lot of overhead every time you call these functions.
So the idea is to not do it naively. If you call
getClass on the
Function1 passed to
flatMap/
map, you're going to get something which is reflective of the definition site of the function passed to the method in question. Note that there are some caveats with this:
val f: Int => Boolean = _ % 2 == 0 ioa.map(f) .map(f)
If you trace that with this technique, both
map calls will have the same "call site". I really think that's fine though, and arguably even more useful than the alternative. Anyway…
You need to figure out which stack frame entry actually represents the tru call site, and this is where things get very tricky with Cats Effect because the
f in question may be threaded through some other methods, such as monad transformers, libraries like fs2, etc. My spec suggests applying some heuristics to the name of the class you get from the
Function1 to take an educated guess, and then go with first best fit. Note that these heuristics can be somewhat expensive at runtime if you need them to be, because you're only doing it once!
Use the
Class as a cache key in a global (static) cache. Note that the size of this cache is bounded by the number of distinct call sites in the program, which is not really that many when you think about it. Cache misses are expensive, but they only happen once. Cache lookups are very, very fast. Note that
ConcurrentHashMap is heavily read-optimized. The spec references a "slug" mode to tracing, which would basically disable caching entirely. The reason to disable caching is so that you can capture more than one stack frame, which would allow us to give really robust traces when people really need to dig into things. Like we can say things like, "the last few constructors which generated this
IO were this
map, which had this stack trace, and this
flatMap, which had this other stack trace, etc". I imagine this being printed as like a nested bullet list, but hopefully you see where I'm going with this. Slug mode would have a lot of overhead and obviously would only be used when debugging in a dev environment, but that's still really useful! And giving these kinds of robust traces would eliminate the information loss that we would otherwise suffer from with just a single stack frame per call site.
Trace information should be stored in the
IO constructors themselves, which avoids the need to maintain a separate data structure representing a "backtrace". In a sense, it's abusing
ArrayStack to represent the trace indirectly. This is cool, but unfortunately
Map fusion completely defeats it. I note this in my spec, and I have hypothesized that map fusion in
IO is entirely pointless in practice and probably doesn't result in any measurable performance gains. Turning it off in
IO and then running a sophisticated benchmark suite (like fs2's or Monix's) on top of
IO without map fusion, and then again with, should be sufficient evidence to decide. If we can't remove map fusion, then (annoyingly!) we either need to have a separate nested stack structure inside of the
IOMap node, or we need to only trace the top-most fused
map. Either is probably okay, but not as nice as the unfused alternative. Needs measuring.
@Avasil The biggest problem with all this is configuration. You can't just thread its configuration through the runloop because some of these calls happen before the
IO is actually running. (for example,
val ioa = pure(42).flatMap(f), the
flatMap call site must run before the
IO starts executing) So that kicks out some things, unfortunately. ZIO does this nice thing where they have like a
notrace function or something (I can't remember what it's called) which presumably threads through the run loop, but there's no possible way it can disable tracing for
val examples like this one.
So my spec proposes a two-pronged solution: runloop-threaded configuration, with global defaults set by a system property. So you can still disable tracing entirely if you need to, but the default way you interact with it is via the runloop based configuration (which has nice lexical properties and a better API).
@Avasil Oh, one final bit of trickiness: you can't call
getClass on a thunked value in Scala and expect to get the class of the thunk, which is what you need. For example, to trace
delay or
>>. So you're probably going to need to implement a tiny helper in Java that has the class metadata to trick scalac into passing the
thunk along without evaluation. In other words, what scalac does when it sees the following:
def foo(s: => String) = bar(s) def bar(s: => String) = ...
bar gets the raw thunk that was passed to
foo, without re-wrapping. If you can define
bar in Java, then you can take that thunk (which will be of type
scala.Function0) and call
getClass on it without forcing. You don't have that option in Scala, since calling
s.getClass will force the thunk and give you the
Class of its contents.
| https://gitter.im/typelevel/cats-effect?at=5da441a480e62056e4009859 | CC-MAIN-2022-33 | refinedweb | 985 | 69.52 |
Introduction to Friend Function in C++
In C++, a friend function is a function which is declared using the friend keyword to achieve the encapsulation feature and can access the private and protected data members easily by using functions. To access the data in C++, friend functions is declared inside the body of the class, or inside the private and public section of the class. Let us see how to declare and use a Friend Function in C++ in this article.
A friend function while declaring is preceded with the “friend” keyword as shown here:
Syntax:
class <className>{
<few lines of code goes here>
private <variable>
protected <variable>
friend <returnDatatype> <functionName>(arguments list);
}
returnDatatype functionName(arguments list){
//function from which protected and private keywords
//can be accessed from as this is a friend method of className
}
As shown in the above code the friend function needs to be declared in the same class where the protected or private keyword has been declared for those data to be accessible outside the class. This function is allowed to be declared anywhere in the entire program just like a normal C++ method. The function definition does not require keywords like friends or any scope resolution operators.
Examples of Friend Function in C++ Program
Let us check out the working of the friend function a little better by taking a few examples below.
Example #1
Code:
/* C++ program which exhibits the working of friend function.*/
#include <iostream>
using namespace std;
class Weight
{
private:
int kilo;
public:
Weight(): kilo(0) { }
//Declaration of a friend function
friend int addWeight(Weight);
};
// Defining a friend function
int addWeight(Weight w)
{
//accessing private data from non-member function
w.kilo += 17;
return w.kilo;
}
int main()
{
Weight W;
cout<<"Weight: "<< addWeight(W);
return 0;
}
Output:
Here the friend function is addWeight() method which is declared inside the Weight class. Kilo is the private keyword declared inside the Weight method which is then accessed from the addWeight function because of it. This example was just to showcase the basic usage of a friend function although there is no real-time usage here. Let us now deep dive into some meaningful examples.
Example #2
Code:
#include <iostream>
using namespace std;
// Forward declaration
class SecondClass;
class FirstClass {
private:
int first_num;
public:
FirstClass(): first_num(12) { }
// Declaring a friend function
friend int divide(FirstClass, SecondClass);
};
class SecondClass {
private:
int sec_num;
public:
SecondClass(): sec_num(4) { }
// Another friend declaration
friend int divide(FirstClass , SecondClass);
};
// Function divide() is the friend function of classes FirstClass and SecondClass
// that accesses the member variables first_num and sec_num
int divide(FirstClass fnum, SecondClass snum)
{
return (fnum.first_num / snum.sec_num);
}
int main()
{
FirstClass fnum;
SecondClass snum;
cout<<"The value got by dividing first by second number: "<< divide(fnum, snum);
return 0;
}
Output:
In this example, both the classes FirstClass and SecondClass have divide() declared as a friend function. Hence this function can access the private variables data from both the class. Here divide() function is used to add private variables first_num and sec_num of two objects fnum and snum and returns its value to the main method.
For this to function properly, a forward declaration for SecondClass needs to be done as shown in the code because SecondClass is referenced within FirstClass using the program:
friend int divide(FirstClass , SecondClass);
Friend Class: There is a friend class just like the friend function. Friend class can also access both private and protected variables of the class as it is a friend to it.
Syntax:
class One{
<few lines of code here>
friend class Two;
};
class Two{
<few lines of code>
};
As shown above, class Two is a friend of class One. Hence class Two can access private and protected variables of class One. But class One cannot access protected or private variables of class Two because this is not a mutual friendship. For mutual friendship, we should declare it explicitly. In the same way, this friendship of the class is not inherited meaning that class Two shall not be a friend of the subclasses of class One even though it is a friend of class One.
Example #3
Code:
#include <iostream>
#include <string>
using namespace std;
class Perimeter{
int len,brd,perimeter,temp;
public:
Perimeter(int len,int brd):len(len),brd(brd)
{}
void calcPerimeter(){
temp = len + brd;
perimeter = 2 * temp;
}
friend class printClass;
};
class printClass{
public:
void printPerimeter(Perimeter a){
cout<<"Perimeter = "<<a.perimeter;
}
};
int main(){
Perimeter a(10,15);
a.calcPerimeter();
printClass p;
p.printPerimeter(a);
return 0;
}
Output:
In this code, we have 2 classes: Perimeter class which finds the perimeter by using the length and breadth values. Variables len, brd, perimeter, and temp are all private variables of the class perimeter. Hence we need to make printClass a friend of Perimeter class. This printClass uses the Perimeter value calculated in the function calcPerimeter() in the Perimeter class. As they all are private members, we have to make printPerimeter a friend of Perimeter class. Once this is done, we have to create an object in the main class to calculate the perimeter and pass this object to the printPerimeter class to display the Perimeter.
Features of Friend Function in C++
- The method and the class to which it has been declared as a friend need not be the same.
- Since it is not in the scope of the respective class, it cannot be called by using its object.
- It can also be called just like a normal method even without usage of the object.
- It can only directly access the member names by using its object name and dot membership operator along with its member name.
- There is no restriction as it is allowed to be declared in either private or the public part.
Conclusion
Considering all the above-discussed features and the examples of friend function in C++ one must also be careful while using a friend’s functions with numerous functions and external classes as it may lessen the importance of encapsulation of different classes in object-oriented programming. Hence it can be both a boon and a bane to the programmer.
Recommended Article
This is a guide to Friend Function in C++. Here we discuss the Introduction to Friend function in C++ and its Examples along with Code Implementation and Output. you can also go through our suggested articles to learn more – | https://www.educba.com/friend-function-in-c-plus-plus/ | CC-MAIN-2020-29 | refinedweb | 1,055 | 56.59 |
bratty_programmer, on 22 July 2011 - 03:19 AM, said:
I am given two arrays with numbers and i have to multiply them both to get the the third array which is the answer. My code is working but for some reason it's not multiplying the numbers correctly. The programme tends to give me the wrong answers for the third array. Maybe someone can take a look at it and guide me on what i am doing wrong please. The code is at the bottom
#include <stdio.h> main(){ int array1[6]={4,20,55,24,60,10}; int array2[6]={2,30,10,12,20,33}; int array3[6]; printf("\n\nArray one(1):\t"); for (int i=0;i<6;i++){ printf("%d\t",array1[i]); } printf("\n\nArray two(2):\t"); for (int j=0;j<6;j++){ printf("%d\t",array2[j]); } printf("\n\n------------------------------------------------------------"); printf("\nResult of multiplying Array1 by Array2:"); printf("\n\nArray three(3):\t"); //for (i=0;i<6;i++); //for (j=0;j<6;j++); for(int k=0;k<6;k++){ array3[k]=(array1[i]*array2[j]); printf("%d\t",array3[k]); } }
This post has been edited by macosxnerd101: 21 July 2011 - 08:23 PM
Reason for edit:: Please use code tags | http://www.dreamincode.net/forums/topic/240515-multiplying-arrays/ | CC-MAIN-2018-22 | refinedweb | 212 | 64.75 |
27 November 2008 12:07 [Source: ICIS news]
MOSCOW (ICIS news)--Belarussian Potash Co (BPC) cut its potash exports by 700,000 tonnes in the fourth quarter, the company said in a statement released on a Thursday.
"The [economic] crisis affected us and our clients," BPC spokesman Vladimir Tafrov said in the statement.
BPC is co-owned by the state-owned Belaruskali and Russian potash producer Uralkali.
Belaruskali is controlled by the ?xml:namespace>
Belaruskali aimed to raise its domestic potash supplies by 400,000 tonnes in the fourth quarter, Tafrov said in the statement.
Belaruskali expected its annual potash output to reach 8.3m tonnes this year, and Uralkali planned to produce 4.9m tonnes of potash in 2008, according to the BPC statement.
Last month, Uralkali cut its fourth-quarter potash production by 500,000. | http://www.icis.com/Articles/2008/11/27/9174939/belarus-potash-co-cuts-q4-exports-700000-tonnes.html | CC-MAIN-2013-20 | refinedweb | 137 | 74.19 |
Now I want to add a third node using an Arduino Yun Generation 1, but I can only barely get it working.
One problem is that the header pins IO10-13 in the ATmega324U are not mapped to SPI. The only place I can access the SPI lines is from the ICSP header.
A second problem is that for SS I am using port 9 because for some reason IO 10 (the default SS on the RFM69 library) doesn't work (even though this pin seems to be totally free on the Yun (i.e. nothing to do with SPI SS)).
Here is the schematic for the Yun: ... ematic.pdf
And this is the reference one for Uno: ... ematic.pdf
To solve that problem I just subclassed the lib like so:
RFM69_YUN.h
Code: Select all
#include <RFM69.h> #define RF69_SPI_CS_YUN 9 class RFM69_YUN : public RFM69 { public: RFM69_YUN(uint8_t slaveSelectPin=RF69_SPI_CS_YUN, uint8_t interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, uint8_t interruptNum=RF69_IRQ_NUM) : RFM69(slaveSelectPin, interruptPin, isRFM69HW, interruptNum) { } };
The problem seem to be that the code running on the ATmega32U is running so slow that radio.sendWithRetry is not able to receive the ACK. Here is some example debug output from both nodes. Node 1 is the Yun and Node 2 is a plain old Uno (FYR I have the same test between 2 Unos and ACK works perfectly):
Node 1 debug output
Code: Select all
sending to node 2, message [HELLOW WORLD] no ACK received TX LED sending to node 2, message [HELLO WORLD] no ACK received TX LED sending to node 2, message [HELLO WORLD] no ACK received TX LED
Code: Select all
Node 2 ready received from node 1, message [HELLOW WORLD], RSSI -25 ACK sent received from node 1, message [HELLO WORLD], RSSI -32 ACK sent received from node 1, message [HELLO WORLD], RSSI -25 ACK sent received from node 1, message [HELLO WORLD], RSSI -20 ACK sent
I think the main reason is that it all seems to be running VERY slow on the ATmega32U. From the time I call radio.sendWithRetry from the YUN side, it takes about 1 second or more to see the LED on Node 2. I'm running the demo code from the RFM69 tutorial.
The main question is, does anyone have any idea why the code seems so slow on the ATmega32U? I have a guess that it's something to do with SPI conflicting somehow but looking at the schematics it seems that only
TIA,
ALex | https://forum.sparkfun.com/viewtopic.php?f=13&t=48345&p=200280 | CC-MAIN-2019-09 | refinedweb | 415 | 74.42 |
This is the eighth lesson in a series introducing 10-year-olds to programming through Minecraft. Learn more here.
One of the most important topics Java we need to understand in for modding Minecraft is classes and how to use them.
A class is a definition (or blueprint) for an object. It is a grouping of variables (called fields) and methods.
public class Block { private String unlocalizedName; public final int blockID; /* Number of hits it takes to break a block. */ public float blockHardness; public Block(int id, Material par2Material) { .... } protected void initializeBlock() { ... } public void setStepSound(StepSound sound) { ... } }
This class has:
3 fields:
unlocalizedName,
blockID, and
blockHardness. Fields are simply variables within a class.
3 methods:
Block(which is a special method called a constructor since it has the same name as the
class),
initializeBlock, and
setStepSound. A method is a group of statements that perform a specific task. The variables listed within parentheses after a method name are called parameters.
Creating Objects
To create an object (an instance of a class), we use the
new keyword.
Block myBlock = new Block(...);
We can then access methods and fields that are part of the class definition.
myBlock.setStepSound(new StepSoundSand(...)); myBlock.blockHardness = 4.0f;
Note that we can only access methods and fields that are marked
public. We will talk more about visibility later.
Inheritance
Let's say we have a
Block class that can already perform a bunch of tasks. We might want to create a special type of snow block that melts if a player stands on it for too long.
Since we don't want to copy all the code we have in
Block into our new
BlockSnow class, we can have
BlockSnow extend
Block. (We could also say that
BlockSnow is derived from
Block or that
BlockSnow inherits from
Block).
What this means is that we automatically get all of the functionality of
Block in
BlockSnow and we can add some new functionality as well.
public class BlockSnow extends Block { public void melt() { ... } } BlockSnow blockOfSnow = new BlockSnow(); blockOfSnow.setStepSound(...); blockOfSnow.melt(...);
Note that although we didn't include
setStepSound in our
BlockSnow class, we can still call that method because it exists in the parent class (
Block). | http://www.jedidja.ca/classes-and-objects-part-one/ | CC-MAIN-2018-05 | refinedweb | 369 | 66.64 |
Recently, I was forced to reconsider my stance on Postel’s law again. I was provided an “XML“ feed that was not well-formed, and did not have the luxury of simply rejecting it due to the multiple well-formedness violations it contained.
Side note: it is a pet peeve of mine when people make quote signs in the air.
Specifically, the “XML” contained several characters that XML 1.0 explicitly forbids, like x008 and x016.. Instead of throwing an exception, as done in the Customized XML Writer Creation topic on MSDN, I was forced to process the “XML” and write portions of it to a new stream, ensuring that it is well-formed. The solution? A custom XmlWriter that overrides the calls to WriteString. The overridden call to WriteString uses a regular expression to determine if the text contains any of the characters not in the Char production in XML 1.0. If any character is encountered that is not within that production, it is escaped with a character entity.
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
namespace XmlAdvice
{
/// <summary>
/// An XmlTextWriter that strives to ensure the generated markup is well-formed.
/// </summary>
public class XmlWellFormedTextWriter : System.Xml.XmlTextWriter
{
Regex _regex = new Regex(@“[\x01-\x08\x0B-\x0C\x0E-\x1F\xD800-\xDFFF\xFFFE-\xFFFF]”);
/// <summary>
/// Creates an instance of the XmlWellFormedTextWriter
/// </summary>
/// <param name=”stream”>The stream to write to.</param>
/// <param name=”encoding”>The encoding for the stream (typically UTF8).</param>
public XmlWellFormedTextWriter(Stream stream, Encoding encoding) : base(stream,encoding)
{
}
/// <summary>
/// Replaces any occurrence of characters not within the production
/// #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
/// with a character entity.
/// </summary>
/// <param name=”text”>The text to write to the output.</param>
public override void WriteString(string text)
{
Match m = _regex.Match(text);
int charCount = text.Length – 1;
int idx = 0;
if(m.Success)
{
while(m.Success)
{
base.WriteString(text.Substring(idx,m.Index – idx));
WriteCharEntity(text[m.Index]);
idx = m.Index + 1;
m = m.NextMatch();
}
if(idx < charCount)
{
base.WriteString(text.Substring(idx, charCount – idx));
}
}
else
{
base.WriteString(text);
}
}
}
}
Update: Dare Obasanjo corrected me. In fact, this example does not assist in creating a well-formed XML document, instead it postpones the problem until the XML document is parsed again.
The XML you are generating isn’t well-formed. Those characters are invalid in XML even if escaped as character entities. All you’ve done is made it possible for the XmlTextReader to consume them when the Normalization (and thus character checking) property is set to false.
Then shouldn’t the WriteCharEntity call throw an XmlException according to the same production?
XmlTextWriter doesn’t do character checking. As mentioned in my post at
"The XmlTextWriter writes Unicode characters in the range 0x0 to 0x20, and the characters 0xFFFE and 0xFFFF, which are not XML characters. "
lightbulb just went off.
This is what I had pointed out in the post you referenced,
The difference is that I had interpreted this statement as "the WriteString method does not attempt to escape character entities", not as "the WriteCharEntity method does not perform checks on character ranges."
I was, admittedly, confused on the concept of that the presence of x0A is considered the same as referring to it with the
character entity. I had been taking advantage of the very issue I was trying to avoid, just changing the semantics of the problem. | https://blogs.msdn.microsoft.com/kaevans/2004/04/19/postel-again-writing-well-formed-xml-with-xmlwriter/ | CC-MAIN-2017-39 | refinedweb | 572 | 50.02 |
Revision as of 03:28, 21 December 2008
Guidelines for cmake
More and more projects are moving to cmake, especially with KDE4 making the jump. It seems like it is time to start collecting cmake best practices for generating Fedora RPMS using cmake
RPM Macros
<!-- /etc/rpm/macros.cmake: --> %_cmake_lib_suffix64 -DLIB_SUFFIX=64 %__cmake %{_bindir}/cmake %cmake \ CFLAGS="${CFLAGS:-%optflags}" ; export CFLAGS ; \ CXXFLAGS="${CXXFLAGS:-%optflags}" ; export CXXFLAGS ; \ FFLAGS="${FFLAGS:-%optflags}" ; export FFLAGS ; \ %__cmake \\\ %if "%{?_lib}" == "lib64" \ %{?_cmake_lib_suffix64} \\\ %endif \ -DCMAKE_INSTALL_PREFIX:PATH=%{_prefix} \\\ -DBUILD_SHARED_LIBS:BOOL=ON
Specfile Usage
%build %cmake . make VERBOSE=1 %{?_smp_mflags} %install rm -rf $RPM_BUILD_ROOT make install DESTDIR=$RPM_BUILD_ROOT %check ctest
Notes
NOTE:
-DCMAKE_SKIP_RPATH:BOOL=ON. With recent cmake-2.4, it should not be used. This cmake version handles. E.g. installing a target with
INSTALL(FILES ... RENAME ...) will not strip rpaths; in this case
INSTALL(TARGETS ...) must be used in combination with changing the
OUTPUT_NAME property.
NOTE: The proposed
%cmake macro defines
-DLIB_SUFFIX=64 on 64bit platforms. Not all packages handle this gracefully. The kdesvn package, for example, included cmake files taken from the KDE upstream that needed to be patched for this to work properly for all files (esp. .la files for loadable KDE modules). You might want to see the patch included in the kdesvn .src.rpm for example changes.
NOTE: cmake has good documentation in two places: | https://www.fedoraproject.org/w/index.php?title=Packaging:Cmake&diff=prev&oldid=66679 | CC-MAIN-2022-40 | refinedweb | 222 | 60.51 |
Has support for optional parameters which makes COM interoperability much easy.
With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
Has the WITH construct which is not in C#.
The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#:
XML documentation is generated from source code but this is now been incorporated in Whidbey.
Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
Use of this statement makes unmanaged resource disposal simple..
How to test your browser support..
System.Net.Mail - FAQs
AM new in Programing would like to learn C# .net where should i start? | http://www.c-sharpcorner.com/Blogs/5335/advantages-of-VB-Net-C-Sharp-net.aspx | crawl-003 | refinedweb | 146 | 61.33 |
24573/listener-currently-service-requested-connect-descriptor
We have an application running locally where we're experiencing the following error:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
I've tested the connection using TNSPing which resolved correctly and I tried SQLPlus to try connecting, which failed with the same error as above. I used this syntax for SQLPlus:
sqlplus username/password@addressname[or host name]
We have verified that:
We don't know of any changes that were made to this environment. Anything else we can test?
I had this issue and the fix was to make sure in tnsnames.ora the SERVICE_NAME is a valid service name in your database. To find out valid service names, you can use the following query in oracle:
select value from v$parameter where name='service_names'
Once I updated tnsnames.ora to:
TEST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = *<validhost>*)(PORT = *<validport>*))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = *<servicenamefromDB>*)
)
)
then I ran:
sqlplus user@TEST
Success! The listener is basically telling you that whatever service_name you are using isn't a valid service according to the DB
NOT operator displays a record when the ...READ MORE
The reasons are as follows:
The MySQL extension:
Does ...READ MORE
I assume you want to know the ...READ MORE
To count the number of records in ...READ MORE
You can use AWS Data pipeline to ...READ MORE
down vote
Had a similar task of exporting ...READ MORE
Follow the below steps and procedures:
Prerequisites
Must have ...READ MORE
Please check the below-mentioned syntax and commands:
To ...READ MORE
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
...READ MORE
Reference the System.Web dll in your model ...READ MORE
OR | https://www.edureka.co/community/24573/listener-currently-service-requested-connect-descriptor?show=24576 | CC-MAIN-2019-35 | refinedweb | 304 | 58.18 |
2013-11-22 01:10 PM
Hey folks,
I'm an old hat at shell scripting, and I have a need to write some scripts in Python against the netapp API.
I'm really new to coding in such an object oriented fashion - last time I did it was college 10 years ago.
I've got a script based on an online example partially working, and I see how it makes some API calls, but I can't figure out how to make calls other than what was in the example. Here is my program in entirety:
import sys
sys.path.append("/lib/python3.2/NetApp")
from NaServer import *
from NaElement import *
def print_usage():
print ("Usage: hello_ontapi.py <filer> <user> <password> \n")
print ("<filer> -- Filer name\n")
print ("<user> -- User name\n")
print ("<password> -- Password\n")
sys.exit (1)
args = len(sys.argv) - 1
if(args < 3):
print_usage()
filer = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
s = NaServer(filer, 1, 6)
s.set_server_type("Filer")
s.set_admin_user(user, password)
s.set_transport_type("HTTPS")
output = s.invoke("system-get-version")
if(output.results_errno() != 0):
r = output.results_reason()
print("Failed: \n" + str(r))
else :
r = output.child_get_string("version")
print (r + "\n")
cmd = NaElement("volume-list-info")
cmd1 = NaElement("snapshot-list-info")
ret = s.invoke_elem(cmd)
ret1 = s.invoke_elem(cmd1)
volumes = ret.child_get("volumes")
snaps = ret1.child_get("snapshots")
for vol in volumes.children_get():
print(vol.child_get_string("name"))
print(vol.child_get_int("size-total"))
print(vol.child_get_string("mirror-status"))
print(vol.child_get_int("snapshot-percent-reserved"))
for snap in snaps.children_get(volume=vol.child_get_string("name")):
print(snap.child_get_string("name"))
The problem comes up when it tries to invoke the snapshots call. I get pretty output if we comment out the last two lines of code - it lists all volumes and sizes. I can't get it to list the snapshots in those volumes.
What am I doing wrong?
Solved! SEE THE SOLUTION
2013-11-24 10:31 PM
Hi Timothy,
Nice to know that you are trying out our Python NMSDK.
We will do our best to help you with this.
There are a lot of resources which you can refer to get an idea of how to use the Python NMSDK.
First, you can go through the SDK_help.htm file (available inside NMSDK zip) which gives you detailed information on how to use the NMSDK. More specifically, you can refer to the "NetApp Manageability SDK > Programming Guide > SDK Core APIs > Python Core APIs" Section of SDK_help.htm to know the Core APIs which you can use for setting connection with NetApp storage systems and manage input and output elements.
Secondly, you can see the sample codes to get an idea of how to invoke Data ONTAP APIs. The Python sample codes can be found under "<nmsdk root directory>/src/sample/Data_ONTAP/Python/" directory. For this particular case (snapshot list), you can check the snapman.py sample code under the same directory.
Apart from these recourses, NMSDK provides a GUI utility named ZExplore Development Interface (ZEDI) which aims to develop the code for you in a automated manner. You can get zexplore.exe (for Windows) and zexplore.jar (for all platforms with jre 1.6 or higher) under "<nmsdk root directory>/zedi/" directory. Using this tool, you just need to select the Data ONTAP API and choose the programming language - the code will be instantly developed by ZEDI. For details on how to use ZEDI, you can go through the following links:
* 5 min demo videos:
video 1.
video 2.
* ZEDI User Guide:
Please feel free to revert to us if you still face any issue using NMSDK.
Regards,
Subhabrata Sen.
2013-11-26 10:30 AM
Thanks, Subhabrata, but that doesn't answer my question.
I appreciate the resource suggestions, but what I'm really looking for is an explanation of why the call to volume-list-info is working but the call to snapshot-list-info is not.
Can you tell?
2013-11-26 11:10 PM
Hi Timothy,
The line
for snap in snaps.children_get(volume=vol.child_get_string("name")):
is the reason of not getting any snapshot.
children_get() does not take any parameter.
However, if you just remove the parameter volume=vol.child_get_string("name") from children_get(), you will get list all the snapshots, and the same list will be printed for each volume obtained from the volume-list-info API output.
From your code, I can assume that for each volume, you want to print the snapshots within the volume.
In such a case, you need to invoke snapshot-list-info API for each volume.
You need to modify your code to something as shown below [not showing the first few lines where you print the version string from system-get-version API, I am just starting from the volume-list-info API part]:
cmd = NaElement("volume-list-info")
ret = s.invoke_elem(cmd)
volumes = ret.child_get("volumes")
for vol in volumes.children_get():
print (vol.child_get_string("name"))
print (vol.child_get_int("size-total"))
print (vol.child_get_string("mirror-status"))
print (vol.child_get_int("snapshot-percent-reserved"))
cmd1 = NaElement("snapshot-list-info")
cmd1.child_add_string("volume", vol.child_get_string("name")) # This is where you set the volume name
ret1 = s.invoke_elem(cmd1)
snaps = ret1.child_get("snapshots")
for snap in snaps.children_get():
print(snap.child_get_string("name"))
Please feel free to let me know if it solved the problem.
Regards,
Subhabrata Sen. | http://community.netapp.com/t5/Software-Development-Kit-SDK-and-API-Discussions/Help-a-Python-newb/td-p/6646 | CC-MAIN-2017-30 | refinedweb | 892 | 69.07 |
A selection sort program is used to demonstrate the profiling process. A selection sort is a general-purpose sort that is a variation of an exchange sort. Basically, this sort passes through a list of elements and finds the index (location) of the smallest (least) element. It exchanges the data at this index with the data stored in the first element of the list. It then repeats the selection process with the remaining list to find the second smallest element, and exchanges the data at this index with the data stored in the second element of the list. The process is repeated until the list is ordered.
There are numerous ways to code a selection sort. Below is a C++ version of this sort.
File : ss.cxx #include using namespace std; // Function prototypes void Get_Data ( int [], int ); void Display ( int [], int ); + void Do_S_Sort ( int [], int ); int Find_Least( const int [], int, int ); int Compare ( const int & , const int & ); void Swap ( int &, int & ); int 10 main( ) { const int max = 10; int List[max]; Get_Data ( List, max ); // Obtain data cout << "Initial list" << endl; + Display ( List, max ); // Show it Do_S_Sort( List, max ); // Sort it cout << "Sorted list" << endl; Display ( List, max ); // Show it again return 0; 20 } // Obtain data to sort from standard input void Get_Data(int a[], int n) { cout << "Please enter " << n << " integers" << endl; + for(int i=0; i < n; ++i) cin >> a[i]; } // Display the current contents of list void 30 Display(int a[], int n) { for(int i=0; i < n; ++i) cout << " " << a[i]; cout << endl; } + // Do the Selection Sort, Display after each pass void Do_S_Sort( int a[], int n ){ int index; for (int i=0; i < n-1; ++i){ 40 index=Find_Least( a, i, n ); if ( i != index ) Swap( a[i], a[index] ); cout << "After pass " << i+1 << " : "; Display( a, n ); + } } // Find the index of the least element in list int Find_Least( const int a[], int start, int stop ){ 50 int Index_of_Least = start; for (int i=start+1; i < stop; ++i ) if ( Compare(a[i], a[Index_of_Least]) ) Index_of_Least = i; return Index_of_Least; + } // Compare two data elements int Compare( const int &a, const int &b ){ return ( a < b ); 60 } // Exchange two data elements void Swap( int &a, int &b ){ int temp; + temp = a; a = b; b = temp; }
As shown, six functions are used to implement the sort
At first glance, using so many functions for such a simple algorithm may seem to be overkill. However, coding some statements (such as the compare in line 52) as a function call will facilitate referencing when generating profile information with gprof .
A good portion of the work done by the selection sort is actually performed by the Find_Least function (see line 49). This function is passed the list and two integer values. The first integer value is the starting point for the search through the remainder of the list. The second value is the size of the list (which in this case reflects its end or stopping point). This function works by storing, in the variable Index_of_Least , the index of the element having the smallest value. Initially, this is the index of the current start of the list (see line 50). It then uses a for loop to pass through the reminder of the list, checking each location against the current smallest value to determine if it has found a lesser value. Each check is carried out by the Compare function. If the value is less, the index (not the value) of the location is stored. When the loop finishes, the index of the element with the smallest value is returned to the calling function. If the returned index is not the index of the current head of list, the two values are exchanged by calling the Swap function. If the current value is already in order, no exchange is needed.
Programs and Processes
Processing Environment
Using Processes
Primitive Communications
Pipes
Message Queues
Semaphores
Shared Memory
Remote Procedure Calls
Sockets
Threads
Appendix A. Using Linux Manual Pages
Appendix B. UNIX Error Messages
Appendix C. RPC Syntax Diagrams
Appendix D. Profiling Programs | https://flylib.com/books/en/1.23.1/d2_sample_program_for_profiling.html | CC-MAIN-2020-24 | refinedweb | 678 | 63.73 |
else
By the end of this lab, you should have submitted the
lab01
assignment using the command
submit lab01.
This lab is due by 11:59pm on 06/26/2014.
Here is a lab01.py starter file for this lab.
Sometimes, you can append certain "flags" on the command line to inspect your code further. Here are a few useful ones that'll come in handy this semester. If you want to learn more about other python flags, you can look at the documentation.
python3 FILE_NAME
-i: The
-ioption runs your Python script, and throws you into an interactive session. If you omit the
-ioption, Python will only run your script. See the next section regarding interactive sessions to learn more!
python3 -i FILE_NAME
-m doctest: Using
-m doctestoptionflag signifies a verbose option. You can append this flag to the
-m doctestflag to be notified of all results (both failing and passing tests).
python3 -m doctest -v FILE_NAME >>> 11 / 3 3.6666666666666665
Floor Division (integer division):
>>> 1 // 4 0 >>> 4 // 2 2 >>> 11 // 3 3
Modulo (similar to a remainder):
>>> 1 % 4 1 >>> 4 % 2 0 >>> 11 % 3 2
Notice that we can check whether
x is divisible by
y by checking
if
x % y == 0.)
Failing to use parentheses is one of the easiest ways for you to break your program - it is very easy to misunderstand how Python will understand your expression if you don't have parentheses.
Boolean operators, like arithmetic operators, have an order of operation:
nothas the highest priority
and
orhas the lowest priority
In Python,
and and
or are examples of short-circuiting operators.
Consider the following code:
10 or 1 / 0 != 1
Notice that if we just evaluate
1 / 0, Python will raise an error,
stopping evaluation altogether!
However, the original line of code will not cause any errors — in
fact, it will evaluate to
10..
>>> True and 1 / 0 == 1 and False ______ZeroDivisionError >>> True or 1 / 0 == 1 or False ______True >>> True and "Anything" ______'Anything' >>> False or "Something" ______'Something' >>> 1 and 3 and 6 and 10 and 15 ______15 >>> "" or 0 or False or "Andrew and Rohin" or "The TA's" or 1 / 0 ______'Andrew and Rohin'
The following snippet of code doesn't work! Figure out what is wrong and fix the bugs.
def both_positive(x, y): """ Returns True if both x and y are positive and False otherwise. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True >>> both_positive(0, 0) False """ return x and y > 0
The line
x and y > 0 is incorrect. It should be
return x > 0 and y > 0:
The original line will check that two things are true:
x
y > 0
When will
x be considered True? In Python, any number that is not 0
is considered True. Thus, the first doctest will fail:
x = -1
and
-1 != 0, and
y = 1 > 0, so both clauses are True.
Disneyland is having a special where they give discounts for
grandparents accompanying their grandchildren. Help Disneyland figure
out when the discount should be given. Define a function
gets_discount that takes two numbers as input (representing the two
ages) and returns
True if one of them is a senior citizen (age at
least 65) and the other is a child (age no more than 12). You should
not use
if in your solution.
def gets_discount(x, y): """Returns True if this is a combination of a senior citizen and a child, False otherwise. >>> gets_discount(65, 12) True >>> gets_discount(9, 70) True >>> gets_discount(40, 45) False >>> gets_discount(40, 75) False >>> gets_discount(65, 13) False >>> gets_discount(7, 9) False >>> gets_discount(73, 77) False >>> gets_discount(80, 13) False >>> gets_discount(10, 25) False """ "*** YOUR CODE HERE ***"
def gets_discount(x, y): return (x <= 12 and y >= 65) or (x >= 65 and y <= 12)
Define a function
is_factor that checks whether its first argument
is a factor of its second argument. We will assume that
0 is not a
factor of any number but any non-zero number is a factor of
0.
You should not use
if in your solution.
def is_factor(x, y): """Returns True if x is a factor of y, False otherwise. >>> is_factor(3, 6) True >>> is_factor(4, 10) False >>> is_factor(0, 5) False >>> is_factor(0, 0) False >>> is_factor(10, 2) False """ "*** YOUR CODE HERE ***"
def is_factor(x, y): return x != 0 and y % x == 0
Predict what Python will print in response to each of these expressions. Then try it and make sure your answer was correct, or if not, that you understand why!
>>> z, y = 1, 2 >>> print(z) ______1 >>> def square(x): ... print(x * x) # Hit enter twice ... >>> a = square(2) ______4 >>> print(a) ______None >>> def square(y): ... return y * y # Hit enter twice ... >>> a = square(2) >>> print(a) ______4
>>> a, b = 10, 6 >>> if a == 4: ... 6 ... elif b >= 4: ... 6 + 7 + a ... else: ... 25 ... ______23
else
Consider the following function:
>>> def abs(x): ... if x >= 0: ... return x ... else: ... return -x ...
It is correct to rewrite
abs in the following way:
>>> def abs(x): ... if x >= 0: ... return x ... return -x # missing else statement! ...
This omitting the
else only works, omitting the
else will make your code more concise —
however, if you find that it makes your code harder to read, by all
means use an
else statement.
The following snippet of code doesn't work! Figure out what is wrong and fix the bugs.
def compare(a, b): """ Compares if a and b are equal. >>> compare(4, 2) 'not equal' >>> compare(4, 4) 'equal' """ if a = b: return 'equal' return 'not equal'
The line
a = b will cause a
SyntaxError. Instead, it should be
if a == b:
>>> ______ # Q4 >>> n = 2 >>> def exp_decay(n): ... if n % 2 != 0: ... return ... while n > 0: ... print(n) ... n = n // 2 ... >>> exp_decay(64) ______64 32 16 8 4 2 1 >>> exp_decay(5) ______# No output
Define a function
factors(n) which takes in a number,
n, and
prints out all of the numbers that divide
n evenly. For example, a
call with
n = 20 should result as follows:
def factors(n): """ Prints out all of the numbers that divide `n` evenly. >>> factors(20) 20 10 5 4 2 1 """ "*** YOUR CODE HERE ***"
def factors(n): x = n while x > 0: if n % x == 0: print(x) x -= 1 | http://inst.eecs.berkeley.edu/~cs61a/su14/lab/lab01/lab01.html | CC-MAIN-2018-05 | refinedweb | 1,052 | 72.36 |
A macro defined in all ISO C (and ISO C++) implementations in the stddef.h header file (or cstddef, in C++...). offsetof(TYPE, MEMBER) takes a struct TYPE (or class, if C++) and the name of a field in that structure. Its value is a size_t giving the number of bytes beyond the start of the structure where that member is stored. Note that C (and C++...) allows padding on structs, so the offset is not just the sum of sizeofs all previous elements in the structure!
offsetof(TYPE, MEMBER)
struct
class
size_t
sizeof
For instance, on a machine with 4-byte words, after
#include <stddef.h>
struct x {
char a[5];
double b;
int c;
};
offsetof(struct x, b)
offsetof(struct x, c)
offsetof(struct x, a)
offsetof
The C standard specifies (elsewhere from the definition of offsetof) that the offsetof the first member of a struct is always . But note, in particular, that very little is guaranteed about offsets! In particular, b is the next member after a, but on almost every architecture offsetof(struct x, a)+5 != offsetof(struct x, b), despite the sizeof a being 5. About the only things you can rely on are that offsetofs successive members will be increasing, and that at least the sizeof an element will be allocated before the next element.
b
a
offsetof(struct x, a)+5 != offsetof(struct x, b)
It is not possible to define offsetof portably (that's why you get a standard header file defining it for you!). But if stuck without, this code is almost legal C, and will work on most implementations:
#define my_offsetof(type, member) ((char *)(((type*)NULL)->member)-(char *)NULL)
offsetof isn't often useful, but when needed it can't be beaten. For instance, if you need to read or write part of a struct, you'll need to use offsetof in conjuction with sizeof.
Log in or register to write something here or to contact authors.
Need help? accounthelp@everything2.com | https://everything2.com/title/offsetof | CC-MAIN-2017-34 | refinedweb | 332 | 61.56 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On Mon, Mar 19, 2012 at 10:33 AM, H.J. Lu <hjl.tools@gmail.com> wrote: > On Sat, Mar 17, 2012 at 10:21 AM, Richard Henderson <rth@twiddle.net> wrote: >> On 03/17/2012 10:11 AM, H.J. Lu wrote: >>> GCC 4.7.0 defines __corei7__ for -march=corei7. ?This patch adds >>> __corei7__ check in i386/x86_64 bits/byteswap.h. ?OK to install? >> >> Isn't this (and the last couple added) recent enough that we can just >> defer to the gcc builtin? ?I.e. >> >> #if __GCC_PREREQ(4,2) >> # define __bswap_16(x) ?__builtin_bswap32((unsigned)(x) << 16) >> # define __bswap_32(x) ?__builtin_bswap32(x) >> #else >> ... rest >> #endif >> > > Here is a patch to use __builtin_bswap[32|64] in i386/x86_64 bits/byteswap.h > for GCC >= 4.2. ?I didn't use __builtin_bswap32 for __bswap_16 since it is > less efficient: > > > > Thanks. > > > -- > H.J. > -- > 2012-03-19 ?H.J. Lu ?<hongjiu.lu@intel.com> > > ? ? ? ?* sysdeps/i386/bits/byteswap.h: Include <features.h>. > ? ? ? ?(__bswap_32): Use __builtin_bswap32 for GCC >= 4.2. > ? ? ? ?(__bswap_64): Use __builtin_bswap64 for GCC >= 4.2. Unfortunately __builtin_bswap32/__builtin_bswap64 don't work with printf format: We may need to cast the results explicitly. -- H.J. | http://sourceware.org/ml/libc-alpha/2012-03/msg01041.html | CC-MAIN-2014-35 | refinedweb | 208 | 71.71 |
FileInfo Constructor
.NET Framework 4.6 and 4.5
Namespace: System.IONamespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
The following example uses this constructor to create two files, which are then written to, read from, copied, and deleted..: // //Hello //And //Welcome //c:\MyTest.txt was copied to c:\MyTest.txttemp. //c:\MyTest.txttemp was successfully deleted.
The following example opens an existing file or creates a file, appends text to the file, and displays the results.
using System; using System.IO; public class FileInfoMainTest { public static void Main() { // Open an existing file, or create a new one. FileInfo fi = new FileInfo("temp.txt"); // Create a writer, ready to add entries to the file. StreamWriter sw = fi.AppendText(); sw.WriteLine("This is a new entry to add to the file"); sw.WriteLine("This is yet another line to add..."); sw.Flush(); sw.Close(); // Get the information out of the file and display it.missionAccess.Read
Show: | https://msdn.microsoft.com/en-US/library/system.io.fileinfo.fileinfo(v=vs.80).aspx | CC-MAIN-2015-32 | refinedweb | 156 | 63.56 |
Seaborn is a plotting library that is built on top of Matplotlib. For folks already using Matplotlib, it makes it easy to generate visually pleasing plots that use contemporary colors and features. The key selling point is that you can do this by making zero or very few additions to your Matplotlib code! 🙂
To install Seaborn:
$ sudo apt install python-scipy python-pandas $ sudo pip install seaborn
It takes just a single line of code for Seaborn to change your plots:
import seaborn
With just this line, it changes the fonts, layout and colors used resulting in a much more pleasing plot. If you want to go further, you can use Seaborn to use beautiful color palettes and other features described in their tutorial.
Tried with: Seaborn 0.5.1, Matplotlib 1.3.1, Python 2.7.6 and Ubuntu 14.04 | https://codeyarns.com/2015/03/04/how-to-install-seaborn/ | CC-MAIN-2018-30 | refinedweb | 142 | 73.37 |
When you have installed Varnish Cache Plus 6.0, most probably you can simply start varnish with your old configuration files.
This page is a guide to you when you start to upgrade to
6.0.
It is not a not a list of new features of VCL, but a minimal set of changes that is needed to achieve equivalent operation on
6.0.
This list might not be complete. If you run into problems with using your existing configuration with 6.0, contact support. We will help you to get going, and update this list accordingly.
In 6.0,
All VCL Objects should now be defined before used. The compiler will generate an error if objects are defined before use.
VCL names are restricted to alphanumeric characters, dashes and underscores. In addition, the first character should be alphabetic. That is, the name should match “[A-Za-z][A-Za-z0-9_-]*“.
In
sub vcl_recv, the
rollback function has been retired.
In
sub vcl_hit, replace
return (fetch) with
return (miss). Failing to do this will give you many error log lines in the shared memory log.
The variable
req.ttl is deprecated.
The VMOD
softpurge has been retired. The functionality is covered by the new
purge VMOD.
kvstore is now object oriented. Please see the kvstore 6.0 API doc page.
Note that there are many improvements to VCL in Varnish 6.0, but these are not covered here. | https://docs.varnish-software.com/varnish-cache-plus/upgrading/config-41-to-60/ | CC-MAIN-2019-51 | refinedweb | 239 | 70.8 |
Important: Please read the Qt Code of Conduct -
Blank screen on Android devices. Works on emulator.
I am using Qt 5.3.2.
Does anyone have an idea what might be the cause? The solution seems to be rewrite the UI in Java :\
Without any details about your project, it's impossible to guess what can be your problem.
Please, share some details.
For what concerns the samples, you should take as a guidelines for developing not as production products. This means, that maybe the Maroon sample run in a fixed screen size just to show you how to create a game simplifying the code removing that code needed for scaling and adapting to any mobile screen.
My startup code:
@int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<MapWidget>("MapWidget", 1,0, "MapWidget");
QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec();
}@
and my QML code. The MapWidget is a derived class from QQuickPaintedItem, but I already proved it is not to blame, as I get the same outcome, if I remove it from the QML file.
@import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.1
import MapWidget 1.0
ApplicationWindow {
visible: true
title: qsTr("A* search demo")
menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("Open...") onTriggered: fileDialog.setVisible(true); } MenuItem { text: qsTr("Run") onTriggered: mapWnd.startSearch(); } MenuSeparator { } MenuItem { text: qsTr("Exit") onTriggered: Qt.quit(); } } } FileDialog { id: fileDialog title: qsTr("Please choose a map file") nameFilters: [ qsTr("Map files (*.txt)") ] onAccepted: { console.log("You chose: " + fileDialog.fileUrl) mapWnd.loadMap(fileDialog.fileUrl); mapWnd.update(); } } MapWidget { id: mapWnd startPos: "20,20" endPos: "60,60" anchors.fill: parent focus:true Keys.onPressed: { if (event.key === Qt.Key_G) { showGrid = true update() } else if (event.key === Qt.Key_H) { showGrid = false update() } } }
}@
Ok, one things that you can try is to set a fixed dimension of the ApplicationWindow setting width and height properties.
Maybe, one problem on the real device is that the ApplicationWindow does not goes full screen automatically.
In my apps, I usually use QQuickView that has an esplicity method for resizing the root item:
@
QQuickView viewer;
viewer.setResizeMode( QQuickView::SizeRootObjectToView );
viewer.setSource( backend->commonPath()+"/qml/splash.qml" );
viewer.show();
@
Give a try and let me know how is going.
Actually I had width and height configured, just removed them when I came to the conclusion it didn't had any visible effect.
It doesn't work. It seems I am forced to rewrite my QML to be able to use a QQuickView instead.
bq..
Does this force me to do manually the work provided by ApplicationWindow?
Thanks for the support.
Just had another attempt at it.
This plain QML file
@import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.1
ApplicationWindow {
visible: true
width: 640
height: 400
title: qsTr("A* search demo")
menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("Open...") } MenuItem { text: qsTr("Run") } MenuSeparator { } MenuItem { text: qsTr("Exit") onTriggered: Qt.quit(); } } }
}@
Just dies on the device, while working on the emulator.
bq. I/Adreno-EGL(12125): <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050__release_AU ()
I/Adreno-EGL(12125): OpenGL ES Shader Compiler Version: 17.01.12.SPL
I/Adreno-EGL(12125): Build Date: 03/28/14 Fri
I/Adreno-EGL(12125): Local Branch:
I/Adreno-EGL(12125): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050
I/Adreno-EGL(12125): Local Patches: NONE
I/Adreno-EGL(12125): Reconstruct Branch: NOTHING
D/OpenGLRenderer(12125): Enabling debug mode 0
I give up. :(
Thanks again for the support.
Qt 5.4 fixes this issue. | https://forum.qt.io/topic/46815/blank-screen-on-android-devices-works-on-emulator/3 | CC-MAIN-2021-31 | refinedweb | 614 | 53.07 |
Hi , i was just wondering how you would produce a time delay in java. Bascically all im trying to do is draw a circle in a bunch of random places. Just draw circles way to fast. Here my code
import java.awt.*; import hsa.Console; public class Delay { static Console c; public static void main (String[] args) { c = new Console (); design(); } static public void design () // randomly draws circles over HSA Console { int up = 0; int x ; int y; int height; int width ; for (int counter = 0 ;; counter ++ ) // need to waste time between each { // for statement repetion x = (int) (Math.random () * 500); y = (int) (Math.random () * 500); height = (int) (Math.random () * 100 ); width = (int) (Math.random () * 100 ); c.setColor (Color.red); c.drawOval (x,y,height,width); delay (10000); } } public void delay (int howLong) // delay function to waste time { for (int i = 1 ; i <= howLong ; i++) { double garbage = Math.PI * Math.PI; } } } | https://www.daniweb.com/programming/software-development/threads/37443/time-delay | CC-MAIN-2018-05 | refinedweb | 151 | 74.49 |
Routines written in Fortran and C/C++ can be
mixed in a single program. The xlf compiling system
assumes that C/C++ routine names are all lower
case. Following this convention
will make compiling and linking easier.
Care must be taken with data types that are
passed to the subroutines. Here is a table
showing corresponding datatypes.
The subsections of this topic are
For further information beyond that found on this page, see
The XL Fortran User's Guide, chapter 10,
"Interlanguage Calls."
As long as you keep in mind how the variable types correspond to each
other in Fortran and C as shown in the table above, calling a C
routine from Fortran is straightforward as long as the name of the
C routine is all lowercase.
Fortran passes addresses in subroutines calls, so the C routine
should accept a pointer to the proper data type.
Below is a simple example. First, the Fortran main program:
!FILENAME: f_main.f
!
PROGRAM f_calls_c
IMPLICIT NONE
REAL :: p1_x, p1_y, p2_x, p2_y
EXTERNAL calc_dist
p1_x = 0.0
p1_y = 0.0
p2_x = 3.0
p2_y = 4.0
CALL calc_dist(p1_x,p1_y,p2_x,p2_y)
END PROGRAM f_calls_c
And the C routine:
/* FILENAME: calc_c.c
*/
#include <math.h>
void calc_dist(float *x1, float *y1, float *x2, float *y2)
{
float dxsq, dysq, distance;
dxsq = (*x2-*x1)*(*x2-*x1);
dysq = (*y2-*y1)*(*y2-*y1);
distance = sqrt( dxsq + dysq );
printf("The distance between the points is %13.5e\n",
distance);
}
Compiling and executing:
% cc -c calc_c.c
% xlf90 -o f_calls_c f_main.f calc_c.o
** f_calls_c === End of Compilation 1 ===
1501-510 Compilation successful for file f_main.f.
% ./f_calls_c
The distance between the points is 5.00000e+00
Calling a Fortran routine from C is similar. Here are the same
two routines as shown above, but with the languages switched for
each file.
/* FILENAME: c_main.c
Shows how to call a FORTRAN routine from C
*/
extern void calc_dist(float*, float*, float*, float*);
void main()
{
float p1_x,p1_y,p2_x,p2_y;
p1_x = 0.0;
p1_y = 0.0;
p2_x = 3.0;
p2_y = 4.0;
calc_dist(&p1_x,&p1_y,&p2_x,&p2_y);
}
! FILENAME: calc_f.f
!
% xlf90 -c calc_f.f
** calc_dist === End of Compilation 1 ===
1501-510 Compilation successful for file calc_f.f.
% cc -o c_calls_f c_main.c calc_f.o -lxlf90 -lm
% ./c_calls_f
The distance between the points is 5.00000E+00
Note that we had to explicitly link with -lxlf90 -lm when
using cc.
In order to mix Fortran and all C++ functions, you must pass the
interlanguage calls through C "wrapper" functions. This is because
the C++ compiler "mangles" the names of some C++ functions. C++ functions
that are declared and used like regular C functions can be called just
like C functions, however.
In addition, you must use the xlC command to perform the final
linkage step.
Here's C++ code that performs the same task as does the C
function above that calculates the distance between points.
/* FILENAME: calc_c++.h
This is the C++ routine.
*/
#include <iostream.h>
#include <math.h>
template<class T> class calc {
public:
calc() {cout <<"Inside C++ constructor"<<endl;}
~calc() {cout <<"Inside C++ destructor"<<endl;}
void calc_dist(T *x1, T *y1, T *x2, T *y2)
{
T dxsq, dysq, distance;
dxsq = (*x2-*x1)*(*x2-*x1);
dysq = (*y2-*y1)*(*y2-*y1);
distance = sqrt( dxsq + dysq );
cout <<"The distance between the points is "
<<distance<<" \n"<<endl;
}
};
In order to call this routine safely from Fortran, you must "wrap" the
function with a C-style function, something like this:
/* Filename: calc_cwrapper.C */
#include <stdio.h>
#include "calc_c++.h"
extern "C" void calc_dist(float *x,float *y,float *X,float *Y);
void calc_dist(float *x,float *y,float *X,float *Y) {
printf("Inside C function, creating C++ object\n");
calc<float>* c=new calc<float>();
c->calc_dist(x,y,X,Y);
printf("Back in C function, will delete C++ object\n");
delete c;
}
Compiling and running (using f_main.f):
% xlf90 -c f_main.f
** f_calls_c === End of Compilation 1 ===
1501-510 Compilation successful for file f_main.f.
% xlC -c calc_cwrapper.C
% xlC -o f_calls_c++ calc_cwrapper.o f_main.o -lm -lxlf90
% ./f_calls_c++
Inside C function, creating C++ object
Inside C++ constructor
The distance between the points is 5
Back in C function, will delete C++ object
Inside C++ destructor
You can call Fortran subroutines from C++ by declaring the routine
extern "C" void fortran_routine_name
extern "C" return_type fortran_function_name
To call routines from C that are defined in Fortran 90 modules,
you must refer to the Fortran ROUTINE as
__modulename_NMOD_routine.
ROUTINE
__modulename_NMOD_routine
For example, the Fortran routine:
! FILENAME: calc_mod_f.f
!
MODULE CALCULATION
CONTAINS
END MODULE CALCULATION
is called from the main C program in this way:
/* FILENAME: c_main_mod.c
Shows how to call a FORTRAN routine from C
In this case the FORTRAN routine, named CALC_DIST,
is in the FORTRAN module named calculation
*/
extern void __calculation_NMOD_calc_dist(float *, float *,
float *, float *);
void main()
{
float p1_x,p1_y,p2_x,p2_y;
p1_x = 0.0;
p1_y = 0.0;
p2_x = 3.0;
p2_y = 4.0;
__calculation_NMOD_calc_dist(&p1_x,&p1_y,&p2_x,&p2_y);
}
Compiling and running:
% xlf90 -c calc_mod_f.f
** calculation === End of Compilation 1 ===
1501-510 Compilation successful for file calc_mod_f.f.
% cc -o c_calls_f_mod c_main_mod.c calc_mod_f.o -lxlf90 -lm
% ./c_calls_f_mod
The distance between the points is 5.00000E+00
Passing characters and strings between Fortran and C is not
straightforward.
When Fortran passes a CHARACTER string, it passes (by value) an extra
argument that contains the length of the string.
In addition, C strings are usually null-terminated,
while Fortran character strings are not.
To pass a Fortran CHARACTER to a C routine that accepts
a char, the string must be null terminated.
The only character type in Fortran is CHARACTER, which is stored as a set of contiguous bytes, one character
per byte. The length is not stored as part of the entity. Instead, it is passed by value as an extra argument at the
end of the declared argument list when the entity is passed as an argument.
If you are writing both parts of the mixed-language program, you can make the C routines deal with the extra Fortran
length argument, or you can suppress this extra argument by passing the string using the %REF function. If you use
%REF, which you typically would for pre-existing C routines, you need to indicate where the string ends by
concatenating a null character to the end of each character string that is passed to a C routine.
Following is an
example that shows some correct and incorrect ways to pass and handle
characters and strings from Fortran to C.
!FILENAME: give_chars.f
!
! Gives some examples of passing Fortran strings to
! a C routine that prints a character string beginning
! at the address of the start of the passed character
! string and ending at the C string termination character, which is
! CHAR(0) in Fortran.
PROGRAM give_chars
IMPLICIT NONE
CHARACTER(LEN=1):: a(9),d
CHARACTER(LEN=8):: b,c,e
REAL:: f
EXTERNAL TAKE_CHARS
! These are put in COMMON block to insure they are all
! adjacent in memory
COMMON//b,c,d
COMMON/c2/e,f
a(1) = 'a'
a(2) = 'b'
a(3) = 'c'
a(4) = 'd'
a(5) = 'e'
a(6) = 'f'
a(7) = 'g'
a(8) = 'h'
! This behavior of this call is undefined, since there is
! no string terminator character being passed to the C
! routine. It will 'work' if there fortuitously happens to be
! a zero in the next memory location after a(8).
PRINT *, ""
PRINT *, "This may or may not print a(1) to a(8):"
CALL TAKE_CHARS(a)
! This puts a string terminator character in a(6)
a(6) = CHAR(0) ! String terminator for C routine
PRINT *, ""
PRINT *, "This will print a(1) to a(5):"
CALL TAKE_CHARS(a)
!
b='ABCDEFGH'
c='ijklmnop'
d = CHAR(0) !String terminator for C routine
! The string terminator in d follows the string c in memory
! but there is no string terminator character between c and d
! (All this controlled by COMMON block declaration).
PRINT *, ""
PRINT *, "This will print string b and c:"
CALL TAKE_CHARS(b)
! Here we append a string terminator character to the
! string b when we pass it.
PRINT *, ""
PRINT *, "This will print string b only:"
CALL TAKE_CHARS(b // CHAR(0)) !Appends string terminator to b
! The following will print string e plus garbage
! because the C routine does not see a string terminator
! before the REAL value f
e = 'abcdefgh'
f = ATAN(1.)
PRINT *, ""
PRINT *, "This will print string e plus garbage:"
CALL TAKE_CHARS(e)
END PROGRAM give_chars
/* FILENAME: take_chars.c
A routine to take a Fortran character string
and print it. It assumes that the Fortran routine
has explicitly appended a string terminator character
to the string before passing it.
*/
void take_chars(char *fstring, long int fstringLen)
{
/* This printf() function (with %s) will print characters until
it encounters a \0 character, which it interprets as an
end-of-string signal.
*/
printf("The passed string is: %s\n",fstring);
printf("The passed string length is: %d\n",fstringLen);
}
Compile these routines with
% xlf90 -c give_chars.f
% cc -c take_chars.c
% xlf90 -o give_chars give_chars.o take_chars.o
When we run the program, we get:
% ./give_chars
This may or may not print a(1) to a(8):
The passed string is: abcdefgh
The passed string length is: 1
This will print a(1) to a(5):
The passed string is: abcde
The passed string length is: 1
This will print string b and c:
The passed string is: ABCDEFGHijklmnop
The passed string length is: 8
This will print string b only:
The passed string is: ABCDEFGH
The passed string length is: 9
This will print string e plus garbage:
The passed string is: abcdefgh?IÛ
The passed string length is: 8
Sometimes you may want to link with code containing C/C++ routines
that have mixed-case or upper-case names. You can use these routines
by using the -U option when compiling with xlf.
However, this makes all functions, variables, and names case-sensitive.
You can also use the @PROCESS MIXED directive to declare
case sensitivity. For example:
@process mixed
external C_Func ! now we can call C_Func, not just c_func
integer aBc, ABC ! now these are two different variables
common /xYz/ aBc ! the same applies to common block names -
common /XYZ/ ABC ! these two are different
end | http://www.nersc.gov/nusers/resources/software/ibm/c_and_f.php | crawl-002 | refinedweb | 1,713 | 66.74 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Migrating the Database5:16 with Alena Holligan
All of the content that's entered via the control panel is stored in the database. When you upload and download files using FTP you don't transfer the information that's stored in the database. We'll be using PHPMyAdmin to transfer the database manually so that you understand what is going on behind the scenes and are able to troubleshoot if something goes wrong. There are also many plugin options you can use.
Notes on FTP
FTP stands for File Transfer Protocol. Most hosting providers also allow for SFTP which is a SECURE File Transfer Protocol. If your hosting company supports this option, it is the better choice.
You can use any FTP software you would like. In this video we have used FileZilla but another great option is Cyberduck. You can find tutorials for using the FTP software from their site.
For more information, you can view the course to Upload the Website
SQL Statements
UPDATE wp_options SET option_value = replace(option_value, '', '') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, '','');
UPDATE wp_posts SET post_content = replace(post_content, '', '');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'','');
Word of Caution and Plugins for Updating URLs
Some plugins may place URLs in other places in the database. ** )
Backup and Migration Plugins
Here are some plugins you may wish to try.
- 0:00
You want to start in phpMyAdmin on your development environment.
- 0:05
As long as you have access to phpMyAdmin,
- 0:07
it doesn't matter where your environment is hosted.
- 0:10
You can follow the same steps.
- 0:13
In phpMyAdmin, choose the development database.
- 0:17
Along the top, we'll click to Export.
- 0:21
We'll do a Custom export with everything selected and Save output to a file.
- 0:29
We also want to make sure that we add drop table.
- 0:35
When we click Go, we should now have our database successfully backed up.
- 0:40
Take note of the table prefix.
- 0:43
It's easiest if the table prefix for your development and
- 0:46
production environments both match.
- 0:50
If you have a fresh installed WordPress on your production environment,
- 0:54
this may not be the case.
- 0:56
I'm going to change my production environment to match my development
- 1:01
environment.
- 1:02
In wpconfig.php, we'll find a table prefix.
- 1:11
I'm going to change this to localwp.
- 1:15
Now, we can come in to phpMyAdmin on our hosted production server, and
- 1:20
choose our production database Since the prefix was not correct,
- 1:26
I'm going to drop all the tables in this database first.
- 1:36
We can then import the file that we've just exported from my local development.
- 1:42
We should now see all of our database information
- 1:49
successfully stored on our production server.
- 1:56
Let's take a look at the production site.
- 2:00
Now it's quite possible that you continue to work on your local server,
- 2:05
maybe editing your theme, or a plugin, or some other part of the site.
- 2:10
Before you start developing on your local site, you may want pull down the freshest
- 2:15
database from the production server by exporting the production database.
- 2:21
You would then import that data to the local database.
- 2:26
Export from the database you wish to keep, and
- 2:29
import the database you wish to override.
- 2:32
Be extremely careful when updating your database, or
- 2:36
you can easily override the wrong data.
- 2:38
You can always download a copy of any database for backup.
- 2:43
Although we're technically set up now, there's one final step that you should do.
- 2:47
And that's to run a search and replace on the database for the URL.
- 2:51
This will change all the hard coded URL references.
- 2:55
This is particularly helpful if you have images on your site,
- 2:59
since some of those images may still be pointing to the old file location.
- 3:04
We haven't made any updates to the URLs to reflect the change in the site
- 3:08
within the database itself, only the configuration file.
- 3:13
I'm going to run a couple SQL commands that I'll add to the teacher's notes.
- 3:17
You can also update these URLs using a search and replace plugin.
- 3:22
On our production server, we'll go to SQL.
- 3:25
We're going to update the local WP options, and
- 3:30
we'll replace our old URL with a new URL,
- 3:34
where option name equals home or option name equals site URL.
- 3:44
Next, we'll update the post, again, setting our old URL to our new URL.
- 3:57
One more update for our post.
- 4:05
And then we can also update the post meta.
- 4:11
Great, all the URLs for our images and
- 4:14
anything else should be updated in the database.
- 4:18
I wanted to show you how to migrate WordPress manually, so
- 4:22
that you understand the different parts of a WordPress site, and
- 4:25
be able to troubleshoot if something goes wrong.
- 4:28
However, remember that all of the content that's entered
- 4:33
via the WordPress dashboard is stored in the database.
- 4:38
And when you upload and download files using FTP,
- 4:42
you don't necessarily transfer all the information that's stored in a database.
- 4:48
You do not always have to transfer a site manually.
- 4:52
There are many different plugins that allow you to both back up and
- 4:56
migrate part or all of your WordPress site.
- 5:00
I've included links in the teacher's notes for some plugins that you may wish to try.
- 5:06
Some of them include a free version, which is limited in the capabilities,
- 5:11
while also including a pro version that costs money. | https://teamtreehouse.com/library/migrating-the-database | CC-MAIN-2017-43 | refinedweb | 1,061 | 71.95 |
Hey guys, today’s post is about how to create a watchdog in Python. But what is a ”watchdog”?
A watchdog is a little piece of software that monitors our filesystem looking for any changes (like the creation, change or deletion of a file or of a directory). When a change occurs, the watchdog report it to us raising a specific event that we can handle.
For example, let’s suppose you have developed a program that use a configuration file. Your program could set a watchdog to monitor that file and if the configuration file is modified you could think to reload it and apply the new configuration at runtime, without the need of restarting your program.
That’s cool, uh?
So, today we will code a watchdog in Python.
To code this program we will need an additional module called “watchdog” (wow, who could have guessed it?) written by Yesudeep Mangalapilly, so let’s start by installing it. As always, I raccomand to use virtual environments instead of installing packages system wide. If you want to find out more about virtual environments (that’s probabilly because you haven’t read all my previous post, so shame on you!), just have a look at this article.
Now, create your virtual environment (optional but raccomended… at least by me), activate it and install the package watchdog with the following command:
Done, we have almost finished, haven’t we?
I mean, we still need to code the program that will actually use this module, but trust me, that will be really easy!
pip install watchdog
Ok, let’s start and pretend that we want to create a program that logs all the file that are created or modified in the same directory of our program.
Step 1. Import some stuff
import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler
I won’t explain these imports right now, they will be clear in a moment.
Step 2. Create the event handler
The event handler is the object that will be notified when something happen on the filesystem you are monitoring.
if __name__ == "__main__": patterns = "*" ignore_patterns = "" ignore_directories = False case_sensitive = True my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
In my example I have used some variables just to made the configuration of the event handler a little bit easier to be undestood.
The “patterns” variable contains the file patterns we want to handle (in my scenario, I will handle all the files), the “ignore_patterns” variable contains the patterns that we don’t want to handle, the “ignore_directories” is just a boolean that we can set to True if we want to be notified just for regular files (not for directories) and the “case_sensitive” variable is just another boolean that, if set to “True”, made the patterns we previously introduced “case sensitive” (that’s normally a good idea, unless you are working with stupid case-insensitive-file-systems… yeah, I’m talking about you Windows! 😛 ).
Step 3. Handle all the events
Now that we have created the handler we need to write the code we want to run when the events are raised.
So, let’s start creating four different functions that will be used when a file is modified, created, deleted or moved.
def on_created(event): print(f"hey, {event.src_path} has been created!") def on_deleted(event): print(f"what the f**k! Someone deleted {event.src_path}!") def on_modified(event): print(f"hey buddy, {event.src_path} has been modified") def on_moved(event): print(f"ok ok ok, someone moved {event.src_path} to {event.dest_path}")
In our example we will just print out something regarding the events that has been captured. It goes without saying that this is just an example, we could execute any kind of code instead of these useless print functions…
And now, under the creation of our event handler (the code of the previous step) we need to specify to the handler that we want these functions to be called when the corresponding event is raised
my_event_handler.on_created = on_created my_event_handler.on_deleted = on_deleted my_event_handler.on_modified = on_modified my_event_handler.on_moved = on_moved
Step 4. Create an observer
We need another object, known as the observer, that will monitor our filesystem, looking for changes that will be handled by the event handler.
Let’s create it right now.
path = "." go_recursively = True my_observer = Observer() my_observer.schedule(my_event_handler, path, recursive=go_recursively)
As you can see, I have just created an object of the Observer class and then called the schedule method, passing to it:
- the event handler that will handle the event
- the path to be monitored (in my case is “.”, that’s the current directory)
- a boolean that allow me to catch all the event that occurs even in the sub directories of my current directory.
Step 5. Start the observer
Ok, we almost finished our program, now we need just to start the observer thread.
my_observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: my_observer.stop() my_observer.join()
I think this snippet doesn’t need any comments, does it? We are just starting the observer thread to get all the events.
Ok, if everything is correct the result should be the one you can see below.
Testing our new shiny watchdog
And now it’s showtime guys, let’s test our watchdog!
Start the program from a terminal and you will see your cursor just hang. That’s a good start.
Now open a different terminal, move under the directory of your program and try to do something. For example, I have started vim (my favourite editor) to create a file:
$ vim dave.txt
by the time vim started, in my running console some statement has been printed:
hey, ./.dave.txt.swp has been created! hey buddy, . has been modified
Wow, it works! When you try to create a file with Vim it start by creating a .swp file and that’s what our program has detected, printing the first line. But why the second line? Well, if the current directory has a new file we can say that it’s changed as well, can’t we?
Now I will try to save my file and…
hey, ./dave.txt has been created! hey buddy, . has been modified
Ok, Vim has created my file (dave.txt) and my program has detected it! Well done!
Now I quit vim (for the record and for all the “Windows guys” that are currently reading this… you don’t need to unplug the power cord of your pc to quit vim, it’s enough to press the [esc] key and to type :q )
what the f**k! Someone deleted ./.dave.txt.swp! hey buddy, . has been modified
Ok, vim has deleted the temporary .swp file and the program has detected it. Mission accomplished! 🙂
The bottom line
In this article you have seen how easy it could be to set up a watchdog in Python that monitors a filesystem and react when a change occurs.
If you want to find out more about the watchdog module, you can have a look at the official documentation.
Happy Coding!
D. | https://www.thepythoncorner.com/2019/01/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/ | CC-MAIN-2020-05 | refinedweb | 1,179 | 63.59 |
I want to limit the size of a list control box. Let us take the following code:
The result of above code is shown in picture belowThe result of above code is shown in picture belowCode:
import wx
class Students(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(380, 230))
hbox = wx.BoxSizer(wx.HORIZONTAL)
panel = wx.Panel(self, -1)
self.list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT)
self.list.InsertColumn(0, 'name')
self.list.InsertColumn(1, 'age')
hbox.Add(self.list, 1,wx.EXPAND)
panel.SetSizer(hbox)
self.Centre()
self.Show(True)
app = wx.App()
Students(None, -1, 'studs')
app.MainLoop()
If I make the horizontal box sizer's proportion=0 (as shown in the code snippet below):
then the result of the code is shown in picture below:then the result of the code is shown in picture below:Code:
hbox.Add(self.list, 0,wx.EXPAND)
The problem with proportion=1 is that after 'Age' column, there is a lot of empty space the list control box is eating up for the third column which doesn't exist.
The problem with proportion=0 is that it is too short in width.
I want to display the list control box with 'Name' and 'Age' columns only and save the rest of the space. How do I do that? | http://forums.codeguru.com/printthread.php?t=511179&pp=15&page=1 | CC-MAIN-2015-14 | refinedweb | 229 | 68.47 |
I ran into a problem with some legacy code which looked like this:
And the corresponding function:
function doDelete() { var submitForm = function() { document.forms[1].method="POST"; document.forms[1].action="myThing.do?dispatch=delete"; document.form[1].submit(); } var messageBoxConfig = { message:"Are you sure you want to delete?", title:"Confirm", style:YUI.widget.MessageBox.STYLES.CONFIRM, buttons:YUI.widget.MessageBox.BUTTONS.YESNO, callback:submitForm }; YUI.widget.MessageBox.show(messageBoxConfig); }
Inline onclick handler aside (again legacy code), IE6 would submit the form without causing a page refresh. The form would submit transparently, leaving the user on the same page, which meant the backend wouldn’t have a chance to update the page with the results of the action. Firefox on the other hand, had no trouble submitting the form as I would expect.
In order to get IE6 to behave correctly, I had to use a setTimeout 0 in order to defer the action, and get IE6 to execute it.
function doDelete() { var submitForm = function() { document.forms[1].method="POST"; document.forms[1].action="myThing.do?dispatch=delete"; setTimeout(function() { document.form[1].submit(); },0); } var messageBoxConfig = { message:"Are you sure you want to delete?", title:"Confirm", style:YUI.widget.MessageBox.STYLES.CONFIRM, buttons:YUI.widget.MessageBox.BUTTONS.YESNO, callback:submitForm }; YUI.widget.MessageBox.show(messageBoxConfig); }
From what I understand, Internet Explorer 6 has issues with submitting from an onclick event in an anchor, although when I remove the MessageBox code, it worked as expected again (without the setTimeout). Some people have reported onmousedown instead of onclick gets IE6 to work correctly. Possibly the default behavior of the anchor is causing it to break? Nevertheless, using timers to queue the submit action makes it work properly regardless of the browser. Will update this post if I find out more!
Related posts:
Demo: PubSub in jQuery
Recently I did a post on Data Binding in JavaScript using the YUI3 Library as my base. h3 and MikeInVB wanted to see it in jQuery, so I rewrote it and it turns out is a great example of PubSub (publish / subscribe) for jQuery.
For this example, we’re using an object named DB, which is short for DataBind. Basically it’s an object with getters and setters.
var DB = function (data) { this._d = null; this.set = function (data) { this._d = data; }; this.get = function () { return this._d; }; this.set(data); };
Really, this is just an abstracted way to store data. To create an instance of it, set it and get the value back, we would do something like:
var myData = new DB(); myData.set("We can't fight in here, this is a war room!"); console.log(myData.get();) // "We can't fight in here, this is a war room!"
But lets say, we want to subscribe to this data object, and be notified whenever it changes. Instead of polling it and checking to see if the value is the same as last time, we can use jQuery’s custom events to trigger a custom event.
var DB = function (data) { this._d = null; this.set = function (data) { this._d = data; // notify all subscribers when this function is used $(this).trigger("change"); }; this.get = function () { return this._d; }; this.set(data); };
Now, we can subscribe to it like this:
$(myData).bind("change", function() { alert("The data was changed!"); });
Additionally, we can access that data in our handler:
$(myData).bind("change", function() { alert("My data was set to " + myData.get()); });
You can set up any number of subscribers to myData this way now, and they’ll be triggered when that instance is set().
If you want to further improve DB, you can add a function to make it easier to attach change events, jQuery style:
var DB = function (data) { this._d = null; this.set = function (data) { this._d = data; // notify all subscribers when this function is used $(this).trigger("change"); }; this.get = function () { return this._d; }; // shortcut for functions trying to bind to the change custom event this.change = function (fn) { $(this).bind("change", fn); }; this.set(data); };
With our new shortcut, we can subscribe to it like this:
var alexSez = new DB(); alexSez.set("Initiative comes to thems that wait."); alexSez.change(function() { alert("Alex says: '" + myData.get() + "'"); }); alexSex.set("Welly, welly, welly, welly, welly, welly, well. To what do I owe the extreme pleasure of this surprising visit?") // an alert will come up that says "Alex says: 'Welly, welly, welly, welly, welly, welly, well. To what do I owe the extreme pleasure of this surprising visit?'".
In the same way, you can set up two input boxes to “share” the same value by subscribing to a shared instance of DB like this:
var myData = new DB(); var inputs = $("#in1, #in2"); myData.change(function() { inputs.val(myData.get()); }); inputs.bind("keyup", function(ev) { myData.set($(ev.target).val()); });
Ta da!
If you’re still interested in PubSub for jQuery, I recommend checking out Jamie Thompson’s example using the $(document) namespace instead of specific object instances, or Peter Higgin’s jQuery.pubsub, which reportedly is significantly faster, although doesn’t allow object specific subscribing.
Demo: PubSub in jQuery
What do you think? Would you do this differently? Leave a comment, I read them all!
See the demo here: Data Binding in JavaScript
Back when I was in Flex land one of the things that I found to be really neat was data binding… you could essentially have widgets that would update if the data updated automagically. I also wanted to take a stab at doing publishing and subscribing in YUI3, so built this an object called DB, which stores data. It can do three things, it can set() data, it can get() data, and it’s an EventTarget, so you can subscribe to it’s change event:
var DB = function (data) { this._d = null; this.publish("change",{emitFacade: true}); this.set = function (data) { this._d = data; this.fire("change"); }; this.get = function () { return this._d; }; this.set(data); }; Y.augment(DB, Y.EventTarget);
And to instantiate an instance of DB you just do
var myData = new DB();, and then you can subscribe to it any number of times to be notified when the data has been updated. For example:
var myData = new DB(); var inputs = Y.all("#in1, #in2"); myData.on("change", function() { inputs.each(function(node) { node.set('value', myData.get()); }); }); inputs.on("keyup", function(ev) { myData.set(ev.currentTarget.get('value')); });
This code is pretty simple. In YUI3 it creates an instance of DB, which has it’s own private data (unset initially), subscribes to the change event with a function that updates both text inputs on the page if myData gets set(), and then binds to the keyup event on the text inputs to call myData.set() whenever the contents of either text input has something typed into it. This results in a page where both inputs update whenever you type into either one.
See the demo here: Data Binding in JavaScript
Is this useful? Practical? UnJavaScripty? I don’t know, but I’d love to hear what you think
I recently had to do some really heavy lifting with templates in JavaScript, and opted to use John Resig’s “Micro-templating” within the Underscore.js Library. It’s nice, you can write JavaScript within your templates to control your flow, like:
It's been <%= (new Date()).getTime() %> milliseconds since the epoch.
Which, if you’re like me is great. You could use Google Closure Templates, which probably is faster, but then you would have to precompile your templates, which is a pain.
The only problem I personally had with the Resig solution was that if you tried to call a variable that didn’t exist within your data object, it would fail horrifically, so I modified it slightly to be slightly more forgiving:
// JavaScript templating a-la ERB, pilfered from John Resig's // "Secrets of the JavaScript Ninja", page 83. // Single-quote fix from Rick Strahl's version. _.template = function(str, data) { var fn = new Function('obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, " ") .replace(/'(?=[^%]*%>)/g,"\t") .split("'").join("\\'") .split("\t").join("'") .replace(//g, "',(typeof($1)!='undefined') ? $1:'','") // modified to allow undefined variables pass through .split("").join("p.push('") + "');}return p.join('');"); return data ? fn(data) : fn; };
The 12th line where it says .replace(//g…) includes a test for the data that is being passed into the function that’s being created to output just an empty string if the variable is undefined. | http://truefalsemaybe.com/category/javascript/ | CC-MAIN-2014-15 | refinedweb | 1,425 | 58.58 |
Abstract class used as an intermediate pipe stage between executed processes. More...
#include <stx-execpipe.h>
Abstract class used as an intermediate pipe stage between executed processes.
Derived classes can be inserted into an execution pipe between two externally executed processes. It will receive all data from the preceding pipe stage and after processing it may forward output to the next pipe stage.
The class is derived from PipeSink and receives data from the preceding stage via the inherited functions process() and also the eof() signal. Usually process() will perform some action on the data and then forward the resulting data block to the next pipe stage via write().
Definition at line 100 of file stx-execpipe.h.
Constructor which clears m_impl and m_stageid.
Definition at line 1681 of file stx-execpipe.cc.
Write input data to the next pipe stage via a buffer.
Definition at line 1686 of file stx-execpipe.cc.
association to the pipe implementation for write access to m_impl.
Definition at line 110 of file stx-execpipe.h.
pointer to associated pipe filled by ExecPipe::add_function()
Definition at line 104 of file stx-execpipe.h.
pipe stage identifier
Definition at line 107 of file stx-execpipe.h. | https://panthema.net/2010/stx-execpipe/stx-execpipe-0.7.0/doxygen-html/a00007.html | CC-MAIN-2020-10 | refinedweb | 201 | 50.43 |
{-# LANGUAGE FlexibleContexts #-} {- | Module : Data.Random.Shuffle.Weighted Copyright : 2010 Aristid Breitkreuz License : BSD3 Stability : experimental Portability : portable Functions for shuffling elements according to weights. Definitions: [Weight] A number above /0/ denoting how likely it is for an element to end up in the first position. [Probability] A weight normalised into the /(0,1]/ range. [Weighted list] A list of pairs @(w, a)@, where @w@ is the weight of element @a@. The probability of an element getting into the first position is equal by its weight divided by the sum of all weights, and the probability of getting into a position other than the first is equal to the probability of getting in the first position when all elements in prior positions have been removed from the weighted list. [CDF Map] A map of /summed weights/ to elements. For example, a weighted list @[(0.2, 'a'), (0.6, 'b'), (0.2, 'c')]@ corresponds to a CDF map of @[(0.2, 'a'), (0.8, 'b'), (1.0, 'c')]@ (as a 'Map'). The weights are summed from left to right. -} module Data.Random.Shuffle.Weighted ( -- * Shuffling weightedShuffleCDF , weightedShuffle -- * Sampling , weightedSampleCDF , weightedSample -- * Extraction , weightedChoiceExtractCDF -- * Utilities , cdfMapFromList ) where import Control.Applicative ((<$>)) import Data.Random.RVar import Data.Random.Distribution import Data.Random.Distribution.Uniform import Data.Random.Distribution.Uniform.Exclusive import qualified Data.Map as M moduleError :: String -> String -> a moduleError n s = error $ "Data.Random.Shuffle.Weighted." ++ n ++ ": " ++ s -- | Randomly shuffle a CDF map according to its weights. weightedShuffleCDF :: (Num w, Ord w, Distribution Uniform w, Excludable w) => M.Map w a -> RVar [a] weightedShuffleCDF m | M.null m = return [] | otherwise = weightedChoiceExtractCDF m >>= \(m', a) -> (a:) <$> weightedShuffleCDF m' -- | Randomly shuffle a weighted list according to its weights. weightedShuffle :: (Num w, Ord w, Distribution Uniform w, Excludable w) => [(w, a)] -> RVar [a] weightedShuffle = weightedShuffleCDF . cdfMapFromList -- | Randomly draw /n/ elements from a CDF map according to its weights. weightedSampleCDF :: (Num w, Ord w, Distribution Uniform w, Excludable w) => Int -> M.Map w a -> RVar [a] weightedSampleCDF n m | M.null m || n <= 0 = return [] | otherwise = weightedChoiceExtractCDF m >>= \(m', a) -> (a:) <$> weightedSampleCDF (n - 1) m' -- | Randomly draw /n/ elements from a weighted list according to its weights. weightedSample :: (Num w, Ord w, Distribution Uniform w, Excludable w) => Int -> [(w, a)] -> RVar [a] weightedSample n = weightedSampleCDF n . cdfMapFromList -- | Randomly extract an element from a CDF map according to its weights. The -- element is removed and the resulting "weight gap" closed. weightedChoiceExtractCDF :: (Num w, Ord w, Distribution Uniform w, Excludable w) => M.Map w a -> RVar (M.Map w a, a) weightedChoiceExtractCDF m | M.null m = moduleError "weightedChoiceExtractCDF" "empty map" | M.null exceptMax = return (exceptMax, maxE) | otherwise = extract <$> uniformExclusive 0 wmax where Just ((wmax, maxE), exceptMax) = M.maxViewWithKey m extract w = (a `M.union` M.mapKeysMonotonic (subtract gap) c, b) where (a, e, r') = M.splitLookup w m r = case e of Nothing -> r' Just ex -> M.insert w ex r' Just ((k, b), c) = M.minViewWithKey r gap = case M.minViewWithKey c of Nothing -> 0 Just ((k2, _), _) -> k2 - k -- | Generate a CDF map from a weighted list. cdfMapFromList :: (Num w, Eq w) => [(w, a)] -> M.Map w a cdfMapFromList = M.fromAscListWith (const id) . scanl1 (\(w1, _) (w2, x) -> (w1 + w2, x)) . dropWhile ((==0) . fst) | http://hackage.haskell.org/package/random-extras-0.19/docs/src/Data-Random-Shuffle-Weighted.html | CC-MAIN-2016-07 | refinedweb | 538 | 52.87 |
's mission is to organize the world's information and make it universally accessible and useful. This includes making information accessible in contexts other than a web browser and accessible to services outside of Google.
The Google Data Protocol provides a secure means for external developers to write new applications that let end users access and update the data stored by many Google products. External developers can use the Google Data Protocol directly, or they can use any of the supported programming languages provided by the client libraries.
Audience
This set of documents is intended for anyone who wants to understand Google Data Protocol. Even if you just want to write code that uses the language-specific client libraries, this document set can be helpful if you want to understand what's going on beneath the client-library abstraction layer.
If you're looking for the Developer's Guide for a specific API, visit the Google Data Protocol API Directory.
If you want to access an API in your favorite programming language, visit the Client Libraries download page.
Background
A number of Google products, such as Calendar and Spreadsheets, provide APIs that are based on the Google Data Protocol. You, the developer, can use these APIs to write client applications that give end users new ways to access and manipulate the data they store in those Google products.
Note: Google products that provide APIs are sometimes referred to as services in these and other related documents.
If you write code that uses the Google Data Protocol directly, it accesses the API using HTTP requests like
GET or
POST. With these requests, data stored by the Google product is transferred back and forth over the wire in the form of data feeds. The data feeds are simply structured lists that contain the data. Historically, the primary feed format has been AtomPub XML, but now JSON, or JavaScript Object Notation, is also available as an alternate format.
If you prefer not to write code that makes HTTP requests directly, you can instead program your client application using one of the programming languages available in the set of client libraries provided. When you do this, the details of the HTTP requests are handled by the client library; you write your code at a more conceptual level using the language-specific methods and classes provided by the client library.
Refer to the product-specific documentation for more information about the particular languages available for the API, or API version, you are using.
Versions of the protocol
Protocol Version 2.0 vs. Protocol Version 1.0
The first version of the Google Data Protocol was developed before the Atom Publishing Protocol was finalized. The second version of the Google Data Protocol is fully compliant with the AtomPub RFC 5023 standard.
The Google Data Protocol Version 2.0 also includes support for:
- HTTP ETags. A web standard that helps your client applications make better use of HTTP caching. The services included in the client libraries that support Protocol v2.0 handle ETags automatically.
- Partial Response and Partial Update (Experimental). Features that let you make requests that transfer less data. By requesting only the information that you actually need, or by sending updates that include only the data that you actually want to change, your client application can be much more efficient in its use of network, CPU, and memory resources. Currently, partial response and partial update are available only for some products; see the product-specific documentation to find out if your API supports it.
Updating your application
If the API you are using was built upon the latest version of the protocol, then the Protocol v2.0 functionality is included in its documentation. In general, we recommend that you upgrade your client application to the latest version available for your API.
Updating a client-library-based client
If your client application uses a client library, such as the Java client library or the .NET client library, it may contain a version of the API that supports Protocol v2.0 features. To find out, refer to the API documentation for the Google product you are using to find out if both of the following are true:
- There is an API version that supports Google Data Protocol v2.0 features.
- The client library you are using also supports that API version.
If the client library supports it and you want to update your existing application, just download and use the latest version of the client library. All of your code still works, and the client library takes care of the Protocol v2.0 changes under the hood.
Updating a raw HTTP client
If you wrote your client application using the Google Data Protocol directly, you need to make these changes:
- Non-default version requests. Add an HTTP version header (
GData-Version: X.0) to every HTTP request you send, where
Xis the version of the API that supports Google Data Protocol v2.0 features. Alternatively, add a query parameter (
v=X.0) to the URL of every request, where
Xis, again, the correct version of the API. If you do not specify a later version, your requests are sent to the earliest supported version of the API by default.
- Optimistic concurrency. If you were using a version of an API that supported optimistic concurrency, you may need to change your update and delete code to use ETags. For more information, read the ETags section of the Google Data Protocol reference documentation, and read the Update and Delete sections of the Protocol developer's guide for the service your client application is using.
- Self or edit URIs. If your client keeps track of self or edit URIs for feeds or entries, note that those URIs may have changed. To get the new URI, re-request the item using the old URI, but mark the request as a version X.0 request, where X is the version of the API that supports Google Data Protocol v2.0 features. The server returns the new representation of the entry, including the new URIs, which you can store in place of the old ones.
- Namespace URIs. If your client stores Google Data Protocol API namespace URIs locally, or has them hard-coded, you'll need to update them:
- The AtomPub namespace (prefix
app) has been changed from.
- The OpenSearch namespace (prefix
openSearch) has been changed from. | https://developers.google.com/gdata/docs/developers-guide?authuser=0&hl=ja | CC-MAIN-2021-25 | refinedweb | 1,064 | 61.26 |
I notice a strange problem with doxygen 1.8.2. Including a header label
causes the header title to disappear from the output html.
With the following markdown file:
Title
{#title}=====Section 1 {#section1}---------Text for section 1
I get the output as:
Title
Text for s
I'm writing an Fast-CGI application that makes use of sqlAlchemy &
MySQL for persistent data storage. I have no problem connecting to the DB
and setting up ORM (so that tables get mapped to classes); I can even add
data to tables (in memory).
But, as soon as I query the DB
(and push any changes from memory to storage) I get a 500 Internal Server
Error and my error.log records
I have the following code in my global.asax.cs, to enable cross domain
AJAX requests for certain domains:
protected void
Application_BeginRequest(object sender, EventArgs e) {
string whiteList =
System.Configuration.ConfigurationManager.AppSettings["AjaxCrossDomainWhitelist"]; if (!string.IsNullOrWhiteSpace(whiteList))
I've been looking and trying to no avail on how to disable the default
headers provided by jquery mobile on nested lists and insert my own, like
this:
<ul data-<li ><a href="#">This
is a List Item</a><ul data-<li><a href="#"> This s a Nested Lis
MSDN says you can compile your .hlsl files into byte arrays that are
defined in header files. And this is the code they give.
#include "PixelShader.h" ComPtr<ID3D11PixelShader>
m_pPixelShader; hr = pDevice->CreatePixelShader(g_psshader, sizeof(g_psshader), nullptr, &m_pPixelShader);
So g_psshader
g_psshader
Is there a way to hide all the DataGrid columns, and not make them
included in layout, and still show the header row along with its header
text?
I was able to make the DataGrid columns not visible, and
not included in layout, but that makes the header text no longer appear.
If no data comes back from the data provider, I want all the
columns to disappear and then the h
In GIMP, you're able to save an image as a C header file. I did so with
an XPM file, which looks like the image below:
If
I were to save the XPM image as a C header file, GIMP will output this C
header file.
In order to process each pixel of the given image
data, the header pixel is called repeatedly. What I don't understand is
what the header pixel does to
I would like to have a back button on the page, using
data-add-back-btn="true". However I also want a popup on the
same page, with a header, that doesn't have a back button on it. It seems
that the data-add-back-btn="true" attribute applies to
everything on the page.
data-add-back-btn="true"
I've played around with different
settings here: but have had
This code works, and I can see the request go out to my php script
through charles with my custom header GUID attached.
NSMutableURLRequest *loginRequest = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:feedURLString]]; NSData
*myRequestData = [NSData dataWithBytes:[myRequestString
UTF8String]length:[myRequestString length]]; [ loginRequest
setHTTPMethod
I've been given a design which entails a header for a page to have a
coloured background the full width of the body, but to have
transparent borders between the h1 and nav options in the
header.
body
h1
I've done a jsfiddle for it here. If you imagine that
the spaces to the left and right of the header were the same green as the
middle of the header but you could s | http://bighow.org/tags/header/1 | CC-MAIN-2017-26 | refinedweb | 584 | 55.37 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
Gradual Typing for Python
This package provides the runtime type-checking semantics of Gradual Typing for Python. Get a short introduction to gradual typing here.
Installing
This package only works on Python 3. To install gradual on your system, you must first get the Python 3 version of pip-3.2:
sudo apt-get install python3-pip
Now, you can easily install the gradual package via:
pip install gradual
If you wish to install it to your base system, then the above command would require root. If you already have gradual and wish to upgrade the existing package then you can use the --upgrade flag:
pip install --upgrade gradual
Usage
Once you have installed the package, fire up the Python 3 interpreter and just do:
from gradual import * @typed def calculate_total(a:int, b:int) -> int: return a + b//100
If you would like to avoid the from gradual import * syntax, you can manually import all the names such as:
from gradual import typed, obj, func
Any class or function marked with @typedon decorator will produce a typed class or a typed function. Consider the following example:
from gradual import * @typed class DogInterface(object): def wag_tail()->str: return 'woff woff' @typed def use_dog(dog: DogInterface): print(dog.wag_tail()) class Cat(object): pass c = Cat() c.wag_tail = lambda: 'meow' use_dog(c) | https://bitbucket.org/gradual/py-gradual | CC-MAIN-2018-22 | refinedweb | 243 | 50.67 |
OK, here's some of my reactions to the core part.> +#define KEVENT_SOCKET 0> +#define KEVENT_INODE 1> +#define KEVENT_TIMER 2> +#define KEVENT_POLL 3> +#define KEVENT_NAIO 4> +#define KEVENT_AIO 5I guess we can't really avoid some form of centralized list of theconstants in the API if we're going for a flat constant namespace.It'll be irritating to manage this list over time, just like it'sirritating to manage syscall numbers now.> +/*> + * Socket/network asynchronous IO events.> + */> +#define KEVENT_SOCKET_RECV 0x1> +#define KEVENT_SOCKET_ACCEPT 0x2> +#define KEVENT_SOCKET_SEND 0x4I wonder if these shouldn't live in the subsystems instead of in kevent.h.> +/*> + *And couldn't we just use the existing poll bit definitions for this?> +struct kevent_id> +{> + __u32 raw[2];> +};Why not a simple u64? Users can play games with packing it into othertypes if they want.> + __u32 user[2]; /* User's data. It is not used, just copied to/from user. */> + void *ptr;> + };Again just a u64 seems like it would be simpler. userspace librarywrappers can help massage it, but the kernel is just treating it as anopaque data blob.> +};> +> +thrilled with), we should at least make these arguments explicit in thesystem call. It's weird to hide them in a struct. We could also thinkabout making them u32 or u64 so that we don't need compat wrappers, butmaybe that's overkill.Also, can we please use a struct timespec for the timeout? Then thekernel will have the luxury of using whatever mechanism it wants tosatisfy the user's precision desires. Just like sys_nanosleep() usestimespec and so can be implemented with hrtimers.> +struct kevent> +{(trivial nit, "struct kevent {" is the preferred form.)> +look up instances for us. Asking for 'lock' is hilarious.> footprint is higher and as cacheline contention hits as there aremultiple buckets per cacheline. For now I'd simplify the hash into asingle lock and an array of struct hlist_head. In the future it couldbe another user of some kind of relatively-generic hash implementationbased on rcu that has been talked about for a while.> +#define KEVENT_MAX_REQUESTS PAGE_SIZE/sizeof(struct kevent)This is unused?> + uselist_for_each_entry_safe_reverse() in list.h but nothing is calling it? Either way, it should be removed :).> +#define sock_async(__sk) 0It's a minor complaint, but these kinds of ifdefs that drop argumentscan cause unused argument warnings if they're the only user of the givenargument. It'd be nicer to do something like ({ (void)_sk; 0; }) .> +struct kevent_storage> +{> + void *origin; /* Originator's pointer, e.g. struct sock or struct file. Can be NULL. */Do we really need this pointer? When the kevent_storage is embedded inthe origin, like struct inode in your patch sets, you can usecontainer_of() to get back to the inode. For sources that aren't builtlike that, like the timer_list, you could introduce a parent structurethat has the timer_list and the _storage embedded in it.> I suspect that we won't want this configurable if it gets merged, but Icould be wrong and don't feel strongly about it.> + switch (k->event.type) {> + case KEVENT_NAIO:> + err = kevent_init_naio(k);> + break;> + case KEVENT_SOCKET:> + err = kevent_init_socket(k);> + break;I wonder if it wouldn't be less noisy to have something likestructuse list_del_init() and list_empty() instead.> +static void __kevent_requeue(struct kevent *k, u32 event)> +{A few things here. First, the event argument isn't used?> + err = k->callback(k);This is being called while holding both the kevent_list->kevent_lock andthe k->st->lock. So ->callback is being called with locks held andinterrupts blocked which is going to greatly restrict what can be donethere. If that's what we want to do we should document the heck out of it.> + spin_lock_irqsave(&k->lock, flags);> + spin_lock_irqsave(&k->user->ready_lock, flags);It also now creates lock nesting three deep, which starts to feeluncomfortable. Have you run this under lockdep? It might be fine, butthis kind of depth means those of us auditing have to stare very veryclosely at the locks that paths acquire. The fewer locks that are heldat a time, the better.> +void kevent_storage_ready(struct kevent_storage *st, > + kevent_callback_t ready_callback, u32 event)Hmm, the only caller that provides a callback is using it to callkevent_break() on each event. Could that not be done by the helperitself if the caller provides the right event? Is there some morecomplicated use of the callback on the horizon? Not a big deal, butthere are those who prefer to avoid code paths that nest lots ofcallbacks in sequence.> + struct kevent *k, *n;In general, it's nicer to user longer names please. You'll noticethroughout the kernel that we use things like dentry, inode, page, sock,etc, instead of d, i, p, and s.> printk() seems like a poor choice if this is meant to be a more formalfunctionality. If it's just a debugging aid then pr_debug() and DEBUGmight be nicer.> +/*> + *argument that says whether to lock or not? You know, the usual:void __thingy() { doit();}void thingy() { lock(); __thingy(); unlock();}> + list_del(&k->kevent_entry);> + u->kevent_num--;I wonder if these shouldn't get micro helpers that then have BUG_ON()sto test bad conditions. like BUG_ON(list_empty() && kevent_num), thatsort of thing.> and lock into one struct (like struct sk_buff_head) or hoist the codeinto the caller.> +get this in a hash, or something, before merging.> +have their own locks. What are the mutexes serializing? Why can't werely on the finger-grained object locking to make sure that concurrentoperations behave resonably? One can imagine wanting to modify twokevents in a context that have nothing to do with each other and notwanting to serialize them at the context.> in kevent_user_ctl_add() and then here into the kevent. We shouldrework things a bit so that we only copy it once.> +#ifdef CONFIG_KEVENT_USER_STAT> + u->total++;> +#endifFWIW, this could hide behind some kevent_user_stat_inc(u) that could beifdefed away in the header.> + {> +or hoist the locals up into the main function and lose the braces.> +static int kevent_user_ctl_add(struct kevent_user *u, > + struct kevent_user_control *ctl, void __user *arg)> +{> + orig = arg;> + ctl_addr = arg - sizeof(struct kevent_user_control);Ugh. This is more awkwardness that comes from packing the system callarguments in neighbouring structs behind a void *. We should reallyhave explicit typed args.> + atime. (Like, say, a certain database writing back lots of cacheddirtied database blocks.) I wonder if we should arrange this so that wecan get some batching done and reduce the amount of lock traffic perevent added.> +/*> + *1 second come from? :) It seems pretty crazy to require programmers tocheck that their timer math didn't just end up at 0 and magically tellthe kernel to wait a second.> +some refactoring.> by calling _CTL_INIT (which then magically ignores the fd argument?).That seems confusing.Anyway, that's enough for now. I hope this helps.- z-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/8/1/439 | CC-MAIN-2014-35 | refinedweb | 1,138 | 66.74 |
Using Drupal 122
Michael J. Ross writes Web sites. A new book, Using Drupal, aims to fill this need." Keep reading for the rest of Michael's review plug-in Web site, and is wrapped up with discussion of additional modules applicable to the kind of Web site Web sites. Web sites. homepage Web site,.
Michael J. Ross is a Web developer and freelance writer.
You can purchase Using Drupal from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
What we REALLY need (Score:5, Funny)
"Pronouncing 'Drupal'"
Re: (Score:1)
Or pronouncing "Web 2.0" application names in general...
But for the record: DROO-puhl
Re: (Score:2, Flamebait)
Anyone who can't read well enough to figure out how to pronounce the name, probably isn't going to be saying it. Its not really that difficult.
Re: (Score:3, Informative)
Funny you should say that because the other day I was talking with a friend about our involvements with open source communities (he's on the Debian project) and I mentioned I was getting into DROOpal and he's like "you know, it's actually DRApal." He pointed out it was based off the Dutch word druppel for rain drop.
Re: (Score:2)
well, according to this page [suseroot.com] (contains a video of an interview with Linus) there are multiple pronounciations for 'Linux' and 'Linus', so there isn't really a definitive answer to what's the correct pronounciation.
Linus seems to pronounce his name differently depending on what language he's using and/or where he's living. but in the video he does say that 'Linux' is always linn-uks.
Re: (Score:2)
'Linux' has always been linn-uks. Torvald's accent, as heard in torvalds-says-linux.wav, made it sound slightly ee-like, and that managed to confuse many people (although I don't know how, as it has always been quite clear to me that he is saying linn-uks). Now that his accent has become more americanized, as in the video, it should be clear to everyone.
Re: (Score:2)
Re: (Score:1)
A short OO, rather than a long one, i assume?
Re: (Score:2)
In English, it's pronounced Drupal. That's the big problem with using an actual word (and not a name or something made up) as a trademark (which Drupal is.) There are simply multiple ways to pronounce it and although you could insist it be pronounced a certain way specific to your language, you'd be an asshole. Thinking about this sort of thing is not new;
Re: (Score:1)
Re: (Score:2)
Isn't that a reason to hate the English?
Re: (Score:1)
Who needs a reason to hate the English?
Re: (Score:2)
Nigera?
Re: (Score:1)
Huh???
Re: (Score:2)
It is okay, go back to playing WOW
Re: (Score:1)
It's the same with all words in English if you've never heard them spoken before! English spelling is a joke.
Anyway, almost all of the English language is made up of "foreign" words!
Re: (Score:1)
The pronunciation of "drupal" is unusually easy across many different languages. I guess you could pronounce the "up" like the south eastern English pronunciation of the word "up", but can can't see why you would...
Drupal and the CMS. (Score:3, Interesting)
I like Drupal. I've used it many times and have always thought of it as one of the better CMS packages available.
What I would like to see, would be a more freeing kind of extensibility, so that I could whip up fast plugins that would behave in a very reliable and systematic manner. I've tried to extend it in the past but have always preferred how easily Wordpress reacts to new code. The Wordpress docs and forums appear to have a faster method of making information available to developers.
However, if I was planning a brochure-based website that would have some fresh content from time-to-time, I would not object to Drupal, but only if I was certain that I would never have to extend the core mechanics of what they offer... it's simply too unpredictable (at least as of this past August, which is when I last fiddled with it).
Re: (Score:3, Informative) ver
Re: (Score:1)
There were some features of Drupal that I really loved, but could not extend. I remember being mixed up between what people on the forum were saying, when much of it was not bound to a particular build or release so it was indeed out of date and then you have much time wasted spinning your wheels, instead of just knowing a particular answer, fast.
I think this kind of thing happen
Re: (Score:2).
Re: (Score:1)
I've just moved one of my blogs from Wordpress to Drupal - for the sole purpose of learning about Drupal - and i'm not sure which one has the worst documentation!
Wordpress's documentation is very good - if you can find what you're looking for, which is usually next to impossible. Drupal's seems to be a bit better organised, but i don't think it's as well written.
My general impression of the two is that, at first glance, Drupal looks a lot slicker than Wordpress, but below the surface Wordpress is a better p
Re: (Score:3, Interesting)
i just started learning CakePHP and jQuery to build a new informational & e-commerce site for our company (a record label). this is actually the first time i've worked with any web development frameworks, so it's all very new to me. originally i was thinking about going with an open source CMS--preferably an e-Commerce-oriented CMS like osCommerce--but i wasn't sure how extensible it would be.
is Drupal suitable for mid-sized e-commerce sites that might require a lot of custom features (shopping cart, mp
Re: (Score:2) coupl
Re: (Score:1)
FWIW, Warner Bros. Records uses Drupal very heavily for its artist sites.
Check this out post, for example, on WBR's VP of Technology Ethan Kaplan's blog: [blackrimglasses.com]
(Mind you, it appears that ecommerce may be handled outside of Drupal--whether that's due to some a lack in Drupal or some WBR-specific reason (e.g. legacy system), you'd have to ask check w/Ethan).
Concrete5... (Score:3, Informative)
It's a little sparse (you won't find nearly as many pre-made plugins, ala Wordpress) but if you need a clean base to build on you might like it.
Good target (Score:2)
I've been using Drupal for a while, but only in the most minimal way. To me this looks like an excellent book to really ramp up the use of Drupal in more advanced ways that I had been considering, but was not quite sure the best direction to take.
I'm not sure exactly why Drupal appeals to me more than the other CMS systems - I reviewed quite a few pretty carefully before selecting Drupal (about two years ago), and I just liked Drupal from a feature and technology perspective.
Drupal.. (Score:2, Insightful)
Re: (Score:2)
Wow, thanks for the great review! (Score:5, Informative) [usingdrupal.com] as well.
:)
*forehead slap* I can't believe we forgot to put that there. I blame the holiday rush.
;) Added a note to the front page of [usingdrupal.com].
I'll also speak with our contacts over at O'Reilly about mirroring these items on their "official" infrastructure.. :)!
Re: (Score:2, Interesting).
Re:Wow, thanks for the great review! (Score:4, Informative)..
Re: (Score:2, Informative)
This information can be found in the back of all O'Reilly books in the Colophon section (along with information about the animal on the cover
:) ). For Using Drupal, "The cover font is Adobe ITC Garamond. The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and th
Re: (Score:1)
Uhhh, hi there. Not to be annoying, but I still can't quite get WTH Drupal is exactly. It looks like custom interpreter combined with a database frontend, but I'm not quite sure. Content management system doesn't speak heaps either. Sorry.
Disclaimer: I'm in high-school specializing physics, soooo... I'm not exactly a webdev in the making. Sorry if the question is idiotic.
Drupal Pros and Cons (Score:5, Insightful)
Re: (Score:1)
I'm trying to decide what CMS to use for a site, and this was useful to know. Thanks.
I need to setup a blog and forum, and I've been debating over Drupal or a Wordpress + forum hybrid. I like the fact that Drupal has a forum integrated, so you can just create one user login and have access to both sections of the site.
I think Wordpress is a bit easier to work with if all you want is a blog, but I'm probably leaning towards Drupal right now since I need a bit more.
I also tried looking at bbPress, which is
Re: (Score:2)
I am amazed you cited Wordpress as better than Drupal. Wordpress is a horrible piece of code, written by people who care only about the newest in oooh-shiney.
I've got several Wordpress sites under administration and they give me nothing but headaches. I'm a rotten sysadmin but Wordpress just makes my life that much harder. My brief foray into Drupal was like a trip to heaven in comparison.
Tip: by far the best way to install and update Wordpress is through the subversion checkout and switch commands.
And need
Re: (Score:1)
I've done several sites using Drupal and ran into some of the upgrade and module installation SNAFUs mentioned here.
I found DRUSH [drupal.org] to be one of the most useful modules available for handling module updates and installation. It is basically a CLI swiss army knife for tasks like module management, cache management, log management, etc. In short it is just plain awesome.
By using Drush and having Drupal Core checked out via CVS it is trivial to keep everything up to date in an automated fashion.
Re: (Score:1)
Re: (Score:2)
There is NO EXCUSE for the fact that drupal does not upgrade modules, or for that matter itself, for you. It is NOT a difficult task, it is in fact very easy. I wrote a module installer once, it took me less than a day, I am simply not interested in maintaining a Drupal module right now or I would already have written one. It should be easy to wrap around the update status module, which has its failings but mostly works these days.
Excuse (Score:2)
Your complaint is neatly self-contradictory, both complaining that there is NO EXCUSE while giving an excuse.
The person who should write this module is you - you have experience, you've clearly given it thought, you use Drupal and understand the update status module, it would benefit you and others - but you can't be arsed to. Good one.
The Drupal Song (Score:5, Funny) [lullabot.com]
Amuse/annoy your coworkers!
Another review of this book (Score:4, Informative)
Re: (Score:2)
Check out this [packtpub.com] one. I found that it filled in the gaps left by the online handbook quite nicely. I also like that the publisher funnels some of their profits back in to the projects their books cover.
What I need is an end-user guide (Score:3, Interesting)
I've read a couple books, but I still don't know how to use it. All the books I read thus far spent 1/2 the time on installing it, which should only be a chapter. The rest of the time, they talk about "nodes" which is too abstract a concept for my friend Prudence, who runs a counseling website to grasp.
What we really need is a guide on "do this to make a menu", "do this to make a blog", "do this to enter the blog article", do this..., etc. I really have no idea to layout a site and get what I want. So there Drupal sits, well-installed, but doing nothing. Because that's what the books covered.
You might want to check it out... (Score:3, Informative) appr
Re: (Score:3, Interesting)
It would be more than sufficient to show several sites, with various layouts and allow the reader to select one, or elements from several, and see the steps which made the site or element. This would vastly increase confidence and shorten time to deploy.
Call it "The Drupal Cookbook"
Not me... (Score:2)
"In any computer programming book, screenshots and other figures can be most helpful to the reader"... not me, I tend to find the BNF of the grammar the most helpful.
Project Management modual? (Score:2)
I've looked over the moduals at drupal.org, but haven't found anything useful. Does anyone know of a decent project management modual? I've used PHPProject in the past, it doesn't need to be as complex as that. I really just need to be able to assign tasks to users, define projects, and maybe allocate resources to tasks and projects. Gnatt, time estimates, milestones and such would be a positive bonus, but not a requirement. And no, I don't really have the time to make one myself...
Re: (Score:2, Informative)
I've used Project + Project Issue Tracking with success. [drupal.org] [drupal.org].
Everything else (except Gantt charts) could be created as content pages within the project.
For a more integrated system, I'm a fan of Trac, which is Python, not PHP. The wiki markup linking of Trac is worth it on its own.
Re: (Score:2)
Sweet! Thanks, I'll look at those over the weekend. I've gotten many of my friends to loving Drupal because of it's vast amount of plugins. I have yet to dip into doing any of my own, because this was really the only thing I couldn't find that already existed. I knew their had to be something out there, I just couldn't really find it. Now if I can just fix the access problems I'm having with it and cron.org to update my feeds lol
Drupal or other CMS? (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:1)
As I already commented below, check out [cmsmatrix.org]. This site has lots of choices with comparisons and a discussion board. I've found it to be quite helpful.
Re: (Score:2)
Check who uses drupal (Score:4, Informative)
I have extensive experience building in Drupal -- module and theme development.
I've noticed that immediate impression people have about Drupal is that it's only a blog CMS. But it isn't so at all. I welcome you to visit Drupal founder's blog, where he lists all interesting sites that use Drupal. Sometimes even I am (pleasantly) surprised at the ogranizations and institutions who move on to use Drupal. Check it out: [buytaert.net]
Excellent book (Score:2, Insightful)
This book fills out the lineup of Drupal books rather nicely:
Building Powerful and Robust Websites With Drupal 6: good intro book for the non-programmer
Learning Drupal 6 Module Development: the basics of module development
Pro Drupal Development, 2nd ed: exhaustive documentation/reference of how Drupal works, system by system
Using Drupal: Now that you understand the above, how you put it all together
And there are some other ones for specific applications like multimedia and education.
I've Got that Feelin (Score:2)
or maybe I've just had to use too much eighties music to get a point across to some students this past week.
yes, I know there is a 'd' at the front of the back end system.
If you're just getting into drupal, get this book! (Score:1)
Fun Fact (Score:1, Troll)
Re: (Score:2)
Re: (Score:1)
The Font (Score:1)
And yet the last part of the entire book, the Colophon, where these things go, says this:
Nobody mentions SharePoint (Score:2)
Every time I looked at Drupal I found it too complex for whatever simple site I was setting up. I have used Joomla, which was easier to jump into, but simplistic and inflexible. Honestly, SharePoint 2007 is much easier to use and fairly powerful and flexible. If you don't want to set up and administer the swerver, you can buy hosting or even get it free (with limitations) from a number of providers.
Drupal is great BUT (Score:1)
Its definitely designed more towards community/portal/media/big sites then say a small business site. It can be used towards small sites but the way the breadcrumbs and taxonomy works it'll be way easier to use something like WebsiteBaker or Etomite. Having said that I've used Drupal for the last 6 sites I've built.
Also once Ubercart is much more mature Drupal/Ubercart will be a killer combo.
The other thing that Drupal is missing is a little better forum system and a proper photo/media gallery. The current
Re: (Score:2).
;-) But for small-to-medium-sized sites, it's easily my go-to CMS.
We use Drupal for our site (Score:2)
Drupal is awesome. I'm not crazy about the fact that it's written in PHP... but I have to admit it's one of the better-written PHP projects.
I use it for a bunch of Web sites, including my company's site. It's extremely powerful and pretty easy to customize.
Intersect my liking for Drupal with my love of O'Reilly books and I feel a purchase coming on...
oh boy here we go again (Score:2)
Drupal is software written by amateurs--oh, they are well-meaning and their sheer numbers swamps the efforts of most other projects, making it a powerful temptation for the get-it-done-now. But Drupal is terribly convoluted, inefficient, buggy and expensive (it is impossible to deploy a Drupal site without an admin on retainer to apply the numerous security updates)--its arcane architecture was written to accomodate the quirks of the non-object oriented and now-obsolete PHP4--its a bandwagon with a long and
All CMS's suck. Drupal sucks less. (Score:2)
(with apologies to Michael Elkins)
I've had occasion to download and test out dozens of Content Management Systems over the past ten years or so. Drupal is the first one where I looked at the code and didn't immediately think "Oh, crap. I should really rewrite half of this."
Drupal has a steep learning curve. After working with it for two years, I feel like I'm just beginning to grasp some of the underlying concepts.
Drupal isn't the fastest CMS out there; it isn't the easiest to use; it isn't the biggest o
Drupal rocks! (Score:1)
Joomla! Rules (Score:1)
Drupal changed my life (Score:2, Interesting)
I'm not kidding. So much of what I used to do for a living is trivial with Drupal. Writing custom modules for our clients is fun again and I never have to worry about mundane every-site stuff like user management, perms, front controller dispatching...you name it; if it's common, Drupal will do it for you. Or a contrib module will.
I started picking up Drupal in late 2005, played and learned for a couple of years, and 2008 was almost entirely Drupal builds. From cookpolitical.com where we worked out seri
Petty Much? (Score:5, Insightful)
I can't shake the feeling this is something of a troll, but I'll bite. There are two reasons that I will purchase a tangible copy (physical--as someone else mentioned, dead tree):
1) I like to have a physical copy of a text. Sure, digital prints are easier to search and just as easy to browse, but there are times when I'd like to have something to read through no matter where I am, particularly if I don't happen to have a laptop with me. (Increasingly rare, but likely. Doctor's offices come to mind; there's no way I'm reading the cruft they have stacked atop a bare table in the waiting room.)
2) It's a great way to show your support for the authors' work and to help offset the publication costs. I've done that with the Baen Library before. I'll read some of their texts online, and if I like it, I'll go to the bookstore to purchase a couple of copies for myself and friends. If the author is especially interesting, I'll even buy a few of his or her works while I'm there if I haven't read them.
The desire to have a tangible asset isn't the result of ignorance or stupidity (though, I'd argue it's pretty stupid to waste your own paper printing out the entire thing when there's a perfectly good bound copy you can buy), and I think it's petty to attribute it to that.
Re: (Score:1)
The reason i like to buy a hardcopy book when i'm learning something new is because it usually pays to read the whole thing from start to finish - and i can never manage that with a PDF or web version.
If i read it from start to finish, i don't miss out on things that i don't know i need to know and therefore don't look at them while i'm skipping through the digital version. Read through the whole thing and you get the whole story.
Also, i like to get away from the bloody computer as much as i can - and being
Re: (Score:2)
I don't think people who buy books instead of searching online "can't seek out information on the own". I mean, how hard is it? Does anybody outside of Myranmar and Ask Slashdot not know how to use Google? Some people just have to have hard copy. Where I work, all employees have Safari Books Online accounts that give them unlimited access to to electronic versions of all the IT titles from O'Reilly, Prentice-Hall, Microsoft Press, and about 20 other publishers. Safari's web versions are well done, too, much
Re: (Score:2, Interesting)
I don't think it's as much a case of people in Myranma not being able to find things using Google, but a case of Google not being able to find Myranma.
Not quite... (Score:5, Informative) [drupal.org]..
Re: (Score:2, Interesting)
It has been an absolute lifesaver.
One thing that I still cannot get my head around is how one does a master-detail type relationship with CCK and views, or insert a view into a page and add new nodes to a page . In other words how common Db structures are implemented with CCK.
Again the book is lucid and usable as a reference and I hope there is a part 2 to it that covers more advanced techniques (not features)
T
Re: (Score:2)
Because if you don't have any use for views/cck, other CMS are way easier to style and maintain.
Examples of what CMS are easier to style and maintain would be nice. I would really like to know.
Re: (Score:1)
Anything not written in PHP?
Re: (Score:3, Insightful)
Implementation languages seldom affect what can be developed. I could write a crappy CMS in Python, or C, or RoR, or Perl. The problem is the data and how it is structured. Usually its an interface issue. And that is a design/coding issue issue. Not because my if require {} or
:\n\t
Re: (Score:1)
But languages and their libraries inform design decisions. And I have tended to find that people who prefer a more structured language are generally more structured in their design.
Re: (Score:2)
Assembly is highly structured, yet I'd like to see you write a CMS in it.
C is highly structured (no pun intended) yet I'd like to see you write a CMS in it.
Really, the only thing you are partially right on is libraries. But I think you are right for the wrong reason. The libraries carry what the language is intended for. For Python, it is simplicity in everything. For PHP, its a hacked-together scripting languages for websites.
But all these languages have interfaces, be it an H file or an abstract base clas
Re: (Score:1)
Assembly is highly structured, yet I'd like to see you write a CMS in it.
C is highly structured (no pun intended) yet I'd like to see you write a CMS in it.
I think we're using the word "structured" to mean different things. The so-called Structured Programming languages of Dijkstra's era tried to get people away from the JMPs of assembly language, and object-oriented programming is more structured still.
What do you mean by structured?
I'm really surprised that I am contradicting someone with a 4-digit UID.
Let's get our terminology straight, and see if we still disagree
:)
Re: (Score:2)
Until recently, at least, PHP didn't even have any implementation of namespaces -- it was (is?) genuinely a crippled language, whose main technical advantage was a small memory footprint. It was adopted largely because ISPs perceived -- rightly or wrongly -- that it was easier/safer to give PHP to newbies to mess with rather than something like perl.
Embracing PHP was a really remarkable turn of events -- it's the "worse is better" philosophy
Re: (Score:2)
Re: (Score:1)
Sorry, I don't have much experience with CMSs. I've just written enough PHP in my life to know that I never want to use it again
:)
Re: (Score:1)
Re: (Score:2)
Re: (Score:2)
API's that have hundreds to thousands of functions available are much easier to use and understand. This was in 1993'ish.
So lets not, "fuck Kernighan and
Re: (Score:1)
Couldn't you get your head around PHP? Not similar enough to BASIC for you, ey? | http://developers.slashdot.org/story/09/01/09/1423203/using-drupal | CC-MAIN-2016-07 | refinedweb | 4,431 | 70.94 |
Scope of Variables in Java Programming
Get FREE domain for 1st year and build your brand new site
Scope of a variable defines how a specific variable is accessible within the program or across classes. An assigned value to a variable makes sense and becomes usable only when the variable lies within the scope of the part of the program that executes or accesses that variable.
Variables are mainly of the following types:
- Static Variables
- Non-Static Varaiables
Reference: Oracle Official Documentation
The non-static variables are further classified into:
- Block Variables
- Local Variables
- Class Variables (non-static)
Static Variables:
Static variables are global variables and are variables declared inside the class but outside of all methods and loops. These variables have scope within the class such that the methods and blocks can access these.
package scope_ariables; public class area_calculation { static int b=5; //class variable public static void main(String[] args) { double a=5.7; double RectangleArea=area_of_rectangle(a,b); System.out.println(RectangleArea); } public static double area_of_rectangle(double length, double breadth) { double area= length * b; return area; } }
Here the variable declared outside the main method and within the scope of the class, is accessed by both the loops inside the class and the methods.
- Static variables can be accessed by both static and non static methods. All the instances of the class can access these static variables by just using the class name.
- Static variables are common for all the instances of the class. This is similar to a chocolate cake shared among friends. Any addition made to the variable affects the other instances using the variable.
Non-Static Variables:
Non static variables of a class, in case of a class variable
are accessed only within the class. This is subject to the presence of access modifiers which is discussed later in this article.
Block Variables:
These are variables used specifically within a bracket such as within loops. A good example is the variable declared within a for loop. In the example below, the variable i is only accessible within the for loop, which means that the scope of the variable i ends outside the loop. Only the variables declared outside the for loop such as the variable int a, can be called either inside or outside the loop.
package scope_variables; public class variablescope{ public static void main(String[] args) { int a =5; // integer i is declared within the for loop. for(int i=0; i<5; i++) { System.out.println(i); } System.out.println(a); } }
What happens when a block variable is called outside the loop? An error is thrown
Local Variables:
Local variables are also called as method variables. These variables are accessed only within the methods they are declared and the scope ends once the method is finished executing.
package scope_variables; public class area_calculation { public static void main(String[] args) { double a = 5.7; double SquareArea=area_of_square(a); } public static double area_of_square(double side) { double area=side * side; return area; // scope of variable area is limited to this method } }
What happens to a local variable outside the method?
An error is thrown due to unresolved compilation problem
Class Variables (Non-Static):The non-static class variables, which are also knows as member variables, can be accessed by only by creating the instance of the class. Unlike static variables where the variable is shared among the instances, here each instance has its unique copy of the variable. Hence the changes made by these instances do not affect the value of variables in other instances.
public class area_calculation { int side = 10; // non-static variable public static void main(String[] args) { // need an instance to access the non-static variable area_calculation AreaCalc = new area_calculation(); System.out.println("The class variable is " + AreaCalc.side); } }
Scope based on access modifiers
Sometimes, the scope of the declared class variables depends on the access modifier of the class. There are four types of access modifiers:
- Default
- Private
- Protected
- Public
- A default class, which has no specified modifier has its member variables easily accessible by the same class, its subclass in the same package, and different class in both same package. This is a package only access scope. For a good analogy to understand this concept, consider an on line class, where only specific students enrolled in the course can access the link.
The member variable of a private class can not be accessed by another other class irrespective of its package or sub-class status.To understand this, consider the example of your personal bank account, where only you can access the account.
The class variable of protected class is accessed by both its subclass and non-subclass within the same package.Here, access is denied to only non-subclass in a different package. An example for protected class is your home. Whoever stays there including guests can stay. When a child from the house stays in a far away place, he or she can still keep his or her things at home.
The member variables of public class has universal scope, which means that the variables declared as global variables are accessed by all the subclasses and non-subclasses that may be within or not within the package. Public classes are similar to public libraries, where anyone can access the materials with no restrictions.
The following table shows the scope of variables based on access modifiers: | https://iq.opengenus.org/scope-of-variables-in-java/ | CC-MAIN-2021-43 | refinedweb | 895 | 51.89 |
Euler problems/91 to 100
From HaskellWiki:
import Data.List import Data.Char pow2=[a*a|a<-[0..9]] sum_pow 1=0 sum_pow 89=1 sum_pow x= sum_pow(sum [pow2 !! y |y<-digits x]) digits n {- change 123 to [3,2,1] -} |n<10=[n] |otherwise= y:digits x where (x,y)=divMod n 10 groups=1000 problem_92 b=sum [sum_pow a|a<-[1+b*groups..groups+b*groups]] gogo li =if (li>9999) then return() else do appendFile "file.log" ((show$problem_92 li) ++ "\n") gogo (li+1) main=gogo 0) -- The.
9 Problem 99
Which base/exponent pair in the file has the greatest numerical value?
Solution:
problem_99 = undefined
10 Problem 100
Finding the number of blue discs for which there is 50% chance of taking two blue.
Solution:
problem_100 = undefined | https://wiki.haskell.org/index.php?title=Euler_problems/91_to_100&oldid=17172 | CC-MAIN-2016-07 | refinedweb | 132 | 60.41 |
Azure queues help to communicate data between web role and worker role. Web roles are nothing but web applications which can be accessed by the end browser. Worker roles are background processes which run in the Azure system and they do not take direct request from the web.So if we want to pass data to worker roles, we need to use Queues. Queues are temporary storage which act like a bridge between web role and worker role. So you can post data to web role, web role posts data to queues and worker role picks the data from queues to do further processing.Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more @ click here , you can also catch me on my trainings @ click here.
In this article, we will create a simple application which will allow us to enter customer feedbacks. These customer feedback messages will go through a quality check whether the messages have any kind of spam keywords. Currently we will only check for “XXX”.
In other words, the above web role will submit the feedback message to queues, worker role will pick up the message, do-requisites in place. You can read this you define the configuration name while service configuration actually set the value.
Below is how the service definition file looks like, we need the account name, shared key, queue storage and table storage end point. We need to define both these definitions both for worker role as well as for web role.
We are not sure if there is a way to avoid this redundancy. We Googled and found that we needed to define different definitions even if the names are the same. This link, it's time to define the configuration values for these.
<?xml version="1.0"?>
<ServiceConfiguration serviceName="QueueStorage"
xmlns="">
<Role name="Web="Worker>
The next step is to create our entity class which has customer name and message. So below is a simple entity class called as CustomerInfo which inherits from TableStorageEntity. This class has 2 properties - CustomerName and Message.
CustomerInfo
TableStorageEntity
CustomerName:
TableStorageDataServiceContext
public class CustomerInfoDataContext : TableStorageDataServiceContext
{}
In the same class, we create an initializetable method which will create the table structure define by the CustomerInfo class. Below is the code snippet explanation with comments.
initializetable IQueryable interface which exposes CustomerInfo class which can be used by the Azure system to create Azure table structure.
IQueryable
public IQueryable<CustomerInfo> CustomerInfos
{
get
{
return this.CreateQuery<CustomerInfo>("CustomerInfos");
}
}
We are also exposing.
AddCustomer
AddObject
SaveChanges
public void AddCustomer(CustomerInfo _objCustomer)
{
this.AddObject("CustomerInfos", _objCustomer);
this.SaveChanges();
}
Once we add the customer entity into the table, we would like to display the same, so we have exposed a GetCustomerInfo function which is typecasted to list and this can be binded to the gridview.
GetCustomerInfo
gridview
public List<CustomerInfo>.
gridview.
Queuestorage
MessageQueue queue = qs.GetQueue("customer");
Create the customer queue if it does not exist using the DoesQueueExist method.
DoesQueueExist
if (!queue.DoesQueueExist())
queue.CreateQueue();
Create the message object by concaten
CustomerInfoDataContext objCustomerDataContext = new CustomerInfoDataContext();
Use the GetCustomerInfo function which was discussed in the previous steps to get a list of CustomerInfo objects.
List<CustomerInfo> _objCustomer = objCustomerDataContext.GetCustomerInfo();
Finally bind the customer objects with the gridview.
if (_objCustomer.Count > 0)
{
GridView1.DataSource = _objCustomer;
GridView1.DataBind();
}
In step 7, we have seen how the web role inserts data into the queue. Now the queue is read by the worker role, the message is parsed and searched for ‘xxx’. If it's not found, it will add the same to the tables.
So the first step is ‘XXX’, we add it to the table as entity using the data context object as shown in the below code snippet:
while ‘Create test storage tables’ as shown below:
Enjoy your hard work. If you now add ‘XXX’ in the feedback message, it's not added to the table and rejected by the worker role. If you add a normal message, it's displayed on the gridview source of the web. | https://www.codeproject.com/Articles/58039/Simple-Steps-to-Run-your-First-Azure-Queue-Progr?msg=3644676 | CC-MAIN-2017-09 | refinedweb | 677 | 55.95 |
:
.
What to notice here is that the
to is not the end of the route (the world
) in this example it's used in the middle of the Pipes and filters. In fact we can change the
bean types to
to as well:.
A
CamelContext object represents the Camel runtime system. You typically have one
CamelContext object in an application. A typical application executes the following steps.
CamelContextobject.
CamelContextobject.
CamelContextobject to connect the endpoints.
start()operation on the
CamelContextobject. This starts Camel-internal threads that are used to process the sending, receiving and processing of messages in the endpoints.
stop()operation on the
CamelContextobject. Doing this gracefully stops all the endpoints and Camel-internal threads..
The
Processor interface represents a class that processes a message. The signature of this interface is shown below..
Return to the main Getting Started page for additional introductory reference information.
At a high level Camel consists of a CamelContext which contains a collection of Component instances. A Component is essentially a factory of Endpoint instances. You can explicitly configure Component instances in Java code or an IoC container like Spring or Guice, or they can be auto-discovered using URIs.
An Endpoint acts rather like a URI or URL in a web application or a Destination in a JMS system; you can communicate with an endpoint; either sending messages to it or consuming messages from it. You can then create a Producer or Consumer on an Endpoint to exchange messages with it.
The DSL makes heavy use of pluggable Languages to create an Expression or Predicate to make a truly powerful DSL which is extensible to the most suitable language depending on your needs. The following languages are supported
Most of these languages is also supported used as Annotation Based Expression Language.
For a full details of the individual languages see the Language Appendix
Camel makes extensive use of URIs to allow you to refer to endpoints which are lazily created by a Component if you refer to them within Routes.
important
Make sure to read How do I configure endpoints to learn more about configuring endpoints. For example how to refer to beans in the Registry or how to use raw values for password options, and using property placeholders etc.
EventNotifierlog all sent to endpoint events and how long time it took..
The following annotations is supported and inject by Camel's
CamelBeanPostProcessor.
Bean Binding in Camel defines both which methods are invoked and also how the Message is converted into the parameters of the method when it is invoked.
The binding of a Camel Message to a bean method call can occur in different ways, in the following order of importance:
@Handlerannotation, then that method is selected
In cases where Camel cannot choose a method to invoke, an
AmbiguousMethodCallException is thrown.
By default the return value is set on the outbound message body..
You can use the Parameter Binding Annotations to customize how parameter values are created from the Message
For example, a Bean such as:
Or the Exchange example. Notice that the return type must be void when there is only a single parameter of the type
org.apache.camel.Exchange:.
Available as of Camel 2.9
Camel uses the following rules to determine if it's a parameter value in the method option
trueor
falsewhich denotes a boolean value
123or
7
nullvalue:
Available as of Camel 2.8
If you have a Bean with overloaded methods, you can now specify parameter types in the method name so Camel can match the method you intend to use.
Given the following bean:.
We support the injection of various resources using @EndpointInject or @BeanInject. This can be used to inject..
To consume a message you use the @Consume annotation to mark a particular method of a bean as being a consumer method. The uri of the annotation defines the Camel Endpoint to consume from.
e.g. lets invoke the
onCheese() method with the String body of the inbound JMS message from ActiveMQ on the cheese queue; this will use the Type Converter to convert the JMS ObjectMessage or BytesMessage to a String - or just use a TextMessage from JMS
The Bean Binding is then used to convert the inbound Message to the parameter list used to invoke the method .
What this does is basically create a route that looks kinda like this.
See the warning above.
You can use the
context option to specify which CamelContext the consumer should only apply for. For example:
The consumer above will only be created for the CamelContext that have the context id =
camel-1. You set this id in the XML tag:
If you want to invoke a bean method from many different endpoints or within different complex routes in different circumstances you can just use the normal routing DSL or the Spring XML configuration file.
For example
which will then look up in the Registry and find the bean and invoke the given bean name. (You can omit the method name and have Camel figure out the right method based on the method annotations and body type).
You can always use the bean
Now the property is named 'service' which then would match step 3 from the algorithm, and have Camel invoke the getServiceEndpoint method.
We could also have omitted the property attribute, to make it implicit
Now Camel matches step 5, and loses the prefix on in the name, and looks for 'service' as the property. And because there is a getServiceEndpoint method, Camel will use that..
We recommend Hiding Middleware APIs from your application code so the next option might be more suitable.
You can add the @Produce annotation to an injection point (a field or property setter) using a ProducerTemplate or using some interface you use in your business logic. e.g.
Here Camel will automatically inject a smart client side proxy at the @Produce annotation - an instance of the MyListener instance. When we invoke methods on this interface the method call is turned into an object and using the Camel Spring Remoting mechanism it is sent to the endpoint - in this case the ActiveMQ endpoint to queue foo; then the caller blocks for a response.
If you want to make asynchronous message sends then use an @InOnly annotation on the injection point.
We support the use of @RecipientList on a bean method to easily create a dynamic Recipient List using a Java method..
For a complete example please see the BAM Example, which is part of the standard Camel Examples.
Testing of distributed and asynchronous processing is notoriously difficult. The Mock, Test and DataSet endpoints work great with the Camel Testing Framework to simplify your unit and integration testing using Enterprise Integration Patterns and Camel's large range of Components together with the powerful Bean Integration..
Where someName can be any string that uniquely identifies the endpoint.
You can append query options to the URI in the following format,
?option=value&option=value&...:
You can see from the javadoc of MockEndpoint the various helper methods you can use to set expectations. The main methods are as follows::
There are some examples of the Mock endpoint in use in the camel-core processor tests.:component:".
The same example using the Test Kit
Available as of Camel 2.10.
Available as of Camel 2.7:
In all approaches the test classes look pretty much the same in that they all reuse the Camel binding and injection annotations.
Here is the Camel Test example:
CamelTestSupportbut has no CDI, Spring or Guice dependency injection configuration but instead overrides the
createRouteBuilder()method.
Here is the CDI Testing example:
camel-example-cdi-testexample and the test classes that come with it.
Here is the Spring Testing example using XML Config:
@DirtiesContexton the test methods to force Spring Testing to automatically reload the
CamelContextafter.
ContextConfigclass does all of the configuration; so your entire test case is contained in a single Java class. We currently have to reference by class name this class in the
@ContextConfigurationwhich:
@RunWithannotation to support the features of
CamelTestSupportthrough annotations on the test class. See Spring Testing for a list of annotations you can use in your tests.
Here is the Blueprint Testing example using XML Config:
getBlueprintDescriptorsto indicate that by default we should look for the
camelContext.xmlin the package to configure the test case which looks like this: CDI Testing, Spring Testing or Guice the camel-test module was introduced so you can perform powerful Testing of your Enterprise Integration Patterns easily.
To get started using Camel Test you will need to add an entry to your pom.xml
Available as of Camel 2.8
You might also want to add slf4j and log4j to ensure nice logging messages (and maybe adding a log4j.properties file into your src/test/resources directory).
Available as of Camel 2.7
Tests that use port numbers will fail if that port is already on use.
AvailablePortFinder provides methods for finding unused port numbers at runtime..CamelTestSupport) and deliver integration with Spring into your test classes. Instead of instantiating the CamelContext and routes programmatically, these classes rely on a Spring context to wire the needed components together. If your test extends one of these classes, you must provide the Spring context by implementing the following method.
You are responsible for the instantiation of the Spring context in the method implementation. All of the features available in the non-Spring aware counterparts from Camel Test are available in your test.
In this approach, your test classes directly inherit from the Spring Test abstract test classes or use the JUnit 4.x test runner provided in Spring Test. This approach supports dependency injection into your test class and the full suite of Spring Test annotations but does not support the features provided by the CamelSpringTestSupport classes.
Here is a simple unit test using JUnit 3.x support from Spring Test using XML Config.
Also notice the use of @ContextConfiguration to indicate that by default we should look for the FilterTest-context.xml on the classpath to configure the test case which looks like this
For instance, like this maven folder layout:
You can completely avoid using an XML configuration file by using Spring Java Config. Here is a unit test using JUnit 4.x support from Spring Test using Java.
You can avoid extending Spring classes by using the SpringJUnit4ClassRunner provided by Spring Test. This custom JUnit runner means you are free to choose your own class hierarchy while retaining all the capabilities of Spring Test.
When using Spring 4.1 onwards, you need to use the @BootstrapWith annotation to configure it to use Camel testing, as shown below.
Using org.apache.camel.test.junit4.CamelSpringJUnit4ClassRunner runner with the @RunWith annotation or extending org.apache.camel.testng.AbstractCamelTestNGSpringContextTests provides the full feature set of Spring Test with support for the feature set provided in the CamelTestSupport classes. A number of Camel specific annotations have been developed in order to provide for declarative manipulation of the Camel context(s) involved in the test. These annotations free your test classes from having to inherit from the CamelSpringTestSupport classes and also reduce the amount of code required to customize the tests.
The following example illustrates the use of the @MockEndpoints annotation in order to setup mock endpoints as interceptors on all endpoints using the Camel Log component and the @DisableJmx annotation to enable JMX which is disabled during tests by default. Note that we still use the @DirtiesContext annotation to ensure that the CamelContext, routes, and mock endpoints are reinitialized between test methods.
If you wish to programmatically add any new assertions to your test you can easily do so with the following. Notice how we use @EndpointInject to inject a Camel endpoint into our code then the Mock API to add an expectation on a specific message.
Sometimes once a Mock endpoint has received some messages you want to then process them further to add further assertions that your test case worked as you expect.
So you can then process the received message exchanges if you like....
We have support for Google Guice as a dependency injection framework.
Maven users will need to add the following dependency to their
pom.xml for this component:
The GuiceCamelContext is designed to work nicely inside Guice. You then need to bind it using some Guice Module.
The camel-guice library comes with a number of reusable Guice Modules you can use if you wish - or you can bind the GuiceCamelContext yourself in your own module.
So you can specify the exact RouteBuilder instances you want
Or inject them all
You can then use Guice in the usual way to inject the route instances or any other dependent objects.
A common pattern used in J2EE is to bootstrap your application or root objects by looking them up in JNDI. This has long been the approach when working with JMS for example - looking up the JMS ConnectionFactory in JNDI for example.
You can follow a similar pattern with Guice using the GuiceyFruit JNDI Provider which lets you bootstrap Guice from a jndi.properties file which can include the Guice Modules to create along with environment specific properties you can inject into your modules and objects.
If the jndi.properties is conflict with other component, you can specify the jndi properties file name in the Guice Main with option -j or -jndiProperties with the properties file location to let Guice Main to load right jndi properties file.
You can use Guice to dependency inject whatever objects you need to create, be it an Endpoint, Component, RouteBuilder or arbitrary bean used within a route.
The easiest way to do this is to create your own Guice Module class which extends one of the above module classes and add a provider method for each object you wish to create. A provider method is annotated with @Provides as follows
You can optionally annotate the method with @JndiBind to bind the object to JNDI at some name if the object is a component, endpoint or bean you wish to refer to by name in your routes.
You can inject any environment specific properties (such as URLs, machine names, usernames/passwords and so forth) from the jndi.properties file easily using the @Named annotation as shown above. This allows most of your configuration to be in Java code which is typesafe and easily refactorable - then leaving some properties to be environment specific (the jndi.properties file) which you can then change based on development, testing, production etc.
It is sometimes useful to create multiple instances of a particular RouteBuilder with different configurations.
To do this just create multiple provider methods for each configuration; or create a single provider method that returns a collection of RouteBuilder instances.
For example included in the Camel distribution you could use
or the following external Camel components
Here's a simple example showing how we can respond to InOut requests on the My.Queue queue on ActiveMQ with a template generated response. The reply would be sent back to the JMSReplyTo Destination.
If you want to use InOnly and consume the message and send it to another destination you could use
Camel can work with databases in a number of different ways. This document tries to outline the most common approaches.
Camel provides a number of different endpoints for working with databases
Various patterns can work with databases as follows
Supported versions
The information on this page applies for Camel 2.4 onwards. Before Camel 2.4 the asynchronous processing is only implemented for JBI where as in Camel 2.4 onwards we have implemented it in many other areas. See more at Asynchronous Routing Engine.
Camel supports a more complex asynchronous processing model. The asynchronous processors implement the AsyncProcessor interface which is derived from the more synchronous Processor interface. There are advantages and disadvantages when using asynchronous processing when compared to using the standard synchronous processing model.
Advantages:
Disadvantages:
We recommend that processors and components be implemented the more simple synchronous APIs unless you identify a performance of scalability requirement that dictates otherwise. A Processor whose process() method blocks for a long time would be good candidates for being converted into an asynchronous processor.
The AsyncProcessor defines a single
process() method which is very similar to it's synchronous Processor.process() brethren. Here are the differences:
trueif it does complete synchronously, otherwise it returns
false.
callback.done(boolean sync)method. The sync parameter MUST match the value returned by the
process()method.. See below for an example.
Now that we have understood the interface contract of the AsyncProcessor, and have seen how to make use of it when calling processors, lets looks a what the thread model/sequence scenarios will look like for some sample routes.
The Jetty component's consumers support async processing by using continuations. Suffice to say it can take a http request and pass it to a camel route for async processing. If the processing is indeed async, it uses 2 separate threads are used to complete the processing of the original http request. The first thread is synchronous up until processing hits the jhc producer which issues the http request. It then reports that the exchange processing will complete async since it will use a NIO to complete getting.
Lets say we have 2 custom processors, MyValidator and MyTransformation, both of which are synchronous processors. Lets say we want to load file from the data/in directory validate them with the MyValidator() processor, Transform them into JPA java objects using MyTransformation and then insert them into the database using the JPA component. Lets 2nd part of the thread sequence.
Generally speaking you get better throughput processing when you process things synchronously. This is due to the fact that starting up an asynchronous thread and doing a context switch to it adds a little bit of of overhead. So it is generally encouraged that AsyncProcessors do as much work as they can synchronously. When they get to a step that would block for a long time, at that point they should return from the process call and let the caller know that it will be completing the call asynchronously..
To include the Camel Tranport into your CXF bus you use the CamelTransportFactory. You can do this in Java as well as (or camel-cxf.jar if your camel version is less than 2.7.x) in your app, cxf will scan the jar and load a CamelTransportFactory for you.
Camel transport provides a setContext method that you could use to set the Camel context into the transport factory. If you want this factory take effect, you need to register the factory into the CXF bus. Here is a full example for you.
The elements used to configure.
destinationelement
You configure.
The
camel:destination element for Spring has a number of child elements that specify configuration information. They are described below.
conduitelement.
The
camel:conduit element has a number of child elements that specify configuration information. They are described below.
From Camel 2.11.x, Camel Transport supports to be configured with Blueprint.
If you are using blueprint, you should use the the namespace and import the schema like the blow.
In blueprint
camel:conduit
camel:destination only has one camelContextId attribute, they doesn't support to specify the camel context in the camel destination.
This example shows how to use the camel load balancing feature in CXF. You need to load the configuration file in CXF and publish the endpoints on the address "camel://direct:EndpointA" and "camel://direct:EndpointB"
Better JMS Transport for CXF Webservice using Apache Camel.
There now follows the documentation on camel tutorialsWe have a number of tutorials as listed below. The tutorials often comes with source code which is either available in the Camel Download or attached to the wiki page.:
We use the following Camel components:.
from="jmsbroker:queue:numbers).to("multiplier");
The Server is started using the
org.apache.camel.spring.Main class that can start camel-spring application out-of-the-box. The Server can be started in several flavors:
org.apache.camel.spring.Mainclass
In this sample as there are two servers (with and without AOP) we have prepared some profiles in maven to start the Server of your choice.
The server is started with:.
And the CamelClient source code:
ProducerTemplateis retrieved from a Spring
ApplicationContextand used to manually place a message on the "numbers" JMS queue. The
requestBodymethod:
ProducerTemplate. In a non-trivial example you would have the bean injected as in the standard Spring manner."then its just a matter of getting hold of this endpoint instead of the JMS and all the rest of the java code is exactly the
Also see the Maven
pom.xml file how the profiles for the clients is defined...
In this part we will introduce Camel so we start by adding Camel to our pom.xml:
That's it, only one dependency for now.
Synchronize IDE
If you continue from part 1, remember to update your editor project settings since we have introduce new .jar files. For instance IDEA has a feature to synchronize with Maven projects.
Now we turn towards our webservice endpoint implementation where we want to let Camel have a go at the input we receive. As Camel is very non invasive its basically a .jar file then we can just grap Camel but creating a new instance of
DefaultCamelContext that is the hearth of Camel its context..
Component Documentation
Then we change the code in the method that is invoked by Apache CXF when a webservice request arrives. We get the name and let Camel have a go at it in the new method we create sendToCamel:
Next is the Camel code. At first it looks like there are many code lines to do a simple task of logging the name - yes it is. But later you will in fact realize this is one of Camels true power. Its concise API. Hint: The same code can be used for any component in Camel.
Okay there are code comments in the code block above that should explain what is happening. We run the code by invoking our unit test with maven
mvn test, and we should get this log line:
Okay that isn't to impressive, Camel can log
Well I promised that the above code style can be used for any component, so let's store the payload in a file. We do this by adding the file component to the Camel context
And then we let camel write the payload to the file after we have logged, by creating a new method sendToCamelFile. We want to store the payload in filename with the incident id so we need this parameter also:
And then the code that is 99% identical. We have change the URI configuration when we create the endpoint as we pass in configuration parameters to the file component.
And then we need to set the output filename and this is done by adding a special header to the exchange. That's the only difference:
After running our unit test again with
mvn test we have a output file in the target folder:
In the file example above the configuration was URI based. What if you want 100% java setter based style, well this is of course also possible. We just need to cast to the component specific endpoint and then we have all the setters available:
That's it. Now we have used the setters to configure the
FileEndpoint that it should store the file in the folder target/subfolder. Of course Camel now stores the file in the subfolder.
Okay I wanted to demonstrate how you can be in 100% control of the configuration and usage of Camel based on plain Java code with no hidden magic or special XML or other configuration files. Just add the camel-core.jar and you are ready to go.
You must have noticed that the code for sending a message to a given endpoint is the same for both the log and file, in fact any Camel endpoint. You as the client shouldn't bother with component specific code such as file stuff for file components, jms stuff for JMS messaging etc. This is what the Message Endpoint EIP pattern is all about and Camel solves this very very nice - a key pattern in Camel.
Now that you have been introduced to Camel and one of its masterpiece patterns solved elegantly with the Message Endpoint its time to give productive and show a solution in fewer code lines, in fact we can get it down to 5, 4, 3, 2 .. yes only 1 line of code.
The key is the ProducerTemplate that is a Spring'ish xxxTemplate based producer. Meaning that it has methods to send messages to any Camel endpoints. First of all we need to get hold of such a template and this is done from the CamelContext
Now we can use template for sending payloads to any endpoint in Camel. So all the logging gabble can be reduced to:
And the same goes for the file, but we must also send the header to instruct what the output filename should be:
Well we got the Camel code down to 1-2 lines for sending the message to the component that does all the heavy work of wring the message to a file etc. But we still got 5 lines to initialize Camel.
This can also be reduced. All the standard components in Camel is auto discovered on-the-fly so we can remove these code lines and we are down to 3 lines.
Component auto discovery
When an endpoint is requested with a scheme that Camel hasn't seen before it will try to look for it in the classpath. It will do so by looking for special Camel component marker files that reside in the folder
META-INF/services/org/apache/camel/component. If there are files in this folder it will read them as the filename is the scheme part of the URL. For instance the log component is defined in this file
META-INF/services/org/apache/component/log and its content is:
The class property defines the component implementation.
Tip: End-users can create their 3rd party components using the same technique and have them been auto discovered on-the-fly.
Okay back to the 3 code lines:
Later will we see how we can reduce this to ... in fact 0 java code lines. But the 3 lines will do for now.
Okay lets head back to the over goal of the integration. Looking at the EIP diagrams at the introduction page we need to be able to translate the incoming webservice to an email. Doing so we need to create the email body. When doing the message translation we could put up our sleeves and do it manually in pure java with a StringBuilder such as:
But as always it is a hardcoded template for the mail body and the code gets kinda ugly if the mail message has to be a bit more advanced. But of course it just works out-of-the-box with just classes already in the JDK.
Lets use a template language instead such as Apache Velocity. As Camel have a component for Velocity integration we will use this component. Looking at the Component List overview we can see that camel-velocity component uses the artifactId camel-velocity so therefore we need to add this to the pom.xml
And now we have a Spring conflict as Apache CXF is dependent on Spring 2.0.8 and camel-velocity is dependent on Spring 2.5.5. To remedy this we could wrestle with the pom.xml with excludes settings in the dependencies or just bring in another dependency camel-spring:
In fact camel-spring is such a vital part of Camel that you will end up using it in nearly all situations - we will look into how well Camel is seamless integration with Spring in part 3. For now its just another dependency.
We create the mail body with the Velocity template and create the file
src/main/resources/MailBody.vm. The content in the MailBody.vm file is:
Letting Camel creating the mail body and storing it as a file is as easy as the following 3 code lines:
What is impressive is that we can just pass in our POJO object we got from Apache CXF to Velocity and it will be able to generate the mail body with this object in its context. Thus we don't need to prepare anything before we let Velocity loose and generate our mail body. Notice that the template method returns a object with out response. This object contains the mail body as a String object. We can cast to String if needed.
If we run our unit test with
mvn test we can in fact see that Camel has produced the file and we can type its content:
What we have seen here is actually what it takes to build the first part of the integration flow. Receiving a request from a webservice, transform it to a mail body and store it to a file, and return an OK response to the webservice. All possible within 10 lines of code. So lets wrap it up here is what it takes:
Okay I missed by one, its in fact only 9 lines of java code and 2 fields.
I know this is a bit different introduction to Camel to how you can start using it in your projects just as a plain java .jar framework that isn't invasive at all. I took you through the coding parts that requires 6 - 10 lines to send a message to an endpoint, buts it's important to show the Message Endpoint EIP pattern in action and how its implemented in Camel. Yes of course Camel also has to one liners that you can use, and will use in your projects for sending messages to endpoints. This part has been about good old plain java, nothing fancy with Spring, XML files, auto discovery, OGSi or other new technologies. I wanted to demonstrate the basic building blocks in Camel and how its setup in pure god old fashioned Java. There are plenty of eye catcher examples with one liners that does more than you can imagine - we will come there in the later parts.
Okay part 3 is about building the last pieces of the solution and now it gets interesting since we have to wrestle with the event driven consumer.
Brew a cup of coffee, tug the kids and kiss the wife, for now we will have us some fun with the Camel. See you in part 3..
URL Configuration::.
In OGNL glory this is done as:
where
request.body.incidentId computes to:
getIncidentId()method on the body..
Removed from distribution.
Now we need to configure Axis itself and this is done using its
server-config.wsdd file. We nearly get this for for free from the auto generated code, we copy the stuff from
deploy.wsdd and made a few modifications:!
If you use Maven to build your application your directory tree will look like this...
You should update your Maven pom.xml to enable WAR packaging/naming like this...
To enable more rapid development we highly recommend the jetty:run maven plugin.
Please refer to the help for more information on using jetty:run - but briefly if you add the following to your pom.xml
Then you can run your web application as follows
Under Construction
This tutorial is a work in progress.
So there's a company, which we'll call Acme. Acme sells widgets, in a fairly unusual way. Their customers are responsible for telling Acme what they purchased. The customer enters into their own systems (ERP or whatever) which widgets they bought from Acme. Then at some point, their systems emit a record of the sale which needs to go to Acme so Acme can bill them for it. Obviously, everyone wants this to be as automated as possible, so there needs to be integration between the customer's system and Acme.
Sadly, Acme's sales people are, technically speaking, doormats. They tell all their prospects, "you can send us the data in whatever format, using whatever protocols, whatever. You just can't change once it's up and running."
The result is pretty much what you'd expect. Taking a random sample of 3 customers:
Now on the Acme side, all this has to be converted to a canonical XML format and submitted to the Acme accounting system via JMS. Then the Acme accounting system does its stuff and sends an XML reply via JMS, with a summary of what it processed (e.g. 3 line items accepted, line item #2 in error, total invoice $123.45). Finally, that data needs to be formatted into an e-mail, and sent to a contact at the customer in question ("Dear Joyce, we received an invoice on 1/2/08. We accepted 3 line items totaling $123.45, though there was an error with line items #2 [invalid quantity ordered]. Thank you for your business. Love, Acme.").
So it turns out Camel can handle all this:
This tutorial will cover all that, plus setting up tests along the way.
Before starting, you should be familiar with:
You'll learn:
You may choose to treat this as a hands-on tutorial, and work through building the code and configuration files yourself. Each of the sections gives detailed descriptions of the steps that need to be taken to get the components and routes working in Camel, and takes you through tests to make sure they are working as expected.
But each section also links to working copies of the source and configuration files, so if you don't want the hands-on approach, you can simply review and/or download the finished files.
Here's more or less what the integration process looks like.
First, the input from the customers to Acme:
And then, the output from Acme to the customers:
To get through this scenario, we're going to break it down into smaller pieces, implement and test those, and then try to assemble the big scenario and test that.
Here's what we'll try to accomplish:
List<List<String>>to the above JAXB POJOs
We'll use Maven for this project as there will eventually be quite a few dependencies and it's nice to have Maven handle them for us. You should have a current version of Maven (e.g. 2.0.9) installed.
You can start with a pretty empty project directory and a Maven POM file, or use a simple JAR archetype to create one.
Here's a sample POM. We've added a dependency on camel-core, and set the compile version to 1.5 (so we can use annotations):.
Down the road we'll want to deal with the XML as Java POJOs. We'll take a moment now to set up those XML binding POJOs. So we'll update the Maven POM to generate JAXB beans from the XSD file.
We need a dependency:
And a plugin configured:
That should do it (it automatically looks for XML Schemas in
src/main/xsd to generate beans for). Run mvn install and it should emit the beans into
target/generated-sources/jaxb. Your IDE should see them there, though you may need to update the project to reflect the new settings in the Maven POM.
To get a start on Customer 1, we'll create an XSLT template to convert the Customer 1 sample file into the canonical XML format, write a small Camel route to test it, and build that into a unit test. If we get through this, we can be pretty sure that the XSLT template is valid and can be run safely in Camel.
Start with the Customer 1 sample input. You want to create an XSLT template to generate XML like the canonical XML sample above – an
invoice element with
line-item elements (one per item in the original XML document). If you're especially clever, you can populate the current date and order total elements too.
Solution: My sample XSLT template isn't that smart, but it'll get you going if you don't want to write one of your own.
Here's where we get to some meaty Camel work. We need to:
The easiest way to do this is to set up a Spring context that defines the Camel stuff, and then use a base unit test class from Spring that knows how to load a Spring context to run tests against. So, the procedure is:
src/test/java/your-package-here, perhaps called
XMLInputTest.java
src/test/resources, perhaps called
XMLInputTest-context.xml
src/test/resourcesinstead of in a package directory under there.
setUpmethod that instantiates it from the CamelContext. We'll use the ProducerTemplate later to send messages to the route.
Test it by running mvn install and make sure there are no build errors. So far it doesn't test much; just that your project and test and source files are all organized correctly, and the one empty test method completes successfully.
Solution: Your test class might look something like this:
So now we're going to write a Camel route that applies the XSLT to the sample Customer 1 input file, and makes sure that some XML output comes out:
src/test/resources
src/main/resources
src/test/javasomewhere). This route should use the Pipes and Filters integration pattern to:
mock:finishusing code like this:
direct:startendpoint, using code like this:
finish.getExchanges().get(0).getIn().getBody().
Solution: Your finished test might look something like this:
Test Base Class
Once your test class is working, you might want to extract things like the @Autowired CamelContext, the ProducerTemplate, and the setUp method to a custom base class that you extend with your other tests.
To get a start on Customer 2, we'll create a POJO to convert the Customer 2 sample CSV data into the JAXB POJOs representing the canonical XML format, write a small Camel route to test it, and build that into a unit test. If we get through this, we can be pretty sure that the CSV conversion and JAXB handling is valid and can be run safely in Camel.
To begin with, CSV is a known data format in Camel. Camel can convert a CSV file to a List (representing rows in the CSV) of Lists (representing cells in the row) of Strings (the data for each cell). That means our POJO can just assume the data coming in is of type
List<List<String>>, and we can declare a method with that as the argument.
Looking at the JAXB code in
target/generated-sources/jaxb, it looks like an
Invoice object represents the whole document, with a nested list of LineItemType objects for the line items. Therefore our POJO method will return an
Invoice (a document in the canonical XML format).
So to implement the CSV-to-JAXB POJO, we need to do something like this:
src/main/java, perhaps called
CSVConverterBean.
List<List<String>>and the return type
Invoice
Invoice, using the method on the generated
ObjectFactoryclass
List)
LineItemType(using the
ObjectFactoryagain)
List) and put them into the correct fields of the
LineItemType
DatatypeFactoryto create the
XMLGregorianCalendarvalues that JAXB uses for the
datefields in the XML – which probably means using a
SimpleDateFormatto parse the date and setting that date on a
GregorianCalendar
Invoice
Invoice
Solution: Here's an example of what the CSVConverterBean might look like.
Start with a simple test class and test Spring context like last time, perhaps based on the name
CSVInputTest:
Now the meaty part is to flesh out the test class and write the Camel routes..
Invoiceas the body. You could write a simple line of code to get the Exchange (and Message) from the MockEndpoint to confirm that.
Solution: Your finished test might look something like this:
To get a start on Customer 3, we'll create a POJO to convert the Customer 3 sample Excel data into the JAXB POJOs representing the canonical XML format, write a small Camel route to test it, and build that into a unit test. If we get through this, we can be pretty sure that the Excel conversion and JAXB handling is valid and can be run safely in Camel.
Camel does not have a data format handler for Excel by default. We have two options – create an Excel DataFormat (so Camel can convert Excel spreadsheets to something like the CSV
List<List<String>> automatically), or create a POJO that can translate Excel data manually. For now, the second approach is easier (if we go the
DataFormat route, we need code to both read and write Excel files, whereas otherwise read-only will do).
So, we need a POJO with a method that takes something like an
InputStream or
byte[] as an argument, and returns in
Invoice as before. The process should look something like this:
src/main/java, perhaps called
ExcelConverterBean.
InputStreamand the return type
Invoice
Invoice, using the method on the generated
ObjectFactoryclass
InputStream, and get the first sheet from it
LineItemType(using the
ObjectFactoryagain)
LineItemType(you'll need some data type conversion logic)
DatatypeFactoryto create the
XMLGregorianCalendarvalues that JAXB uses for the
datefields in the XML – which probably means setting the date from a date cell on a
GregorianCalendar
Invoice
Invoice
Solution: Here's an example of what the ExcelConverterBean might look like.
The unit tests should be pretty familiar now. The test class and context for the Excel bean should be quite similar to the CSV bean.
unmarshalstep since the Excel POJO takes the raw
InputStreamfrom the source endpoint
<bean>and endpoint for the Excel bean prepared above instead of the CSV bean
Logging
You may notice that your tests emit a lot less output all of a sudden. The dependency on POI brought in Log4J and configured commons-logging to use it, so now we need a log4j.properties file to configure log output. You can use the attached one (snarfed from ActiveMQ) or write your own; either way save it to
src/main/resources to ensure you continue to see log output.
Solution: Your finished test might look something like this:
With all the data type conversions working, the next step is to write the real routes that listen for HTTP, FTP, or e-mail input, and write the final XML output to an ActiveMQ queue. Along the way these routes will use the data conversions we've developed above.
So we'll create 3 routes to start with, as shown in the diagram back at the beginning:
....:.
Example::
In Camel 2.2: you can avoid the
BeanLanguage and have it just as:
You can use EL dot notation to invoke operations. If you for instance have a body that contains a POJO that has a
getFamiliyName method then you can construct the syntax as follows:).:
For example you could use Mvel).:
For example you could use OGNL).
Otherwise, you'll also need OGNL.
The recipientList element of the Spring DSL can utilize a property expression like:
In this case, the list of recipients are contained in the property 'myProperty'.
And the same example in Java DSL::
However any JSR 223 scripting language can be used using the generic DSL methods.
You should add the camel-groovy dependeny when using Groovy language with Camel. The generic camel-script is not optimized for best Groovy experience, and hence you should add camel-groovy as dependency.
Sometimes you may need to use custom
GroovyShell instance in your Groovy expressions. To provide custom
GroovyShell, add implementation of the
org.apache.camel.language.groovy.GroovyShellFactory SPI interface to your Camel registry. For example after adding the following bean to your Spring context...
...Camel will use your custom GroovyShell instance (containing your custom static imports), instead of the default one.
And the Spring DSL:).
The Simple Expression Language was a really simple language when it was created, but has since grown more powerful. It is primarily intended for being a really.
Alternative syntax
From Camel 2.5 onwards you can also use the alternative syntax which uses $simple{ } as placeholders.
This can be used in situations to avoid clashes when using for example Spring property placeholder together with Camel.
Configuring result type it is encouraged to always use ${ } tokens for the built-in functions.
The range operator now requires the range to be in single quote as well as shown:
"${header.zip} between '30000..39999'".
To get the body of the in message:
"body", or
"in.body" or
"${body}".
A complex expression must use ${ } placeholders, such
It is also possible to index in
Map or
List types, so you can do:
To assume the body is
Map based and lookup the value with
foo as key, and invoke the
getName method on that value. ${ }.
Important
There must be spaces around the operator.:
Using and,or operators
In Camel 2.4 or older the
and or
or can only be used once in a simple language expression. From Camel 2.5 onwards you can use these operators multiple times.:
Ranges are also supported. The range interval requires numbers and both from and end are inclusive. For instance to test whether a value is between 100 and 199:
Notice we use
.. in the range without spaces. It is it is lost in the deep blue sea
..
We can use the
?method=methodname option that we are familiar with the Bean component itself:
And from Camel 2.3 onwards you can also convert the body to a given type, for example to ensure that it is a String you can do:. Camel 2:
Available as of Camel 2.6
You can set a spring bean into an exchange property as shown below:
The Simple language is part of camel-core...
We have a
java.io.File handle for the file
hello.txt in the following relative directory:
.\filelanguage\test. And we configure our endpoint to use this starting directory
.\filelanguage.
The file tokens returned are:
We have a
java.io.File handle for the file
hello.txt in the following absolute directory:
\workspace\camel\camel-core\target\filelanguage\test. And we configure out endpoint to use the absolute starting directory:
\workspace\camel\camel-core\target\filelanguage.
The file tokens return are:
You can enter a fixed Constant expression such as
myfile.txt:
Lets assume we use the file consumer to read files and want to move the read files to backup folder with the current date as a sub folder. This can be achieved.
PropertyPlaceholderConfigurerwith) to avoid clashing with Spring's
PropertyPlaceholderConfigurer.
Notice how we use the
$simple{} syntax in the
toEndpoint above. If you don't do this, they will clash and Spring will throw an exception:.
If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).
Camel supports SQL to allow an Expression or Predicate to be used in the DSL or Xml Configuration. For example you could use SQL to create an Predicate in a Message Filter or as an Expression for a Recipient List.
And the spring.
You can easily use namespaces with XPath expressions using the Namespaces helper class.
Variables in XPath is defined in different namespaces. The default namespace is.:
variablesthat has been set using the
variable(name, value)fluent builder.
message.in.headerif there is a header with the given key.
exchange.propertiesif there is a property with the given key.
Camel adds the following XPath functions that can be used to access the exchange:
Here's an example showing some of these functions in use..
Available as of Camel 2.11
Some users may have XML stored in a header. To apply an XPath statement to a header's value you can do this by defining the
headerName attribute.
In XML DSL:
headerNameas the 2nd parameter as shown:
Here is a simple example using an XPath expression as a predicate in a Message Filter | http://camel.apache.org/manual/camel-manual-2.16.4.html | CC-MAIN-2018-39 | refinedweb | 8,071 | 62.07 |
Keypad input showed to serial monitor with arduino uno and 4x4 keypad full code...
Step 1: Connecting With Arduino
Connecting keypad with aruduino digital pins:
Keypad Pin Connects to Arduino Pin
1 D9
2 D8
3 D7
4 D6
5 D5
6 D4
7 D3
8 D2
Step 2: Code
CODE :
#include <Keypad.h>
const byte numRows= 4
const byte numCols= 4;
keymap[numRows][numCols]= { {'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'} };);
}
}
Step 3:
here is my blogspot link it has some extra diagram which you might find helpfull... blogspot link
Step 4: Adding Library
Adding the library :
To add the library go to Skeetches -->>Include library--> Type the libray name "keypad" then press install.Then upload the sketch to your arduino.
Here's Some optional link :
2 People Made This Project!
Samu Cacapupu made it!
AzwadA made it!
13 Discussions
Question 7 months ago on Step 2
what is const byte
Answer 5 weeks ago
const means constant - you can't change the value once set,
byte - it can only be one byte of storage long
const byte - a one byte long value that cannot be changed
Question 1 year ago on Step 1
Error message: No such file or directory
1 year ago
What are the materials needed to make that happen thing?
1 year ago
Error message:
" 'keymap' does not name a type"
Reply 1 year ago
put "char" (without quotation) in front that line.
1 year ago
Thank You very much...
2 years ago
i tried a lot for connecting the keypad in the above given way but it showed no output in serial monitor, i think this technique does not work
Reply 1 year ago
Are you using arduino uno? can you please upload a pic of the connections you made. i guess you misunderstood the pin 8 of your keypad as pin 1 at the very beginning i made that mistake too... i would like to help you out...Thanks
2 years ago
If you wan't to save four arduino pins you can use way: it's only require eight extra cheap diodes.
Reply 2 years ago
Thanks :)
2 years ago
This would be a great way to make your own DIY keypad security lock.
Reply 2 years ago
Thanks for your query ill upload it soon...stay connected.. | https://www.instructables.com/id/Arduino-Keypad-4x4-Tutorial/ | CC-MAIN-2019-26 | refinedweb | 393 | 75.24 |
C is perhaps not the easiest language to use for text handling- Both C++ and C# are much better. The problem is that C lacks an explicit string type and uses an array of char.
What is an Array?An array is a variable that holds a list of variables of the same type and size. A map might hold a two dimensional array (known as a matrix) of ints. An array of char can hold text but the very last character must be a NULL or '\0'.
In an array, the elements are accessed by their position and the first position is always 0, not 1 as in some other languages.
The declaration of an array uses square brackets after the variable name.
#include <stdio.h>
#include <string.h>
int main() {
char name[6];
int values[10];
strcpy(name,"David") ;
values[0]= 8;
printf("My name is %s",name) ;
return 0;
}
If you Make and run this, you'll see it outputs "My name is David". The %s matches to the first string parameter in the printf() function call, that is the value in name.
I also declared an array of 10 ints and set the first one to a value of 8.
The assignment of the string was done using a function strcpy(). We'll come back to functions in a later lesson. Accept it for now.
On the next page : More on assigning strings. | http://cplus.about.com/od/learningc/ss/clessonthree.htm | crawl-002 | refinedweb | 237 | 82.54 |
jay Yadav(13)
Vijay Prativadi(9)
Anubhav Chaudhary(2)
Satya Prakash(2)
Richa Garg(2)
Sharad Gupta(2)
Puran Mehra(2)
Delpin Susai Raj(1)
Amit Choudhary(1)
Chetankumar G Shetty(1)
Mahesh Chand(1)
Akshay Teotia(1)
Wolfgang Pleus(1)
Mahesh Alle(1)
Prakash Tripathi(1)
Chhavi Goel(1)
Vithal Wadje(1)
Nanhe Siddique(1)
Rakesh Singh(1)
Selva Ganapathy(1)
Avinash Kumar(1)
Raj Bandi(1)
Nitin Bhardwaj(1)
Sapna (1)
Dhananjay Kumar (1)
Resco (1)
Igor (1)
Dmitiriy Salko(1)
Tin Lam(1)
Prasad (1)
John Schofield(1)
Bipin Joshi(1)
Resources
No resource found
How To Reverse Geocode An Address In Xamarin Android App Using Visual Studio 2015
Nov 11, 2016.
In this article, you will learn how to reverse geocode an address in Xamarin Android app, using Visual Studio 2015.
Customize Reverse Engineer Code First - EF Power Tool Enhancement
Mar 07, 2016.
In this article you will learn how to customize reverse engineer code first .
Current Location Tracking and Reverse Geocoding in Windows Store Apps
Dec 21, 2014.
This article covers methods to display the user's location using GPS, the usage of Pushpins and Reverse Geocoding.
Exploiting Windows Server Reverse Shell
Dec 04, 2014.
This article demystifies the remote shell accesses by exploitation of unpatched Windows 2003 Server vulnerabilities and taking complete control over the target remote computers, which is in fact, a complex and difficult undertaking.
Applied Reverse Engineering With IDA Pro
Nov 13, 2014.
In this article you will learn Live Binary Sample Target, Target Analysis with IDA Pro, cracking the Target and an alternative way of tracing.
Bypassing Obfuscation: Ciphered Code Reverse Engineering
Nov 11, 2014.
In this article, we have performed reverse engineering over a protected binary by deep analysis of both obfuscated source code and MSIL assembly code.
Java Bytecode Reverse Engineering
Nov 09, 2014.
This paper explaines the mechanism of disassembling Java byte code in order to reveal sensitive information when the source of the Java binary is unavailable. We have come to an understanding of how to implement such reverse engineering using JDK utilities.
Extreme .NET Reverse Engineering: Part 5
Oct 27, 2014.
In this article, we have seen how to obtain sensitive information without having access to real source code, including how to manipulate IL code to do that.
Applied Reverse Engineering With OllyDbg
Oct 27, 2014.
The objective of this paper is to show how to crack an executable using the OllyDbg tool without seeing its source code.
.
.NET Binary Reverse Engineering: Part 1
Oct 23, 2014.
The prime objective of this article is to explain the .NET mother language called Common Instruction Language (CIL) that has laid the foundation of .NET.
Apply Reverse Function on Observable Array Using KnockoutJS
Oct 17, 2013.
In today's article I will explaiin how to apply a Reverse Function on an Observable Array using KnockoutJS.
How to Configure the DNS Reverse Lookup Zone
May 13, 2013.
In this Article you will learn about How to Configure the DNS Reverse Lookup Zone.
Insert and Select Data in Reverse Engineering POCO Generator
Feb 16, 2013.
This article demonstrates an interesting and very useful concept in Entity Framework.
Delete and Update Data in Reverse Engineering POCO Generator
Feb 16, 2013.
This article demonstrates an interesting and very useful concept in Entity Framework.
Find Substring and Reverse it in Windows Store App
Feb 07, 2013.
In this article I will explain how to find a substring from a string and if present then reverse the substring in a Windows Store Application.
Delete Data With Reverse Engineering Via EDM Framework
Dec 28, 2012.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Update Data With Reverse Engineering Via EDM Framework
Dec 28, 2012.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Select and Insert Data With Reverse Engineering Via EDM Framework
Dec 20, 2012.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Distinct and Reverse Operations Using LINQ
Nov 05, 2012.
Today, in this article let's play around with the most useful operations "Distinct" and "Reverse" in LINQ.
How to reverse a C# List
Jul 06, 2012.
How to reverse items of a List using C#.
Perform Sorting, Searching and Reverse Operations in List Using C#
May 15, 2012.
In this article I explain the concept of searching an item from a list, sorting elements in a list and reverse elements in a list.
BinarySearch, Sort And Reverse Method of ArrayList in C#
Jan 10, 2012.
The ArrayList class provides a number of properties and methods that are used to work with an ArrayList..
Anti-Reverse Engineering (Assembly Obfuscation)
Nov 10, 2014.
The modus operandi of this paper is to demystify the .NET assembly obfuscation as a way to deter Reverse Engineering.
Reverse Geocoding in Bing Maps With REST Service Using ASP.Net
Oct 05, 2014.
In this article you will learn Reverse Geocoding in Bing Maps with REST Service using ASP.NET.
Reverse a String in Various Ways Using C#
Jan 30, 2014.
This article explains different ways one can think of to reverse a String using C#. Here we explored the possible ways using both Iterative and Recursive methodologies without using Reverse method of .NET framework.
Reverse Geocoding in Android Studio
Jun 20, 2013.
In this article you will learn Reverse Geocoding using XML request format
Reverse Words of a String in C#
Apr 24, 2013.
In this article I explain how to reverse full string content with the help of c#.
Reverse String and Empty String in PHP
Feb 28, 2013.
In this article I describe the PHP how to reverse and how to identify string is empty or not.
Reverse Number in Windows Store App
Jan 30, 2013.
In this article you will learn about reversing numbers in a Windows Store App.
Reverse a String Without Using Function in C#
Nov 02, 2012.
In this article we will learn how to reverse a string without using any string functions.
String Manipulation in C#
Mar 26, 2015.
This article shows some string operations in C# that helps beginners to improve their programming skills.
MSIL Programming: Part 2
Nov 16, 2014.
The primary goal of this article is to exhibit the mechanism of defining (syntax and semantics) the entire typical Object Oriented Programming “terms” like namespace, interface, fields, class and so on.
.NET Binary Patching, Reversing With Reflexil
Oct 31, 2014.
In this article you will learn .NET Binary Patching and Reversing with Reflexil.
Functions in SQL Server
Apr 29, 2014.
Here, we will take a look at how to use functions in SQL Server.
Simple and Effective Compression and Decompression Logic in C#
Oct 30, 2013.
We have various compression techniques and I have a simple compression logic that compresses text data into an image and does the reverse in an effective way.
Assignment Compatibility, Covariance and Contravariance
Aug 12, 2013.
The terms covariance and contravariance enable implicit references to conversion of array type, delegate type, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.
IFrame Cross Domain Communication Using IIS ARR and URL Rewrite
May 01, 2013.
This article demonstrates how to override browser same-origin policy and communicate from main page to its iframe loaded with content from external domain using ARR and URL Rewrite.
Array Object In TypeScript: Part 4
Jan 16, 2013.
In this article, you will learn about the array object method in TypeScript.
Select and Insert Data With Entity State (Unchanged) Via EDF Framework
Dec 31, 2012.
Today, in this article let's play around with one of the interesting and most useful concepts in EDM Framework.
Delete Stored Proc With Raw SQL Query Via EDF Framework
Dec 28, 2012.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Insert Data With Raw SQL Query Via EDF Framework
Dec 28, 2012.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
While Loop In TypeScript
Oct 26, 2012.
In this article I will explain how to use a while loop in TypeScript.
A Mouseover Zoom Effect Using jQuery and CSS
Mar 27, 2012.
The hover zoom effect basically reverses zooms in an image while fading in a label on top of it when the mouse hovers over it.
Reading EXCEL FILE in a Collection sing Open XML SDK 2.0
Oct 10, 2011.
In this post, let us try to do the reverse process. We will read all the rows of an Excel file List of Bloggers. Again starting with creating a custom.
Custom String Methods using C#
Jan 27, 2010.
In this article I will explain you about the Custom String Methods using C#.
Sorting, Reversing, and Searching in Arrays in C#
Jan 17, 2010.
In this article I will explain you about Sorting, Reversing, and Searching in Arrays in C#.
Power of Yield, Generics and Array in C#
Jul 14, 2008.
This article tells you an additiional way to get reverse processing of array with help of generics and yield.
Building ASP.NET bot protection (CAPTCHA-like)
Feb 29, 2008.
This article shows how to build captcha-like protection from spam and other bots in ASP.NET..
String Jargon in C#
Sep 05, 2001.
The following article shows some String functions which are not currently available directly in C#.
Displaying Exception Information
Aug 21, 2001.
This is a simple utility to display exceptions. Each exception in the chain is added to an ArrayList and displayed in reverse order in a ListView control.
Serializing Objects in C#
May 14, 2001.
In simple words serialization is a process of storing the object instance to a disk file. Serialization stores state of the object i.e. member variable values to disk. Deserialization is reverse of serialization.
About Reverse
NA
File APIs for .NET
Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more! | http://www.c-sharpcorner.com/tags/Reverse | CC-MAIN-2017-09 | refinedweb | 1,704 | 65.62 |
.
If you're not using Visual Studio .NET (any edition) to run the examples in the book you'll need to include Imports statements within your code. See page 261 for details about the Imports statement. At the very least, you'll need to import the System namespace for every example:
System.Windows.Forms.MessageBox.Show("Hello World", _
"A First Look at VB.NET", _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Information)
The version number of an assembly takes the form: Major.Minor.Build.Revision, not Major.Minor.Revision.Build.
The example programs on pages 64 - 66 use Debug.WriteLine to print statements instead of Console.WriteLine. In each case the call to Debug.WriteLine should be replaced with a call to Console.WriteLine, in order for the statements to be printed to the command line.
The final sentence of the first paragraph should read, "Consider the following code, which uses the System.Text.StringBuilder class:"
The final paragraph on this page should refer to Singles, not Shorts - as reflected in the code.
The first line of code on this page should check if lngLong is less than Short.MaxValue rather than greater than:
The final paragraph on this page refers to "Object Strict". It should refer to "Option Strict".
The 4th bullet in the summary should read, "Beware that parameters are passed ByValue by default so changes are not returned."
The final two lines of code on this page contain parantheses that break the code. The code should read:
The final paragraph of the Method Signatures
section states that the ByRef and ByVal modifiers can be used to create
distinct method signatures. This is incorrect. ByVal and ByRef cannot
be used as a differentiating feature when overloading a property or
procedure.
mdtBirthDate should be declared as a Date, not a String:
The code that checks if a key is present in the HashTable should read:
The 2nd paragraph on this page should read, "..., we also need to comment out the lines that refer to the OfficeNumber property, ..."
The MyBase keyword cannot be used to invoke a Friend element from the parent class if the parent class is in a different assembly.
The code that checks if a key exists in the HashTable should read:
The final paragraph on this page should read, "We can then move on to implement the other two elements defined..."
The third paragraph of the Reusing Common Implementation section should read, "..., our Value method is linked to IPrintableObject.Value using this clause:"
The first paragraph on this page should read, "... Do this by clicking on the project name in the Solution Explorer window and..."
The
method declaration for PrintPage() should include an underscore
character at the end of the second line top indicate that the
declaration continues onto the next line:
The fourth paragraph should read, "... Selecting the Microsoft Visual Basic.NET Compatability Runtime component..."
In order to use the example code on page 289 you will need to import System.IO, by adding a Imports System.IO
statement to your code. In addition, so that the code will run even if
the C:\mytext.txt file does not exist the first statement in the LoggingExample2() sub should read:
Please not that "prescription" is misspelt as "presciption" several times in the example code in this chapter.
The first line of code on this page should read:
The final sentence of the first paragraph on this page should read, "An example code snippet that uses the GetXml method is as follows:".
The code is presented as a snippet only and so is not included in the code download for the book.
The XML shown on this page should read:
Please note that the code on this page is extracted from the TraverseDataReader method on the following page. You'll need to wait until page 354 to find the complete code necessary to run the example demonstrating the Command object.
In response to reader
feedback some clarification about stored procedures is required. The
book states stored procedures are compiled prior to execution. In fact,
a stored procedure in SQL Server 7 and 2000 is compiled at execution
time, just like any other T-SQL statement. The execution plan of the
SQL statement is cached and SQL Server uses algorithms to reuse these
execution plans efficiently.
[You can find more information about stored procedures in SQL Server in the Stored Procedures and Execution Plans section of SQL Server Books Online.]
The code that checks if the password is blank should read:
If passwordTextbox.Text = "" Then
MessageBox.Show("Password cannot be blank")
End If
Using a <DefaultValue> attribute will allow designers (such as Visual Studio .NET) to set the property to a default value but please note that your property still needs to be set to an intitial value in code so that it can be used outside of such designers.
DefaultMaxSelectedItems()
Private Function DefaultMaxSelectedItems() As Integer
Dim attributes As AttributeCollection = _
TypeDescriptor.GetProperties(Me) ("MaxItemsSelected").Attributes
Dim myAttribute As DefaultValueAttribute = _
CType(attributes(GetType(DefaultValueAttribute)), _
DefaultValueAttribute)
Return CInt(myAttribute.Value)
End Function
The first paragraph refers to CheckedListBox1; it should refer to LimitedCheckedListBox1.
The first line of the OnPaint() method code should read:
The
first line on this page should read, "Client-side events are
automatically processed in the client browser without making a round
trip to the server. So, for..."
This page incorrectly states that you cannot use a @OutputCache directive in a Web User Control, when in fact you can.
Note that you will need to alter the code for the table element of the navigation bar in order to use the BackColor custom property
The menuSaveChanges_Click method is missing a Handles statement. It should read:
The thirds stored procedure on this page has a spelling mistake (sp_exectsql instead of sp_executesql) and doesn't declare the third parameter. It should read:
exec sp_executesql N'UPDATE authors SET city=@p1, state=@p2
WHERE au_id=@p3, N'@p1 varchar(10), @p2 char(2), @p3 varchar(11), @p1 =
'Scottsdale', @p2 = 'AZ', @p3 = '238-95-7766'
The code for the ColumnChanged() event handler should be:
The comments in the code on this page include some dots where there should be double-quote marks. The correct comment is:
The first line of the final paragraph on this page should read, "To test this out, take the HTTP URL and add ?WSDL on to the end."
The screenshot and instructions on page 836 for adding a strong name
are incorrect. In the final release of Visual Studio .NET 2002 the
Strong Name tab in the Common Properties section of the Property Pages
dialog has been removed.
Instead, you should use the AssemblyKeyFile attribute in an Assembly Information File, as described here.
The SendKeys class has been moved to the System.Windows.Forms namespace not the System.IO namespace. | http://www.wrox.com/WileyCDA/WroxTitle/Professional-VB-NET-2nd-Edition.productCd-0764544004,descCd-ERRATA.html | CC-MAIN-2020-05 | refinedweb | 1,142 | 64.1 |
On Jun 23, 1:24 am, "Josip" <i... at i.i> wrote: > > Why > > Still, I'm going for object > oriented solution because I want the value and it's limits to be kept > together as I'll have many such values with different limits. In that case, "overriding assignment" makes no sense since if an operation is done on two values that have two different limits, what would happen? Take the first's or second's limits, or interpolate the new limit by some magic function? A much better solution would be for operation to always return plain vanilla int, and we set limits explicitly. > Storing all > the limits in caller namespace is not really an option. You want to store limits in the object too? Try this: (_LimitedInt inherits from int, so operator overloading is unnecessary) ### #!/usr/bin/env python class _LimitedInt(int): class InvalidLimitsError(Exception): pass def __init__(self, value, base = 10): int.__init__(value, base) def setlimits(self, lim): ''' Set the limits and if value is not within limit, raise ValueError The lim argument accepts: - A _LimitedInt instance, from which to copy the limits - A two-tuple, which specifies the limits i.e. (min, max) If lim isn't those or lim[0] > lim[1], raise InvalidLimitsError Accepting _LimitedInt instance is just for convenience ''' if isinstance(lim, _LimitedInt): lim = lim.limits try: self.min, self.max = [int(x) for x in lim] if self.min > self.max: raise ValueError except (ValueError, TypeError): raise self.InvalidLimitsError, ('limit = %s' % str(lim)) if not (self.min < self < self.max): raise ValueError, \ ('val = %s, min = %s, max = %s' % \ (self, self.min, self.max)) def getlimits(self): return (self.min, self.max) limits = property(getlimits, setlimits) def lint(value, limits, base = 10): if base != 10: ret = _LimitedInt(value, base) else: ret = _LimitedInt(value) ret.limits = limits return ret ### END OF REAL CODE ### ### THE REST ARE JUST TESTING CODES ### if __name__ == '__main__': print 'Instantiating lint...' a = lint(50, (0, 200)) # Limit explicitly specified b = lint(150, a) # Copy the limits of a c = lint(a, (0, 1000)) # Value = a, Limit = (0, 1000) d = lint(a, c) # Value = a, Limit = c print print 'Printing the value and the limits...' print a, a.limits print b, b.limits print c, c.limits print d, d.limits print print 'Changing limits' print 'Note: lint is partially immutable,' print ' its limits is mutable,' print ' while its value is immutable' a.limits = (0, 300) b.limits = a print a, a.limits print b, b.limits print print '"Changing" values' a = lint(b, a) print a, a.limits print print 'Operations...' e = lint(a + b - c * d + 100, (-10000, 1000)) f = a + b - c * d ## Operation returns plain integer g = lint(f, (-100000, 100000)) ## Always recast result of operator print e, e.limits, type(e) ## This is an int, not lint print f, type(f) ## BEWARE: f is integer, it has no limits print g, g.limits, type(g) ## INVALIDS # a = lint(100, (1000, 100000)) # a = lint(100, 'ab') # a = lint(100, (10000, 0)) # a = lint(100, 10) # a = lint(100, (10, 1000, 10000))### | https://mail.python.org/pipermail/python-list/2008-June/513943.html | CC-MAIN-2014-15 | refinedweb | 515 | 58.48 |
Is it possible to find the length of a Bezier curve in Blender 2.5.6a? I’m sure in 2.4x you could see how long a Bezier was on one of the panels. I am animating a length of hose uncurling, but I want to make sure its length stays approximatley “true”, and doesn’t appear to stretch as I move the control points of the Bezier curve that controls its shape.
yes, in blender-2.49 there was this little “print length” button in the curve-window - it did calculate the length of the curve. Looks like i have to dive into the spline-length calculation …
and i wonder … i have seen something about it in the python -section - somenone who did already calc. the length with pyhton.
Anyone some hints what this was?
I have tried to find it with the forum-search fuction … but without success.
keywords… are? spline… bezier… curve … ??
For this situation you could use some reference object and apply a curve modifier to it, as you are editing the curve the object will deform but remain the same length.
If only I knew some Python I think it must be easy… Pressing Alt+C converts a Bezier to a mesh - a set of vector edges - using the U resolution of the Bezier to determine the number of segments. If a Python script could “do an Alt+C” in code using a high U resolution (say 1000) and then sum the segment lengths, you would get quite an accurate approximation of the Bezier curve length.
@litero: It’s not quite as simple as it seems, I must use a Bezier for this and other purposes too.
Hmm I thought liero was spot on so i did a little test file. Plane is a single vertex object is applied to a curve with the modifier… at x=13.37 in the direction of the modifier it is at the end of the curve… however, Plane.001 a two vertex mesh given an array modifier set to fit the curve has a length of 26.7 when array is applied… and the curve modifier turned off. The unmodified (unit) length of Plane.001 is 0.1… it could be scaled to fit the accuracy required.
Firstly the fit curve array modifier suggests that the curves length is being used in this calculation and is therefore a property that should be available…without having to apply the modifier or convert to mesh or any other tricks… and any thoughts why the curve modifier for the single vertex object indicates it’s half that length… I tried it with bending and flexing and scaling and straightening the curve and always comes out the same …pretty much half.
The applied array fit curve line should solve your hose probs… by leaving on the curve modifier you can see if it is longer or shorter than the “hose”… or use it as the hose as liero suggests… just twigged.
. also the other way with the single vert mesh there is a sphere copying it’s location so you can see where it is… i keyframed it to traverse the hose… it’s at one end at frame 1 and the other at 250… modify the hose and you want the sphere to stay pretty much on the tip… (at frame 250 in the example that is) I use the curve modifier approach to animate objects along curves and thought it was pretty much a 1:1 relationship … this points to it being a 2:1…
EDIT: I did a try with Reaction’s suggested approach, momentarily convert to mesh and sum the length of all edges.
It seems to work fine, it is a tab in properties panel, press N to see it.
Should work on any kind of curve now.
import bpy, mathutils from mathutils import Vector le = 'get length of a curve' class PANEL(bpy.types.Panel): bl_label = "Curve length" bl_space_type = "VIEW_3D" bl_region_type = "UI" def draw(self, context): layout = self.layout layout.operator("boton.le") box = layout.box() box.label(text="Length: " + str(le)) class BOTON(bpy.types.Operator): bl_idname = "boton.le" bl_label = "Calculate" def execute(self, context): ob = context.active_object if ob and ob.select and ob.type == 'CURVE': em = (ob.mode == 'EDIT') bpy.ops.object.mode_set() bpy.ops.object.convert(target='MESH', keep_original=False) ve = ob.data.vertices global le dd = le = 0 for i in ob.data.edges: dd = ve[i.vertices[0]].co - ve[i.vertices[1]].co le += dd.length le = round(le,4) bpy.ops.ed.undo() if em: bpy.ops.object.mode_set(mode='EDIT', toggle=False) else: le = 'not a curve object' return{'FINISHED'}
Thanks for this little script
but i tough there was a way in 2.49 to use the values from the Curve itself to calculate the lenght of curves!
i mean this is used in several place in blender and it has to be possible to evaluate this lenght on the curve!
may be you have to first convert to a Poly type may be then use the points to calculate the lenght of each segment !
understand that with the control poinst from bezier the calculated lenght might be a lillte shorted cause you don’t see all the other points in between which add to the lenght!
Thanks
You’re welcome
I think the accuracy depends of the preview resolution of the curve… when converted to mesh it creates lots of segments betwen control points. There may be an easier way that I couldn’t find, but this was a little python exercise.
Hi, thought I’d have a go at using the array modifier approach for length of curve as a learning excersize too… lifted liero’s script n came up with this. The script creates a single edged object the length of the accuracy prop and applies the fit curve array modifier to it…
import bpy, mathutils from mathutils import Vector le = 'get length of a curve' def initSceneProperties(scn): bpy.types.Scene.Accuracy = bpy.props.FloatProperty( name="Accuracy", default = 0.01, min = 0.0001, max = 1) scn['Accuracy'] = 0.01 initSceneProperties(bpy.context.scene) class UIPanel(bpy.types.Panel): bl_label = "Curve length" bl_space_type = "VIEW_3D" bl_region_type = "UI" def draw(self, context): layout = self.layout layout.prop(context.scene, "Accuracy") #layout.prop(dx) layout.operator("object.LengthButton") box = layout.box() box.label(text="Length: " + str(le)) class OBJECT_OT_LengthButton(bpy.types.Operator): bl_idname = "OBJECT_OT_LengthButton" bl_label = "Calculate" def execute(self, context): ob = context.active_object if ob and ob.select == True and ob.type == 'CURVE': dx = context.scene.Accuracy verts = [] edges = [(0,1)] #add a small mesh mesh = bpy.data.meshes.new("mesh") verts.append(Vector((0,0,0))) verts.append(Vector((dx,0,0))) mesh.from_pydata(verts,edges,[]) lo = bpy.data.objects.new("lengthfinder",mesh) mod = lo.modifiers.new("length","ARRAY") mod.fit_type = "FIT_CURVE" mod.curve = ob base = bpy.context.scene.objects.link(lo) global le bpy.context.scene.update() le = lo.dimensions[0] #clean up bpy.context.scene.objects.unlink(lo) bpy.data.objects.remove(lo) return{'FINISHED'}
A couple of questions… rather than have the UI there and test whether it’s a curve … is there a way to only have the UI if the context is a curve…
PS… any thoughts on post 5 as to why the curve modifier travels 2:1???
would like to see the equivalent of the first script in 2.5
i could learn from that one too how to play with edges vertices ect…!
you added it into the N panel i know that usually you an find values there
but i’m so use seeing things in tool prop i’ll probablymoce it there !LOL
i have to look how this second srcipt works
i mean can you use the array modif to calculate the lenght ?
are you taking let say a specific lenght and ttryng to see how many fit up to the end of fthe curve?
THanks happy 2.5
Yes and no check out the fit-curve property of the array modifier … does it for you.
does it always work ok or do you have to Ctrl-A the 2 objects before to be certain it will calculate the real lenght and not a fake value ?
happy 2.5
If you remove or comment out the 2 lines after the # clean up comment it leaves the array modified line with the x dimension being the length of the curve after running the script. Seems there is no need to apply the modifier… which is handy as its one of those things i’m not sure how to do without context.
Also I concur with your comment re curve length is used in several places in blender … fit_curve being one of them.
If you add a curve modifier to it you will see its a pretty good copy of the curve… the smaller the bits the more accurate.
i already did post this part in another thread (about the bvh-workflow and anim. bvh-parts along a curve)
#calculate length of bezierline with iteration=3 - accurate enough? def bezier1(p, depth=0): #recursive for iteration-depth for the 2 bezier-points + their handles l = 0 if depth == 0: pass #return if depth > 3: #set_line(p[0], p[3]) #print(p[0], p[3]) return( (p[3]-p[0]).length ) else: depth += 1 p01 = 0.5*(p[0]+p[1]) p12 = 0.5*(p[1]+p[2]) p012 = 0.5*(p01+p12) p23 = 0.5*(p[2]+p[3]) p123 = 0.5*(p12+p23) p0123 = 0.5*(p012+p123) l += bezier1( [p[0],p01,p012,p0123], depth) l += bezier1( [p0123,p123,p23,p[3]], depth) return(l) def bezierlength(beziercurvename): #calculate length of beziercurve and return length and duration l = 0 b = get_object(beziercurvename) if b == None: return(0) #error if not found! if b.type != "CURVE": return(0) #i should print some error if len(b.data.splines) == 0: return(0) bzp = b.data.splines[0].bezier_points #is the first the only one? if len(bzp) == 0: return(0) #how to calculate other lines with spline-points? for i in range( len(bzp)-1 ): l += bezier1( [bzp[i].co, bzp[i].handle_right, bzp[i+1].handle_left, bzp[i+1].co] ) return(l, b.data.path_duration)
it only works for BezierCurves - not for bsplines … i have not tried to check whats the big difference (the bsplines have bezierpoints =0 in their object-structure and i am not shure if it is a cubic-line according to the spline-points … - if someone knows, it should be possible to extend the script to use the cubic-calc.-routine if the curve does not use bezierpoints)
@test-dr nice one, still not that accurate and do not work on closed curves as it is now
@batFINGER your script relies on the way Blender internally calculates the array length from a curve, mine in the way it interpolates it to create some mesh, so in both cases the accuracy only depends on the curve preview resolution, test that with a circle… the convert to mesh algorithm seems more reliable, I rounded the results to 4 decimals cause this are all aproximations
@liero: for closed curves there is the need to calculate an edititional bezier-part (last point to first one, thats why bezierpoints have 2 handles, left - right , even if the outer-space-handles not used for not-closed beziercurves) - and for accurracy there one might set the same iteration-level as for the default blender-beziercurve (it seems to be 12 … could be tweaked in the curve-options … and if you go down to 2 … you end at straight lines … connecting the points …).
One could use the mathutils-function:
mathutils.geometry.interpolate_bezier( …
and run this over the bezierpoints of the curve-object.
The iteration 3 (i used) was only for a prove of concept and the result was enough for the patched animation …
What i miss, there should be a routine in the c-source-code of blender, that does this (calculating the length according to the different settings of the curve-properties) - and shure … i did not find any docs about it … its (blender) a real development in action
edit: i did say, there are needs to check for the other curve-special-settings … “closed-curve” is only one … iteration seems to be the little parts visible in edit-mode of the curve…
ok, and this is (might be ) real SPAM
…
why i did write down the algo for bezier-parts,
there is
this joke…
about a mathematican, physics and engineer -
everyone is trapped in a room with time-code-door,
that opens only in 2 weeks.
They have enough water, but only one tin-can-box of SPAM.
(thats the meat … spam-mails got their name …)
And they have no tin-can opener.
After 2 weeks the time-code-door opens and
the survivor was:
the physicist
(maybe the joke is wrong at this part …)
On the wall of the dead mathematica was written down
the prove, that the tin-can with spam could be opened
and the meat would help to survive the time till the door
opens again.
On the wall of the engineer were a lot of deep impacts.
The tin-can was still closed and was only very dented
but still closed.
On the wall of the physicist was writen down a calculation
how to throw the tin-can against the wall to hit the week
corners and make it splash …
and btw. … most times i do use “trial and error” …
Yeah that prop needs a better name than accuracy… its just the size of bits that make up the whole to approximate the length… on investigation with the circle 0.001 is a good value to use. The convert to mesh is more accurate but the array mod is a dang bit quicker on my machine… anyway when can we use that internal calculation directly from a property on the curve object.
PS: looks like both our scripts need to copy original curve and apply scale to work.
@test-dr I’ve heard that the term spam comes from the monty python skitt about the “meat” known as spam
the last script for bezier curves only
is this for 2.5 ?
do you havea complete script like first one so we can test this
would be good to include all these little script inot one script with a menu may be
anyone knows how to make a test on a curve to determine if it is a bezier poly or spline one?
that would be interesting
hope there was not much API changes for curves lately!
and i wont’ laugh on that one cause it’s not a joke anymore more like a pain in the neck!
happy 2.5
<deleted double post> self posted???.. think this baby has to go down for a while. | https://blenderartists.org/t/length-of-a-bezier-curve-in-2-5/496672 | CC-MAIN-2021-49 | refinedweb | 2,494 | 70.43 |
Tell us what you think of the site.
Ok - I have a simple list of characters in my scene displayed in a drop down box… Selecting a character returns the value of the character as per the initial list derived from:
charList = []
scene = FBSystem().Scene
charList = scene.Characters
So I can populate a variable with an individual character…
However - the reason for doing this is to run an export script I have specifically for the chosen character - all the characters in my scene are duplicated apart from namespaces…
How do I find the Namespace of the selected character...? When I try:
varSelectedCharacter.LongName
...all I get is the name as it appears in the Navigator list...?
You’ll want to split the string being returned by the LongName to just include the namespace.
You’re probably getting something like “rig 1:Character” and you just want “rig 1”
Try the following
charList = []
scene = FBSystem().Scene
charList = scene.Characters
for char in charList:
theNameSpace = char.LongName.split(":")[0]
print theNameSpace
Seems like there should be an easier way to get the namespace...like getNameSpace()
the pyMoBu module has just that…
Hope this helped :)
Thanks Omni...!! | http://area.autodesk.com/forum/autodesk-motionbuilder/python/finding-a-namespace-from-a-selected-character-from-a-drop-down-list/ | crawl-003 | refinedweb | 194 | 64.51 |
I'm using Atmel's Atmega328P-PU and its CPU speed is set to 8MHz. This code actually worked fine when I 1st wrote it but I had to change some stuff in UART section so had to compile and flush it again but this time it was done from Linux using avrdude command line tools instead of Windows 7(which was on my friends PC and got deleted).
This is data timing diagram for WS2812B
Everything in code works fine except for sending '1' and '0' to LED and it happens in function set_leds_color. Weird thing is that if I leave the __builtin_avr_delay_cycles(); values as they were before my UART code updates (and as are shown in code) it always sets LED's color to white kind of like it would always send only '1' to led (255,255,255). Even if I set delay for '0' to __builtin_avr_delay_cycles(1) nothing changes - any color is displayed as white. Now the interesting part is that if I remove this delay for '0' so code become like this
When I set the same color multiple times in a row - LED actually sets my desired color 1 time but 2nd time sets white again. This goes on. I have no idea what the problem is. I tested that __builtin_avr_delay_cycles() works as expected and my CPU frequency is indeed 8Mhz. I also sent rgb_array[] values from mcu to my PC thought UART and they are fine as well. Can anybody give me some suggestions what might be wrong? Thanks.
Code: Select all
//send 0 else{ DATA_PORT = high_data; DATA_PORT = low_data; }
Here is my final code
Code: Select all
#include <avr/io.h> #include <util/delay.h> #define DATA_PORT PORTD #define DATA_PIN PD2 #define DATA_DDR DDRD /* UART stuff */ void fill_array(unsigned int* arr, unsigned int color) { for(int i = 0; i < 8; ++i) arr[i] = color & (1 << (7 - i)); } void set_color(unsigned int* arr, unsigned int red, unsigned int green, unsigned int blue) { fill_array(arr, green); fill_array(&arr[8], red); fill_array(&arr[16], blue); } void set_leds_color(unsigned int red, unsigned int green, unsigned int blue) { //prepare 24 color bits to send to LED unsigned int rgb_array[24]; set_color(rgb_array, red, green, blue); int high_data = DATA_PORT | (1 << DATA_PIN); int low_data = DATA_PORT & (~(1 << DATA_PIN)); for(int i = 0; i < 24; ++i){ //send 1 if(rgb_array[i]){ DATA_PORT = high_data; __builtin_avr_delay_cycles(6); //1 clock cycle is 0.125us DATA_PORT = low_data; } //send 0 else{ DATA_PORT = high_data; __builtin_avr_delay_cycles(3); //1 clock cycle is 0.125us DATA_PORT = low_data; } } } int main(void) { DATA_DDR = (1 << DATA_PIN); DATA_PORT &= ~(1 << DATA_PIN); initialize_UART(); while(1) { int color_code[3]; if(receive_color_from_uart(color_code)) { set_leds_color(color_code[0], color_code[1], color_code[2]); } } } | https://forums.linuxmint.com/viewtopic.php?f=58&t=265363 | CC-MAIN-2018-30 | refinedweb | 441 | 54.46 |
Hi everybody,
i've been having some problems with the following piece of code. The uP is a mega644.
The USART is initialized as UART for 38400@16MHz, only for transmission.
However, if I try to send something to the UART, the 644 will go back to execute things at address 0x0000. The MCUSR shows that there is no external or power on reset source (it shows 0 as its value).
I might have a hardware problem maybe, or is it a mega644 bug?
here it's main.c
#include "globals.h" extern void mytest(void); int main() { u08 st = MCUSR; MCUSR = 0; UBRR0L = (unsigned char)(51); // inits midi! UBRR0H = (unsigned char)(51 >> 8); UCSR0A = (1<<U2X0); UCSR0B = (1<<TXEN0) ; UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); setbit(DDRD,1); clrbit(DDRD,0); //fin usart init UDR0 = st; for(;;) { mytest(); //nada mas! } while(1); return 1; }
mytest.c
void mytest(void) { return; }
globals.h just defines testbit(), setbit(), etc. along with some types (u08, u16, etc).
If I don't call mytest() in main then everything is fine, the avr never goes back to the reset vector.
I already tried with two different atmega644, and the same applies to both of them.
Thanks!
I'd guess that you are not building for the chip you are using, and the stack pointer is out in space somewhere. I'd expect an AVR I/O include file somewhere to get "UBRR0H" etc.
Lee
You can put lipstick on a pig, but it is still a pig.
I've never met a pig I didn't like, as long as you have some salt and pepper.
Top
- Log in or register to post comments
Lee, thanks for the reply.
I'm building for the right uP, my Makefile is configured with MCU = atmega644 (using WinAVR and MFile here).
I thought of that too.
The strange thing is that the reset happens only if I send a character to the USART.
I thought something would be causing a short circuit there, but I've found nothing.
I just made another test here.. No USART involved in the code, just turning something on if the uP resets, and off when it's running.
Strangely when I send chars from the PC to the uP, the avr resets.. I believe there is a hardware thing, but I still can't find the cause.
thanks!
Top
- Log in or register to post comments
here is the code for what I said above..
If I call test() and send something to the UART (which is completely disabled) the uP will reset itself.
If I comment the test() call, it won't.
I'll keep investigating this matter..
thanks once again.
Top
- Log in or register to post comments
Is there a bootloader that is enabling the USART and associated interrupt, then using the bits in MCUSR (IIRC) to shift the vector table to your application section? That would leave the USART enabled, and cause a reset when the now non-existant vector fires.
Had something like that happen to me once, with the Butterfly bootloader setting USART bits I wasn't expecting - that was "fun" to debug!
- Dean :twisted:
Make Atmel Studio better with my free extensions. Open source and feedback welcome!
Top
- Log in or register to post comments
Dean,
I don't use a bootloader, and the fuse bits are programmed to start from 0x0000.
I still can't imagine what is causing this behaviour. I'm using a FT232 to connect the RS232 TTL level signals to the USB port in my laptop. Signals are routed right.
If at least the problem was always there, but it changes depending on mytest() call.
Thanks again,
Carlos
Top
- Log in or register to post comments
just another thing I found..
I compiled the same code with IAR AVR compiler (just small changes about include files) and the AVR won't reset on any test.
Also, I tried routing the FT232 TX output to different pins, apart from the AVRs RX one. I found that the only pin which causes trouble is the RX one, just that one.
Still strange, looks like some USART interrupts are set up somewhere, but where?
AVRStudio shows everything "clean" when simulating on the PC.
Top
- Log in or register to post comments
I just built this, for globals.h I used:
Can you confirm that you .lss contents are the same:
In particular, the key thing in here is:
which is setting the stack pointer to 0x10FF which is the RAMEND figure defined in iom644.h
This codes works exactly as expected in the simulator.
Top
- Log in or register to post comments
To check whether it really is an interrupt firing you could write a catch-all isr and see if it is ever entered. But since there's no sei() anywhere in your program, I'd guess it is something else. The stack pointer would be my first guess.
Top
- Log in or register to post comments
Well, I think I solved it. It was a hardware thing.
I forgot to add the 33pF caps to the new PCB.
The USART pin is near the XTAL ones in the AVR, that seemed to be causing some noise when clocking the AVR.
It's strange knowing that the only pin which would cause such behaviour is the RX one, who knows.
Just a so stupid thing. It looks strange, since it resets the AVR by "software" (going to address 0x000).
Well, thanks to everyone who helped here.
Carlos
Top
- Log in or register to post comments
Oh so it wasn't a bug in the compiler or the silicon after all? I'm totally stunned given that both are known to be riddled with bugs and have hardly ever been tested by anybody.
Top
- Log in or register to post comments
It looks like it.
I don't know about bugs in avr-gcc, are there so many?
I mean, should I buy a commercial compiler if I'm really working with it?
Maybe this should be another topic.
thanks again
Top
- Log in or register to post comments
Clearly sarcasm does not cross the international divide then?
(you are not the first to postulate that the silicon or the compiler/assembler they are using is the source of their problems when it almost NEVER is ;))
Top
- Log in or register to post comments
well actually the problem might be I'm not that fuild in english.. nevermind, I won't start a debate on that.
I've been using avr-gcc for quite a while, looks stable but...
The winavr suite is really nice. Makefiles and avrdude make things quick and easy.
I hope I never have to change to another compiler.
Top
- Log in or register to post comments
Man, I gota tell ya...
I love the ImageCraft ICCAVR C compiler!!!
It cost more then "Free " AVR-GCC. It cost less then IAR. But I have found ICCAVR to satisfy all of my AVR programming needs.
You can avoid reality, for a while. But you can't avoid the consequences of reality! - C.W. Livingston
Top
- Log in or register to post comments | https://www.avrfreaks.net/forum/solved-mega644-bug-avr-gcc-bug-or | CC-MAIN-2020-05 | refinedweb | 1,202 | 83.36 |
HighLine
Description
Welcome to HighLine.
HighLine was designed to ease the tedious tasks of doing console input and
output with low-level methods like
gets and
puts. HighLine provides a
robust system for requesting data from a user, without needing to code all the
error checking and validation rules and without needing to convert the typed
Strings into what your program really needs. Just tell HighLine what you're
after, and let it do all the work.
Documentation
See: Rubydoc.info for HighLine. Specially HighLine and HighLine::Question.
Usage
require 'highline' # Basic usage cli = HighLine.new answer = cli.ask "What do you think?" puts "You have answered: #{answer}" # Default answer cli.ask("Company? ") { |q| q.default = "none" } # Validation cli.ask("Age? ", Integer) { |q| q.in = 0..105 } cli.ask("Name? (last, first) ") { |q| q.validate = /\A\w+, ?\w+\Z/ } # Type conversion for answers: cli.ask("Birthday? ", Date) cli.ask("Interests? (comma sep list) ", lambda { |str| str.split(/,\s*/) }) # Reading passwords: cli.ask("Enter your password: ") { |q| q.echo = false } cli.ask("Enter your password: ") { |q| q.echo = "x" } # ERb based output (with HighLine's ANSI color tools): cli.say("This should be <%= color('bold', BOLD) %>!") # Menus: cli.choose do || .prompt = "Please choose your favorite programming language? " .choice(:ruby) { cli.say("Good choice!") } .choices(:python, :perl) { cli.say("Not from around here, are you?") } .default = :ruby end ## Using colored indices on Menus HighLine::Menu.index_color = :rgb_77bbff # set default index color cli.choose do || .index_color = :rgb_999999 # override default color of index # you can also use constants like :blue .prompt = "Please choose your favorite programming language? " .choice(:ruby) { cli.say("Good choice!") } .choices(:python, :perl) { cli.say("Not from around here, are you?") } end
If you want to save some characters, you can inject/import HighLine methods on Kernel by doing the following. Just be sure to avoid name collisions in the top-level namespace.
require 'highline/import' say "Now you can use #say directly"
For more examples see the examples/ directory of this project.
Requirements
HighLine from version >= 1.7.0 requires ruby >= 1.9.3
Installing
To install HighLine, use the following command:
$ gem install highline
(Add
sudo if you're installing under a POSIX system as root)
If you're using Bundler, add this to your Gemfile:
source "" gem 'highline'
And then run:
$ bundle
If you want to build the gem locally, use the following command from the root of the sources:
$ rake package
You can also build and install directly:
$ rake install
Contributing
Open an issue
Fork the repository
Clone it locally
git clone git@github.com:YOUR-USERNAME/highline.git
Add the main HighLine repository as the upstream remote
cd highline# to enter the cloned repository directory.
git remote add upstream
Keep your fork in sync with upstream
git fetch upstream
git checkout master
git merge upstream/master
Create your feature branch
git checkout -b your_branch
Hack the source code, run the tests and pronto
rake test
rake acceptance
pronto run
Commit your changes
git commit -am "Your commit message"
Push it
git push
Open a pull request
Details on:
- GitHub Guide to Contributing to Open Source -
- GitHub issues -
- Forking -
- Cloning -
- Adding upstream -
- Syncing your fork -
- Branching -
- Commiting -
- Pushing -
The Core HighLine Team
- James Edward Gray II - Author
- Gregory Brown - Core contributor
- Abinoam P. Marques Jr. - Core contributor
For a list of people who have contributed to the codebase, see GitHub's list of contributors. | http://www.rubydoc.info/github/JEG2/highline/frames | CC-MAIN-2016-50 | refinedweb | 567 | 58.79 |
#include "ltwrappr.h"
L_INT LImageViewerCell::ReverseBitmap(nSubCellIndex, uFlags)
Reverses images in the specified cell or sub-cell. This function is available only in the PACS Imaging toolkit. This feature is available in version 16 or higher.
A zero-based index into the image list attached to the cell. This sub-cell contains the image that will be reversed. Pass -1 to apply this effect on all sub-cells. Pass -2 to apply this effect on the selected sub-cell.
Flags that determine whether to apply the feature on the one cell only, or more than one cell. This value can only be used when the cell is attached to the LImageViewer through the function LImageViewer::InsertCell. Possible values are:
To determine whether the image has been reversed, call LImageViewerCell::IsBitmapReversed.
Required DLLs and Libraries
For an example, refer to LImageViewerCell::BeginUpdate.
Direct Show .NET | C API | Filters
Media Foundation .NET | C API | Transforms
Media Streaming .NET | C API | https://www.leadtools.com/help/sdk/v22/imageviewer/clib/limageviewercell-reversebitmap.html | CC-MAIN-2022-21 | refinedweb | 158 | 60.82 |
I'm going to have a series many integers, and after a while, I want to get all their values, and return the largest int in the series, then perform an action based on the actual variable returned (not its value).
Ex. Suppose we took a bunch of ints that represented foods, and after comparing the amount of each food present,apple has the most and is returned as 'apple' (or maybe its index if using an array), not the amount of apples.
I was thinking of using an array and an enum, but I'm not sure of the easiest and least redundant approach to doing this.
Answer by Wolfram
·
Jan 10, 2013 at 07:53 PM
Today is your lucky day, I was in the mood to provide a script ;-)
using UnityEngine;
using System.Collections;
public class FruitClass : MonoBehaviour {
public enum Fruits {
Apple,
Orange,
Banana,
numEntries // we use this as marker for the number of entries
}
public int[] myFruits;
void Awake(){
// provide necessary space
myFruits=new int[(int)Fruits.numEntries];
// fill array
myFruits[(int)Fruits.Apple]=3;
myFruits[(int)Fruits.Orange]=1;
myFruits[(int)Fruits.Banana]=4;
// find index of maximum value
int maxIndex=-1;
int maxValue=0;
for(int i=0;i<(int)Fruits.numEntries;i++){
if(myFruits[i]>maxValue){
maxValue=myFruits[i];
maxIndex=i;
}
}
// output result
if(maxIndex>=0)
Debug.Log("The fruit I have most of are "+(Fruits)maxIndex+"s, of which there are "+maxValue+".");
}
}
The int<->Fruits casts cannot be prevented with this approach in C#, it forces a compiler error when missing.
EDIT: Look! I even documented it! :-D
Thank you so much. I'm going to try this as soon as I get in front of my workstation!
Answer by $$anonymous$$
·
Jan 10, 2013 at 11:06 PM
Or you can use System.Collections.Generic.Dictionary, where your keys are from the Fruit enum, the values are integers.
System.Collections.Generic.Dictionary
For getting the min/max items, you can use LINQ, like described here:
This is a simple and elegant solution.
Answer by Landern
·
Jan 10, 2013 at 01:44 PM
The easiest way of doing it using a standard array(square brackets).
// c#
int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
nums.Max(); // Will result in 7
nums.Min(); // Will result in 1
// US/JS
var nums: int[] = { 1, 2, 3, 4, 5, 6, 7 };
nums.Max(); // Will result in 7
nums.Min(); // Will result in 1
Ah, so in the declaration of int[] nums, could I do something like int[] nums = { apple = 3, orange = 1, banana = 4} and expect to have the min be orange and the max be banana? Would I need to declare the fruit outside of the int[] declaration? Lastly, is min and max returning the index or the actual largest value?
you could not, in this case i would create a custom class(i'm not sure if you are using c# or unity/javascript) that used an enum type for say Fruit property and a property of type int that was i assume the Amount.
It is returning the max or min because this is an int type, it will find the highest or lowest value in the array and return a single int.
Ah, okay. I happen to be using C#
@z_murc: I think that comment deserves to be posted as a separate answer.
With the drawback in mind you always have when using Linq: it's very elegant and can accomplish a lot with only one or two lines of code - but if you need performance, you need to be careful and know exactly what's going on, otherwise it can become very expensive very quickly.
@Wolfram : converted it. You can put this comment under it. Indeed you have to be careful with it, but in this case (some fruits and their amounts) I don't tink it poses.
Comparing Two Arrays
1
Answer
Changed array type, different functions?
1
Answer
Sort only considering last entry in my array
1
Answer
Comparing two objects properties for the closest
0
Answers
populate array values automatically in inspector
2
Answers | https://answers.unity.com/questions/378015/comparing-value-of-multiple-ints-and-returning-the.html | CC-MAIN-2019-47 | refinedweb | 687 | 60.85 |
Spacing of ButtonItem's
Is there a way to influence the spacing of
ButtonItem's in a title row bar? They seem to be pretty far apart. In the iPhone layout of my app I have four (one left and three right) of them and now there's hardly any room left for the title itself. Thanks a lot!
Not really... It's possible to get something similar by using
objc_utilthough. This way, you can create a
ButtonItemthat uses a custom view instead of an image/title, and you could add multiple buttons with custom spacing/size to that view...
A Button as a custom view of a ButtonItem doesn't behave completely like a normal ButtonItem with an image though. For example, the touch target of regular ButtonItems is much larger (taps don't need to be as precise).
Anyway, here's a little demo of what I mean. The spacing is very tight in this example, but it's easy to change.
import ui from objc_util import * v = ui.View(frame=(0, 0, 400, 400), name='Demo') v.background_color = 'white' btn_images = [ui.Image.named(n) for n in ['iob:beaker_32', 'iob:beer_32', 'iob:coffee_32']] btn_container = ui.View(frame=(0, 0, len(btn_images)*32, 44)) for i, img in enumerate(btn_images): btn = ui.Button(image=img) btn.frame = (i*32, 0, 32, 44) btn_container.add_subview(btn) btn_item = ui.ButtonItem() btn_item_objc = ObjCInstance(btn_item) btn_item_objc.customView = ObjCInstance(btn_container) v.right_button_items = [btn_item] v.present('sheet')
@omz Hi there! Thanks a lot for offering this sample code snippet. I'm currently turning it into a utility class. Unfortunately, there seems to be an issue with the
actionmethod of the
ButtonItem's: they are never called. I can see the icons being pressed but nothing else happens. Do I need a little more ObjC wizadry for this? Thanks! I appreciate your help!
You'd have to use the
actionof the individual buttons that are added to the container.
@omz That's exactly what I'm using. The methods of the individual buttons are not called, at least, not in my setup. See my gist.
The first problem is that you cannot pass an
actionas a keyword argument to the
ui.Buttonconstructor. It's a bit unfortunate that this is silently ignored instead of raising an exception... but you have to assign the
actionattribute separately.
Unfortunately, your code will crash after you do so. The reason for this is that the container view (and with it, the buttons) get garbage-collected because there are no references to them anymore after
get_condensed_listreturns. The underlying (ObjC) views still exist, but the Python objects are gone, which leads to garbage pointers and crashes... In short, you have to keep a reference to the
btn_containerview somehow. I would suggest that you simply assign it as an attribute of
v(something like
v.button_container = btn_container). This requires some refactoring of your
get_condensed_listmethod. This should work:
# coding: utf-8 # This file is part of import ui from objc_util import * DEFAULT_X_SPACING = 8 DEFAULT_HEIGHT = 44 class ButtonItemCondenser (object): def __init__(self, button_item_list, x_spacing=DEFAULT_X_SPACING): self.button_item_list = button_item_list self.x_spacing = x_spacing def get_condensed_list(self): # see i = 0 x = 0 btn_container = ui.View(name='test') for button_item in self.button_item_list: btn = ui.Button(image=button_item.image, action=button_item.action) #button_item.action(btn_container) width = button_item.image.size[0] btn.frame = (x, 0, width, DEFAULT_HEIGHT) x = x + width + self.x_spacing btn_container.add_subview(btn) i = i + 1 x = x - self.x_spacing btn_container.frame = (0, 0, x , DEFAULT_HEIGHT) btn_item = ui.ButtonItem() btn_item_objc = ObjCInstance(btn_item) btn_item_objc.customView = ObjCInstance(btn_container) return [btn_item] def handle_action(sender): #print "handle_action: sender.name=%s" % sender.name print str(sender) #def handle_action(): # print "handle_action" def test(): icon_names = [ 'iob:beaker_32', 'iob:beer_32', 'iob:bag_32' ] button_item_list = map(lambda name : ui.ButtonItem(image=ui.Image.named(name), action=handle_action), icon_names) condenser = ButtonItemCondenser(button_item_list) v = ui.View(frame=(0, 0, 400, 400), name='Demo') v.background_color = 'white' condensed_list = condenser.get_condensed_list() normal_item = ui.ButtonItem(image=ui.Image.named('iob:checkmark_32'), action=handle_action) condensed_list.append(normal_item) v.right_button_items = condensed_list v.present('sheet') if __name__ == '__main__': test()
@omz Hi there! I've incorporated your changes and created references to all otherwise dangling instances. It still crashes, usually when pressing the third button. See here. Any idea?
@JonB Sorry for addressing you directly, but you seem to have an abundance of experience in this area. Do you have any idea what could be wrong in my implementation of @omz's ObjC approach (see my gist link below)? Thanks a lot!
@marcus67 A simple one-line fix would be to add a reference to the
condenserobject to the view before you present it:
# ... v.condenser = condenser v.present('sheet') # ...
This way, you can make sure that the objects you reference in
condenserdon't get garbage-collected as long as the view is on screen... | https://forum.omz-software.com/topic/2724/spacing-of-buttonitem-s/9 | CC-MAIN-2021-49 | refinedweb | 799 | 52.87 |
Our team architect has asked us this question which is said to be an interview question from Microsoft long time ago:
Please implement one function which accepts two integers as input and generate the following result accordingly:
If a > b, return 1, if a = b, return 0, if a < b, return -1
For simplification reason here we can just consider unsigned int ( that is, all importing parameter of integers are greater than or equal to 0 ).
Inside the implementation, you are NOT allowed to use +, -, *, /, > and < for comparison.
There must be multiple ways to achieve it, here below is just one among them. Even we are not allowed to use four arithmetic operations and > or <, we can still leverage the bit operation supported on Integer.
The basic idea is, say we have 6 and 5 for comparison.
Binary format of 6: 0110 Binary format of 5: 0101
If we can generate the biggest-sub-bits-series which differentiate the two integers, in the example above it is 0010( since the third bit of both integer are equal ), then we can simply know which is bigger by making bit AND operation:
0110 & 0010 = 10 which <> 0. 0101 & 0010 = 0
So we can know 0110 > 0101.
Another example – compare 4 and 3
Binary format of 4: 0100 Binary format of 3: 0011
The biggest-sub-bits-series: 0100
0100 & 0100 = 0100 which <> 0 0011 & 0100 = 0
So 0100 > 0011.
Solution in JavaScript
function compare(a,b){ var diff = a ^ b; if( diff == 0) return 0; diff = diff | ( diff >> 1 ); diff |= diff >> 2; diff |= diff >> 4; diff |= diff >> 8; diff |= diff >> 16; diff ^= diff >> 1; return ( a & diff )? 1:-1; } console.log(compare(1,2)); console.log(compare(3,2)); console.log(compare(300,2)); console.log(compare(3000,2)); console.log(compare(3000,3000)); console.log(compare(3000,3001));
Output:
Solution in Java
public static int compare(int a, int b){ int diff = a ^ b; if( diff == 0) return 0; diff = diff | ( diff >> 1 ); diff |= diff >> 2; diff |= diff >> 4; diff |= diff >> 8; diff |= diff >> 16; diff ^= diff >> 1; return ( (a & diff) == 0 ) ? -1 : 1; } System.out.println(compare(1,2)); System.out.println(compare(3,2)); System.out.println(compare(300,2)); System.out.println(compare(3000,2)); System.out.println(compare(3000,3000)); System.out.println(compare(3000,3001));
Output:
Solution in ABAP
Since it is not possible to directly perform bit operation on integer in ABAP, in my blog Bitwise operation ( OR, AND, XOR ) on ABAP Integer I simulate these three operations with the help of ABAP internal table. Still it is not enough, the bit shift operation like >> and << are also required to finish this exercise, so I make further enhancement, adding two new methods SHIFT_RIGHT and SHIFT_LEFT in ZCL_INTEGER, which could be found from my github.
Now all prerequisite to finish it using ABAP are fulfilled.
Here it is:
Source code:
METHOD compare. DEFINE shift_right. lv_diff = a->get_raw_value( ). a->shift_right( &1 ). lo_diff = zcl_integer=>value_of( lv_diff ). a = lo_diff->or( a ). END-OF-DEFINITION. DATA(a) = zcl_integer=>value_of( iv_a ). DATA(b) = zcl_integer=>value_of( iv_b ). DATA: lv_diff TYPE int4, lo_diff TYPE REF TO zcl_integer. a = a->xor( b ). IF a->get_raw_value( ) IS INITIAL. rv_result = 0. RETURN. ENDIF. shift_right 1. shift_right 2. shift_right 4. shift_right 8. shift_right 16. lv_diff = a->get_raw_value( ). a->shift_right( 1 ). lo_diff = zcl_integer=>value_of( lv_diff ). a = lo_diff->xor( a ). DATA(lo_origin_a) = zcl_integer=>value_of( iv_a ). rv_result = zcl_integer=>value_of( lo_origin_a->and( a )->get_raw_value( ) )->get_raw_value( ). rv_result = COND #( WHEN rv_result IS INITIAL THEN -1 ELSE 1 ). ENDMETHOD.
Test code:
WRITE:/ zcl_comparator=>compare( iv_a = 1 iv_B = 2 ). WRITE:/ zcl_comparator=>compare( iv_a = 3 iv_B = 2 ). WRITE:/ zcl_comparator=>compare( iv_a = 300 iv_B = 2 ). WRITE:/ zcl_comparator=>compare( iv_a = 3000 iv_B = 2 ). WRITE:/ zcl_comparator=>compare( iv_a = 3000 iv_B = 3000 ). WRITE:/ zcl_comparator=>compare( iv_a = 3000 iv_B = 3001 ).
Test output:
Reference
Most Significant Bit introduced in Wikipedia
- An interview question: Compare two integers without +,-,*,/ or > and <
In ABAP we have the awesome internal tables. Put the a and b values in an internal table and sort it. Ta-dah! 🙂
I better be hired now. 🙂
Hello Jelena,
An awesome solution 🙂
Best regards,
Jerry
Follow-up question: Implement sort without using +, -, /, *, >, or <. | https://blogs.sap.com/2017/04/29/an-interview-question-compare-two-integers-without-or-and/ | CC-MAIN-2017-43 | refinedweb | 691 | 55.03 |
In the previous labs in the "Learn Tensorflow" series, you used the Fashion MNIST dataset to train an image classifier. In this case you had images that were 28x28 where the subject was centered. In this lab you'll take this to the next level, training to recognize features in an image where the subject can be anywhere in the image!
You'll be using TensorFlow in this lab to create a Convolutional Neural Network that is trained to recognize images of horses and humans and classify them..
You'll do this by building a horses-or-humans classifier that will tell you if a given image contains a horse or a human, where the network is trained to recognize features that determine which is which.
In the case of Fashion MNIST, the data was built into TensorFlow via Keras. In this case the data isn't so you'll have to do some processing of it before you can train.
First, let's download the data:
!wget --no-check-certificate -O /tmp/horse-or-human.zip
The following python code will use the OS library to use Operating System libraries, giving you access to the file system, and the zipfile library allowing you to unzip the data.
import os import zipfile local_zip = '/tmp/horse-or-human.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/horse-or-human') zip_ref.close()
The contents of the .zip are extracted to the base directory /tmp/horse-or-human, which in turn each contain horses and humans subdirectories.
In short: The training set is the data that is used to tell the neural network model that 'this is what a horse looks like', 'this is what a human looks like' etc.
One thing to pay attention to in this sample: We do not explicitly label the images as horses or humans. If you remember with the fashion example earlier, we had labelled 'this is a 1', 'this is a 7' etc.
Later you'll see something called an ImageGenerator being used -- and that reads images from subdirectories, and automatically label them from the name of that subdirectory. So, for example, you will have a 'training' directory containing a 'horses' directory and a 'humans' one. ImageGenerator will label the images appropriately for you, reducing a coding step.
Let's define each of these directories:
# Directory with our training horse pictures train_horse_dir = os.path.join('/tmp/horse-or-human/horses') # Directory with our training human pictures train_human_dir = os.path.join('/tmp/horse-or-human/humans')
Now, let's see what the filenames look like in the horses and humans training directories:
train_horse_names = os.listdir(train_horse_dir) print(train_horse_names[:10]) train_human_names = os.listdir(train_human_dir) print(train_human_names[:10])
Let's find out the total number of horse and human images in the directories:
print('total training horse images:', len(os.listdir(train_horse_dir))) print('total training human images:', len(os.listdir(train_human_dir)))
Now let's 8 horse and 8.
Let's start defining the model:
Step 1 will be to import tensorflow.
import tensorflow as tf NN..)
from tensorflow.keras.optimizers import RMSprop model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=0.001), metrics=['acc'])).')
Let's train for 15 epochs -- this may take a few minutes to run.
history = model.fit_generator( train_generator, steps_per_epoch=8, epochs=15, verbose=1)
Let's now take a look at actually running a prediction using the model. This code will allow you to choose 1%.
This is due to something called overfitting, which means that the neural network is trained with very limited data -- there are only 500ish images of each class. So it's very good at recognizing images that look like those in the training set, but it can fail a lot at images that are not in the training set.
This is a data point proving that the more data you train on, the better your final network will be!
There are many techniques that can be used to make your training better, despite limited data, including something called Image Augmentation. That's beyond the scope of this lab!")
So, for example to test with this image:
Here's what the colab produces:
..we can see that despite it being a cartoon graphic, it still classifies correctly.
This image also classifies correctly:
Try some images yourself and explore!. | https://codelabs.developers.google.com/codelabs/tensorflow-lab5-compleximages/index.html?index=..%2F..learn-tensorflow | CC-MAIN-2020-10 | refinedweb | 717 | 56.15 |
What Are Events, Why Might You Care, and How Can EventMachine Help?
You Node.js event driven framework. Ruby has had the EventMachine library since 2006, with other event driven programming libraries such as Rev and Coolio being released since then.
Despite this relative wealth of libraries, and growing interest in the event driven programming paradigm, this realm of software design is still shrouded in mystery and unknowns for many developers. People who are new to it tend to misunderstand it, often assuming magic that does not exist, or simply misunderstanding what "event driven" really means. Even developers with experience writing event based software using one of the previously mentioned libraries are often fuzzy on the details. They may assume that their library of choice represents the "real" world of event based programming. Or simply because their use cases only take them to a few familiar neighborhoods of evented programming, they may retain some of that newbie fog for other parts.
This series of articles is going to attempt to rectify some of those situations. The precise course of the articles will be determined as they progress, but for today, let's start at the beginning. Event Based/Driven Programming. It'a hot. All the cool kids are doing it. It's got EVENTS! Raise your hand if you truly know what that means, or why you should actually care.
Event
–noun
- something that happens or is regarded as happening; an occurrence, especially one of some importance.
- the outcome, issue, or result of anything: The venture had no successful event.
- something that occurs in a certain place during a particular interval of time.
That quote was courtesy of
Applying that definition to the world of software is a pretty direct thing, as it turns out. Event based programming is nothing more than letting the flow of the program be determined by some set of events. Hardware interrupts are an example of a ubiquitous source of events. On Unix systems, signals and the signal handlers that deal with them are a type of event based programming, as well. A typical pattern for windowing systems is to operate with an event based model; the software can't know when one is going to click on a menu item, or a dialog button, so the software instead runs in a loop, waiting for some event to happen. When an event occurs, the software calls into another piece of code to handle that event.
At its simplest, that general pattern of the system being divided into a dyad consisting of one part that detects or selects events, with a second part that handles them, is what event based programming is actually about. If you have been programming for any length of time, the odds are pretty good that at least in some small ways, you have engaged in event driven programming even if you didn't realize it.
If you go back and look at any of those libraries that I mentioned at the top of the articles, you will notice a trend. Each of those libraries is an event driven programming library, but there is a fair amount of variation across them. This is because event driven is a vague label, encompassing numerous patterns and feature sets. One of the most common of these patterns is the Reactor pattern.
The Reactor pattern describes a system that handles asynchronous events, but that does so with synchronous event callbacks. There are several ruby implementations of this pattern, including the most common library for event based programming in Ruby today, EventMachine. A reactor is good at handling many concurrent streams of incoming our outgoing IO, but because the callbacks are invoked synchronously, callback handling can severely impact the concurrency, or apparent concurrency, of a reactor implementation. Nonetheless, reactors are easy to implement, and with a little care, can be used to drive high performance IO on a single threaded, single process application.
As I mentioned, EventMachine is a Reactor implementation. And it is perfectly possible to install EventMachine, look at a few documents and a few examples, and start writing your own event based software that uses it without really having a good idea of how the machine is running under the hood. But there is value in understanding what a Reactor actually is, so that you better understand what a library like EventMachine is doing for you. Ruby gives us a lot of tools that make it reasonably easy to write a very simple pure ruby reactor implementation, so let's do that. It should make this topic much clearer when you see how simple it actually is. All of the code shown below can also be found on GitHub at. All of these pure ruby examples should work on every Ruby implementation. I have tried it on MRI 1.8.7_p352 and 1.9.3_p0, as well as JRuby 1.6.5 and Rubinius 2.0.0dev, though I did not extensively test on anything other than MRI 1.9.3, so quirks may exist.For our pure ruby reactor, we want only a few features.
- Unlike EventMachine, which also includes substantial support for managing creations of network connections, servers, and other more sophisticated activities, our reactor is going to limit itself to only being a tool for handling events. Therefor, all that it needs is a way to attach and detach IO objects to/from the reactor. We'll use the built in ruby mechanisms for everything else.
- Ruby has the select() call available to it on all platforms, so our reactor will be designed to use it. The select() call returns readable handles, writeable handles, and errors from a set of filehandles to operate on, so those three events (
:read, :write, :error) will likewise be all that our reactor handles.
- Timers are very useful, and are pretty easy to implement in a reactor, so it would be nice to have a timer implementation.
Even though it is not strictly necessary for a reactor implementation, I will start our implementation with the timer functionality. Timers are events which are time based. Their callback is triggered at some point after a given time threshold is reached. The difficulty with timers is in choosing a mechanism for storing them such that the ones which need to be triggered can be easily and efficiently detected. Time, however, is a sortable attribute, and there are some data structures that are great for storing sortable data where that sorted data order is important. There are tree based data structures which are very efficient at maintaining this sort of data. Ruby doesn't have one of those as a native data type, so for this example, I will just fake it. If I were writing a serious implementation, I would have to do more work to provide an efficient data structure for timer data. The following data structure is built on top of a hash, makes no claims to be efficient, and provides the bare minimum API for our reactor to have the tool that it needs to implement timers.
class SimpleReactor class TimerMap < Hash def []=(k,v) super @sorted_keys = keys.sort v end def delete k r = super @sorted_keys = keys.sort r end def next_time @sorted_keys.first end def shift if @sorted_keys.empty? nil else first_key = @sorted_keys.shift val = self.delete first_key [first_key, val] end end def add_timer time, *args, &block time = case time when Time Time.to_i else Time.now + time.to_i end self[time] = [block, args] if block end def call_next_timer _, v = self.shift block, args = v block.call(*args) end end end
Ok. Now let's start writing a reactor! Since we started with timers, we'll just write enough to make timers work. So, first, an #initialize method, and a method to add timers.
class SimpleReactor def initialize @running = false @timers = TimerMap.new @block_buffer = [] end def add_timer time, *args, &block time = time.to_i if Time === time @timers.add_timer time, *args, &block end
There's nothing interesting with the initialization. It just sets the
@running instance variable false. This will be used in an upcoming bit of code. The method to add a timer also does nothing special; it just passes everything into a method of the same name in the TimerMap. The next part that is needed is the skeleton of our reactor. Here is what it looks like:
def next_tick &block @block_buffer << block end def tick handle_pending_blocks handle_events handle_timers end def run @running = true yield self if block_given? tick while @running end def stop @running = false end def handle_pending_blocks @block_buffer.length.times { @block_buffer.shift.call } end def handle_events end def handle_timers now = Time.now while !@timers.empty? && @timers.next_time < now @timers.call_next_timer end end def empty? @timers.empty? && @block_buffer.empty? end end
There you have it. A reactor skeleton, albeit one that only supports timers and next_tick right now. Here's an example that uses it:
require 'simplereactor' puts <<ETXT This demo will add a sequence of numbers to a sum, via a timer, once a second, for four seconds, with the fifth number immediately following the fourth. 1+2+3+4+5 == 15. Let's see if that's the answer that we get." ETXT n = 0 reactor = SimpleReactor.new reactor.add_timer(1) do puts "one" n += 1 end reactor.add_timer(2) do puts "two" reactor.add_timer(1, n + 2) do |sum| puts "three" reactor.add_timer(1, sum + 3) do |sum| puts "four" n = sum + 4 reactor.next_tick do puts "five" n += 5 puts "n is #{n}\nThe reactor should stop after this." end end end end reactor.tick until reactor.empty?
There's no real magic here. The code shows that one can create timers, and can create new timers within the callback code of existing timers, leveraging Ruby's block syntax. If you run this, you will get output like this:
(This demo will add a sequence of numbers to a sum, via a timer, once a second, for four seconds, with the fifth number immediately following the fourth. 1+2+3+4+5 == 15. Let's see if that's the answer that we get. one two three four five n is 15 The reactor should stop after this. )
Take note of the last line in the example code --
reactor.tick until reactor.empty?. The reactor will not do anything until that line runs. That line sits in a loop, ticking our reactor repeatedly until there's nothing left for it to do. At that point, #empty? returns true, the loop terminates, and the program terminates.
The next step in this adventure is to add enough code to our reactor to do something useful with IO objects, as well. We need to be able to attach them to the reactor, detach them from the reactor, and put enough intelligence into the reactor to find events to respond to, and trigger the callbacks for those events.
First add a constant and some accessors, and change the #initialize method:
Events = [:read, :write, :error].freeze attr_reader :ios def self.run &block reactor = self.new reactor.run &block end def initialize @running = false @ios = Hash.new do |h,k| h[k] = { :events => [], :callbacks => {}, :args => [] } end @timers = TimerMap.new @block_buffer = [] end
(This adds a hash for holding our IO objects. It has an initializer to hold an array of events that that the IO object will respond to, a hash of callbacks (potentially one per event type), and some set of args which can be passed to an invoked callback. A hash is also created to hold unhandled events, should they occur.
Next, let's add some methods to attach an IO object to the reactor, setup callbacks, and detach an IO object to the reactor.)
def attach io, *args, &block events = Events & args args -= events @ios[io][:events] |= events setup_callback io, events, *args, &block self end def setup_callback io, events, *args, &block i = @ios[io] events.each {|event| i[:callbacks][event] = block } i[:args] = args i end def detach io @ios.delete io end
The code takes an IO object, a set of args to pass into the callback, and a block. It adds it to the @ios hash, and sets up the callback for the given events.
Next, we need to add a few small methods to enable triggering on IO events.
def handle_events unless @ios.empty? pending_events.each do |io, events| events.each do |event| if @ios.has_key? io if handler = @ios[io][:callbacks][event] handler.call io, *@ios[io][:args] end end end end end end
The #handle_events method is straightforward. If there are any attached IO objects, iterate through the events, calling the callbacks for each. In the existing code, we should never have unhandled events, but by adding that now, one could take this library and expand it more easily into a larger pure ruby reactor that handles types of events other that just what
select() uses.
def pending_events # Trim our IO set to only include those which are not closed. @ios.reject! {|io, v| io.closed? } h = find_handles_with_events @ios.keys if h handles = Events.zip(h).inject({}) {|handles, ev| handles[ev.first] = ev.last; handles} events = Hash.new {|h,k| h[k] = []} Events.each do |event| handles[event].each { |io| events[io] << event } end events else {} # No handles end end def find_handles_with_events keys select find_ios(:read), find_ios(:write), keys, 0.01 end def find_ios(event) @ios.select { |io, h| h[:events].include? event}.collect { |io, data| io } } end def empty? @ios.empty? && @timers.empty? && @block_buffer.empty? end
This last bit of code just adds the nitty gritty methods that figures out if there are any events that need to be handled. It removes from @ios any handles that are closed, uses
select() to find IO events, and then returns a hash of IO objects and the events that have been triggered on them. String all of this code together, and it is all that you need to have a basic working Reactor pattern for event based programming, with timer support. Here's a trivial example that uses pipes, to illustrate how it works.
require 'simplereactor' chunk = "01234567890" * 30 reactor = SimpleReactor.new reader, writer = IO.pipe reactor.attach writer, :write do |write_io| bytes_written = write_io.write chunk puts "Sent #{bytes_written} bytes: #{chunk[0..(bytes_written - 1)]}" chunk.slice!(0,bytes_written) if chunk.empty? reactor.detach write_io write_io.close end end reactor.attach reader, :read do |read_io| if read_io.eof? puts "finished; detaching and closing." reactor.detach read_io read_io.close else puts "received: #{read_io.read 200}" end end reactor.add_timer(2) do puts "Timer called; the code should exit after this." end reactor.tick until reactor.empty?
All that code does is to open a pair of pipes. The reactor attaches to one end as a writer, and the other end as a reader. The callbacks are used to send data from one end of the pipe to the other, where it is received. The Reactor will run for two seconds, then after the timer runs, the reactor will be empty, and it will exit. It looks like this:
Sent 330 bytes: received:001 received: 23 finished; detaching and closing. Timer called; the code should exit after this.
(Here's another example. This one takes user input through the reactor via STDIN, and at the same time runs the stupidest, simplest web server possible. That web server will return a response that includes whatever the user input. The example code is also written to leverage the #run method defined in the library instead of cranking it ourselves.)
require './simplereactor' require 'socket' server = TCPServer.new("0.0.0.0", 9949) buffer = '' to exit, or wait one minute, and a timer will fire which causes the reactor to stop and the program to exit. ETXT SimpleReactor.run do |reactor| reactor.attach(server, :read) do |server| conn = server.accept conn.gets # Pull all of the incoming data, even though it is not used in this example conn.write "HTTP/1.1 200 OK\r\nContent-Length:#{buffer.length}\r\nContent-Type:text/plain\r\nConnection:close\r\n\r\n#{buffer}" conn.close end characters_received = 0 reactor.attach(STDIN, :read) do |stdin| characters_received += 1 data = stdin.getc # Pull a character at a time, just for illustration purposes unless data reactor.stop else buffer << data end end reactor.add_timer(60) do reactor.stop end end
When this is executed, it attaches to STDIN, allowing one to provide input which is buffered internally. Any connection to port 9949 returns a simple HTTP response that contains the buffer that was created through STDIN. The process will run for 60 seconds, then the reactor will stop. Bearing in mind that this is a ridiculously trivial example, it does perform pretty well, too. Below is an excerpt from a test run, done using Ruby 1.9.3_preview1, on one of my older Linux machines.
Concurrency Level: 25 Time taken for tests: 1.60504 seconds Complete requests: 15000 Failed requests: 0 Write errors: 0 Total transferred: 1275000 bytes HTML transferred: 75000 bytes Requests per second: 14144.22 [#/sec] (mean) Time per request: 1.768 [ms] (mean) Time per request: 0.071 [ms] (mean, across all concurrent requests) Transfer rate: 1173.97 [Kbytes/sec] received
Of course, this is an absurdly trivial example. There may be bugs, and it doesn't really do a lot for you, but it is an event reactor, written in pure ruby, and if you went through the code and examples as you read, you should have a better feel for what a reactor truly is.
If you want to write more sophisticated event based software, you could continue using a simple hand-rolled pure ruby reactor like this one, or you might choose to use one of the other common libraries for Ruby today. There are several of them, each with their own strengths and weaknesses, though the most common is EventMachine. Just like our simple reactor, EventMachine offers timers and asynchronous handling of events, though EventMachine's versions will scale better. This article's version uses the select() call, which limits code using it to 1024 open file descriptors. On the other hand, EventMachine, if used on a platform that support epoll (Linux) or kqueue (various *BSD platforms), can readily support at least 10s of thousands. EventMachine also offers a more rich set of features for implementing event based code than this article's example reactor. As a parting example, here is the HTTP server example from above, written to use EventMachine.
require 'rubygems' require 'eventmachine' module ServerHandler def initialize(buffer) @buffer = buffer super end def receive_data data send_data "HTTP/1.1 200 OK\r\nContent-Length:#{@buffer.length}\r\nContent-Type:text/plain\r\nConnection:close\r\n\r\n#{@buffer}" close_connection_after_writing end end module KeyHandler def initialize buffer @counter = 0 @buffer = buffer super end def receive_data data @counter += 1 if data.chomp.empty? EM.stop else @buffer << data end end end a blank line to exit, or wait one minute, and a timer will fire which causes the reactor to stop and the program to exit. ETXT buffer = '' EventMachine.run do EM.start_server('0.0.0.0',9949,ServerHandler,buffer) EM.attach(STDIN, KeyHandler, buffer) EM.add_timer(60) do EM.stop end end
(And since I demonstrated the performance of the pure Ruby version, here's the performance of the EventMachine version (using EventMachine 0.12.10), running on the same system, using the same Ruby 1.9.3_preview1 installation.)
Concurrency Level: 25 Time taken for tests: 0.696320 seconds Complete requests: 15000 Failed requests: 0 Write errors: 0 Total transferred: 1275425 bytes HTML transferred: 75025 bytes Requests per second: 21541.82 [#/sec] (mean) Time per request: 1.161 [ms] (mean) Time per request: 0.046 [ms] (mean, across all concurrent requests) Transfer rate: 1787.97 [Kbytes/sec] received
The code is structured differently, but as you can see, it works similarly. In our simple reactor example, if you changed
data = stdin.getc to
data = stdin.gets, the STDIN handling would behave similarly to the EM examples STDIN handling. However, given the experience of writing a pure ruby reactor, even if you have never used EventMachine before, I think you can now look at that piece of EventMachine code and generally understand how it works, both at the level of the ruby code itself, and with a good idea of what EventMachine is handling for you. This basic understanding of how event driven software actually works is key to writing software that uses the event paradigm effectively.
I have focused on EventMachine in this article because it is the most commonly used event reactor implementation in the Ruby world today. As I mentioned at the beginning of the article, however, there are other choices, such as Coolio. In future articles I will continue to focus on EventMachine, but I will try to include some examples from other frameworks, and also some examples focused on JRuby and Rubinius. Please let us know if there are particular topics that you would like to see discussed.
Share your thoughts with @engineyard on Twitter | https://blog.engineyard.com/2011/what-are-events-why-might-you-care-and-how-can-eventmachine-help | CC-MAIN-2015-32 | refinedweb | 3,509 | 65.83 |
Finance and the Market
1. What is the difference between the primary market and the secondary market?
2. What is the relationship between financial decision making and risk and return?
3. What is an efficient market and what are the implications of efficient markets for us?
4. There are several limitations to ratio analysis. Name three.
5. Napa Valley Winery (NVW) is a boutique winery that produces a high-quality, nonalcoholic red wine from organically grown cabernet sauvignon grapes. It sells each bottle for $30. NVW's chief financial officer, Jackie Cheng, has estimated variable costs to be 70 percent of sales. If NVW's fixed costs are $360,000, how many bottles of its wine must NVW sell to break even?
6. Define the term operating leverage. What type of effect occurs when the firm uses operating leverage?
7. What is a cash budget? A cash budget consists of what four elements?
8. What is the time value of money?
9. What is an annuity? Distinguish between an annuity and a perpetuity.
10. To what amount will the following investments accumulate?
a. $4,000 invested for 11 years at 9 percent compounded annually
b. $8,000 invested for 10 years at 8 percent compounded annually
c. $800 invested for 12 years at 12 percent compounded annually
d. $21,000 invested for 6 years at 5 percent compounded annually
11. What is the present value of the following future amounts?
a. $800 to be received 10 years from now discounted back to the present at 10 percent
b. $400 to be received 6 years from now discounted back to the present at 6 percent
c. $1,000 to be received 8 years from now discounted back to the present at 5 percent
d. $900 to be received 9 years from now discounted back to the present at 20 percent
Solution Preview
1. What is the difference between the primary market and the secondary market?
Primary markets are markets in which corporations raise capital by issuing new securities. Secondary markets are markets in which securities and other financial assets are traded among investors after they have been issued by corporations.
2. What is the relationship between financial decision making and risk and return?
The relationship between financial decision making and the risk and return is that the final decision making will depend on the risk and return a project can generate. Here is an example where standard deviation or sigma is used to measure risks. High sigma will result in a wider normal distribution curve. This means that rate of return are further away from the mean compared to one with low sigma. Therefore, low sigma will cause the actual rate of return closer to the expected rate of return (the mean). Thus, there is less probability that the actual return will end up far below the expected return. To conclude, the lower the sigma value, the tighter the probability distribution is and consequently has lower risk. Therefore, in a situation where there are stocks with same mean (expected rate of return) but different sigma I will say that lower sigma will stimulate one for a high trading in the stock. However, in a situation where different stocks have different sigma and mean, the one with higher coefficient of variation (CV) will be considered as it represents higher risks per unit of return. In the concept where higher risks have higher returns, this will be contradicted in a two alternatives situation where one with higher risks (higher CV) has lower expected return than one with lower risks (lower CV) but has higher expected return. Therefore, the knowledge of sigma really helps in selecting stocks. Great variability in stock price will not always indicate more risks in all trading situations. Instead, it will depend on how risky an unit of return is, the coefficient of variation. The higher the sigma in proportionate to the expected rate of return, the higher the coefficient of variation.
Therefore, regarding my explanation above, I will make a final decision making and prefer a portfolio with higher expected return and less standard ...
Solution Summary
Various finance terms are defined. Guidelines for calculating future values of investments are also given. | https://brainmass.com/business/six-sigma/251970 | CC-MAIN-2017-22 | refinedweb | 702 | 56.45 |
Runtime is a Swift library to give you more runtime abilities, including getting type metadata, setting properties via reflection, and type construction for native swift objects.
TypeInfo
TypeInfo exposes metadata about native Swift structs, protocols, classes, tuples and enums. It captures the properties, generic types, inheritance levels, and more.
Example
Lets say you have a User struct:
struct User { let id: Int let username: String let email: String }
To get the
TypeInfo of
User, all that you have to do is:
let info = try typeInfo(of: User.self)
Property Info
Within the
TypeInfo object, it contains a list of
PropertyInfo which represents all properties for the type.
PropertyInfo exposes the name and type of the property. It also allows the getting and setting of a value on an object.
Example
Using the same
Person object as before first we get the
TypeInfo and the property we want.
let info = try typeInfo(of: User.self) let property = try info.property(named: "username")
To get a value:
let username = try property.get(from: user)
To set a value:
try property.set(value: "newUsername", on: &user)
It’s that easy! 🎉
Factory
Runtime also supports building an object from it’s
Type. Both structs and classes are supported.
To build a
User object:
let user = try createInstance(type: User.self)
Function Info
FunctionInfo exposes metadata about functions. Including number of arguments, argument types, return types, and whether it can throw an error.
Example
func doSomething(a: Int, b: Bool) throws -> String { return "" } let info = functionInfo(of: doSomething)
Q: When getting and setting a value does it work typeless? (i.e. object casted as
Any)
A: Yes! The whole library was designed with working typeless in mind.
Q: When creating a new instance of a class is it still protected by ARC?
A: Yes! The retain counts are set properly so ARC can do its job.
Installation
Cocoapods
Runtime is available through CocoaPods. To install
it, simply add the following line to your Podfile:
pod 'Runtime'
Swift Package Manager
You can install Runtime via Swift Package Manager by adding the following line to your
Package.swift:
import PackageDescription let package = Package( [...] dependencies: [ .Package(url: "", majorVersion: XYZ) ] )
Contributions
Contributions are welcome and encouraged!
Learn
Want to know how it works?
Here’s an article on how it was implemented.
Want to learn about Swift memory layout?
Mike Ash gave and awesome talk on just that.
License
Runtime is available under the MIT license. See the LICENSE file for more info.
Latest podspec
{ "name": "Runtime", "version": "2.1.0", "summary": "Runtime", "description": "Runtime abilities for native swift objects.", "homepage": "", "license": "MIT", "authors": { "Wesley Wickwire": "[email protected]" }, "platforms": { "ios": "9.0" }, "source": { "git": "", "tag": "2.1.0" }, "source_files": "Sources/Runtime/**/*.swift", "dependencies": { "CRuntime": [] } }
Sun, 05 May 2019 10:45:06 +0000 | https://tryexcept.com/articles/cocoapod/runtime | CC-MAIN-2019-51 | refinedweb | 463 | 60.21 |
Very cool!
Rated 5 / 5 stars
Holy carp!
If this was a game,
IF THIS WAS A GAME,
I would buy it.
Immediatly.
Again, holy carp.
I can't wait for the next one!
:D
Awesome dude. Ok this Wednesday Australian time stage3
Rated 5 / 5 stars
Looks like this is all custom-sprite work? If so, that's pretty amazing. Great graphics, great animation, and plenty of love and storyline interweaved with the action. I like the fast pace the animation keeps too, it never slows down too much, not even the part of hearts. It's a creative and crazy adventure. Now imagine this as a real game, that would be amazing. keep it going!
-cd-
Yeah all custom sprites. The boss character is more cutout approach with layers etc but yeah, was a shitload of work gone into it for sure . Thanks for your comment
Rated 4 / 5 stars
I love the timing of the soundtrack where light-hearted melodies and exciting rock songs guides the action on the scenes (from enjoying a bonus level to surviving an ambush). And much like the previous episode, you somehow make us love or hate characters in less than 2 minutes of introducing them (Princess Mean for Stage 1 and Butt-Kicking Brunette for Stage 2). I don't know if that comes naturally, but that couldn't have been an easy feat to write. Your release of this episode couldn't be better timed as well with Bioshock Infinite recently released, as I have been yearning for more content with strong female characters who aide the protagonists (or better yet, save them). I also liked the detail with the rifle animations and how once again modern technology (weaponry and robots) are forced into a ninja world, making it both out of place and hilarious.
I am assuming the episodes are smaller to make production much more feasible, and that was a wise decision, but I am putting 4 stars instead of 5 because of certain choices that were made due to this limitation. For example, the protagonist didn't get to use any of his original moveset so the "game mechanics" felt drastically different than Stage 1, and then there's the fact that the female character had no real reason to hang out since she's really getting nothing more than an idiot in return (almost made her seem weaker). Solving those example issues would require additional animation and far longer painful production time, but it would make Stage 2 seem more believable as a second level of the "game."
There was also the forced fart joke mentioned by previous commenters. If it had to go in, then perhaps digging up a more uniquely and possibly intriguing gross fart sound effect on Google may be more effective. So with this in mind, I'll see how Stage 4 fleshes out the story more, where a 4 star would not give the series justice and a 5 star will instead be rightfully awarded. I said Stage 4, because I am assuming 3 is near completion and can't have any content changed nor added at this point (though it may already address any issues I had with Stage 2), and I am HOPING Stage 4 is planned for at some point in the future.
I waited three years for the return of Dan The Man, and it was well worth it. Welcome back StudioJOHO and see you next week for Stage 3.
(I also hope to see the release of the soundtrack one day, because the music at the end previewing Stage 3 is awesome.)
Cheers mate. The original ep was made as a pilot with tv in mind as that was my bg, but these days my head is about web, hence the shorter length.
Thanks for the response dude
Rated 5 / 5 stars
like that dan can talk and tell people what he thinks(to bad he couldn't tell the princess that she spent all his money),love that girl since she's got additude (big aditude) | http://www.newgrounds.com/portal/view/615160/review_page/8 | CC-MAIN-2016-44 | refinedweb | 681 | 75.13 |
Price elasticity is a measure of the responsiveness of demand or supply of a good or service to changes in price. The price elasticity of demand measures the ratio of the proportionate change in quantity demanded
to the proportionate change of the price
. The price elasticity of supply is analogous. Demand for a good is said to be "price elastic" if the elasticity measure is greater than one in absolute value and "inelastic" if less than one. The cross-price elasticity of demand measures the proportionate change in the quantity demanded of one good to the proportionate price change of another good. A positive cross-price elasticity indicates that the goods are substitutes for one another; a negative cross price elasticity indicates the goods are complements.
M. Poirot wishes to sell a bond that has a face value of $1,000. The bond bears an interest rate of 9% with bond interest payable semiannually. Six years ago, $980 was paid for the bond. At least a 12% return (yield) on the investment is desired.
A. The semiannual bond interest payment that M. Poirot received is _________
B. The minimum selling price must | http://www.chegg.com/homework-help/definitions/price-elasticity-12 | CC-MAIN-2015-18 | refinedweb | 192 | 56.76 |
When the score is greater than 100 points the program should ask me whether the score is correct The program should ask me whether the score is correct. The program should not add a score that is more than 100 points to the accumulator with out permission (if(score > 1000 cout << "is the score correct?: ";)cin >> permission;.)Modify the program appropiatelly. **If you dont understand my instructions. Please help me correct this program. Please explain to me the errors I made.
**
//Lab7-2.cpp - displays the total points earned and grade //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() { //declare variables int score = 0; int totalPoints = 0; //accumulator char permission = ' '; //get first score cout << "First score (-1 to stop): "; cin >> score; while(score < 100) if(score > 100) out << "is the score correct?: "; cin >> permission; { if(toupper(permission == Y) totalPoints+= score; // Accumulator cout << "NextScore: "; cin >> score; else cout << "Next Score (100 to stop): "; cin >> score; } //display the total points and grade cout << "Total points earned: " << totalPoints << endl; system("pause"); return 0; } //end of main function | https://www.daniweb.com/programming/software-development/threads/419853/homework-help-loop-statements | CC-MAIN-2018-30 | refinedweb | 181 | 66.67 |
GUICam
From Unify Community Wiki
(Difference between revisions)
Revision as of 06:44, 21 July 2010
Here is the script I attach to a camera that holds a Rect with the cameras pixels in GUI co-ordinate space.
import UnityEngine class GUICam (MonoBehaviour): public GUIRect as Rect cam as Camera def Start(): cam = transform.camera def Update (): pr=cam.pixelRect r = cam.rect screenHeight = pr.height / r.height GUIRect = Rect(pr.left,screenHeight-(pr.top+pr.height),pr.width,pr.height)
to use I put this on GUI generation script which is a camera component and draw a button in the top left of the camera viewport.
aGUICam as GUICam def Start (): aGUICam = transform.camera.GetComponent(GUICam) def ButtonGUI(): r=aGUICam.GUIRect GUI.Button ( Rect (r.xMin+10,r.yMin+50,50, 30), "button")) | http://wiki.unity3d.com/index.php?title=GUICam&diff=next&oldid=7322 | CC-MAIN-2020-16 | refinedweb | 134 | 61.93 |
55307/python-code-to-publish-a-message-to-aws-sns
Hey @Dipti, you could use something like this:
import boto3
sns = boto3.client('sns')
# Publish a simple message to the specified SNS topic
response = sns.publish(
TopicArn='arn:aws:sns:region:0786589:my-topic-arn',
Message='Hello World',
)
# Print out the response
print(response)
Hey @Harish, follow these steps:
On the navigation ...READ MORE
You can achieve "automatic" triggering by AWS Lambda or ...READ MORE
Yes, of course, you can. You can ...READ MORE
You can write a python code which ...READ MORE
It can work if you try to put ...READ MORE
Hey @nmentityvibes, you seem to be using ...READ MORE
To solve this problem, I followed advice ...READ MORE
Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE
It might be throwing an error on ...READ MORE
There isn't a built-in solution for this, ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/55307/python-code-to-publish-a-message-to-aws-sns | CC-MAIN-2020-40 | refinedweb | 159 | 69.58 |
Client / Server Programming with TCP/IP Sockets
- Stephany Parsons
- 1 years ago
- Views:
Transcription
1 Client / Server Programming with TCP/IP Sockets Author: Rajinder Yadav Date: Sept 9, 2007 Revision: Mar 11, 2008 Web: Table of Content Networks... 2 Diagram 1 Communication Link... 2 IPv4 Internet Protocol... 2 IP Address... 2 IP Classes... 3 Subnets... 3 IP and the Hardware... 4 IP and DNS... 4 loopback... 5 IP from hostname... 5 hostname from IP... 5 hostent structure... 5 TCP Transmission Control Protocol... 6 Diagram 3 Network Hop Topology... 6 TCP Window... 6 Byte Ordering... 7 Little-Endian: the LSB (Least Significant Byte) is at the lowest address Big-Endian: The MSB (Most Significant Byte) is at the lowest address Diagram 4 Address Byte Order... 7 htons( ) and htonl( )... 7 ntohs( ) and ntohl( )... 7 Sockets... 7 TCP Ports... 8 Table 1 Well Known Ports... 8 Opening and closing a socket... 8 Initializing Winsock... 9 Socket Address Structure... 9 TCP Server Naming the socket TCP Client TCP State Diagram Connection Termination Running The Programs Network Utilities ping netstat Server Socket Code Client Socket Code... 22
2 Introduction In this article we will look at how to program using sockets by implementing an echo server along with a client that we will use to send and receive string messages. I will start off by giving a quick introduction to TCP/IP fundamentals and then explain how sockets fit into the picture. I am going to assume you already understand basic network concepts. When you get done reading this article you should be armed with sufficient information to be able to investigate other concepts in more detail on your own. Sample code can be downloaded for this article from my website for Windows and Linux. I have also included all the Winsock source code in print at the end of the article for others. Networks Most network applications can be divided into two pieces: a client and a server. A client is the side that initiates the communication process, whereas the server responds to incoming client requests. Diagram 1 Communication Link There are numerous network protocols, such as Netbios, RPC (Remote Procedure Call), DCOM, Pipes, IPC (Inter-process Communication) that can be used for the Communication Link. We will only look at TCP/IP here. In particular we will look at sockets IPv4 since this is widely implemented by many socket vendors. IPv4 Internet Protocol The current version for IP supported by many modern networks is version 4, the next generation of IP is version 6 (IPv6) which is not widely supported as of this writting. IP is both a network addressing protocol and a network transport protocol. IP is a connection-less protocol that provides unreliable service for data communication. Most of the properties of data communication such as transmission reliability, flow control and error checking are provided by TCP which we will look at shortly. Most people know IP in its basic form as a quad dotted-numerical string, such as Each integer value separated by a dot can have a value from 0 to 255 (8 bits). Thus IPv4 is a 32 bit unsigned integer values. IP Address Diagram 2a IP Address
3 IP Classes The IP address is made of a network address and a host address. There can be many subnetworks connect together, so a network address help routers to redirect data packet to the proper destination network, from there the data packet is sent to the final destination host PC. The 4 IP classes are: Class Leftmost bit Start Address End Address A 0xxx B 10xx C 110x D E Class A network.local.local.local (small network, large hosts ) Class B network.network.local.local (medium network, medium hosts) Class C network.network.network.local (large network, small hosts ) Class D network.network.network.network (multicast to many hosts ) Class E reserved (*) A special type of IP address is the limited broadcast address (*) IP Mapping: Class A, B, C 1-to-1, Class D is 1-to-many Subnets An IP address can have the host address subdivided into a subnet part and a host part using a subnet mask. The subnet mask is also a 32bit value, the bits for the network and subnet will be set to 1, this way from the mask and IP class we can determine the network address, the subnet address and the host number. Diagram 2b IP Address with Subnet There IP address can be classified as unicast, broadcast and multicast. A unicast address has a 1-to-1 relationship. A broadcast can apply to: a) all hosts on a network, b) all hosts on a subnet, and c) all hosts on all subnets. For multicast, a host needs to belong to the multicast group in order to receive a packet. The main thing to note is that a broadcast or multicast packet is never forwarded by a router/gateway outside the network.
4 IP and the Hardware IP is used to identify a PC on the network. This is done for us at the hardware level by the NIC (Network Interface Card) like a PC s Ethernet card or a Router. A machine NIC or Ethernet uses ARP (Address Resolution Protocol) to convert an IP address into a network address that can be understood by routers and gateways. Likewise the hardware layer use RARP (Reverse Address Resolution Protocol) to convert a hardware network address at the MAC (Media Access Control) level into an IP address. As data packets move around the network, the hardware layer (router) is checking if a packet is meant for it to process by checking the MAC address. If it s not the data packet is transmitted down the line. If the data packet is meant for a host in the network, then the IP address is checked using a lookup table to determine which host PC to send the data packet off to in the network. We really don t need to be concerned with underlying details as all this is handled for us. IP and DNS Most people don t use IP directly, it s not an easy way to remember addresses, so to help humans the DNS (Domain Name System) maps a hostname strings like yadav.shorturl.com into an IP address. If you re developing any type of network application it s better to use the DSN name format to communicate with another computer. DSN mapping can be easily changed (in the router table) thus allowing one to redirect network traffic to another destination. Host File On your local PC the DNS mapping entries are found in the host file. On Windows NT, 2K, XP the file hosts is located at: %WINDOWS%\system32\drivers\etc\ The host files (shown in blue) contains a space separated IP address and hostname. All this info ends up in the router table, where network traffic control occurs localhost freedom.home.com download.bigdaddy.com sal.home.com
5 loopback Note: the loopback address of also known as localhost is the IP address used when communicating with other process running on the same PC. This is how we will test our client and server application, they will run on the same local host PC. IP from hostname The gethostbyname function retrieves host information corresponding to a host name from a host database. struct hostent* FAR gethostbyname( const char* name ); hostname from IP The gethostbyaddr function retrieves the host information corresponding to a network address. struct HOSTENT* FAR gethostbyaddr( const char* addr, int len, int type ); hostent structure [msdn] The hostent structure is used by functions to store information about a given host, such as host name, IP address. An application should never attempt to modify this structure or to free any of its components. Furthermore, only one copy of the hostent structure is allocated per thread, and an application should therefore copy any information that it needs before issuing any other Windows Sockets API calls. typedef struct hostent char FAR* h_name; char FAR FAR** h_aliases; short h_addrtype; short h_length; char FAR FAR** h_addr_list; hostent;
6 TCP Transmission Control Protocol Although TCP can be implemented to work over any transport protocol, it's usually synonymous with IP. TCP is a connection-oriented stream protocol (like a telephone call). TCP communication happens using a handshake process, where each data that is sent is acknowledge by the recipient within the time of TCP s timer value. TCP provides many services such as data reliability, error checking, and flow control. If a data packet is corrupt or lost (not acknowledged), TCP will retransmitted the data from the client side automatically. Because the route a packet takes can be many, one packet may arrive before the one sent earlier. As data packets arrive, it is the job of TCP to assemble the packets into the proper order. This is shown below with a factious network topology layout, where the data packet takes (n) number of hops to get from the source to the destination. On a bigger network like the Internet, there are many routes a data packet can take to arrive at its final destination. Diagram 3 Network Hop Topology TCP Window Any duplicate data packet is silently dropped with no acknowledgement. TCP controls the flow of transmission by using a window that can grow or shrink based on how responsive the (next-hop) node is. If a lot of packets are getting dropped because the receiver s buffer is full, TCP will slow down the rate of transmission by decreasing the size of the window. Usually TCP will negotiate with the receiver for such things as the maximum transmission unit. If the sizes are different, such that the receiver node accepts a smaller sized packet, the out-bound packet will be fragmented by TCP. Again, the data packet segments can arrive at different times by taking different routes. So it s the job of TCP at the destination end to reassemble the original data packet as the segments arrive. The data is placed into a larger buffer by TCP to be read by the application. Data is streamed out from the client side and streamed in at the server side. This is why TCP is called a stream bases protocol, it s work just like a file I/O read and write operation, which is what provides synchronous data access.
7 Byte Ordering There are two types of memory byte ordering in use today that are very much machine dependent. They are known as little-endian and big-endian, because of this we have to be very careful how we interpret numerical data. If we do not take into account the endiannes, the numerical data we read will be corrupt. Little-Endian: the LSB (Least Significant Byte) is at the lowest address. Big-Endian: The MSB (Most Significant Byte) is at the lowest address. Diagram 4 Address Byte Order Generally when working with numeric data, one needs to convert from machine (host) byte order to network byte order when sending data (write-op), and then from network byte order to machine byte order when retrieving data (read-op). The APIs to make the conversion are: htons( ) and htonl( ) // host to network uint16_t htons ( uint16_t host16bitvalue ); uint32_t htonl ( uint32_t host32bitvalue ); ntohs( ) and ntohl( ) // network to host uint16_t ntohs ( uint16_t net16bitvalue ); unit32_t ntohl ( unit32_t net32bitvalue ); Note: network byte order is in Big-Endian, CPU based on the x86 architecture use Little- Endian byte order. Sockets We are now ready to talk about what a socket is. A socket is made up of 3 identifying properties: Protocol Family, IP Address, Port Number For TCP/IP Sockets: The protocol family is AF_INET (Address Family Internet) The IP Address identifies a host/service machine on the network Port defines the Service on the machine we re communicating to/from
8 TCP Ports The port numbers from 0 to 255 are well-known ports, and the use of these port numbers in your application is highly discouraged. Many well-known services you use have assigned port numbers in this range. Service Name Port Number ftp 21 telenet 23 www-http 80 irc 194 Table 1 Well Known Ports In recent years the range for assigned ports managed by IANA (Internet Assigned Numbers Authority) has been expanded to the range of To get the most recent listing of assigned port numbers, you can view the latest RFC 1700 at: In order for 2 machines to be able to communicate they need to be using the same type of sockets, both have to be TCP or UDP. On Windows, the socket definition is defined in the header file <winsock.h> or <winsock2.h>. Our program will be using Winsock 2.2 so we will need to include <winsock2.h> and link with WS2_32.lib Opening and closing a socket To create a TCP/IP socket, we use the socket( ) API. SOCKET hsock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); If the socket API fails, it will return a value of INVALID_SOCKET, otherwise it will return a descriptor value that we will need to use when referring to this socket. Once we are done with the socket we must remember to call the closesocket( ) API. closesocket( hsock ); Note: On Unix/Linux the return type for socket( ) is an int, while the API to close the socket is close( socket_discriptor ); Before we can begin to use any socket API in Windows we need to initialize the socket library, this is done by making a call to WSAStartup( ). This step is not required on Unix/Linux.
9 Initializing Winsock // Initialize WinSock2.2 DLL // low-word = major, hi-word = minor WSADATA wsadata = 0; WORD wver = MAKEWORD(2,2); int nret = WSAStartup( wver, &wsadata ); Before we exit our program we need to release the Winsock DLL with the following call. // Release WinSock DLL WSACleanup(); With the basics out of the way, the process of preparing the client and server application is similar, but differ slightly in their steps. We will talk about how to write the server code first. Socket Address Structure For IPv4 the socket structure is defined as: struct sockaddr u_short sa_family; /* address family */ char sa_data[14]; /* up to 14 bytes of direct address */ ; This is the generic structure that most socket APIs accept, but the structure you will work with is sockaddr_in (socket address internet). struct sockaddr_in short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; ; Note: sockaddr_in and the more generic sockaddr struct are the same size. Padding is used to maintain the size by sin_zero[8]. You will need to typecast between the two in your program.
10 struct in_addr found inside sockaddr_in is a union defined as: struct in_addr union struct u_char s_b1,s_b2,s_b3,s_b4; S_un_b; struct u_short s_w1,s_w2; S_un_w; u_long S_addr; S_un; #define s_addr S_un.S_addr #define s_host S_un.S_un_b.s_b2 #define s_net S_un.S_un_b.s_b1 #define s_imp S_un.S_un_w.s_w2 #define s_impno S_un.S_un_b.s_b4 #define s_lh S_un.S_un_b.s_b3 ; This structure holds the IP address which can be accessed in many ways. You can use the inet_addr( ) API to convert a IP dotted-numerical string into a 32bit IP address and assign it to the s_addr member. The use of this API is shown when we discuss the client code. To do an opposite conversion from network to IP string, use the inet_ntoa( ) API. TCP Server The steps to get a server up and running are shown below (read from top to bottom). This is how our sample code is written, so it's a good idea to get familiar with the process. socket( ) bind( ) +---->listen( ) accept( ) (block until connection from client ) read( ) write( ) close( ) close( ) 1. Create a server socket 2. Name the socket 3. Prepare the socket to listen 4. Wait for a request to connect, a new client socket is created here 5. Read data sent from client 6. Send data back to client 7. Close client socket 8. Loop back if not told to exit 9. Close server socket is exit command given by client
11 Naming the socket When we prepare the socket for the server, we use INADDR_ANY for the IP address to tell the TCP stack to assign an IP address to listen on for incoming connection requests. Do not assign a hard-coded value, otherwise the program will only run on the server defined by the IP address, and if the server is multi-homed then we are restricting it to listen on only one IP address rather than allow the administrator to set the default IP address. // name socket sockaddr_in salisten = 0; salisten.sin_family = PF_INET; salisten.sin_port = htons( ); salisten.sin_addr.s_addr = htonl( INADDR_ANY ); Once we have initialize the sockaddr_in struct, we need to name the socket by calling the bind( ) API. bind( hsock, (sockaddr*)&salisten, sizeof(sockaddr) ); Notice how we are required to typecast the socket address to (sockaddr*). Here hsock is the server socket we created earlier and this binds (names) the socket with the information provided in the socket structure. After the socket has been named, we then wait for incoming connection requests by making the next 2 calls. listen( hsock, 5 ); sockaddr_in saclient = 0; int nsalen = sizeof( sockaddr ); SOCKET hclient = accept( hsock, (sockaddr*)&saclient, &nsalen ); The values of '5' passed to listen( ) is the backlog of connection request that will get queued waiting to be processed. Once this limit is exceeded, all new calls will fail. In the call to accept( ), we do not need to initialize saclient, the sockaddr struct because when this calls returns it will fill saclient with the name of the client s socket. The sample echo server provided is a single thread (iterative) application, it can only handle and process one connection at a time. In a real world application, one would general use multithreading to handle incoming client requests. The primary thread would listen to incoming calls and block on the call to accept( ). When a connection request came in, the main thread would be given the client s socket descriptor. At this point a new thread should be created and the client socket passed to it for processing the request. The main thread would then loop back and listen for the next connection.
12 When a client connection has been established, data is read from the TCP buffer by making a call to recv( ). This function returns the number of bytes read. nsent = recv( hclient, wzrec, nsize, 0 ); The first parameter is the socket to the connected client, the second parameter is a text buffer, followed by it's size, and finally flags on how recv( ) behaves. The flags value is normally zero. Other values for the flag that can be ORed are: MSG_PEEK : Copy data to buffer, but do not remove from TCP buffer. MSG_OOB : Process out of bound data MSG_WAITALL : Wait for the buffer to be completely filled Note: the call to recv( ) will only return the data that has arrived, this means the call can return before the entire data has been received into the TCP buffer. So the best way to write a data fetch routine is by using a fixed buffer size that is able to hold the largest transmitted data set. Then to read using a loop that waits till all the data has arrived before handing off the read buffer. // process data char wzrec[512] = 0; int nleft = 512; int ipos = 0; int ndata = 0; do ndata = recv( hclient, &wzrec[ipos], nleft, 0 ); nleft -= ndata; ipos += ndata; while( nleft > 0 ); Likewise we do the same when sending data with send( ), the parameter values are the same as they are for recv( ). Just because send( ) return successfully saying it sent the data, this does not mean the data was placed on the network. It simply means the TCP buffer had enough room to copy the data. There is a TCP option TCP_NODELAY that will cause the data to appear on the network immediately, but its use is only for specialized applications and should be avoided. Once we are done, we need to close the client's socket and then close the server socket. In the sample program of the echo server, the server loops back into listen mode unit a string containing "!shutdown" is received which tells the server to stop listening and to shutdown.
13 TCP Client Now let's take a look at what steps the client needs to take in order to communicate with the server. socket( ) connect( ) write( ) read( ) close( ) 1. Create a socket with the server IP address 2. Connect to the server, this step also names the socket 3. Send data to the server 4. Read data returned (echoed) back from the server 5. Close the socket The initialization of the sockaddr_in structure is different for the client. With the client the socket address needs to assign the port number along with the IP address of the server. Since we're testing on the localhost, we hard-core the IP address of " " sockaddr_in saserver = 0; saserver.sin_family = PF_INET; saserver.sin_port = htons( ); saserver.sin_addr.s_addr = inet_addr( " " ); Notice the use of htons( ) when setting the port number. The call to inet_addr( ) converts a dotted-numerical string into a 32bit IP value that gets assigned to the s_addr member of the sin_addr struct. We have now covered how both the client and server code is written, lets take a quick look at how to use the both the programs.
14 TCP State Diagram Connection Establishment TCP uses a 3 way handshake. A Server makes a passive open by call bind( ). The Client initiates an active open by calling connect( ). For the connection to be established, the client send a SYN to the server. The Server replies with SYN/ACK and finally the Client replied with ACK. Diagram-5 Created using Visual Paradigm Connection Termination TCP uses a 4 way handshake to close the connection. When an endpoint wants to close, it send out a FIN, the other side then replied with an ACK. A connection is half-open when one side has close the connection. The other side is still free to send. A situation can occur where one side closes the connection and then reopens it immediately, so any lost packets that now arrive will not belong to this new connection and thus TCP we need to insure these packets do not get mixed in with the new packets. So the TIME WAIT state allows a connection to remain open long enough for such packets to be removed from
15 the network. This state usually lasts for about 2 times the round-trip, some implementation hardcode the default value to be anywhere from 30 to 120 seconds. You can use the netstat utility to see TCP/IP states.
16 Running The Programs Bring up two command prompts and go the folder were the client and server executable are each located. In one of the shell type, "EchoServer.exe" to start the server. You should see the following output: In the other shell type: EchoClient.exe "Hello World!!!" At this point the server should display that a connection has been made follow by the data sent. The client shell should state that a connection has been made and what the echo message string is. If we type in the client shell: EchoClient.exe!shutdown The server should now shutdown and exit. Highlighted is the output from the server of the second client connection. The source code on the following pages were colorized using Carlos Aguilar Mares "CodeColorizer" tool, which can be found at
17 Network Utilities Some of the basic tools you will need to know about when working with networking applications are: ping and netstat ping This tools lets you determine if a destination node is reachable. If you re application client application in unable to connect to a server located on another machine over the network You would first try to ping the node to see if the connection was alright. Below is an example of me pinging my router, it shows that all pings were acknowledged, along with the time it took. netstat This utility allows you to view protocol statistics and current TCP/IP connection states. I like to use it with the na option to show all network addresses. If we were you make a call to netstate right after we started the server, here is what one might expect to see. I highlighted the line where the echo server is listening in a passive move on port Notice how the outputs are shows as a IP:Port pairs. If we call EchoClient.exe and then use netstate, we will see a TIME_WAIT state as we discussed earlier. Also there will be another line showing the echo server in the listening state (shown by the 2 yellow markers).
18 Server Socket Code // Module: EchoServer.cpp // Author: Rajinder Yadav // Date: Sept 5, 2007 // #include <winsock2.h> #include <iostream> #include <process.h> #include <stdio.h> #include <tchar.h> #include <windows.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) // Initialize WinSock2.2 DLL // low word = major, highword = minor WSADATA wsadata = 0; WORD wver = MAKEWORD(2,2); int nret = WSAStartup( wver, &wsadata ); if( nret == SOCKET_ERROR ) // WSAGetLastError() cout << "Failed to init Winsock library" << endl; return -1; cout << "Starting server" << endl; // name a socket WORD WSAEvent = 0; WORD WSAErr = 0; // open a socket // // for the server we do not want to specify a network address // we should always use INADDR_ANY to allow the protocal stack // to assign a local IP address SOCKET hsock = 0; hsock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); if( hsock == INVALID_SOCKET ) cout << "Invalid socket, failed to create socket" << endl; return -1;
19 // name socket sockaddr_in salisten = 0; salisten.sin_family = PF_INET; salisten.sin_port = htons( ); salisten.sin_addr.s_addr = htonl( INADDR_ANY ); // bind socket's name nret = bind( hsock, (sockaddr*)&salisten, sizeof(sockaddr) ); if( nret == SOCKET_ERROR ) cout << "Failed to bind socket" << endl; //shutdown( hsock ); closesocket( hsock ); return -1; while( true ) cout << "Listening for connections" << endl; // listen nret = listen( hsock, 5 ); // connection backlog queue set to 10 if( nret == SOCKET_ERROR ) int nerr = WSAGetLastError(); if( nerr == WSAECONNREFUSED ) cout << "Failed to listen, connection refused" << endl; else cout << "Call to listen failed" << endl; closesocket( hsock ); return -1; // connect sockaddr_in saclient = 0; int nsalen = sizeof( sockaddr ); SOCKET hclient = accept( hsock, (sockaddr*)&saclient, &nsalen ); if( hclient == INVALID_SOCKET ) cout << "Invalid client socket, connection failed" << endl; closesocket( hsock ); return -1; cout << "Connection estabilished" << endl;
20 // process data char wzrec[512] = 0; int nleft = 512; int ipos = 0; int ndata = 0; do ndata = recv( hclient, &wzrec[ipos], nleft, 0 ); if( ndata == SOCKET_ERROR ) cout << "Error receiving data" << endl; memset( &wzrec, 0, sizeof( wzrec ) ); break; nleft -= ndata; ipos += ndata; while( nleft > 0 ); cout << "Data Recieved: " << wzrec << endl; // echo data back to client ipos = 0; nleft = 512; do ndata = send( hclient, &wzrec[ipos], nleft, 0 ); if( ndata == SOCKET_ERROR ) cout << "Error sending data" << endl; break; nleft -= ndata; ipos += ndata; while( nleft > 0 ); // close client connection closesocket( hclient ); hclient = 0; // perform a lowercase comparison if( _stricmp( wzrec, "!shutdown" ) == 0 ) break; // clear data buffer memset( &wzrec, 0, sizeof( wzrec ) ); // loop cout << "Shutting down the server" << endl;
21 // close server socket nret = closesocket( hsock ); hsock = 0; if( nret == SOCKET_ERROR ) cout << "Error failed to close socket" << endl; // Release WinSock DLL nret = WSACleanup(); if( nret == SOCKET_ERROR ) cout << "Error cleaning up Winsock Library" << endl; return -1; cout << "Server is offline" << endl; return 0;
22 Client Socket Code // Module: EchoClient.cpp // Author: Rajinder Yadav // Date: Sept 5, 2007 // #include <winsock2.h> #include <iostream> #include <stdio.h> #include <tchar.h> #include <windows.h> using namespace std; int main(int argc, char* argv[]) // Initialize WinSock2.2 DLL // low word = major, highword = minor WSADATA wsadata = 0; WORD wver = MAKEWORD(2,2); int nret = WSAStartup( wver, &wsadata ); if( nret == SOCKET_ERROR ) cout << "Failed to init Winsock library" << endl; return -1; cout << "Opening connection to server" << endl; WORD WSAEvent = 0; WORD WSAErr = 0; SOCKET hserver = 0; // open a socket // // for the server we do not want to specify a network address // we should always use INADDR_ANY to allow the protocal stack // to assign a local IP address hserver = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); if( hserver == INVALID_SOCKET ) cout << "Invalid socket, failed to create socket" << endl; return -1; // name a socket sockaddr_in saserver = 0; saserver.sin_family = PF_INET; saserver.sin_port = htons( ); saserver.sin_addr.s_addr = inet_addr( " " );
23 // connect nret = connect( hserver, (sockaddr*)&saserver, sizeof( sockaddr ) ); if( nret == SOCKET_ERROR ) cout << "Connection to server failed" << endl; closesocket( hserver ); return -1; cout << "Connected to server" << endl; cout << "Sending data to server" << endl; // process data char wzrec[1024] = "Hello from client!!!"; int nleft = 512; int ipos = 0; int ndata = 0; if( argc == 2 ) // copy input string from command argument strcpy_s( wzrec, 1024, argv[1] ); do ndata = send( hserver, &wzrec[ipos], nleft, 0 ); if( ndata == SOCKET_ERROR ) cout << "Error sending data" << endl; break; nleft -= ndata; ipos += ndata; while( nleft > 0 ); // clear data buffer memset( &wzrec, 0, sizeof( wzrec ) ); nleft = 512; ipos = 0; do ndata = recv( hserver, &wzrec[ipos], nleft, 0 ); if( ndata == SOCKET_ERROR ) cout << "Error receiving data" << endl; break; nleft -= ndata; ipos += ndata; while( nleft > 0 ); cout << "Data Echoed: " << wzrec << endl; cout << "Closing connection" << endl;
24 // shutdown socket nret = shutdown( hserver, SD_BOTH ); if( nret == SOCKET_ERROR ) // WSAGetLastError() cout << "Error trying to perform shutdown on socket" << endl; return -1; // close server socket nret = closesocket( hserver ); hserver = 0; if( nret == SOCKET_ERROR ) cout << "Error failed to close socket" << endl; // Release WinSock DLL nret = WSACleanup(); if( nret == SOCKET_ERROR ) cout << "Error cleaning up Winsock Library" << endl; return -1; cout << "Data sent successfully" << endl; return 0;
Socket Programming. Request. Reply. Figure 1. Client-Server paradigm
Socket Programming 1. Introduction In the classic client-server model, the client sends out requests to the server, and the server does some processing with the request(s) received, and returns a reply;
SOCKETS. Sockets. COMP476 Networked Computer Systems. Socket Functions. Sequence of Socket Calls
Sockets SOCKETS Socket functions provide an application programmer interface (API) to send and receive data over a network. COMP476 Networked Computer Systems Socket Functions Sequence of Socket Calls SOCKETS API, PART I
I. Clients and Servers Today s Lecture THE SOCKETS API, PART I Internet Protocols CSC / ECE 573 Fall, 2005 N. C. State University II. III. IV. The Sockets API Data Structures and Conversion Functions Using
Introduction to Socket programming using C
Introduction to Socket programming using C Goal: learn how to build client/server application that communicate using sockets Vinay Narasimhamurthy S0677790@sms.ed.ac.uk CLIENT SERVER MODEL Sockets are
ELEN 602: Computer Communications and Networking. Socket Programming Basics
1 ELEN 602: Computer Communications and Networking Socket Programming Basics A. Introduction In the classic client-server model, the client sends out requests to the server, and the server does some processing
Application Architecture
A Course on Internetworking & Network-based Applications CS 6/75995 Internet-based Applications & Systems Design Kent State University Dept. of Science LECT-2 LECT-02, S-1 2 Application Architecture Today
Introduction to Network Programming using C/C++
Introduction to Network Programming using C/C++ 2007 Jegadish. D 1 Target Audience Prior knowledge of C programming is expected The lecture is for a beginner in network programming Sample code shown are
Implementing Network Software
Implementing Network Software Outline Sockets Example Process Models Message Buffers Spring 2007 CSE 30264 1 Sockets Application Programming Interface (API) Socket interface socket : point where an application/IP Fundamentals. OSI Seven Layer Model & Seminar Outline
OSI Seven Layer Model & Seminar Outline TCP/IP Fundamentals This seminar will present TCP/IP communications starting from Layer 2 up to Layer 4 (TCP/IP applications cover Layers 5-7) IP Addresses Data
NS3 Lab 1 TCP/IP Network Programming in C
NS3 Lab 1 TCP/IP Network Programming in C Dr Colin Perkins School of Computing Science University of Glasgow 13/14 January 2015 Introduction The laboratory exercises
Elementary TCP Sockets
Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens Networks: TCP/IP Socket Calls 1 IPv4 Socket Address Structure Internet socket address structure is named sockaddr_in
INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens
INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens Read: Chapters 1,2, 3, 4 Communications Client Example: Ex: TCP/IP Server Telnet client on local machine to Telnet server on
TCP/IP Tutorial. Transmission Control Protocol Internet Protocol
TCP/IP Tutorial Transmission Control Protocol Internet Protocol 1 TCP/IP & OSI In OSI reference model terminology -the TCP/IP protocol suite covers the network and transport layers. TCP/IP can be used
TCP/IP and OSI model. TCP/IP Protocol (2) B.2
TCP/IP Protocol TCP/IP Transmission Control Protocol/Internetworking Protocol (TCP/IP) standard for the Internet five layers = physical = data link = network = transport = application B.1 TCP/IP and OSI
Unix Network Programming
Introduction to Computer Networks Polly Huang EE NTU phuang@cc.ee.ntu.edu.tw Unix Network Programming The socket struct and data handling System calls Based on Beej's Guide
Daytime Client/Server. CIS-3152, Spring 2014 Peter C. Chapin
Daytime Client/Server CIS-3152, Spring 2014 Peter C. Chapin Addresses IP Addresses are assigned to interfaces A machine with multiple interfaces gets multiple addresses. Interfaces can be physical or virtual.
TCP/IP Concepts Review. Ed Crowley
TCP/IP Concepts Review Ed Crowley 1 Objectives At the end of this unit, you will be able to: Describe the TCP/IP protocol stack For each level, explain roles and vulnerabilities Explain basic IP addressing
Lab 4: Socket Programming: netcat part
Lab 4: Socket Programming: netcat part Overview The goal of this lab is to familiarize yourself with application level programming with sockets, specifically stream or TCP sockets, by implementing a client/server
Internet Protocol (IP)
TCP/IP CIS 218/238 Internet Protocol (IP) The Internet Protocol (IP) is responsible for ensuring that data is transferred between two Intenret hosts based on a 32 bit address. To be ROUTABLE, a protocol
Guide to Network Defense and Countermeasures Third Edition. Chapter 2 TCP/IP
Guide to Network Defense and Countermeasures Third Edition Chapter 2 TCP/IP Objectives Explain the fundamentals of TCP/IP networking Describe IPv4 packet structure and explain packet fragmentation Describe
Packet Sniffing and Spoofing Lab
SEED Labs Packet Sniffing and Spoofing Lab 1 Packet Sniffing and Spoofing Lab Copyright c 2014 Wenliang Du, Syracuse University. The development of this document is/was funded by the following grants from
Chapter 8 TCP/IP. Chapter Figures
Chapter 8 TCP/IP Chapter Figures Application Application TCP UDP ICMP IP ARP RARP Network interface Figure 8. HTTP Request Header contains source & destination port numbers TCP header Header contains source
8.2 The Internet Protocol
TCP/IP Protocol Suite HTTP SMTP DNS RTP Distributed applications Reliable stream service TCP UDP User datagram service Best-effort connectionless packet transfer Network Interface 1 IP Network Interface
CSE 333 SECTION 6. Networking and sockets
CSE 333 SECTION 6 Networking and sockets Goals for Today Overview of IP addresses Look at the IP address structures in C/C++ Overview of DNS Write your own (short!) program to do the domain name IP address
UNIX. Sockets. mgr inż. Marcin Borkowski
UNIX Sockets Introduction to Sockets Interprocess Communication channel: descriptor based two way communication can connect processes on different machines Three most typical socket types (colloquial names):
Chapter 3. Internet Applications and Network Programming
Chapter 3 Internet Applications and Network Programming 1 Introduction The Internet offers users a rich diversity of services none of the services is part of the underlying communication infrastructure
Transport and Network Layer Protocols Lab TCP/IP
Transport and Network Layer Protocols Lab TCP/IP Name: Date Experiment Performed: Group Members: TCP/IP lab Version 1.3, February 2004-1 - PART I: Internet Protocol (IP) Objective Internet Protocols are
How do I get to?
Networking Primer* *caveat: this is just a brief and incomplete introduction to networking to help students without a networking background learn Network Security. How do I get to? Local
Sockets in C Overview
Overview Header library Constants, data type, data structures, system calls Constants Protocol parameters / sizes, address parameters /sizes, Data structures struct templates for addresses, ports, protocols,
Windows. TCP/IP Sockets
I TCP/IP II Socket Windows Socket 2.1 Windows Sockets? Windows Sockets U.C. Berkeley BSD UNIX Socket Micosoft Windows Berkeley Socket Windows Windows Windows Sockets API Windows Windows Sockets ABI Windows.
Module 6. Internetworking. Version 2 CSE IIT, Kharagpur
Module 6 Internetworking Lesson 2 Internet Protocol (IP) Specific Instructional Objectives At the end of this lesson, the students will be able to: Explain the relationship between TCP/IP and OSI model
Network Programming with Sockets. Process Management in UNIX
Network Programming with Sockets This section is a brief introduction to the basics of networking programming using the BSD Socket interface on the Unix Operating System. Processes in Unix Sockets Stream
Hands On Activities: TCP/IP Network Monitoring and Management
Hands On Activities: TCP/IP Network Monitoring and Management 1. TCP/IP Network Management Tasks TCP/IP network management tasks include Examine your physical and IP network address Traffic monitoring
- TCP and UDP - Transport Layer Protocols
1 Transport Layer Protocols - TCP and UDP - The Transport layer (OSI Layer-4) does not actually transport data, despite its name. Instead, this layer is responsible for the reliable transfer of data, by
BSD Sockets Interface Programmer s Guide
BSD Sockets Interface Programmer s Guide Edition 6 B2355-90136 HP 9000 Networking E0497 Printed in: United States Copyright 1997 Hewlett-Packard Company. Legal Notices The information in this document
IP Addressing A Simplified Tutorial
Application Note IP Addressing A Simplified Tutorial July 2002 COMPAS ID 92962 Avaya Labs 1 All information in this document is subject to change without notice. Although the information is believed to
Overview of TCP/IP. TCP/IP and Internet
Overview of TCP/IP System Administrators and network administrators Why networking - communication Why TCP/IP Provides interoperable communications between all types of hardware and all kinds of operating
Transportation Protocols: UDP, TCP & RTP
Transportation Protocols: UDP, TCP & RTP Transportation Functions UDP (User Datagram Protocol) Port Number to Identify Different Applications Server and Client as well as Port TCP (Transmission Control
Troubleshooting Tools
Troubleshooting Tools An overview of the main tools for verifying network operation from a host Fulvio Risso Mario Baldi Politecnico di Torino (Technical University of Turin) see page 2 Notes n The commands/programs
LAB THREE STATIC ROUTING
LAB THREE STATIC ROUTING In this lab you will work with four different network topologies. The topology for Parts 1-4 is shown in Figure 3.1. These parts address router configuration on Linux PCs and a
Network Programming with Sockets. Anatomy of an Internet Connection
Network Programming with Sockets Anatomy of an Internet Connection Client socket address 128.2.194.242:51213 socket address 208.216.181.15:80 Client Connection socket pair (128.2.194.242:51213, 208.216.181.15:80)
Objectives of Lecture. Network Architecture. Protocols. Contents
Objectives of Lecture Network Architecture Show how network architecture can be understood using a layered approach. Introduce the OSI seven layer reference model. Introduce the concepts of internetworking.
Operating Systems Design 16. Networking: Sockets
Operating Systems Design 16. Networking: Sockets Paul Krzyzanowski pxk@cs.rutgers.edu 1 Sockets IP lets us send data between machines TCP & UDP are transport layer protocols Contain port number to identify
Hands-On Ethical Hacking and Network Defense - Second Edition. Chapter 2 - TCP/IP Concepts Review
Objectives After reading this chapter and completing the exercises, you will be able to: Overview of TCP/IP Describe the TCP/IP protocol stack Explain the basic concepts of IP addressing Explain the binary,
04 Internet Protocol (IP)
SE 4C03 Winter 2007 04 Internet Protocol (IP) William M. Farmer Department of Computing and Software McMaster University 29 January 2007 Internet Protocol (IP) IP provides a connectionless packet | http://docplayer.net/18460010-Client-server-programming-with-tcp-ip-sockets.html | CC-MAIN-2018-09 | refinedweb | 6,615 | 51.07 |
ExternalDNS with AKS & Azure DNS
ExternalDNS with kubelet identity to access to Azure DNS
After deploying a public facing web application on Kubernetes, you need to update DNS records so that traffic can reach the server. ExternalDNS can automate this process during deployment stage of the web application, so there is no need for extra configuration outside of Kubernetes.
This tutorial demonstrates how to setup and configure this on Azure Kubernetes Services (AKS) and Azure DNS zones.
📔 NOTE: This was tested on following below and may not work if versions are significantly different.* Kubernetes API v1.22
* kubectl v1.24
* az v2.36.0
* helm v3.82
* ExternalDNS v0.11.0
Knowledge Requirements
This tutorial requires basic understanding of DNS, managing cloud platforms like Azure, and one’s way around container orchestration with Kubernetes.
Using Azure CLI (
az command) to provision cloud resources, and
kubectl to provision Kubernetes services. This requires using
KUBECONFIG env var to configure access.
Tool requirements
The following tools are needed:
- Azure CLI (
az)
v2.36.0(Python
3.10.4)
- Kubernetes client (
kubectl)
v1.24or higher
- Helm
v3.8.2or higher (optional for the ingress)
All client scripts were tested using using bash
v5.1, (other POSIX shells should work) with Kubernetes
v1.22.6.
Setup
Use these environment variables and adjust as needed:
The
DOMAIN_NAME will need to change to a domain that is under your control. The domain
example.com will be used as an example domain for this tutorial.
Azure DNS zone
If you do not yet have a Azure DNS zone available, you can create one through these steps:
This should output a list similar to this:
ns1-06.azure-dns.com.
ns2-06.azure-dns.net.
ns3-06.azure-dns.org.
ns4-06.azure-dns.info.
The variable
$NS_LIST will be used later in verification stages.
The Kubernetes cluster can deploy containers across a several virtual machines called nodes. These are managed as a set and called a node pool. On Azure, a node pool is implemented as virtual machine scale set (VMSS).
Create Azure Kubernetes Service cluster
You can create the resource group, the Azure Kubernetes Service cluster, as well as local cluster operator access through set by the
KUBECONFIG with the following commands.
Create namespaces
A common practice is to install applications into separate namespaces.
Personally, I like to put cluster-wide platforms such as an ingress controller and ExternalDNS into a
kube-addons namespace, and applications into their own unique namespace.
Whatever namespace you chose, here’s how you can create all the namespaces that are used in this project, with the following commands:
Granting access using the Kubelet identity method
In this method, access to Azure DNS will be granted to the kubelet identity. This is a managed identity that is added to all of the nodes in the node pool. A managed identity is simply a service principal, whose life cycle (creation, renewal, destruction) is managed on your behalf.
A kubelet identity can be created before the cluster and added with the
--assign-kubelet-identity flag, or created automatically. For this tutorial, the kubelet identity that came with the cluster on creation will be used.
⚠️ WARNING: This access method grants ALL containers running in the node pool to access the Azure DNS zone, not just the ExternalDNS container. This is suitable for disposable test environments. This is not recommended for production systems.
ExternalDNS Secret
Create and deploy a configuration that tells ExternalDNS to use the kubelet identity.
This configuration simply tells ExternalDNS to use the kubelet identity, or the managed identity that comes with the cluster’s node pool..
The variable
$AZ_DNS_RESOURCE_GROUP needs to be changed to the DNS resource group, for example:
my-dns-group. should peek at the logs to see the health and success of the ExternalDNS deployment.
POD_NAME=$(kubectl get pods \
--selector "app.kubernetes.io/name=external-dns" \
--namespace ${EXTERNALDNS_NS:-"default"} --output name)kubectl logs $POD_NAME --namespace ${EXTERNALDNS_NS:-"default"}
If things are not working, you will see something like:
time="2022-05-26T04:57:34Z" level=error msg="dns.ZonesClient#ListByResourceGroup: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code=\"AuthorizationFailed\" Message=\"The client '7af5b0ee-5c59-4285-b8b1-47ee6ee65aee' with object id '7af5b0ee-5c59-4285-b8b1-47ee6ee65aee' does not have authorization to perform action 'Microsoft.Network/dnsZones/read' over scope '/subscriptions/11122233-1112-1112-1112-111222333111/resourceGroups/my-dns-group/providers/Microsoft.Network' or the scope is invalid. If access was recently granted, please refresh your credentials.\""
When things are working, you should see something like this:
time="2022-05-26T05:10:07Z" level=info msg="Instantiating new Kubernetes client"
time="2022-05-26T05:10:07Z" level=info msg="Using inCluster-config based on serviceaccount-token"
time="2022-05-26T05:10:07Z" level=info msg="Created Kubernetes client"
time="2022-05-26T05:10:07Z" level=info msg="Using managed identity extension to retrieve access token for Azure API."
time="2022-05-26T05:10:07Z" level=info msg="Resolving to system assigned identity."
Verify with a service object
When using a service as an endpoint for your web application, you can have ExternalDNS update DNS records so that users can reach the endpoint. ExternalDNS will scan for annotations in the service object. Here’s how you can set DNS records using a service object. Azure DNS zone
Check if the records were updated in the zone:
az network dns record-set a list \
--resource-group ${AZ_DNS_RESOURCE_GROUP} \
--zone-name ${DOMAIN_NAME} \
--query "[?fqdn=='nginx.$DOMAIN_NAME.']" \
--output yaml
This should show something like:
Service: nginx.$DOMAIN_NAME
dig +short nginx.$DOMAIN_NAME
Service: test with curl
Use curl to get a response using the FQDN:
curl nginx.$DOMAIN_NAME
This should show something like:
Verify with an ingress object
An ingress controller is a reverse-proxy load balancer that will route traffic to your services based on the FQDN (fully qualified domain name) value you set for the
host name key. ExternalDNS monitors ingress changes, and will fetch the host name, and update corresponding DNS records.
⚠️ NOTE: This tutorial creates two endpoints for the same web server for demonstration purposes. This is unnecessary, as one endpoint will do, so if you are using an ingress resource, you can change the type of the service to
ClusterIP.
Ingress manifest
Save the following below as
ingress.yaml:
Change
$DOMAIN_NAME to a domain, such as
example.com
After a minute, check to see if the ingress controller has a public IP address.
kubectl get service ingress-nginx-controller \
--namespace ${INGRESSNGINX_NS:-"default"}
This should show something like:
Deploy the ingress Azure DNS zone
Check if the records were updated in the zone:
az network dns record-set a list \
--resource-group ${AZ_DNS_RESOURCE_GROUP} \
--zone-name ${DOMAIN_NAME} \
--query "[?fqdn=='server.$DOMAIN_NAME.']" \
--output yaml
This should show something like:
Ingress: server.$DOMAIN_NAME
dig +short server.$DOMAIN_NAME
Ingress: test with curl
Use
curl to get a response using the FQDN:
curl server.$DOMAIN_NAME
This should show something like:
Cleaning up
The cluster and resources created from Kubernetes can be destroyed with:
az aks delete \
--resource-group ${AZ_AKS_RESOURCE_GROUP} \
--name ${AZ_AKS_CLUSTER_NAME}
The zone can be removed with:
az network dns zone delete \
--resource-group ${AZ_DNS_RESOURCE_GROUP} \
--name ${DOMAIN_NAME}
The resource groups can be deleted with:
az group delete --name ${AZ_DNS_RESOURCE_GROUP}
az group delete --name ${AZ_AKS_RESOURCE_GROUP}
Resources
These are resources I came across in making this article.
Azure Documentation
- What are managed identities for Azure resources?
- Use managed identities in Azure Kubernetes Service
- Best practices for authentication and authorization in Azure Kubernetes Service (AKS)
- Service principals with Azure Kubernetes Service (AKS)
ExternalDNS
The original documentation only covered using static credentials and partially documented managed identities (previously called managed service identities). I recently updated this to fully document managed identities and add AAD Pod Identity.
- Setting up ExternalDNS for Services on Azure (ExternalDNS project)
Conclusion
The goal of all of this fun stuff is to show ExternalDNS on AKS with Azure DNS, and walk through using
az and
kubectl tools to set all this up.
A common practice on Azure is to segregate resources like DNS into another resource group, and workloads (application containers running on a cluster) into another resource group.
The method to use kubelet identity, the default managed identity that is assigned to the worker nodes on AKS, is really only suitable when all containers on the cluster need the same level of access. A common use case for this is when using a private container registry like ACR (Azure Container Registry), and the containers need read access to pull down containers.
Alternatives creating a service principal and secrets file, but this is not recommended either as you have to securely deliver the secret, rotate the secret, and audit it when access, and also manage the service principal manually as well. Better solutions are the AAD Pod Identity service, and more recently in beta Workload Identity, which would allow a KSA (Kubernetes service account) to masquerade as a service principal on Azure to access resources. | https://joachim8675309.medium.com/externaldns-with-aks-azure-dns-941a1804dc88?source=user_profile---------6---------------------------- | CC-MAIN-2022-33 | refinedweb | 1,495 | 53.81 |
#include <ldap.h>
The
ldap_parse_vlv_control
is used to decode the information returned from a search
operation that used a VLV (virtual list view)control. It
takes a null terminated array of LDAPControl structures,
usually obtained by a call to the
ldap_parse_resultfunction, a
target_pos which points to the
list index of the target entry. If this parameter is NULL,
the target position is not returned. The index returned is an
approximation of the position of the target entry. It is not
guaranteed to be exact. The parameter
list_countp points to the
server's estimate of the size of the list. If this parameter
is NULL, the size is not returned.
contextp is a pointer to the
address of a berval structure that contains a
server-generated context identifier if server returns one. If
server does not return a context identifier, the server
returns a NULL in this parameter. If this parameter is set to
NULL, the context identifier is not returned. You should use
this returned context in the next call to create a VLV
control. When the berval structure is no longer needed, you
should free the memory by calling the ber_bvfree function.e
errcodep is an output
parameter, which points to the result code returned by the
server. If this parameter is NULL, the result code is not
returned.
See ldap.h for a list of possible return codes.
OpenLDAP Software is developed and maintained by The OpenLDAP Project <>. OpenLDAP Software is derived from University of Michigan LDAP 3.3 Release. | http://manpages.courier-mta.org/htmlman3/ldap_parse_vlv_control.3.html | CC-MAIN-2017-22 | refinedweb | 252 | 56.86 |
What will we cover?
In this tutorial we will calculate and visualize the MACD for a stock price.
Step 1: Retrieve stock prices into a DataFrame (Pandas)
Let’s get started. You can get the CSV file from here or get your own from Yahoo! Finance.
import pandas as pd import matplotlib.pyplot as plt %matplotlib notebook data = pd.read_csv("AAPL.csv", index_col=0, parse_dates=True)
Step 2: Calculate the MACD indicator with Pandas DataFrame
First we want to calcite the MACD.
The calculation (12-26-9 MACD (default)) is defined as follows.
- MACD=12-Period EMA − 26-Period EMA
- Singal line 9-Perioed EMA of MACD
Where EMA is the Exponential Moving Average we learned about in the last lesson.
exp1 = data['Close'].ewm(span=12, adjust=False).mean()exp2 = data['Close'].ewm(span=26, adjust=False).mean()data['MACD'] = exp1 - exp2data['Signal line'] = data['MACD'].ewm(span=9, adjust=False).mean()
Now that was simple, right?
Step 3: Visualize the MACD with matplotlib
To visualize it you can use the following with Matplotlib.
fig, ax = plt.subplots() data[['MACD', 'Signal line']].plot(ax=ax) data['Close'].plot(ax=ax, alpha=0.25, secondary_y=True)
Resulting in an output similar to this one.
Next Steps?
Want to learn more?
This is part of the FREE online course on my page. No signup required and 2 hours of free video content with code and Jupyter Notebooks available on GitHub.
Follow the link and read more. | https://www.learnpythonwithrune.org/calucate-macd-with-pandas-dataframes/ | CC-MAIN-2021-25 | refinedweb | 245 | 60.92 |
07 November 2012 10:16 [Source: ICIS news]
(releads and adds detail)
SINGAPORE (ICIS)--President Barack Obama has won a second term in the White House, defeating Republican challenger Mitt Romney.
Obama secured the 270 votes in the electoral college required to win the election.
In his victory speech. Obama congratulated Romney on “a hard-fought campaign”.
“I also look forward to sitting down with Governor Romney to talk about where we can work together to move this country forward,” he added.
Democrats kept their majority in the Senate, while Republicans remained in control of the House.
Obama secured 303 electoral votes against Romney’s 206, with ?xml:namespace>
A very strong turnout was reported on Tuesday with voters waiting two and three hours in key swing states to cast their ballots.
As voting began President Obama and Romney were almost evenly matched in nationwide polls, each showing 49% support among likely voters.
Voters were also deciding contests for all 435 seats in the US House of Representatives and about a third of the 100 Senate seats.
As many as 135m Americans were expected to vote, about 65% of the nation’s estimated 205m eligible voters.
Broadly speaking,
Joe Kamal | http://www.icis.com/Articles/2012/11/07/9611634/obama-beats-romney-to-win-second-term-as-us-president.html | CC-MAIN-2014-35 | refinedweb | 200 | 63.49 |
Our final result asserts that if the om-space is rich enough then the full first-order language of order-of-magnitude distance comparisons is decidable. Specifically, if the collection of orders of magnitude is dense and unbounded above, then there is a decision algorithm for first-order sentences over the formula, ``od(W,X) << od(Y,Z)'' that runs in time O(4n (n!)2 s) where n is the number of variables in the sentence and s is the length of the sentence.
The basic reason for this is the following: As we have observed in corollary 4, a cluster tree T determines the truth value of all constraints of the form ``od(a,b) << od(c,d)'' where a,b,c,d are symbols in the tree. That is, any two instantiations of T in any two om-spaces agree on any such constraint. If we further require that the om-spaces are dense and unbounded, then a much stronger statement holds: Any two instantiations of T over such om-spaces agree on any first-order formula free in the symbols of T over the relation ``od(W,X) << od(Y,Z)''. Hence, it suffices to check the truth of a sentence over all possible cluster trees on the variables in the sentence. Since there are only finitely many cluster trees over a fixed set of variables (taking into account only the relative order of the labels and not their numeric values), this is a decidable procedure.
Let L be the first-order language with equality with no constant or function symbols, and the single predicate symbol ``much_closer(a,b,c,d)''. It is easily shown that L is as expressive as the language with the function symbol ``od'' and the relation symbol <<.
Definition 7: An om-space O with orders of magnitude D is dense if it satisfies the following axiom:
If D is the collection of orders of magnitude in the hyperreal line, then both of these are satisfied. In axiom [A.9], if 0 << d1 << d3, choose d2 =sqrt (d1 d3), the geometric mean. If 0 = d1 << d3, choose d2 = d3 d where d << 1. In axiom [A.10] choose d2 = d1 / d where 0 < d << 1.
Definition 8: Let T be a cluster tree. Let l0=0, l1, l2 ... lkbe the distinct labels in T in ascending order. An extending label for T is either (a) li for some i; (b) lk+1 (note that lk is the label of the root); (c) (li-1 + li)/2 for some i between 1 and k.
Note that if T has k distinct non-zero labels, then there are 2k+2 different extending labels for T.
Definition 9: Let T be a cluster tree. Let x be a symbol not in T. The cluster tree T' extends T with x if T' is formed from T by applying one of the following operations (a single application of a single operation).
Note that if T is a tree of n symbols and at most n-1 internal nodes then
Hence, there are less than 4n2 different extensions of T by x. (This is almost certainly an overestimate by at least a factor of 2, but the final algorithm is so entirely impractical that it is not worthwhile being more precise.)
Definition 10: Let T be a cluster tree, and let p be a formula of L open in the variables of T. T satisfies p if.
function decide(T : cluster tree; p : formula) return boolean convert p to an equivalent form in which the only logical symbols in p are not, and, exists, = (equals) and variable names, and the only non-logical symbol is the predicate ``much_closer''. case p has form X=Y: return (distance(X,Y,T) = 0); p has form ``much_closer(W,X,Y,Z)'': return distance(W,X,T) < distance(Y,Z,T)); p has form not q: return not(decide(T,q)) p has form q and r: return(decide(T,q) and decide(T,r)) p has form existsX a; if for some extension T' of T by X, decide(T',a) = true then return true else return false endif endcase end decide
function distance(X,Y : symbol; T : cluster tree) return integer N := the common ancestor of X and Y in T; return(N.label) end distance
The proof of theorem 4 is given in the appendix.
Running time: As we have remarked above, for a tree T of size k there are at most 4k2 extensions of T to be considered. The total number of cluster trees considered is therefore bounded by the product from k=1 to n of 4k2, which is 4n (n!)2. It is easily verified that the logical operators other than quantifiers add at most a factor of s where s is the length of the sentence. Hence the running time is bounded by O(4n (n!)2 s).
A key lemma, of interest in itself, states the following:.
That is, either p is true for all instantiations of T or for none. The proof is given in the appendix.
It should be observed that the above conditions on O in lemma 28 are necessary, and). Let p be the formula ``exists X od(V,W) << od(W,X)'', free in V and W. Then the valuation { U -> d, V -> 0, W -> 1} satisfies T but not p, whereas the valuation { U -> d2, V -> 2 d2, W -> d} satisfies both T and p. | http://cs.nyu.edu/faculty/davise/om-dist/node11.html | CC-MAIN-2015-18 | refinedweb | 919 | 67.59 |
Opened 6 years ago
Closed 3 years ago
#15995 closed Bug (duplicate)
Problems in ModelForm._post_clean
Description
Hi,
I have a model with the following field:
author = models.ForeignKey(User, on_delete=models.PROTECT)
The related modelform sets this field to required = False
This field should obviously pass form validation in the admin since required will be False! But then in _post_clean of the modelform it tries to construct the instance:
which immediately fails cause author can't be None:
Oddly enough, the code later on collects the fields for model validation: exclude = self._get_validation_exclusions(). This code would add author to the ignore list:
So model validation would be happyily exclude my field from validation, but it already fails in construct_instance. I think _post_clean should use the calculated exclude list instead of opts.exclude for the construct_instance call
Attachments (2)
Change History (8)
Changed 6 years ago by
Changed 6 years ago by
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
The idea makes sense. It would make the form validation slightly more tolerant, but that's not significantly backwards incompatible.
comment:3 Changed 6 years ago by
Hmm, my suggested solution won't work out. It works in my case, but if someone supplies real data it won't get set :( On the other way I fail to find an easy way around it *gg*
comment:4 Changed 5 years ago by
Personally I think that using "construct_instance" function inside form's _post_clean method is not good idea.
Maybe it should me method? - If it would be a method it will be easy to change the way of instance construction.
Everybody who is unhappy with it will have opportunity to change it easily.
Here's my idea (should be part of django.forms.models.BaseModelForm class)
{{
def _construct_instance(self):
opts = self._meta
return django.forms.models.construct_instance(self, self.instance, fields=opts.fields, exclude=opts.exclude)
def _post_clean(self):
self.instance = self._construct_instance()
# ... the rest of _post_clean method
}}
Attached models.py and admin.py. My endgoal was to be able to set the author later on, without making the field nullable, If pass the excludes from _get_validation_excludes into construct_instance everything works… | https://code.djangoproject.com/ticket/15995 | CC-MAIN-2016-50 | refinedweb | 367 | 54.63 |
Set difference of two dataframe in pandas is carried out in roundabout way using drop_duplicates and concat function. It will become clear when we explain it with an example.
Set difference of two dataframe in pandas Python:
Set difference of two dataframes in pandas can be achieved in roundabout way using drop_duplicates and concat function. Let’s see with an example. First let’s create two data frames.
import pandas as pd import numpy as np #Create a DataFrame df1 = { 'Subject':['semester1','semester2','semester3','semester4','semester1', 'semester2','semester3'], 'Score':[62,47,55,74,31,77,85]} df2 = { 'Subject':['semester1','semester2','semester3','semester4'], 'Score':[90,47,85,12]} df1 = pd.DataFrame(df1,columns=['Subject','Score']) df2 = pd.DataFrame(df2,columns=['Subject','Score']) print(df1) print(df2)
df1 will be
df2 will be
Set Difference of two dataframes in pandas python:
concat() function along with drop duplicates in pandas can be used to create the set difference of two dataframe as shown below.
Set difference of df2 over df1, something like df2.set_diff(df1) is shown below
set_diff_df = pd.concat([df2, df1, df1]).drop_duplicates(keep=False) print(set_diff_df)
so the set differenced dataframe will be (data in df2 but not in df1)
| http://www.datasciencemadesimple.com/set-difference-two-dataframe-pandas-python-2/ | CC-MAIN-2018-51 | refinedweb | 200 | 66.64 |
:confused: I am writing a java algorithm to find the factorial of a number (for example the factorial of 5 is 5*4*3*2*1 or 120), I know I can use recursion but I am already have a code that uses such a style and would like to develop another piece of code that does not. The code below involves user input. The code's objective is to take a user input, which is a positive into its scanner and run it through the for loop. The for loop takes the user's variable multiplies it to 1 the first time then takes that results and multiplies that result with the second run and so and so fourth until the user's variable reaches 1. However, the result when run on eclipse is nothing, it terminates after inputting any number and does not give the specified error if I type in a negative number. There is no output at all. Can someone please suggest a solution for this problem?
Code Java:
import java.util.Scanner; public class factorial { private Scanner factint; public void calfact() { int x; factint = new Scanner(System.in); System.out.println("Enter a positive number you would like to take the factorial of"); for(x= factint.nextInt(); x ==1 ;) { if(x < 0) System.err.println("Error: Invalid Declaration for Input Variable"); int newresult = 1; newresult= newresult * x; System.out.println(newresult); } } public static void main(String[] args) { factorial fobj = new factorial(); fobj.calfact(); } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/34526-whats-wrong-my-code-printingthethread.html | CC-MAIN-2016-36 | refinedweb | 248 | 54.02 |
swarm robotics platform"
# =
# = docs
#illic, Slovak,
# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
OUTPUT_LANGUAGE = English
# if your file system
#Sharp, makes penalty.
# If the system has enough physical memory increasing the cache will improve the
# performance by keeping more symbols in memory. Note that the value works on
# a logarithmic scale so increasing the size by one will roughly = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file namespaces FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
# will list include files with double quotes in the documentation
# rather than with sharp brackets.
FORCE_LOCAL_INCLUDES = NO
#
SORT_BRIEF_DOCS = NO
#.
SORT_MEMBERS_CTORS_1ST =
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper type resolution of all parameters of a function it will reject a
# match between the prototype and the implementation of a member function even if there is only one candidate or it is obvious which candidate to choose by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
# will still accept a match between prototype and implementation in such cases.
STRICT_PROTO_MATCHING = macro consists of for it to appear in
# the documentation. If the initializer consists of more lines than specified
# here it will be hidden. Use a value of 0 to hide initializers completely.
# The appearance of the initializer of individual variables and macros
# The WARN_NO_PARAMDOC option can be enabled file system feature) are excluded
# from the input.
EXCLUDE_SYMLINKS = NO
# or if
# non of the patterns match the file name, INPUT_FILTER is applied.
FILTER_PATTERNS =
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will be used to filter the input files when producing source
# files to browse (i.e. when SOURCE_BROWSER is set to YES).
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
# and it is also possible to disable source filtering for a specific pattern
# using *.ext= (so without naming a filter). This option only has effect when
# FILTER_SOURCE_FILES is enabled.
FILTER_SOURCE_PATTERNS =
#
# then for each documented function all documented
# functions referencing it will be listed.
REFERENCED_BY_RELATION = NO
# If the REFERENCES_RELATION tag is set to YES
# then for each documented function all documented entities
# called/used by that function will be listed.
REFERENCES_RELATION = NO
# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
# link to the source code.
# Otherwise they will link to the documentation. =
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
# Doxygen will adjust the colors in the stylesheet and background images
# according to this color. Hue is specified as an angle on a colorwheel,
# see for more information.
# For instance the value 0 represents red, 60 is yellow, 120 is green,
# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
# The allowed range is 0 to 359.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
# the colors in the HTML output. For a value of 0 the output will use
# grayscales only. A value of 255 will produce the most vivid colors.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
# the luminance component of the colors in the HTML output. Values below
# 100 gradually make the output lighter, whereas values above 100 make
# the output darker. The value divided by 100 is the actual gamma applied,
# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
# and 100 does not change the gamma.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting
# this to NO can help when comparing the output of multiple runs.
HTML_TIMESTAMP = YES
# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
# files or namespaces will be aligned in HTML using tables. If set to
# NO a bullet list will be used.
HTML_ALIGN_MEMBERS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded. For this to work a browser that supports
# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
HTML_DYNAMIC_SECTIONS = NO
# If the GENERATE_DOCSET tag is set to YES, additional index files
# will be generated that can be used as input for Apple's Xcode 3
# integrated development environment, introduced with OSX 10.5 (Leopard).
# To create a documentation set, doxygen will generate a Makefile in the
# HTML output directory. Running make will produce the docset in that
# directory and running "make install" will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
# it at startup.
# See
# for more information.
GENERATE_DOCSET = NO
# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
# feed. A documentation feed provides an umbrella under which multiple
# documentation sets from a single provider (such as a company or product suite)
# can be grouped.
DOCSET_FEEDNAME = "Doxygen generated docs"
# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
# should uniquely identify the documentation set bundle. This should be a
# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
# will append .docset to the name.
DOCSET_BUNDLE_ID = org.doxygen.Project
# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES, additional index files
# will be generated that can be used as input for tools like the
# Microsoft HTML help workshop to generate a compiled CHM_INDEX_ENCODING
# is used to encode HtmlHelp index (hhk), content (hhc) and project file
# content.
CHM_INDEX_ENCODING =
#
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
# that can be used as input for Qt's qhelpgenerator to generate a
# Qt Compressed Help (.qch) of the generated HTML documentation.
GENERATE_QHP = NO
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
# be used to specify the file name of the resulting .qch file.
# The path specified is relative to the HTML output folder.
QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating
# Qt Help Project output. For more information please see
#
QHP_NAMESPACE = org.doxygen.Project
# =
# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
# be used to specify the location of Qt's qhelpgenerator.
# If non-empty doxygen will try to run qhelpgenerator on the generated
# .qhp file.
QHG_LOCATION =
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
# will be generated, which together with the HTML files, form an Eclipse help
# plugin. To install this plugin and make it available under the help contents
# menu in Eclipse, the contents of the directory containing the HTML and XML
# files needs to be copied into the plugins directory of eclipse. The name of
# the directory within the plugins directory should be the same as
# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
# the help appears.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have
# this name.
ECLIPSE_DOC_ID = org.doxygen.Project
# [0,1..20])
# that doxygen will group on one line in the generated HTML documentation.
# Note that a value of 0 will completely suppress the enum values from appearing in the overview section.
ENUM_VALUES_PER_LINE = 4
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information.
# If the tag value is set to YES, a side panel will be generated
# containing a tree-like index structure (just like the one that
# is generated for HTML Help). For this to work a browser that supports
# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
# Windows users are probably better off using the HTML help feature. EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
# links to external symbols imported via tag files in a separate window.
EXT_LINKS_IN_WINDOW = NO
# Use this tag to change the font size of Latex formulas included
# as images in the HTML documentation. The default is 10. Note that
# when you change the font size after a successful doxygen run you need
# to manually remove any form_*.png images from the HTML output directory
# to force them to be regenerated.
FORMULA_FONTSIZE = 10
# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are
# not supported properly for IE 6.0, but are supported on all modern browsers.
# Note that when changing this option you need to delete any form_*.png files
# in the HTML output before the changes have effect.
FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
# (see) which uses client side Javascript for the
# rendering instead of using prerendered bitmaps. Use this if you do not
# have LaTeX installed or if you want to formulas look prettier in the HTML
# output. When enabled you also need to install MathJax separately and
# configure the path to it using the MATHJAX_RELPATH option.
USE_MATHJAX = NO
# When MathJax is enabled you need to specify the location relative to the
# HTML output directory using the MATHJAX_RELPATH option. The destination
# directory should contain the MathJax.js script. For instance, if the mathjax
# directory is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the mathjax.org site, so you can quickly see the result without installing
# MathJax, but it is strongly recommended to install a local copy of MathJax
# before deployment.
MATHJAX_RELPATH =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box
# for the HTML output. The underlying search engine uses javascript
# and DHTML and should work on any modern browser. Note that when using
# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
# (GENERATE_DOCSET) there is already a search function so this one should
# typically be disabled. For large projects the javascript based search engine
# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
SEARCHENGINE = YES
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a
#.
# Note that when enabling USE_PDFLATEX this option is only used for
# generating bitmaps for formulas in the HTML output, but not in the
# Makefile that is written to the output directory., letter, legal and
# executive. If left blank a4wide will be used.
PAPER_TYPE = a4
# = YES
#
# If LATEX_SOURCE_CODE is set to YES then doxygen will include
# source code with syntax highlighting in the LaTeX output.
# Note that which sources are shown also depends on other settings
# such as SOURCE_BROWSER.
LATEX_SOURCE_CODE =
# By default doxygen will write a font called Helvetica to the output
# directory and reference it in all dot files that doxygen generates.
# When you want a differently looking font you can specify the font name
# using DOT_FONTNAME. You need to make sure dot is able to find the font,
# which can be done by putting it in a standard location or by setting the
# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
# containing the font.
DOT_FONTNAME = Helvetica
# =
# options
#.
# MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the
# \mscfile command).
MSCFILE_DIRS =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
# nodes that will be shown in the graph. If the number of nodes in a graph
# becomes larger than this value, doxygen will truncate the graph, which is
#
# | http://roboticsclub.org/redmine/projects/scoutos/repository/revisions/ad0e9d483cfaadfcf48bc820652c410076c7340e/entry/scout/Doxyfile | CC-MAIN-2014-15 | refinedweb | 1,984 | 54.22 |
Version 5.4 of Laravel is now officially released! This release has many new features, and improvements and here is quick video going over some of the highlights:
Laravel Dusk
Laravel Dusk is an end-to-end browser testing tool for JavaScript enabled applications. It aims to provide the right way to do page interaction tests, so you can use Dusk for things like click buttons/links, forms, as well as drag and drop!
Dusk utilizes the ChromeDriver and the Facebook Php-webdriver for tests. It can work with any Selenium browser, but comes with ChromeDriver by default which will save you from installing a JDK or Selenium.
Dusk is very easy to use without setting up Selenium and starting the server every time.
Laravel Mix
Laravel Mix is the next generation of Elixir. It is built with webpack, instead of Gulp. It was renamed because of the significant changes.
Unless you customized your Elixir setup, moving to Mix shouldn’t be a problem and Laracasts has a video covering this updated tool.
Blade Components and Slots
Components and Slots are designed to give you even more flexibility in your Blade templates. As an example, imagine you have an include template that is used for showing an alert:
// alert.blade.php <div class="alert"> {{ $slot }} </div>
Then, in your template file you can include it like this:
@component('inc.alert') This is the alert message here. @endcomponent
Markdown Emails
Laravel 5.3 introduced two new features around email, Mailables and Notifications which allow you to send the same message through email, SMS, and other channels.
Building on top of these improvements, Laravel 5.4 includes a brand new Markdown system for creating email templates.
Under the hood, this feature implements the Parsedown parser with its companion, Markdown Extra so you can use tables.
@component('mail:message') # Thank You Thank you for purchasing from our store. @component('mail::button', ['url' => $actionUrl, 'color' => $color]) {{ $actionText }} @endcomponent @endcomponent
Automatic Facades
You can now use any class as a Facade on the fly. Here is an example:
namespace App; class Zonda { public function zurf() { return ‘Zurfing’; } }
Then, in your routes or controller:
use Facades\ { App\Zonda }; Route::get('/', function () { return Zonda::zurf(); });
Route Improvements
Another new feature is the ability to use fluent syntax to define a named route or a middleware:
Route::name('profile')->get('user/{id}/profile', function ($id) { // some closure action... }); Route::name('users.index')->middleware('auth')->get('users', function () { // some closure action... }); Route::middleware('auth')->prefix('api')->group(function () { // register some routes... }); Route::middleware('auth')->resource('photo', 'PhotoController');
The route caching layer also received improvements which will allow route matching on very large applications to see a significant enhancement.
Higher Order Messaging for Collections
The best way of showcasing this new feature is through code samples. Pretend you have a collection, and you want to perform an operation on each of the items:
$invoices->each(function($invoice) { $invoice->pay(); });
Can now become:
$invoices->each->pay();
More New Features
Some other changes and improvements include the following:
- New
retryhelper
- New
array_wraphelper
- Added a default 503 error page
- Switched to the
::classnotation through the core.
- Added names to password reset routes
- Support for PhpRedis
- Added IPv4 and IPv6 validators
date_formatvalidation is now more precise
Upgrading to Laravel 5.4
The official docs include a full upgrade guide, and there are some of the changes you should be aware of.
Laravel Tinker is now a stand-alone package, and installation is simple. Require the package and include the service provider:
composer require laravel/tinker
When that finishes, add the service provider to your config/app.php file:
Laravel\Tinker\TinkerServiceProvider
Your existing tests that utilize browser kit will either need to be migrated to Laravel Dusk or include the older package:
composer require laravel/browser-kit-testing --dev
To get the latest version modify your
composer.json file and change the
laravel/framework dependency to
5.4.*.
Learning More About Laravel 5.4
Laracasts has a complete series available on all these new features, and the official docs has the upgrade guide as well as the release notes. | https://laravel-news.com/laravel-5-4 | CC-MAIN-2021-10 | refinedweb | 685 | 53.41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.