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
Big data is the rage, distribution is the rage, and so to is the growth of streaming data. The faster a company is, the better. Such speed requires, no demands, solid matrix performance. Worse yet, big data is inherently sparse and testing and implementation of new algorithms requires sparse matrices (CSR,CSC, COO; the like). Sadly, Java is not up to the task. Let’s revisit some facts. Java is faster than Python at its core. Many tasks require looping over data in ways numpy or scipy simply do not support. A recent benchmark on Python3 v. Java highlights this. Worse, Python2 and Python3 use the global interpreter lock (GIL) making attempts at speed through concurrency often slower than single threading and forcing developers to use the dreaded multiprocessing (large clunky programs using only as many processes as cores). Still, multiprogramming and other modern operating systems concepts are helping Python achieve better albeit still quite slow speeds. That said, Numpy and Scipy are the opposite of any of these things. They require the slower Cython but are written in C, performing blazingly fast, and leave all Java matrix libraries in the dust. In fact, in attempting to implement some basic machine learning tasks, I found myself not just writing things like text tiling which I fully expected to do but also starting down the path of creating a full fledged sparse matrix library with hashing library. The following is the sad state of my Matrix tests. The Libraries The following libraries were used in the test: The Cosines Test An intensive test of a common use case is the calculation of the dot product (a dot b, a * b.t). Taking this result and dividing by norm(a)*norm(b) yields the cosine of pheta. This simple test includes multiplication, transposing, and mapping division across all active values. The Machine and Test Specs The following machine specifications held: - CPU : Core i3 2.33 ghz - RAM : 8 GB (upgraded on laptop) - Environment: Eclipse - Test: Cosine Analysis - Languages: Scala and Python(scipy and numpy only) - Iterations: 32 - Alloted Memory: 7gb either with x64 Python3 or -Xmx7g - Average: Strict non-smoothed average The Scipy/Numpy Gold Standard Not many open source libraries can claim the speed and power of the almighty Scipy and Numpy. The library can handle sparse matrices with m*n well over 1,000,000. More telling, it is fast. The calculation of the cosines is an extremely common practice in NLP and is a valuable similarity metric in most circumstances. import scipy.sparse import scipy.sparse.linalg mat = sparse.rand(1000,50000,0.15) print scipy.sparse.dot(mat,mat.t)/pow(linalg.norm(mat),2) Result : 5.13 seconds The Results The following resulted from each library: - Breeze : Crashes with Out of Memory Error (developer notified) [mat * mat.t] - UJMP : 128.73 seconds - MTJ : 285.13 seconds - La4j : 420.2 seconds - BidMach : Crashes (sprand(1000,50000,0.15)) Here is what the author of Breeze had to say. Rest assured, Numpy has been stable for over a decade now with constant improvements. Conclusion Java libraries are slow and seemingly undeserving of praise. Perhaps, due to the potential benefits of not necessarily distributing every calculation, they are not production grade. Promising libraries such as Nd4J/Nd4s still do not have a sparse matrix library and have claimed for some time to have one in the works. The alternatives are to use Python or program millions of lines of C code. While I find C fun, it is not a fast language to implement. Perhaps, for now Python will do. After all, PySpark is a little over 6 months old.
https://dadruid5.com/tag/breeze/
CC-MAIN-2019-30
refinedweb
610
66.23
John E. Howland Department of Computer Science Trinity University 715 Stadium Drive San Antonio, Texas 78212-7200 Voice: (210) 999-7364 Web: October 24, 2005 Subject Areas: Computer Graphics. Keywords: 2D Viewing, 3D Viewing, modeling, linear algebra. Computer graphics deals with the problem of image synthesis. Given a model (usually mathematically based) the problem of computer graphics is to produce realistic image data which may be viewed on a graphics display device. The process of producing the image data from the scene model is called rendering. That images are synthesized from mathematical models implies that computer graphics is a mathematcally based subject. Image synthesis involves the physics of light, properties of materials, etc. Animated imagery involves simulation theory, finite element analysis, kinematics, sampling theory and other mathmatically based fields. The study of computer graphics necessarily involves the study of many areas of mathematics. In the following sections we give an elementary view of some of these topics. Students who have an interest in computer graphics should study as much mathematics as possible. The reverse problem of starting with image data and recovering information is called image processing. We now consider the problem of representing 2D graphics images which may be drawn as a sequence of connected line segments. Such images may be represented as a matrix of 2D points . The J programming notation [Hui 2001] is used to describe the viewing transformations and data object representations. square rectangle. Three dimensional objects may be modeled by a collection of points , representing the vertices of the object, together with additional information which describes which vertices are used to form planes, surface properties such as color and texture, etc. Such an image model is often refered to as a polygonal model. For example, the vertices of a cube of size 2, centered at the origin of three-dimensional space can be generated by: [ cube =: _1 ^ #: i. 8 1 1 1 1 1 _1 1 _1 1 1 _1 _1 _1 1 1 _1 1 _1 _1 _1 1 _1 _1 _1 The top plane of this cube are describe by vertices 0 1 5 4. 0 1 5 4 { cube 1 1 1 1 1 _1 _1 1 _1 _1 1 1 The five other planes in this cube are similarly described. For example, the left face is given by 4 5 7 6 { cube _1 1 1 _1 1 _1 _1 _1 _1 _1 _1 1 The 2D transformations of Section 5.1 may be extended to the 3D case as follows. Using homogeneous coordinates we extend the Equations 8 to three dimensional space: Consider the 4 by 4 matrix We see that the Equations 14 may be written as the matrix equation We define the J monad translate which is applied to a list of three translate values to produce the translation matrix. translate =: monad def '((=/ ~ i. 3) , y. ) ,. 0 0 0 1' translate 1 1 1 1 0 0 0 0 1 0 0 0 0 1 0 1 1 1 1 Hence, (cube ,. 1) mp 4 3 {. translate 1 1 1 2 2 2 2 2 0 2 0 2 2 0 0 0 2 2 0 2 0 0 0 2 0 0 0 translates the cube to the positive sector of 3-space. Next we extend the Equations 3 to three dimensional space as the follows: Consider the 4 by 4 matrix We write the Equations 16 as: We define the J monad scale which is applied to a list of three scale factors to produce the scaling matrix. scale =: monad def '4 4 $ (0 { y.), 0 0 0 0 , (1 { y.), 0 0 0 0 , (2 { y.), 0 0 0 0 1' We can scale cube to size 4 by: (cube ,. 1) mp 4 3 {. scale 2 2 2 2 2 2 2 2 _2 2 _2 2 2 _2 _2 _2 2 2 _2 2 _2 _2 _2 2 _2 _2 _2 Extending the Equations 1 to three dimensional space is a bit more complex as we need to describe three rotation matrices which rotate points about the , , and axes respectively. The axis rotation equations are: Consider the 4 by 4 matrix We write Equations 18 as: We define the J monad z_rotate which is applied to an angle to produce the axis rotation matrix. z_rotate =: monad def '(1 1 _1 1 * 2 1 1 2 o. (o. y.) % 180) (0 0;0 1;1 0;1 1) } =/ ~ i. 4' z_rotate 90 0 1 0 0 _1 0 0 0 0 0 1 0 0 0 0 1 We can rotate cube 90 degrees about the axis by (cube ,. 1) mp 4 3 {. z_rotate 90 _1 1 1 _1 1 _1 1 1 1 1 1 _1 _1 _1 1 _1 _1 _1 1 _1 1 1 _1 _1 We can also see that rotating the top face of cube produces the left face of cube described in Section 9 (0 1 5 4 { cube ,. 1) mp 4 3 {. z_rotate 90 _1 1 1 _1 1 _1 _1 _1 _1 _1 _1 1 The axis rotation equations are: Consider the 4 by 4 matrix We write Equations 20 as: We define the J monad y_rotate which is applied to an angle to produce the axis rotation matrix. y_rotate =: monad def '(1 _1 1 1 * 2 1 1 2 o. (o. y.) % 180) (0 0;0 2;2 0;2 2) } =/ ~ i. 4' y_rotate 90 0 0 _1 0 0 1 0 0 1 0 0 0 0 0 0 1 We can rotate cube 90 degrees about the axis by (cube ,. 1) mp 4 3 {. y_rotate 90 1 1 _1 _1 1 _1 1 _1 _1 _1 _1 _1 1 1 1 _1 1 1 1 _1 1 _1 _1 1 The axis rotation equations are: Consider the 4 by 4 matrix We write Equations 22 as: We define the J monad x_rotate which is applied to an angle to produce the axis rotation matrix. x_rotate =: monad def '(1 1 _1 1 * 2 1 1 2 o. (o. y.) % 180) (1 1;1 2;2 1;2 2) } =/ ~ i. 4' x_rotate 90 1 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 1 We can rotate cube 90 degrees about the axis by (cube ,. 1) mp 4 3 {. x_rotate 90 1 _1 1 1 1 1 1 _1 _1 1 1 _1 _1 _1 1 _1 1 1 _1 _1 _1 _1 1 _1 The initial viewing parameters are choosen so as to be able to give an unrestricted view of the scene. In practice, however, some simplifications are most often used as default viewing parameters. The projection plane, shown in Figure 10, has the view plane defined by a point on the plane (VRP) and the view plane normal (VPN). The VPN gives the orientation of the view plane and is often (but not required to be) parallel to the view direction. The VPN is used to define a left-handed coordinate system screen coordinate system. The VUP vector defines a direction which is not parallel to VPN and is taken to be the viewer's concept of up. VUP need not (but often is taken to) be perpendicular to VPN. The projection of VUP on the view plane defines the V axis of the screen coordinate system. The U axis of the screen coordinate system is choosen to be perpendicular to both (orthogonal to) V and VPN. These vectors are choosen so as to form a left-handed V, U, VPN 3D coordinate system. The VRP is the origin of the 2D screen coordinate system. However, VRP is not the origin of the left-handed 3D coordinate system we wish to define. Its origin is the location of the eye (COP). The coordinates of COP are defined relative to the VRP using world coordinates. We now have all of the parameters necessary to describe the 3D viewing transformation which maps the world coordinate system into the eye coordinate system. A rectangular region, Figure 11, (viewport) describes the clipping region of the screen coordinate system which is visible to the viewer. This 2 dimensional viewport has sides which are parallel to the V U axis and the location and size of the viewport are given in units of the screen coordinate system using VRP as the origin. The viewport forms a viewing pyramid which gives the visible portion of world coordinate space from COP. All objects outside this pyramid are clipped from the scene. Actually, two additional clipping planes (Near and Far; see Figure 12) which are parallel to the view plane define portions of the seen which are either too close or too far from COP to be seen. The line from the COP through the center of the viewport defines the viewing direction and will be the positive Z axis of the eye coordinate system. A few concepts from elementary linear algebra are useful at this point. Let and be two 3D vectors. The dot product or inner product of and is defined as: Notice that the inner product of two vectors is a real number. The cosine of the acute angle between two vectors and is defined as: where is the length of the vector and is the length of the vector . Hence we may write: Notice that if and are two perpendicular vectors, then the angle between each other is and . Hence, the inner product of two perpendicular vectors is . The length of a vector is defined as . The inner product of with itself yields: or If , then . Given two vectors and , then the sum of and is the vector which is shown in Figure 13. Inner product (dot product) distributes over vector addition. That is, given vectors , , , and a real number , then Suppose is a vector whose length is 1 and is a vector not parallel to . We wish to project to a vector which lies on a plane perpendicular to (see Figure 14). To solve this problem define the vector by the equation: Then, But since is of length one. Hence, and from this it follows that and are perpendicular. Therefore, is a vector that lies on a plane perpendicular to The cross product of two vectors and is the vector: The cross product of two non-parallel vectors is a vector which is perpendicular to both vectors. Hence, the inner product of either or with is zero. The direction of the vector is such that if the fingers of the right hand are curled around in the direction of , then is pointing in the direction of the thumb. Cross product is not commutative. which means that the direction of is the opposite of the direction of . The 3-D viewing pipline is shown in Figure 15. The second step of the pipeline involves transforming the vertices of model objects which are given in world coordinates to the eye coordinate system. This process starts from the initial parameters of , , , and . These vectors are first used to compute the coordinate system as: The next step is to transform the left-handed eye coordinate system defined by , and into the right-handed world coordinate system. This is accomplished by three steps: The matrices required to accomplish this transformation are given next. Since the center of projection, is defined relative to the , the translation matrix is: The rotation matrix is The matrix to change the direction of the z-axis is We can combine the matrices and by computing the matrix product and rename it producing the matrix The final matrix to produce the transformation from world coordinates to eye coordinates is the product of the two matrices . After multiplying world coordinate vertices by the viewing transformation, , and clipping to the truncated viewing pyramid, it is necessary to perform the perspective projection onto the view plane. Given a vertex in the eye coordinate system, , the projected screen coordinates, are computed as: where is the distance from to the view plane. These formulas are easily derived by considering the projection onto the (Figure 16) and planes and noting that from similar triangles The equation for is derived in a similar fashion. In this section we give some C program fragments to illustrate algorithms for computation of the 3D viewing transformation which transforms world coordinates to eye coordinates. typedef double Xform3d[4][4]; typedef struct Point3d /* the 3D homogeneous point */ { double x, y, z, w; } Point3d, *Point3dPtr, **Point3dHdl; typedef struct Graph3dView /* the 3D graphics viewing parameters */ { CWindowPtr wPtr; /* the color graph port */ GrafPtr oldPort; /* the previous graph pointer */ Point3d vrp; /* the view reference point */ Point3d vpn; /* the view plane normal */ Point3d vup; /* the view up direction */ Point3d cop; /* the center of projection (viewpoint) */ Rect viewport; /* the intersection of the viewing pyramid */ double back; /* the z coordinate of the back clipping plane */ double front; /* the z coordinate of the front clipping plane */ double distance; /* the distance of the cop from the view plane */ Xform3d xform; /* the current transformation */ } Graph3dView, *Graph3dViewPtr, **Graph3dViewHdl; /* ______________________________________________________________ scale3d This function returns the 3D scaling matrix given x, y and z scaling factors. */ void scale3d(double sx, double sy, double sz, Xform3d scaleMatrix) { scaleMatrix[0][0] = sx; scaleMatrix[0][1] = 0.0; scaleMatrix[0][2] = 0.0; scaleMatrix[0][3] = 0.0; scaleMatrix[1][0] = 0.0; scaleMatrix[1][1] = sy; scaleMatrix[1][2] = 0.0; scaleMatrix[1][3] = 0.0; scaleMatrix[2][0] = 0.0; scaleMatrix[2][1] = 0.0; scaleMatrix[2][2] = sz; scaleMatrix[2][3] = 0.0; scaleMatrix[3][0] = 0.0; scaleMatrix[3][1] = 0.0; scaleMatrix[3][2] = 0.0; scaleMatrix[3][3] = 1.0; } /* End of scale3d */ /* ______________________________________________________________ translate3d This function returns the 3d translation matrix given x, y and z translation factors. */ void translate3d(double tx, double ty, double tz, Xform3d transMatrix) { transMatrix[0][0] = 1.0; transMatrix[0][1] = 0.0; transMatrix[0][2] = 0.0; transMatrix[0][3] = 0.0; transMatrix[1][0] = 0.0; transMatrix[1][1] = 1.0; transMatrix[1][2] = 0.0; transMatrix[1][3] = 0.0; transMatrix[2][0] = 0.0; transMatrix[2][1] = 0.0; transMatrix[2][2] = 1.0; transMatrix[2][3] = 0.0; transMatrix[3][0] = tx; transMatrix[3][1] = ty; transMatrix[3][2] = tz; transMatrix[3][3] = 1.0; } /* End of translate3d */ /* ______________________________________________________________ identity3d This function returns the 4 by 4 identity matrix. */ void identity3d(Xform3d identity) { identity[0][0] = 1.0; identity[0][1] = 0.0; identity[0][2] = 0.0; identity[0][3] = 0.0; identity[1][0] = 0.0; identity[1][1] = 1.0; identity[1][2] = 0.0; identity[1][3] = 0.0; identity[2][0] = 0.0; identity[2][1] = 0.0; identity[2][2] = 1.0; identity[2][3] = 0.0; identity[3][0] = 0.0; identity[3][1] = 0.0; identity[3][2] = 0.0; identity[3][3] = 1.0; } /* End of identity3d */ /* ______________________________________________________________ rotateX3d This function returns the x axis rotation matrix given an angle in radians. */ void rotateX3d(double theta, Xform3d rotateMatrix) { double sine = sin(theta), cosine = cos(theta); rotateMatrix[0][0] = 1.0; rotateMatrix[0][1] = 0.0; rotateMatrix[0][2] = 0.0; rotateMatrix[0][3] = 0.0; rotateMatrix[1][0] = 0.0; rotateMatrix[1][1] = cosine; rotateMatrix[1][2] = sine; rotateMatrix[1][3] = 0.0; rotateMatrix[2][0] = 0.0; rotateMatrix[2][1] = -sine;X3d */ /* ______________________________________________________________ rotateY3d This function returns the y axis rotation matrix given an angle in radians. */ void rotateY3d(double theta, Xform3d rotateMatrix) { double sine = sin(theta), cosine = cos(theta); rotateMatrix[0][0] = cosine; rotateMatrix[0][1] = 0.0; rotateMatrix[0][2] = sine; rotateMatrix[0][3] = 0.0; rotateMatrix[1][0] = 0.0; rotateMatrix[1][1] = 1.0; rotateMatrix[1][2] = 0.0; rotateMatrix[1][3] = 0.0; rotateMatrix[2][0] = -sine; rotateMatrix[2][1] = 0.0;Y3d */ /* ______________________________________________________________ rotateZ3d This function returns the z axis rotation matrix given an angle in radians. */ void rotateZ3d(double theta, Xform3d rotateMatrix) { double sine = sin(theta), cosine = cos(theta); rotateMatrix[0][0] = cosine; rotateMatrix[0][1] = sine; rotateMatrix[0][2] = 0.0; rotateMatrix[0][3] = 0.0; rotateMatrix[1][0] = -sine; rotateMatrix[1][1] = cosine; rotateMatrix[1][2] = 0.0; rotateMatrix[1][3] = 0.0; rotateMatrix[2][0] = 0.0; rotateMatrix[2][1] = 0.0; rotateMatrix[2][2] = 1.0; rotateMatrix[2][3] = 0.0; rotateMatrix[3][0] = 0.0; rotateMatrix[3][1] = 0.0; rotateMatrix[3][2] = 0.0; rotateMatrix[3][3] = 1.0; } /* End of rotateZ3d */ /* ______________________________________________________________ shearZ3d This function produces the Z shearing transformation which maps an arbitrary line through the origin and passing through the non-zero point (x, y, z) into the Z axis without changing the z values of points on the line. */ void shearZ3d(double x, double y, double z, Xform3d zshear) { zshear[0][0] = 1.0; zshear[0][1] = 0.0; zshear[0][2] = 0.0; zshear[0][3] = 0.0; zshear[1][0] = 0.0; zshear[1][1] = 1.0; zshear[1][2] = 0.0; zshear[1][3] = 0.0; zshear[2][0] = -x / z; zshear[2][1] = -y / z; zshear[2][2] = 1.0; zshear[2][3] = 0.0; zshear[3][0] = 0.0; zshear[3][1] = 0.0; zshear[3][2] = 0.0; zshear[3][3] = 1.0; } /* End of shearZ3d */ /* ______________________________________________________________ copy3dXform This function copies the src 4 by 4 transformation matrix to the dst 4 by 4 matrix. It is assumed that the storage for the matrices is allocated in the calling routine. */ void copy3dXform(Xform3d dst, Xform3d src) { register int i, j; for(i = 0; i < 4; i++) for(j = 0; j < 4; j++) dst[i][j] = src[i][j]; } /* End of copy3dXform */ /* ______________________________________________________________ mult3dXform This function multiplies two 4 by 4 transformation matricies producing a resulting 4 by 4 transformation. For efficiency, we assume that the last column of the Xform3d is 0 0 0 1 (36 multiplications and 27 additions) */ void mult3dXform(Xform3d xform1, Xform3d xform2, Xform3d resultxform) { Xform3d result; /* row 0 (9 * and 6 +) */ result[0][0] = xform1[0][0] * xform2[0][0] + xform1[0][1] * xform2[1][0] + xform1[0][2] * xform2[2][0]; result[0][1] = xform1[0][0] * xform2[0][1] + xform1[0][1] * xform2[1][1] + xform1[0][2] * xform2[2][1]; result[0][2] = xform1[0][0] * xform2[0][2] + xform1[0][1] * xform2[1][2] + xform1[0][2] * xform2[2][2]; result[0][3] = 0.0; /* row 1 (9 * and 6 +) */ result[1][0] = xform1[1][0] * xform2[0][0] + xform1[1][1] * xform2[1][0] + xform1[1][2] * xform2[2][0]; result[1][1] = xform1[1][0] * xform2[0][1] + xform1[1][1] * xform2[1][1] + xform1[1][2] * xform2[2][1]; result[1][2] = xform1[1][0] * xform2[0][2] + xform1[1][1] * xform2[1][2] + xform1[1][2] * xform2[2][2]; result[1][3] = 0.0; /* row 2 (9 * and 6 +) */ result[2][0] = xform1[2][0] * xform2[0][0] + xform1[2][1] * xform2[1][0] + xform1[2][2] * xform2[2][0]; result[2][1] = xform1[2][0] * xform2[0][1] + xform1[2][1] * xform2[1][1] + xform1[2][2] * xform2[2][1]; result[2][2] = xform1[2][0] * xform2[0][2] + xform1[2][1] * xform2[1][2] + xform1[2][2] * xform2[2][2]; result[2][3] = 0.0; /* row 3 ( 9 * and 9 +) */ result[3][0] = xform1[3][0] * xform2[0][0] + xform1[3][1] * xform2[1][0] + xform1[3][2] * xform2[2][0] + xform2[3][0]; result[3][1] = xform1[3][0] * xform2[0][1] + xform1[3][1] * xform2[1][1] + xform1[3][2] * xform2[2][1] + xform2[3][1]; result[3][2] = xform1[3][0] * xform2[0][2] + xform1[3][1] * xform2[1][2] + xform1[3][2] * xform2[2][2] + xform2[3][2]; result[3][3] = 1.0; /* copy the result */ copy3dXform(resultxform, result); } /* End of mult3dXform */ /* ______________________________________________________________ transform3dObject This function multiplies an n array of Point3d by a 4 by 4 transformation matrix producing a resulting n array of Point3d. We assume that the last column of xform is 0 0 0 1. ( 9n multiplications and 9n additions) */ void transform3dObject(int n, Point3d object[], Xform3d xform, Point3d result[]) { register int i; for(i = 0; i < n; i++) /* each row */ { /* column 0 (3 * and 3 +) */ result[i].x = object[i].x * xform[0][0] + object[i].y * xform[1][0] + object[i].z * xform[2][0] + xform[3][0]; /* column 1 (3 * and 3 +) */ result[i].y = object[i].x * xform[0][1] + object[i].y * xform[1][1] + object[i].z * xform[2][1] + xform[3][1]; /* column 2 (3 * and 3 +) */ result[i].z = object[i].x * xform[0][2] + object[i].y * xform[1][2] + object[i].z * xform[2][2] + xform[3][2]; /* column 3 */ result[i].w = object[i].w; } } /* End of transform3dObject */ /* ______________________________________________________________ copy3dObject This function copies a src n array of Point3d to a dst n array of Point3d. It is assumed that storage for the src and dst arrays is allocated in the calling function. */ void copy3dObject(int n, Point3d dst[], Point3d src[]) { register int i; for(i = 0; i < n; i++) /* each row */ dst[i] = src[i]; } /* End of copy3dObject */ /* ______________________________________________________________ pitch This function multiplies the transform associated with the given graph3dView by an X axis rotation and stores the resulting transformation as the new graph3dView xform. */ void pitch(double theta, Graph3dViewPtr viewPtr) { Xform3d rotX; rotateX3d(theta, rotX); mult3dXform((*viewPtr).xform, rotX, (*viewPtr).xform); } /* End of pitch */ /* ______________________________________________________________ roll This function multiplies the transform associated with the given graph3dView by an Z axis rotation and stores the resulting transformation as the new graph3dView xform. */ void roll(double theta, Graph3dViewPtr viewPtr) { Xform3d rotZ; rotateZ3d(theta, rotZ); mult3dXform((*viewPtr).xform, rotZ, (*viewPtr).xform); } /* End of roll */ /* ______________________________________________________________ yaw This function multiplies the transform associated with the given graph3dView by an Y axis rotation and stores the resulting transformation as the new graph3dView xform. */ void yaw(double theta, Graph3dViewPtr viewPtr) { Xform3d rotY; rotateY3d(theta, rotY); mult3dXform((*viewPtr).xform, rotY, (*viewPtr).xform); } /* End of yaw */ a/* ______________________________________________________________ dotProduct This function computes the dot product (inner product) of two Point3d's. The w component of the homogeneous representation of the 3d points is ignored in this calculation */ double dotProduct(Point3dPtr p1, Point3dPtr p2) { return (*p1).x * (*p2).x + (*p1).y * (*p2).y + (*p1).z * (*p2).z; } /* End of dotProduct */ /* ______________________________________________________________ scalarProduct This function computes the scalar product of a double and a Point3d. The w component of the homogeneous representation of the 3d points is ignored in this calculation. */ void scalarProduct(double a, Point3dPtr p, Point3dPtr result) { (*result).x = a * (*p).x; (*result).y = a * (*p).y; (*result).z = a * (*p).z; } /* End of scalarProduct */ /* ______________________________________________________________ crossProduct This function computes the cross product of two Point3d's. The w component of the homogeneous representation of the 3d points is ignored in this calculation. */ void crossProduct(Point3dPtr p1, Point3dPtr p2, Point3dPtr result) { (*result).x = (*p1).y * (*p2).z - (*p1).z * (*p2).y; (*result).y = (*p1).z * (*p2).x - (*p1).x * (*p2).z; (*result).z = (*p1).x * (*p2).y - (*p1).y * (*p2).x; } /* End of crossProduct */ /* ______________________________________________________________ normalize This function normalizes the Point3d, a pointer to which is passed as an argument. The w component of the homogeneous representation of the 3d point is ignored in this calculation. */ void normalize(Point3dPtr p) { double length = sqrt(dotProduct(p, p)); if(length != 0.0) { (*p).x /= length; (*p).y /= length; (*p).z /= length; } } /* End of normalize */ /* ______________________________________________________________ transform3dPoint This function applies an Xform3d to a Point3d, transforming that Point3d. A pointer to a Point3d is passed. The w component of the homogeneous representation of the 3d point is ignored in this calculation. */ void transform3dPoint(Point3dPtr p, Xform3d xform) { Point3d t = *p; (*p).x = t.x * xform[0][0] + t.y * xform[1][0] + t.z * xform[2][0] + xform[3][0]; (*p).y = t.x * xform[0][1] + t.y * xform[1][1] + t.z * xform[2][1] + xform[3][1]; (*p).z = t.x * xform[0][2] + t.y * xform[1][2] + t.z * xform[2][2] + xform[3][2]; } /* End of transform3dPoint */ /* ______________________________________________________________ subtract3dPoint This function subtracts Point3dPtr p2 from Point3dPtr p1 producing Point3dPtr result. The w component of the homogeneous representation of the 3d point is ignored in this calculation. */ void subtract3dPoint(Point3dPtr p1, Point3dPtr p2, Point3dPtr result) { (*result).x = (*p1).x - (*p2).x; (*result).y = (*p1).y - (*p2).y; (*result).z = (*p1).z - (*p2).z; } /* End of subtract3dPoint */ /* ______________________________________________________________ add3dPoint This function adds Point3dPtr p2 to Point3dPtr p1 producing Point3dPtr result. The w component of the homogeneous representation of the 3d point is ignored in this calculation. */ void add3dPoint(Point3dPtr p1, Point3dPtr p2, Point3dPtr result) { (*result).x = (*p1).x + (*p2).x; (*result).y = (*p1).y + (*p2).y; (*result).z = (*p1).z + (*p2).z; } /* End of add3dPoint */ /* ______________________________________________________________ initGraph3dView This function initializes the 3D graphics viewing structure and makes a full screen drawing window. The Graph3dView is initialized with some default viewing parameters. These parameters (except for the wPtr) may be changed before 3D drawing occurs. */ void initGraph3dView(Graph3dViewPtr viewPtr) { GDHandle mainDevice = GetMainDevice(); Rect mainRect = (**mainDevice).gdRect; short width, height; /* set view reference point to origin */ (*viewPtr).vrp.x = 0.0; (*viewPtr).vrp.y = 0.0; (*viewPtr).vrp.z = 0.0; (*viewPtr).vrp.w = 1.0; /* set view plane normal to z axis */ (*viewPtr).vpn.x = 0.0; (*viewPtr).vpn.y = 0.0; (*viewPtr).vpn.z = 1.0; (*viewPtr).vpn.w = 1.0; /* set view up direction to y axis */ (*viewPtr).vup.x = 0.0; (*viewPtr).vup.y = 1.0; (*viewPtr).vup.z = 0.0; (*viewPtr).vup.w = 1.0; /* set view center of projection (viewpoint) */ (*viewPtr).cop.x = 0.0; (*viewPtr).cop.y = 0.0; (*viewPtr).cop.z = 720.0; (*viewPtr).cop.w = 1.0; /* set view Rect */ width = (mainRect.right - mainRect.left - 5) / 2; height = (mainRect.bottom - mainRect.top - 43) / 2; /* order lower left to upper right */ SetRect(&(*viewPtr).viewport, - width, - height, width, height); /* set back and front Z clipping plane values */ (*viewPtr).back = 1000.0; (*viewPtr).front = 0.0; (*viewPtr).distance = (*viewPtr).cop.z - (*viewPtr).vrp.z; GetPort(&(*viewPtr).oldPort); (*viewPtr).wPtr = makeDrawingWindow((char *)"\p3D Graphics View", mainRect.left + 2, mainRect.top + 40, mainRect.right - 3, mainRect.bottom -3); /* set the transformation to be identity */ identity3d((*viewPtr).xform); } /* End of initGraph3dView */ /* ______________________________________________________________ viewing This function produces the viewing transformation matrix which transforms an abject from world coordinates to eye coordinates.. */ void viewing(Graph3dViewPtr viewPtr, Xform3d *view) { Point3d t, v, u; Xform3d tr, rot; /* project vup on the viewing plane getting the v axis for viewing plane*/ scalarProduct(dotProduct(&((*viewPtr).vpn), &((*viewPtr).vup)), &((*viewPtr).vpn), &t); subtract3dPoint(&((*viewPtr).vup), &t, &v); /* compute the u axis of the viewing plane */ crossProduct(&((*viewPtr).vpn), &v, &u); /* translate the cop + vrp to the origin */ add3dPoint(&((*viewPtr).cop), &((*viewPtr).vrp), &t); translate3d(-t.x, -t.y, -t.z, tr); /* compute the rotation matrix */ identity3d(rot); rot[0][0] = u.x; rot[1][0] = u.y; rot[2][0] = u.z; rot[0][1] = v.x; rot[1][1] = v.y; rot[2][1] = v.z; rot[0][2] = (*viewPtr).vpn.x; rot[1][2] = (*viewPtr).vpn.y; rot[2][2] = (*viewPtr).vpn.z; /* multiply the translation and rotation producing the view transformation */ mult3dXform(tr, rot, *view); } /* End of viewing */
http://www.cs.trinity.edu/~jhowland/cs3353/intro/intro/
CC-MAIN-2013-48
refinedweb
4,532
58.28
PEP 484, mypy, typeshed, pytype, pyre and typing in PyCharm tmp.py:29: error: Incompatible return value type (got "Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]", expected "Callable[..., Awaitable[Any]]")with this gist @graingert @gaborbernat is it worth re-opening again? Got very late the notification for this. I think the feature would be very useful in a post no python 2 world too. It's a matter of fact that type annotations make the code more verbose; so there will be projects who don't want to pay the price of this, or projects you can't modify. In this case, you want to provide the type information as stubs... and for maintaining those stubs would be great if you can use some merge-check tool to validate they're correct against the source. I'm seeing what I think Is a mypy false positive: def mypy_type_issue(foo: List[str], bar: List[str]) -> Tuple[List[str], List[str]]: new_foo: List[str] new_bar: List[str] pairlis = list(zip(foo, bar)) pairlis.sort(key=lambda x: x[0]) new_foo, new_bar = zip(*pairlis) # ******* return new_foo, new_bar The line with the asterisks gives me this error: Incompatible types in assignment (expression has type "Tuple[Any, ...]", variable has type "List[str]"). Is mypy not understanding the * or am I not understanding mypy? Thanks! rebelCoderA quick question: When you create a class in python, and when you create instances of that class, is Pyhton smart enough to have just one copy of most of the functions in that class and just link every class instance to the function when it is needed? Or does it make a copy for each instance? rebelCoder* A quick question: When you create a class in python, and when you create instances of that class, is Python smart enough to have just one copy of most of the functions in that class and just link every class instance to the function when it is needed? Or does it make a copy for each instance? exceptionarg/kwarg (function has multiple args, exception is not in the first 3) -- it returns Dict[str, Any]in the nominal case, though if the inner function raises one of a set of predefined exceptions, it raises the passed in exception. HOWEVER if exceptionis Noneit doesn't raise an exception and returns None-- without rewriting logic is there a way to express this in typing? mypy foo, but it doesn't detect the source files mypy foo/bar/az/sub_project, but then it doesn't pick up the imports between a.py and b.py correctly --namespace-packages mypy --namespace-packages foo/bar/baz/sub_project. I was almost sure I already checked that. Thanks either way! rebelCoderHey smart people. Any idea why overloading __count__method does not work? I have my custom string class and everything else works just fine, but the count method: def __cout__(self, item): return self.seq.count(item) # I call: print(test_seq.count('a')) # Error: print(test_seq.count('a')) AttributeError: 'bio_seq' object has no attribute 'count' one more question, about configuration now. let's assume such configuration: foo +-- bar +-- baz +-- sub_project +-- a.py +-- b.py +-- experiment/ where experiment directory contains experimental code, that I don't want to run mypy against. my mypy config looks like so: [mypy] namespace_packages=True files=foo/bar/baz/sub_project [mypy-foo.bar.baz.sub_project.experiment.*] ignore_errors=True and the errors still show up if I change [mypy-foo.bar.baz.sub_project.experiment.*] -> [mypy-experiment.*] so that config is as follows, the errors within experiment are ignored: [mypy] namespace_packages=True files=foo/bar/baz/sub_project [mypy-experiment.*] ignore_errors=True is that on purpose, that I need to specify the relative path? can I force specifying the full path rather than the relative path? rebelCoder > <@gitter_fulaphex:matrix.org> @matrixbot wouldn't you want to overload count rather than __count__? str = "teststring" print(dir(str)) __count__ is in the list. rebelCoder * Wow! This makes sense. Not fully sure why count is not defined as __count__ ? If you look up: str = "teststring" print(dir(str)) __count__ is in the list. stras the name as it's the name of the builtin type and you don't want to cause confusion for people reading the code. furthermore, I cannot really reproduce the behaviour you posted, I only get 'count'in dir("teststring"). which python version are you using? I tested with 3.7.4 and 2.7.16, none of them show the same behaviour I have some Model classes (which is basically like @dataclass). I want to write a generic class called Schema[T] with the following properties Tcan only be a Model m = FooModel()has fields m.barof type Barand m.bazof type Baz, an object of ms =Schema[FooModel]should have fields ms.barof type Schema[Bar]and ms.bazof type Schema[Baz]. I think I can make it work with dynamic attribute on class Schema(Generic[T]) but that wouldn't auto-complete on IDE. So I'm thinking may be code-gening is the only route although if there is anything which do without code-gen would be excellent . Can someone point me in the right direction. I'm not sure what would I codegen in this case so that the typing-gods are satisfied. I can of course generate a class called class FooModelSchema: \n bar: Schema[Bar] \n baz: Schema[Baz] but how do I make it such that Schema[FooModel] and FooModelSchema are treated similarly.
https://gitter.im/python/typing?at=5e31b666f6945f41ef3a848d
CC-MAIN-2020-16
refinedweb
912
66.13
java version "1.3.0" Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C) Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode) KeyStroke.getKeyStroke(String s) should accept the string returned by KeyStroke.toString(). In particular, if there exists a <code>KeyStroke a</code>, then <code>KeyStroke.getKeyStroke(a.toString)</code> should return. Currently, KeyStroke.toString() does not return a string that matches the documented grammar for KeyStroke.getKeyStroke(String). This makes the KeyStroke class's toString method fairly useless. In my particular project, I would like to be able to use the KeyStroke's toString() method as a serialization mechanism in a properties file. Let's say that I have an application that has user-defined accelerator keys (a.k.a. hotkeys, shortcut keys). I have a Print bean in class org.brianlsmith.PrintBean and I want to store the information for the PrintBean's shortcut key in a property file (actually, a property-backed resource bundle). I need to have a way to convert from a KeyStroke to a String and back, but there is no way to do that short of writing my own parser for KeyStoke.toString()'s format (which is unspecified) or by reimplementing KeyStroke.toString(). Since KeyStroke.toString()'s format is undocumented, there should be no political problems in changing it to match KeyStroke.getKeyStroke(String)'s documented grammer. In the test program below, The output should be: shift F1 shift F1 1st Copy equals original: true shift F1 2nd Copy equals original: true // BEGIN A.java import java.awt.event.KeyEvent; import javax.swing.KeyStroke; public class A { public static void main(String [] args) { KeyStroke original = KeyStroke.getKeyStroke(KeyEvent.VK_F1,KeyEvent.SHIFT_MASK); System.out.println(original); KeyStroke firstCopy = KeyStroke.getKeyStroke(original.toString()); System.out.println(firstCopy); System.out.println("1st Copy equals original: " + (original ==firstCopy)); KeyStroke secondCopy = KeyStroke.getKeyStroke("shift F1"); System.out.println(secondCopy); System.out.println("2nd Copy equals original: " + (original == secondCopy)); } } // END A.java (Review ID: 108792) ====================================================================== Overriding KeyStroke.getString() or providing a correctly-behaving KeyStroke- >String converter is the best way to work around this issue. Also look at using the numeric values for the key code and the shift mask (although this would require some very simple parsing to split the two numbers apart when they are written as a pair of strings). ====================================================================== KeyStroke is currently a swing class, so I'm assigning this rfe to them for evaluation. xxxxx@xxxxx 2000-09-13 This is a reasonable suggestion, and we should consider it for a future release. Any change should apply to both java.awt.AWTKeyStroke and javax.swing.KeyStroke. xxxxx@xxxxx 2001-07-13
http://bugs.sun.com/bugdatabase/view_bug.do%3Fbug_id=4370733
crawl-002
refinedweb
445
60.51
import "cuelang.org/go/internal" Package internal exposes some cue internals to other packages. A better name for this package would be technicaldebt. MaxDepth indicates the maximum evaluation depth. This is there to break cycles in the absence of cycle detection. It is registered in a central place to make it easy to find all spots where cycles are broken in this brute-force manner. TODO(eval): have cycle detection. BaseContext is used as CUEs default context for arbitrary-precision decimals CheckAndForkRuntime checks that value is created using runtime, panicking if it does not, and returns a forked runtime that will discard additional keys. CheckAndForkRuntime checks that value is created using runtime, panicking if it does not, and returns a forked runtime that will discard additional keys. CoreValue returns an *runtime.Index and *adt.Vertex for a cue.Value. It returns nil if value is not a cue.Value. DebugStr prints a syntax node. ErrIncomplete can be used by builtins to signal the evaluation was incomplete. EvalExpr evaluates an expression within an existing struct value. Identifiers only resolve to values defined within the struct. Both value and result are of type cue.Value, but are an interface to prevent cyclic dependencies. TODO: extract interface FromGoType converts an arbitrary Go type to the corresponding CUE value. instance must be of type *cue.Instance. The returned value is a cue.Value, which the caller must cast to. FromGoValue converts an arbitrary Go value to the corresponding CUE value. instance must be of type *cue.Instance. The returned value is a cue.Value, which the caller must cast to. GetRuntime reports the runtime for an Instance or Value. GetRuntime reports the runtime for an Instance or Value. MakeInstance makes a new instance from a value. UnifyBuiltin returns the given Value unified with the given builtin template. func FileComment(f *ast.File) *ast.CommentGroup GenPath reports the directory in which to store generated files. IsEllipsis reports whether the declaration can be represented as an ellipsis. ListEllipsis reports the list type and remaining elements of a list. If we ever relax the usage of ellipsis, this function will likely change. Using this function will ensure keeping correct behavior or causing a compiler failure. func NewComment(isDoc bool, s string) *ast.CommentGroup NewComment creates a new CommentGroup from the given text. Each line is prefixed with "//" and the last newline is removed. Useful for ASTs generated by code other than the CUE parser. ToExpr converts a node to an expression. If it is a file, it will return it as a struct. If is an expression, it will return it as is. Otherwise it panics. ToFile converts an expression to a file. Adjusts the spacing of x when needed. ToStruct gets the non-preamble declarations of a file and puts them in a struct. Attr holds positional information for a single Attr. NewNonExisting creates a non-existing attribute. Flag reports whether an entry with the given name exists at position pos or onwards or an error if the attribute is invalid or if the first pos-1 entries are not defined. Int reports the integer at the given position or an error if the attribute is invalid, the position does not exist, or the value at the given position is not an integer. Lookup searches for an entry of the form key=value from position pos onwards and reports the value if found. It reports an error if the attribute is invalid or if the first pos-1 entries are not defined. String reports the possibly empty string value at the given position or an error the attribute is invalid or if the position does not exist. A Decimal is an arbitrary-precision binary-coded decimal number. Right now Decimal is aliased to apd.Decimal. This may change in the future. Package internal imports 13 packages (graph) and is imported by 39 packages. Updated 2020-09-18. Refresh now. Tools for package owners.
https://godoc.org/cuelang.org/go/internal
CC-MAIN-2020-40
refinedweb
657
60.72
Today. That´s great news! Lots of customers had been asking for this. Awesome!! Thanks Scott. Can't wait for the final release. Jose Guay Great! We are waiting for v1.0. Very excited! Thanks for all of the hard work! This really is great news. We've been working holding off on a CMS project for months waiting for the release. Holy long post Batman! Awesome news.. been waiting for this since your teaser a few weeks back :-) Thanks Scott eagerly waiting for the final release... Great news. Will there be an official release of "Scott Crazy Look"? Scott, Thanks to you and your entire team. Your timing couldn't be more perfect. Just got the go ahead yesterday to use MVC in a new project we're ramping up for right now. Thank Scott for this info. ASP.nET MVC Is the Best Awesome set of improvements! Thanks Scott & ASP.NET MVC team! Kudos for the Act, Arrange, Assert comments included in the Mocking sample. Awesome, grats on the RC release. =) It really looks nice! It's been a very interesting journey from Preview 1 to this RC1. Tonight will be the 7th update of my MVC demo site, but I think I will enjoy it alot this time. Thanks for an excellent job! thanks guys! Congrats Scott, Phil, et al! It's definitely a very impressive set of features over the Beta. Can't wait for the final release! I wish I had been following ASP.NET MVC since it started. I've only been along for the side since Preview 4, but want to say that the development and community interaction (via blogs such as this and many others by MS employees) has been phenomenal and a model I wish all other MS projects followed. Thanks again! Great news... except now I have to update all my example code ;-) shouldersofgiants.co.uk/Blog Impressive release, you and your team has worked hard on this one. One question I have, do you have a strategy to protect against CSRF GET, opposed to POST attacks? Or is your advice to follow HTTP standards and use GET requests exclusively for read-only actions? Scott.. is the RC compatible with Windows Azure out of the box? Congrats to you and your Team!. Also, in a future post, it would good to highlight pros and cons of each technology... Thanks, and keep it up! Fantastic! I think the new enhancements will go along way to getting more developers interested in the MVC Framework. Very good, I had just downloaded beta yesterday so this makes life so much easier now. going to recreate my project now. Great, but new features in a release candidate? Great news but the Beta refuses to uninstall, at least on Windows 7. "There is a problem with this Windows installer package. A program run as part of the setup did not finish as expected." Hey Scott,? Great. Now it means I don't have to go to production with a Beta version. You know what irritates me, ping backs in. Anyone else getting a Error while installing the RC? Error in devend.exe Exeption: Access Violation Breaks at the current line of devenv.exe: retval = (size_t)HeapSize(_crtheap, 0, pblock); Help anyone? Awesome timing - I'm just wrapping up a project I've been building on beta, and really been waiting for RC for stuff like no-codebehind views etc Great Scott. And I saw you using Windows 7 (there is a Send Feedback message on window).. Hi Scott Good news for MVC. By the way any chance we can get on with the talk on the .Net Coffee Break show some time next week? My fellow developers in Ireland are waiting for your talk ;-)) Thanks for your reply Cheers Paschal Whats happened to: 1) UpdateModel - no longer accepts a FormCollection 2) AuthorizationContext - no longer has a Cancel property 3) UrlHelper - no longer accepts a ViewContext Apart from those breaking changes, looks good. Thanks Awesome post and AWESOME news ASP.NET MVC team! <3 to the entire team! Question Guru-Gu: "This will check for the existence of the appropriate tokens, and prevent our HTTP-POST action method from running if they don’t match (reducing the chance of a successful CSRF attack)." So if a site tries to do a CSRF attack (and this check picks this up), what happens? we goto a 404 page with the correct response codes? Can we customise the 'error' page? is it a 500 server error? cheers :) (yes, i could check the code but I thought I should ask so other people will go 'ahh... ohhh. kewl, i get it!'. cheers! Wow, great improvements! T4 templates are a smart way to do scaffolding, this way we will probably see some scaffolding solutions on codeplex. Also the conventions are starting to look nice, just what I was hoping to see in this project. PS. Props for using Moq, it's sooo great! Congratulations to you and your team. Santos You continue to make life better for your developers and inspire us. @Barry, >>>>> Great news. Will there be an official release of "Scott Crazy Look"? :-) - Scott I have a few questions as well... 1) Is this considered a feature-locked release? In other words, will anything change between now and the final release? 2) This is a pretty radical departure from WebForms, but I'd like my team to start understanding it. What's the state of the documentation? Looking forward to digging in! @Josh, >>>>>>> Impressive release, you and your team has worked hard on this one. One question I have, do you have a strategy to protect against CSRF GET, opposed to POST attacks? Or is your advice to follow HTTP standards and use GET requests exclusively for read-only actions? I think for V1 the CSRF support is primarily for POST scenarios. I generally recommend using POST for any destructive or update scenarios. This not only protects against CSRF but also against search engines that follow links on your site. @James, >>>>>>> Scott.. is the RC compatible with Windows Azure out of the box? It should work in Azure - although you'll need to update the web.config to support it. The RC versions works fine on .NET 3.5 and 3.5 SP1 - which is what Azure supports. Lots of great things added! I'm glad to see that Request.IsAjaxRequest was fixed to work with jQuery. Will make updates to BlogSvc.net. Are there any changes to partial or medium trust support? @YVan, >>>>>>>. Scott Hanselman has done a few blog posts on this. Expect to see a lot more guidance/info on enabling these scenarios in the future since they will be super common. >>>>>>> Also, in a future post, it would good to highlight pros and cons of each technology... Yep - we'll definitely do this. One misperception some people have is that WebForms is going away - it definitely isn't. We have a bunch of great new WebForms features coming out this year (including routing integration, better id and viewstate control, and more) that will be very compelling. Thanks, @Troy, >>>>>>>> I'm specifically curious about the part where it says "when the application is running in *localhost* debug mode." Does this refer to the "debug" attribute on the web.config's compilation element? As far as I know the debug attribute may only be set to true or false, but being able to set it to "localhost" would be GREAT (though I'm not sure how that could work technically). Also, any ETA on the source being available on CodePlex? I just sent mail off to the team to find out! @Sam, >>>>>>>> Great news but the Beta refuses to uninstall, at least on Windows 7. "There is a problem with this Windows installer package. A program run as part of the setup did not finish as expected." Can you send me an email with more details on this issue? We can then figure out how to get it working for you. @Maciej, >>>>>>>>>? Any chance you could ask this question on the ASP.NET MVC forums on I will forward your comment along to the team - but I think it might be best to loop you in directly with them on the forums (they monitor the forums pretty closely). @Graham, >>>>> You know what irritates me, ping backs in comments. Yep - they bug me too, but unfortunately I haven't found an easy way to filter this with my blog. I wouldn't be surprised if in the next release we have a config switch that has some options to have it output automatically by the Html.Form() helpers. There are scenarios, though, where you don't want to have it - which is why we were worried about having it always on by default. >>>>>>> Anyone else getting a Error while installing the RC? If you can send me an email (scottgu@microsoft.com) then I can loop you in with the team to figure out what is wrong. @Vitor, >>>>>>>> Great Scott. And I saw you using Windows 7 (there is a Send Feedback message on window). Yep - I've been running Win7 for a little over a week now. Loving it! @Jim, >>>>>>>>. I don't know of anything specific added to the RC to enable this. I'll see if we can up the documentation/guidance on this though. You guys have done an amazing job. RC is just what I needed to get started. Thanks! The dialogs (such as Add Controller or Add View) do not look correct at 120dpi. There are either scrollbars or overlapping fields. Great work done by the whole team :) There's only one problem that I can see with the early release work on the mvc framework, which is that from Preview 1 people have been blogging/writing samples on how to do certain tasks with the framework. So when you're stuck on how to do a certain task and come to a solution only to find that it still has ControllerAction attributes and incorrect method names it's a little confusing to say the least - especially if you're new and still learning. I'm not really sure what can be done about this - certainly not hold back on getting it out there. Looking forward to the big 1.0! Guru ScottGu, Great news. Congrats for the GREAT work. Congrats on the release. I am dreading learning a whole new way of web development and will probably hold off for a while to let common patterns and solutions emerge, but it looks like this is the right way to do it. Is there anything in my proj files that needs to be updated from Beta to RC ? I didn't see anything significant outside of the web.config, and new MSBuild from the readme - however, I wanted to make sure my previously created Beta project would work ok -and if not, what should I add ? Very exciting stuff. Reading the release notes I noticed the following beta migration requirement : Update the <pages> section the Web.config file In the Views folder to match the following example. (The changed elements are in bold.) However in my Views/web.config I have NOTHING in <pages> and I only created the template BRAND NEW last week from the beta. other than that its perfect :) A tweet from scottgal - "Fun fact, ScottGu was up until 5 am this morning writing his MVC RC blog post, if you ever wondered what it takes to be a VP" Hi ScottGu, You are really amazing. Thanks a lot for your community supports. Thanks for RC.. Thanks. WOW! Thanks so much for making this a reality. I have completely enjoyed using Asp.Net MVC from early preview until now. We've had wild success building a powerful and high performance, standards compliant web application with excellent design patterns in place using your bits. Sure, I may have been frustrated at the loss of RenderUserControl but we overcame and the code is cleaner because of it. A huge thanks to all on your team. You fixed it. I didn't think Asp.Net could be cooler than Rails, but ..somehow... you made it happen. cheers Rusty Scott, Congratulations! This is definately has been long awaited. Will the download be available from Web PI (Web Platform Installer) as well? Thanks! Hi Scott, Scott, Thanks! I'm looking forward to feeling passionate again about development using approaches like MVC. Its a great news. Can you arrange for the download of demo project you have illustrated here. Thanks. Hi Scott, I just wanted to thank you and the MVC team. Not just for the framework but for the manner in which the team has delivered it, they've really took listening to the community to a new level. I hope it's felt like as big a success within MS as it has with me and my colleagues and in the forums etc. Paul @Paul, >>>>>> Whats happened to: >>>>>. >>>>>>>> 2) AuthorizationContext - no longer has a Cancel property >>>>>>>> 3) UrlHelper - no longer accepts a ViewContext I'm not 100% sure on the answer to those ones. If you can ask on the MVC forums on the team should be able to help you with those two. @pure.krome, >>>>>>>> So if a site tries to do a CSRF attack (and this check picks this up), what happens? we goto a 404 page with the correct response codes? Can we customise the 'error' page? is it a 500 server error? cheers :) I haven't verified it myself, but my guess is that the attribute throws an exception. You could probably customize the error page displayed using the [HandleError] attribute. Sweet I got only one problem when going throw the scenarios in the this article. When trying to go throw the strongly typed expression for HTML/AJAX Helpers e.g. <%=Html.TextAreaFor(t=>t.Name)%> I go the error 'System.Web.Mvc.HtmlHelper<Forms.Models.Test>' does not contain a definition for 'TextAreaFor' What am I missing? @Stefan, >>>>>>> It appears that Url.RouteUrl(string routeName) returns blank values (for routes that used to work). I was able to circumvent this problem by doing the following: Can you post more details about this issue on the MVC forum at? Or alternatively send me email with a repro (scottgu@microsoft.com). @Jeff, >>>>>> 1) Is this considered a feature-locked release? In other words, will anything change between now and the final release? The feature-set now is pretty locked. There will probably be a few small tweaks, but in general it is just last minute bug fixes now. >>>>>>> 2) This is a pretty radical departure from WebForms, but I'd like my team to start understanding it. What's the state of the documentation? I'm actually working on an ASP.NET MVC book right now, and will be posted it online for free. If you wait another few weeks you'll have an end to end tutorial that covers the "why and how" ASP.NET MVC works and provides a good blue-print that you and your team will be able to use to build applications with it. @Jarrett, >>>>>>>> Are there any changes to partial or medium trust support? ASP.NET MVC supports partial and medium trust scenarios. >>>>>>> The dialogs (such as Add Controller or Add View) do not look correct at 120dpi. There are either scrollbars or overlapping fields. Thanks for this bug report. I just forwarded it onto the team to look at. @Steve, >>>>>>> Is there anything in my proj files that needs to be updated from Beta to RC ? I don't believe anything changes in your project file - it is more the web.config files that need to be updated. @Angus, >>>>>>> Are you aware of the awesome work Rob Conery has been doing with MVC Storefront? Definitely! Rob's work is awesome. :-) @Alex, >>>>>>>>. You should be able to reference a class in an external assembly, except if that assembly is in the GAC. Can you tell us if the assembly you are trying to use is in the GAC? If not, can you share more details (scottgu@microsoft.com) so that we can investigate? @Ferry, >>>>>>>> Will the download be available from Web PI (Web Platform Installer) as well? Thanks! Yes - it will definitely be part of the Web PI once the V1 release ships. I believe we'll also be updating the Web PI to point to the RC release too some point soon. Our goal is to have everything installable via WebPI. @Parag, >>>>>>>>> Can you kindly make it clear for once and all that should i leave all the hopes to work with IronRuby and Asp.Net MVC or i can still keep on dreaming with this. We are planning to support both IronPython and IronRuby with ASP.NET MVC. Unfortunately I don't have an udpdated timeline on when this will be available - but it is definitely on our roadmap. @Allen, >>>>>> I got only one problem when going throw the scenarios in the this article. When trying to go throw the strongly typed expression for HTML/AJAX Helpers e.g. Html.TextAreaFor(t=>t.Name) I got the error System.Web.Mvc.HtmlHelper<Forms.Models.Test> does not contain a definition for TextAreaFor. What am I missing? You'll want to-do two things: 1) Make sure that your project is referencing the MVCFutures assembly (which is a separate download). This is where the TextAreaFor() helper method lives. 2) Make sure you add the Microsoft.Web.Mvc namespace to the <namespaces> within the <pages> section of your web.config file. This will cause the extension method to be automatically imported on all views. Once you do this do a compile, then close and reopen your project. "Views without Code-Behind Files" - this is great news :) Routing has some bugs (like dealing with special characters). Do you plan to release an updated version of System.Web.Routing.dll with the final version of ASP.NET? I have also a couple of bugs with HTTP cache headers. I can't add [OutputCache(Location=OutputCacheLocation.Client, Duration=30000)] to my actions without getting an exception. The partial views are also resetting the Expires header to DateTime.Now. Is that kind of small issues be fixed in next release? Thanks to the team for the RC! Why we don't have the feature of specifying the routing configurations in the web.config file? Excellent post Scott, Congrats! Nice this compiles in vb with option strict on The "Add View" command doesn't seem to work if the Model is a client-side Data Services Proxy class for an Entity-Framework model. For example, Dim proxy As New Proxy.MyService.MyEntities(New Uri("MyDataService.svc/")) Dim viewData = From p In proxy.Partners Select p Return View(viewData) The view that gets generated from this only shows a "PartnerID", even though there are a dozen properties on the Partner object. <fieldset> <legend>Fields</legend> <p> PartnerID: <%= Html.Encode(Model.PartnerID) %> </p> </fieldset> Link to the futures please! (I still disagree that this isn't in the install to be available...just makes it a pain for people to find it) "Make sure that your project is referencing the MVCFutures assembly (which is a separate download). This is where the TextAreaFor() helper method lives." Thanks :) I have a problem with strongly typed expression in Microsoft.Web.Mvc namespace: <%=Html.ActionLink<MvcApplication1.Controllers.HomeController>(c=>c.Index(), "Link") %> is not work more. Method not found "System.String System.Web.Mvc.Html.LinkExtensions.RouteLink(System.Web.Mvc.HtmlHelper, System.String, System.Web.Routing.RouteValueDictionary, System.Web.Routing.RouteValueDictionary)". I found, you delete method public static string RouteLink(this HtmlHelper htmlHelper, string linkText, RouteValueDictionary values, RouteValueDictionary htmlAttributes) in new version. What to do? MVC is greaaat !! too bad i can't use it ? Which version of ASP.NET MVC Framework will be available with .NET 4.0 - v1 or maybe vNext? Very cool - I really like the new File ActionResult Haha... i just laughed when i scrolled through the pictures. This is AMAZING. Scott and team, GREAT JOB! I am looking forward to taking asp.net mvc to my next project. This is just lovely, this feels like an early birthday present ( birthday tomorrow ). So, THANKS! :) How can one configure or set up Spring 2.0 with ASP.NET MVC 1.0 Release Candidate How can one setup or configure Spring.Net 2.0 with ASP.NET MVC 1.0 Release Candidate or ASP.NET MVC Are you using Linq to SQL in this example? Does this mean I can comfortably continue using Linq to SQL in my development?! Hullo Been playing with this today --- Good job guys. I dont know weather this is a bug or by design but when I try to create my own filter attribute (derived from the ActionFilterAttribute) , I get an error about the constructor not taking 0 args. On envistagation I noticed that the constructor is now protected ---- not visible to my application. Note: The same code was working in the beta release. Can I use it with Mono? Loving the RC! One problem for me though is that the "Add View" dialog isn't picking up my models. It picks up lots of classes including some from my project, referenced projects and referenced assemblies, just not my models. Do I need to do anything special to get that bit working? Scott, what are the asp.net mvc dependencies? i.e. does this require Ent Lib?. Is this not a major problem? I keep my controllers in a separate assembly. The 'goto controller' and 'goto view' features do not work. Is there a work around for this ? Very impressive! Thanks Scott & ASP.NET MVC team! Scott, may I have a vssettings export of your "Fonts and Colors"? Please? I really like that color scheme. The colors rock! ;-) We have developed an application, which is already in production, making its way to the hottest spot (sad I won't e there to see it) in the enterprise. I can't imagine what will happen in the community once it's officially released... Thank you! Hi Scott, I have a action filter that compresses the data and for some reason this line of code throws a null reference exception HttpResponseBase response = filterContext.HttpContext.Response But if I change it to HttpResponseBase response = filterContext.Controller.ControllerContext.HttpContext.Response; It works fine. This was working in Beta but broke in RC1. Any idea? Any plan on releasing MVC Web Site template? View data class in the Add View dialog does not show my linq2sql classes in this build but it worked in beta1. Let's hope Mono guys will make support as release approaches. MVC looks too good for many kinds of apps to continue write them in classic ASP.NET, and windows server os + hardware is too costly for my hobby projects.? I realize I could probably grow my own, especially because of open t4 implementation of the current scaffold as you pointed out (which looks awesome btw), but this seems like something that is so rudimentary to the framework that it needs to be included. plan on supporting Website project type? I kept exceptions thrown when trying to use the new 'add view' Whatever happened to BinaryStreamResult that was part of the MVC Futures assembly? I have tried to add a veiw from the Context menu of the controller. it does added the ASPX pages and it compiles with no error but during execution point i got parse error. Parser Error Message: Could not load type 'System.Web.Mvc.ViewPage<IEnumerable<OriScribe2.Models.Customer>>'. Scott from above : ">>>>>." Sorry Scott - this is very confusing what you are saying: "I'd recommend not specifying a ValueProvider within your Controller action and have it update using the default Request.Forms collection." I'm not, I just call updatemodel with my object and my formcollection. What is a ValueProvider ? Confused... I just went and re-tested that UpdateModel Error in RC1 is now "The given key was not present in the dictionary." var address = new Address(); UpdateModel(address, new [] { "Street1", "Street2", "City", "State", "PostalCode" }); All those names are in the form. This worked perfectly in Beta and is now failing all over the place. I don't see how this is any different than your sample above either. I don't pass a 'FormCollection' - didn't do it in Beta either, didn't need to. I specified exactly what I want to get updated from the form as per previous posts on UpdateModel. Not sure why this has changed ? Except I do this all over the place... :( It seems that a MVC view page only has .aspx file, does everyone have idea on how to add .aspx.cs and .aspx.designer.cs files under a MVC view page? Thanks I should add, my form is mapping to several objects - is the binder unable to handle that senario. I confirmed, all my form variables are named correctly and in the request.form collection. That error is a mystery. Great news!!! Thanks. What is the roadmap for MVC framework? All this is happening in a single project, not useful for many professional websites. Can we use separate projects for controllers and models while using MVC context menus? KK Custom Model Binders (classes which implement IModelBinder) seem to cause problems with Html Helpers (Html.TextBox). Not sure if this is a bug or I am missing something. If you have a model class which is populated via a custom Model Binder then used in a strongly typed view and you render an input via the Html.TextBox helper you get a nullreference exception in the System.web.mvc.htmlhelper.getmodelstatevalue method. In the beta version i have tried to use the GridView with MVC but i found it bit complex and not flexible like normal gridview.I want to know in this release client gridview is improved or not ? Scott, I resolved my UpdateModel problems, etc... It was a base class validator that was causing the issue, not the fantastic MVC setup :) I do look forward to hearing what you say about those of us that split our controller/model/web into different assemblies. Hopefully the new GUI stuff will be able to handle that Great news!! We just start a great project and we take the ASP.NET MVC as a base framework for front end. I have downloaded and tried this release, One question, Can we add code behind for view page? I think you have mentioned that we can add server control to view page and handle page load event to bind server control such as listview. listView1.DataSource = ViewData("Products") listView1.DataBind() When I hit "Show All Files" , it doesn't show up code behind file (such as Index.aspx.vb) Akaka I have been working on mvc beta framework. It is really good. But still the html controllers have limitation; like one of the controller "html Grid" is having lot of limitations. Are you looking to improve html controls in this mvc framework release? Very nice work from the asp.net MVC team! Hoping to see version 1 and documentation released soon... Upload's view part: <% using (Html.BeginForm()) { %> <h2>Select file</h2> <input type="file" name="uploadFile" /> <input type="submit" value="Upload" /> <% } %> My controller: public class FilesController : Controller { public ActionResult Upload(HttpPostedFileBase uploadFile) { return View(); } } After http post uploadFile is still null. Does anyone make it work? I have to add the full namespace in the inherits attribute of the page, even if I add System.Web.Mvc in the pages element of web.config, that shouldn't be necessary right? I see the viewcontext constructor was also cleaned up, that saves a lot of code when mocking it! Nice. One more thing I noticed: Html.TextBox("user.name") will render an input with id=user_name and name=user.name This is confusing, and makes it harder to make labels that are connected to the inputs. Why did you do this? HtmlHelper.cs line 214: internal object GetModelStateValue(string key, Type destinationType) { ModelState modelState; if (ViewData.ModelState.TryGetValue(key, out modelState)) { //if appended by deerchao //other wise NullReferenceException is thorwed sometimes: if(modelState.Value!=null) return modelState.Value.ConvertTo(destinationType, null /* culture */); } return null; Thank you once again for the detailed post explaining the new features. Good ridence to code behind's in my opinion. Does this include the Dynamic Data stuff that has been in the "Futures" pack (which I haven't managed to get to work)? I've been waiting for an official update to that. Thank you so much. I've an issue about the HtmlHelper. The html id generated by HtmlHelper is usually the same as the name. For example, <% = Html.TextBox("Product.Name") %> will output <input type="text" name="Product.Name" id="Product.Name" /> The problem is the dot "." inside the ID will cause problem in many client javascript, like JQuery, the following selector will result "function not found" error. $("#Product.Name") It'll be grade if HtmlHelper can replace all "." to "_" in the Html id field by default. Thank you Charles If I try to use the CTRL+M, CTRL+V with a controller which is not part of the website's assembly I get the message on the status bar - "The key combination is bound to command (&Add View...) which is not currently available". My model class is also in a separate assembly. eg MvcTest.WebApp MvcTest.Model MvcTest.Controllers I did some further tests and it works if the controller class is part of the web project (even if the model is in a separate assembly, contrary to what others comments say). I can see why this might be hard to implement since there may be more than one web project (eg, public and admin apps) and the command wouldn't know which project you want to add it to, however it would definitely be nice to have it if it would be at all possible. Otherwise, seems great. Hello Scott, Found a tiny little bug in Web.config, the authentication loginUrl should point to "~/Account/LogOn" instead of "~/Account/Login". Currently in RC, any controller action with the [Authorize] attribute will get a 404 instead of the log on page. It is a tiny problem, which can be addressed by a developer easily. @Zano, >>>>>>> Routing has some bugs (like dealing with special characters). Can you post details on the issues you are seeing on the ASP.NET MVC forum at:? The team can then take a look at them. @Barney, >>>>>> However, the File helper does not take one argument - it now requires the content type. Is there any way of using this without knowing the content type in advance? Good question - I just sent mail to the team passing along that suggestion. @Col checked with the team, and they said this has always been the behavior, and that the form helpers never directly accessed the Request property to retrieve posted values. From a separation of concerns perspective, it is best to have the UI helpers always work off the data that the Controller passes to the view - can you not pass this data via either the ViewData dictionary or a custom ViewModel object? @Bill, >>>>>>>>? Can you have your Html.StateSelectList return a SelectList object instead of what it currently uses? This should fix the issue. Scott @DevDave, >>>>>>> Are you using Linq to SQL in this example? Does this mean I can comfortably continue using Linq to SQL in my development? Yep - I am using LINQ to SQL in the above examples. LINQ to SQL works great for me. @ray247, >>>>>>>>! I'd recommend looking at the release notes. These document the steps necessary to upgrade. @Anthony, >>>>>>>> Can I use it with Mono? We are working to enable it to be used on Mono as well. @Doug, >>>>>>>> One problem for me though is that the "Add View" dialog isn't picking up my models. It picks up lots of classes including some from my project, referenced projects and referenced assemblies, just not my models. Do I need to do anything special to get that bit working? We found a bug where if you have a class in one assembly that exposes a public property for a type that lives in a separate assembly, the scaffolding templates raise an error. We are going to get that fixed for the final release. @dp6, >>>>>>> Scott, what are the asp.net mvc dependencies? i.e. does this require Ent Lib? ASP.NET MVC requires .NET 3.5 (we recommend 3.5 SP1 - but it will work with vanilla 3.5 too). There are no EntLib requirements (although it will work with it). @Jahedur, >>>>>>>>. We thought showing the full name would be more discoverable and a little less magic. The selection within the dialog is set so that you can just use the keyboard (and don't need to use the mouse to keep the Controller postfix). >>>>>>> I keep my controllers in a separate assembly. The 'goto controller' and 'goto view' features do not work. Unfortunately I'm not sure if we'll be able to enable this in V1 - but I'll forward along to the team for them to look at. @Todd, >>>>>>>> Where can we get the latest source code? The 21526 tag on says DO NOT USE and the previous 17272 tag is older code. The source has been updated on CodePlex with the RC1 source. @Emad, >>>>>>> I have a action filter that compresses the data and for some reason this line of code throws a null reference exception Good question - I just forwarded this report to the team for them to look at. @achu, >>>>>>>> View data class in the Add View dialog does not show my linq2sql classes in this build but it worked in beta1. Are you doing a compile after adding the classes to the project? If you are still having problems please send me email (scottgu@microsoft.com) with more details. @Blake, >>>>>>>. We debated on the scaffolding front exactly the approach to take. One approach would have been to hard-code it with awareness of a specific ORM implementation, but in the end we decided to go a more generic approach so that the base version worked well with any class. Having said that, we are adding a last minute feature for RTM to identify primary keys with Linq to SQL and LINQ to Entities to avoid users having to update the hyperlinks in the views for navigation. Detecting foreign keys and automatically populating drop-downlists is something we are going to look at for the next release. >>>>>>>? We'll be adding support for this in the future (we are working on this now). It won't make V1, but is something we'll enable. >>>>>>> I realize I could probably grow my own, especially because of open t4 implementation of the current scaffold as you pointed out (which looks awesome btw), but this seems like something that is so rudimentary to the framework that it needs to be included. Ultimately we wanted to make sure we provide good base scaffolding that works in all scenarios first, and then add the more specific scaffolding support for specific ORMs. We felt this would ensure that we had the most flexibility out of the box to handle multiple scenarios. We'll be building even more on top of it (including adding specific ORM awareness) in the future though now that we have the base support in. @bchance, >>>>>>>> chance you could re-post this question in the ASP.NET MVC forum on? I'd love for the team to be able to drill into this scenario more with you. @Feng, >>>>>>> Any plan on supporting Website project type? Our built-in tool support for MVC is going to use the web application project option. Note that this project type is now supported with the free Visual Web Developer 2008 edition (just make sure you have SP1 installed to get it). @BSR, >>>>>>>> Whatever happened to BinaryStreamResult that was part of the MVC Futures assembly? This was replaced with the new FileResult feature that is built-in to the ASP.NET MVC RC core. >>>>>>> I kept exceptions thrown when trying to use the new 'add view' We found a bug where if your model class is in one assembly and exposes a public property for a type that lives in a separate assembly, the scaffolding templates raise an error. We are going to get that fixed for the final release. Could this be the issue you are running into? You guys are geniuses. THANK YOU VERY MUCH FOR ALL YOUR HARD WORK!!! My VS IDE crashes when I open the MVC Project. I have VS 2008 SP1. I have MVC Beta before, uninstalled and installed MVC RC and then when I open the MVC Project that I had, the project opens and then IDE closes automatically. Any inputs that you can provide? Is the following a bug in RC1? I have: <%= Html.ActionLink("abc","Index","Home",new{},new{_class="123"}) %> which renders: <a _class="123" href="./">abc</a> how come I am seeing "_class" instead of "class" attribute in the anchor tag? Thank you !!!! What settings do you have in your VS Editor. I just love the dark background. Very excited about the new features, amazing work. Unfortunately, I've had no luck getting the installer to work. i uninstalled the previous beta first. But during install of RC i get up to 'configuring templates' step then it goes to 'removing backup files' for a moment and starts 'rolling back', telling me it didn't install properly. In the event log i see "Installation success or error status: 1603" When I run VS2008 (note:Standard edition) i see MVC project templates in the 'new project' dialog, but when i try to create an MVC project, i get "This template attempted to load an untrusted component. 'Microsoft.VisualStudio.Web.Extensions, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. (Naturally I have screenshots of everything, etc) ;-) lb i tried again with logging on msiexec /i "AspNetMVCRC-setup.msi" /q /l*v mvc.log it looks like the culprit is a failure during ngen. :-(" I love MVC! The lack of code-behind by default is a pain. I like generating my forms in the code-behind because they are compile-time checked and easier to refactor with Resharper. Consider the following example, assigning form to a string in the aspx file: protected override void OnLoad(...) { var formItems = new IFormItem[] { new SomeTypeOfFormItem(...), new OtherTypeOfFormItem(...), ... form = Html.BuildForm<Controller>(c => c.Method(), "FormName", formItems); } Using this method seems much more maintainable. Why cut off the ability to develop our code as cleanly as possible with the most possible support from third party applications?? MVC is great, but in my opinion, removing the code-behind by default is a terrible decision. The Controller.UpdateModel() method provides nice error messages whenever the input value fails to be converted to the model's property type. How to I replace the English text with, say, Norwegian ones? What is the secret to get to the unit test for the Account Controller. I created a new project using the template and expected to be asked if I wanted a unit test project created and I never got this dialog. I don't see the unit tests anywhere. I just have a question about the edit functionality and the state of the view following the simple examples provided. I click the edit and make changes, the changes persist to the database using linq as described but the original values are shown not the new values. The same query code seems to be running again and even if I set a breakpoint in the view display code which loops through displaying records creating a grid, wherein I see the correctly changed value, it doesn't show up in the display. It is peculiar behavior to say the least. Sorry,nix that comment it was I who had made the mistake in my query code. Hi Scott, I submitted my Design on Jan 18 for the MVC Design Contest. I never got approved on my design. Why is that? There is no information anywhere and I never received any email. I think approval should have take 1 day not more. In the ASP.NET Webform, it has a special file called app_offline.htm. Will it be supported in MVC? Dunno if you're still reading the comments on this thread, but this is the only way I could find to contact you on your blog. Besides the fact that it's difficult to find a way to send you a comment NOT related to your blog, I simply wanted to point out that it would be really helpful if you could somehow show the date/time of your blog posts at the top of each post. There's nothing worse than reading an entire article just to find out it's a year old. And it sucks to have to scroll down to find the date/time which is somewhere between your giant posts and the hundreds of comments that follow. Thanks for taking time to consider these improvements! I am new to MVC and am looking at this line of code in an old program that I am trying to update. I have a problem with the dropdownlist and binding the data to it. Html.DropDownList("Categories", ViewData["Categories"]) It does not like this ViewData object. What can I do to fix this? Can't wait for the final 1.0 release. Thanks to you and the team for all of your hard work. Thanks for another incredibly rich ASP.NET MVC release. It's looking like the fact that you include JQuery 1.2.6 with the RC and will move to 1.3.x in the v1.0 release was some helpful timing. I've been reading of people having issues and encountering bugs with the current rev of JQuery 1.3.x. where i can download the ASP.NET MVC 1.0 Release Candidate source code! thanks I tried to include the changes in the project file to Compile the Views (add AspNetCompiler task on AfterBuild target), and yes it works as expected when I Build through Visual Studio. However, it breaks when I build using Team Build, with following error: /temp/global.asax(1): error ASPPARSE: Could not load type 'WebClient.MvcApplication'. It's definitely not something to do with my build server because when I tried to open Visual Studio on the server and build it from there, it also builds fine. Can you please let me know if it is a known issue, and if there's any workaround? Fandi Scott: "@Steve, Scott" I know you know this... :) But a majority of applications built with mvc will have their controllers separated from the web application. It's not even good architecture IMO to not provide this. Especially anything larger than mom and pop shops. Monorail provided a configuration entry to define the assembly with the controllers. This is very short-sided of the development team to think that everyone will have the controllers embedded in the web application. Awesome write up, thanks! Hi Scott... I want to Load a UserControl from my Views Folder. in Old Release it Loads like <%= RenderUserControl("~/Views/Home/TestUC.ascx")%> in RC1 i don't know how u Load a UserControl Well ......i got the Answer....... it should be <% Html.RenderPartial("~/Views/Home/TestUC.ascx", m); %> thanx for RC Refresh I´m getting the same error of SecretGeek... What can i do? I have the similar problem to what SecretGeek mentioned earlier. It says Out of memory in the log but I have plenty. I have VS 2008 team suite, .Net 3.5 SP1, Vista Ultimate if that helps. ExecNetFx: Microsoft (R) CLR Native Image Generator - Version 2.0.50727.3053 ExecNetFx: Out Of" Hi Scott.... I have one question.....why there is two web.config files (one is at rootfolder and anthor is in "Views" folder). Kind Regards, Saurabh Where can I find the new MSBuild task? great work,thank you Sorry, this is not the right place, but the other blog on web deployment project is closed and I found nothing on it after hours of searching the net. OK here we go, this is the question: Creating a Web Site Project (not a Web Application Project) and adding a Web Deployment Project you can deploy your site with a single assembly and all the content files. These content files can be modified by a third party in a working environment (just include the bin folder) without getting your sourcecode. This is a cool workflow till you want to include those content files (ascx/aspx) back to your website solution. It doesn't work, as the deployment project removes in the page directive the CodeFile and ads a class in the inherit attribute. OK, I could write a program that reverts these modifications in those files back. ...but I can't imagine that this is the right way. Please help! Regards I had created an application using MVC Beta. Now the client came to me saying Migrate it and now when the fields are empty and user clicks submit it simple throws Null reference exception. I tried passing data from controller into my View Data ["xyz"] but still it throws null reference exception. I am not able to figure out why? Can anybody help? In Beta it used to show the validation message now it doesnt. Whither the t4 templates? After installing RC, I can't find the t4 templates. 'The directory C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates' does not exist on my system. I've also downloaded the source from codeplex and again no templates. I would like the source to customize and make my own templates. @Steve: I really don't think the majority of web apps will have the controllers in a separate dll. I do think this is a good design for most apps. Now for larger apps, I think divided into areas, would be separate dlls, but still would be able to function as separate units. In most cases, I cannot see a good reason for this separation and in fact think it is a bad idea. thx, good reviews, i like MVC :) nice article. thanks Nice article! Thank you! Very helpful. I'm just getting started with ASP.NET MVC, and this article has given me some pointers on the exact scenarios that I am looking to implement. any chance we'll get the OPTIONAL ability to add codebehind for a view as we create a new one? i'm thinking just an extra checkbox. its quite a pain to create one manually. getting the IDE to correctly link the files and remember to change all the right bits and pieces. here's my exhaustive list of reasons why i want it : stackoverflow.com/.../527189 This may not be the place to ask this questions, but I can't figure out where. I am trying to find out how to access ActionLink<TModel> HtmlHelper. I downloaded the RC 1, also the RC Futures assembly, added the namespace Microsoft.Web.Mvc.Controls. And all I get is ActionLink(). You said that the team will iterate over these for a while, does that mean it's not in the futures assembly either? Maybe I'm missing something obvious. Thanks in advance. Why is it that when i created a new MVC web content the code behind was not created only the aspx?... it looks like the MvcRC is different from the Mvc Beta version... it's very quite strange now i can't get the ViewData.Model when I try to inhirit the viewpage and it give me an error Html.Encode(Model.id) can not find the context when infact i already import this class <%@ Import Namespace="System.Web.Mvc.Html" %> would it be possible to extract an IHtmlHelper interface? the reason I ask this, is it would be really great to be able to have an extension method written as so: in any given view, with regards to user permissions: <%=Html.ForPermission(userPerms).TextBox("blahblah")%> then, instead of having to use ugly if statements in our controllers to route an authorized user to an alternate view, we could just have the view dictate which elements to display, based upon userPerms sent via the controller. I'm sad, yet happy, to say I have finally jumped off the MVC bandwagon. I have been following and using it in a couple of development projects since Preview 1, but the bottom line is, it still takes too long to do anything in this framework. If you want just a straight-forward, data-entry application, well jump right on, but if you want control over your application and need a little spunk and power, please save yourself time and use something like Silverlight or webforms instead. MVC has its [limited] uses but please watch your step and realize how much work will go into your application. You would think with how much time was put into this project they would realize people need more UI functionality than a couple of HTML helpers...where's the grid with the ability to arrange columns, sort, etc without a major hack and a dozen JavaScript files? Sorry Scott, I really was right there with you on this one, but maybe my hopes were too high for RC1. How does MVC plan to handle localization, especially of View resources? We're building new website with MVC, most of UI elements will be implemented as user controls for reusing in other projects. But I've seen no article or tutorial about how to create and use views, user controls, as well as controllers in separate assemblies. Does MVC support it for now? I have the same problem as Fandi. (/temp/global.asax(1): error ASPPARSE: Could not load type 'WebClient.MvcApplication'.) Is there any way to resolve it? Fandi, I understood what's wrong with AspNetCompiler. It's a well known problem. It's because Asp.Net compiler can't find the binaries. Change output path in your web project. For example: <OutputPath Condition=" '$(TeamBuildOutDir)'=='' ">.\Release</OutputPath> <OutputPath Condition=" '$(TeamBuildOutDir)'!='' ">$(TeamBuildOutDir)WebDeploy\</OutputPath> With you example: "When a user attempts to create a Product with invalid Product property values (for example: a string “Bogus” instead of a valid Decimal value), the form will redisplay and flag the invalid input elements in red", it doesn't seem to set a default error message for showing in the validation summary - instead leaving it blank against the item in the ModelState. Is there any way of setting this message such as "Please enter a valid decimal value?" James Excuse me, my English is very poor. ...the fieldName is hard coded in the HtmlHelper class... not "strongly typed" Can anyone tell me what happened to ComponentController? Controls for ASP.net MVC like Rich faces for JSF? Thanks!! Article is usefull ! Hi Scott. Could <%= Html.ValidationMessage() %> be made to work with input "id" aswell as "name". There are scenarios where you might want items a grid to always be editable (e.g. quantity on an inventory list or a shopping cart page.) Also will there be any 'data-pager' / 'data-sort' helpers for LINQ in the final release? I understand you can write custom code, but these seem too fundamental to miss?! Best Regards. Adam. Scott Gu : " We expect to ship the final ASP.NET MVC 1.0 release next month" Thanks for your useful articles. and also for information about MVC Technology! But the question is , what happened to you and MVC ? There aren't any posts of you during the February, And I wanted to Say, Me, my team and of course a lot of other developers are fully worry about you and MVC, So please Keep us inform! ;-) I am hoping that ASP.NET MVC final release is shipped very very soon Migrating from Beta to RC1 Someone had this problem? I've installed MVC RC1 and intend to change the beta notation for no code behind views: Inherits="System.Web.Mvc.ViewPage`1[[Namespace.Class, Assembly]]" to the new and cleaner syntaxis, and I have this error: Parser Error Could not load type 'System.Web.Mvc.ViewPage<Namespace.Class>' I have to remark that on a new clean project the syntaxis works ok. hi scott, today, i read all your MVC tagged blog posts. in this one you said the MVC framework now support views using the expression based syntax (+ intellisense) as well as the the string base approach (): a) i wonder why are you using the string based approach in the scaffolding template generated views? why not using the expression based one for scaffolding now? thanks, tob A very nice article. What's the word on the final release of 1.0? I tested RC2 and like it, but I have to get my team and servers upgraded. If 1.0 is going to be released in a few days/week, should I just wait? Hello, someone know when the final release will be available ? Almost 10 years after Struts MVC...nice ! :)
http://weblogs.asp.net/scottgu/archive/2009/01/27/asp-net-mvc-1-0-release-candidate-now-available.aspx
CC-MAIN-2014-10
refinedweb
8,922
75.5
31 August 2007 16:04 [Source: ICIS news] LONDON (ICIS news)-Saudi Basic Industries Corp (SABIC) has completed the $11.6bn (€8.5bn) acquisition of GE Plastics from General Electric, the Saudi Arabia-based petrochemicals major said on Friday. ?xml:namespace> Brian Gladden has been named CEO of the business, which will be renamed SABIC Innovative Plastics, effective 1 September. SABIC said the business would focus on the global growth of thermoplastics and engineering plastics to serve the automotive, electronics, healthcare and construction sectors. GE Plastics employs 10,300 people. Following the earlier acquisitions of DSM and Huntsman’s petrochemicals businesses in ?xml:namespace> GE said it will use the proceeds from the sale to complete a $27bn stock buyback programme.GE said it will use the proceeds from the sale to complete a $27bn stock buyback programme. ($1 = €0.73) Al Greenwood
http://www.icis.com/Articles/2007/08/31/9058846/SABIC-completes-acquisition-of-ge-plastics.html
CC-MAIN-2015-11
refinedweb
143
56.55
Python .whl files, or wheels, are a little-discussed part of Python, but they’ve been a boon to the installation process for Python packages.. In this tutorial, you’ll dive into what wheels are, what good they serve, and how they’ve gained traction and made Python even more of a joy to work with. In this tutorial, you’ll learn: - What wheels are and how they compare to source distributions - How you can use wheels to control the package installation process - How to create and distribute wheels for your own Python packages You’ll see examples using popular open source Python packages from both the user’s and the developer’s perspective. Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions. Setup To follow along, activate a virtual environment and make sure you have the latest versions of pip, wheel, and setuptools installed: $ python -m venv env && source ./env/bin/activate $ python -m pip install -U pip wheel setuptools Successfully installed pip 20.1 setuptools-46.1.3 wheel-0.34.2 That’s all you need to experiment with installing and building wheels! Python Packaging Made Better: An Intro to Python Wheels Before you learn how to package a project into a wheel, it helps to know what using one looks like from the user’s side. It may sound backward, but a good way to learn how wheels work is to start by installing something that isn’t a wheel. You can start this experiment by installing a Python package into your environment just as you might normally do. In this case, install uWSGI version 2.0.x: 1$ python -m pip install 'uwsgi==2.0.*' 2Collecting uwsgi==2.0.* 3 Downloading uwsgi-2.0.18.tar.gz (801 kB) 4 |████████████████████████████████| 801 kB 1.1 MB/s 5Building wheels for collected packages: uwsgi 6 Building wheel for uwsgi (setup.py) ... done 7 Created wheel for uwsgi ... uWSGI-2.0.18-cp38-cp38-macosx_10_15_x86_64.whl 8 Stored in directory: /private/var/folders/jc/8_hqsz0x1tdbp05 ... 9Successfully built uwsgi 10Installing collected packages: uwsgi 11Successfully installed uwsgi-2.0.18 To fully install uWSGI, pip progresses through several distinct steps: - On line 3, it downloads a TAR file (tarball) named uwsgi-2.0.18.tar.gzthat’s been compressed with gzip. - On line 6, it takes the tarball and builds a .whlfile through a call to setup.py. - On line 7, it labels the wheel uWSGI-2.0.18-cp38-cp38-macosx_10_15_x86_64.whl. - On line 10, it installs the actual package after having built the wheel. The tar.gz tarball that pip retrieves is a source distribution, or sdist, rather than a wheel. In some ways, a sdist is the opposite of a wheel. Note: If you see an error with the uWSGI installation, you may need to install the Python development headers. A source distribution contains source code. That includes not only Python code but also the source code of any extension modules (usually in C or C++) bundled with the package. With source distributions, extension modules are compiled on the user’s side rather than the developer’s. Source distributions also contain a bundle of metadata sitting in a directory called <package-name>.egg-info. This metadata helps with building and installing the package, but user’s don’t really need to do anything with it. From the developer’s perspective, a source distribution is what gets created when you run the following command: $ python setup.py sdist Now try installing a different package, chardet: 1$ python -m pip install 'chardet==3.*' 2Collecting chardet 3 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) 4 |████████████████████████████████| 133 kB 1.5 MB/s 5Installing collected packages: chardet 6Successfully installed chardet-3.0.4 You can see a noticeably different output than the uWSGI install. Installing chardet downloads a .whl file directly from PyPI. The wheel name chardet-3.0.4-py2.py3-none-any.whl follows a specific naming convention that you’ll see later. What’s more important from the user’s perspective is that there’s no build stage when pip finds a compatible wheel on PyPI. From the developer’s side, a wheel is the result of running the following command: $ python setup.py bdist_wheel Why does uWSGI hand you a source distribution while chardet provides a wheel? You can see the reason for this by taking a look at each project’s page on PyPI and navigating to the Download files area. This section will show you what pip actually sees on the PyPI index server: - uWSGI provides only a source distribution ( uwsgi-2.0.18.tar.gz) for reasons related to the complexity of the project. - chardet provides both a wheel and a source distribution, but pipwill prefer the wheel if it’s compatible with your system. You’ll see how that compatibility is determined later on. Another example of the compatibility check used for wheel installation is psycopg2, which provides a wide set of wheels for Windows but doesn’t provide any for Linux or macOS clients. This means that pip install psycopg2 could fetch a wheel or a source distribution depending on your specific setup. To avoid these types of compatibility issues, some packages offer multiple wheels, with each wheel geared toward a specific Python implementation and underlying operating system. So far, you’ve seen some of the visible distinctions between a wheel and sdist, but what matters more is the impact those differences have on the installation process. Wheels Make Things Go Fast Above, you saw a comparison of an installation that fetches a prebuilt wheel and one that downloads a sdist. Wheels make the end-to-end installation of Python packages faster for two reasons: - All else being equal, wheels are typically smaller in size than source distributions, meaning they can move faster across a network. - Installing from wheels directly avoids the intermediate step of building packages off of the source distribution. It’s almost guaranteed that the chardet install occurred in a fraction of the time required for uWSGI. However, that’s arguably an unfair apples-to-oranges comparison since chardet is a significantly smaller and less complex package. With a different command, you can create a more direct comparison that will demonstrate just how much of a difference wheels make. You can make pip ignore its inclination towards wheels by passing the --no-binary option: $ time python -m pip install \ --no-cache-dir \ --force-reinstall \ --no-binary=:all: \ cryptography This command times the installation of the cryptography package, telling pip to use a source distribution even if a suitable wheel is available. Including :all: makes the rule apply to cryptography and all of its dependencies. On my machine, this takes around thirty-two seconds from start to finish. Not only does the install take a long time, but building cryptography also requires that you have the OpenSSL development headers present and available to Python. Note: With --no-binary, you may very well see an error about missing header files required for the cryptography install, which is part of what can make using source distributions frustrating. If so, the installation section of the cryptography docs advises on which libraries and header files you’ll need for a particular operating system. Now you can reinstall cryptography, but this time make sure that pip uses wheels from PyPI. Because pip will prefer a wheel, this is similar to just calling pip install with no arguments at all. But in this case, you can make the intent explicit by requiring a wheel with --only-binary: $ time python -m pip install \ --no-cache-dir \ --force-reinstall \ --only-binary=cryptography \ cryptography This option takes just over four seconds, or one-eighth the time that it took when using only source distributions for cryptography and its dependencies. What Is a Python Wheel? A Python .whl file is essentially a ZIP ( .zip) archive with a specially crafted filename that tells installers what Python versions and platforms the wheel will support. A wheel is a type of built distribution. In this case, built means that the wheel comes in a ready-to-install format and allows you to skip the build stage required with source distributions. Note: It’s worth mentioning that despite the use of the term built, a wheel doesn’t contain .pyc files, or compiled Python bytecode. A wheel filename is broken down into parts separated by hyphens: {dist}-{version}(-{build})?-{python}-{abi}-{platform}.whl Each section in {brackets} is a tag, or a component of the wheel name that carries some meaning about what the wheel contains and where the wheel will or will not work. Here’s an illustrative example using a cryptography wheel: cryptography-2.9.2-cp35-abi3-macosx_10_9_x86_64.whl cryptography distributes multiple wheels. Each wheel is a platform wheel, meaning it supports only specific combinations of Python versions, Python ABIs, operating systems, and machine architectures. You can break down the naming convention into parts: cryptographyis the package name. 2.9.2is the package version of cryptography. A version is a PEP 440-compliant string such as 2.9.2, 3.4, or 3.9.0.a3. cp35is the Python tag and denotes the Python implementation and version that the wheel demands. The cpstands for CPython, the reference implementation of Python, while the 35denotes Python 3.5. This wheel wouldn’t be compatible with Jython, for instance. abi3is the ABI tag. ABI stands for application binary interface. You don’t really need to worry about what it entails, but abi3is a separate version for the binary compatibility of the Python C API. macosx_10_9_x86_64is the platform tag, which happens to be quite a mouthful. In this case it can be broken down further into sub-parts: The final component isn’t technically a tag but rather the standard .whl file extension. Combined, the above components indicate the target machine that this cryptography wheel is designed for. Now let’s turn to a different example. Here’s what you saw in the above case for chardet: chardet-3.0.4-py2.py3-none-any.whl You can break this down into its tags: chardetis the package name. 3.0.4is the package version of chardet. py2.py3is the Python tag, meaning the wheel supports Python 2 and 3 with any Python implementation. noneis the ABI tag, meaning the ABI isn’t a factor. anyis the platform. This wheel will work on virtually any platform. The py2.py3-none-any.whl segment of the wheel name is common. This is a universal wheel that will install with Python 2 or 3 on any platform with any ABI. If the wheel ends in none-any.whl, then it’s very likely a pure-Python package that doesn’t care about a specific Python ABI or CPU architecture. Another example is the jinja2 templating engine. If you navigate to the downloads page for the Jinja 3.x alpha release, then you’ll see the following wheel: Jinja2-3.0.0a1-py3-none-any.whl Notice the lack of py2 here. This is a pure-Python project that will work on any Python 3.x version, but it’s not a universal wheel because it doesn’t support Python 2. Instead, it’s called a pure-Python wheel. Note: In 2020, a number of projects are also dropping support for Python 2, which reached end-of-life (EOL) on January 1, 2020. Jinja version 3.x dropped Python 2 support in February 2020. Here are a few more examples of .whl names distributed for some popular open source packages: Now that you have a thorough understanding of what wheels are, it’s time to talk about what good they serve. Advantages of Python Wheels Here’s a testament to wheels from the Python Packaging Authority (PyPA): Not all developers have the right tools or experiences to build these components written in these compiled languages, so Python created the wheel, a package format designed to ship libraries with compiled artifacts. In fact, Python’s package installer, pip, always prefers wheels because installation is always faster, so even pure-Python packages work better with wheels. (Source) A fuller description is that wheels benefit both users and maintainers of Python packages alike in a handful of ways: Wheels install faster than source distributions for both pure-Python packages and extension modules. Wheels are smaller than source distributions. For example, the sixwheel is about one-third the size of the corresponding source distribution. This differential becomes even more important when you consider that a pip installfor a single package may actually kick off downloading a chain of dependencies. Wheels cut setup.pyexecution out of the equation. Installing from a source distribution runs whatever is contained in that project’s setup.py. As pointed out by PEP 427, this amounts to arbitrary code execution. Wheels avoid this altogether. There’s no need for a compiler to install wheels that contain compiled extension modules. The extension module comes included with the wheel targeting a specific platform and Python version. pipautomatically generates .pycfiles in the wheel that match the right Python interpreter. Wheels provide consistency by cutting many of the variables involved in installing a package out of the equation. You can use a project’s Download files tab on PyPI to view the different distributions that are available. For example, pandas distributes a wide array of wheels. Telling pip What to Download It’s possible to exert fine-grained control over pip and tell it which format to prefer or avoid. You can use the --only-binary and --no-binary options to do this. You saw these used in an earlier section on installing the cryptography package, but it’s worth taking a closer look at what they do: $ pushd "$(mktemp -d)" $ python -m pip download --only-binary :all: --dest . --no-cache six Collecting six Downloading six-1.14.0-py2.py3-none-any.whl (10 kB) Saved ./six-1.14.0-py2.py3-none-any.whl Successfully downloaded six In this example, you change to a temporary directory to store the download with pushd "$(mktemp -d)". You use pip download rather than pip install so that you can inspect the resulting wheel, but you can replace download with install while keeping the same set of options. You download the six module with several flags: --only-binary :all:tells pipto constrain itself to using wheels and ignore source distributions. Without this option, pipwill only prefer wheels but will fall back to source distributions in some scenarios. --dest .tells pipto download sixto the current directory. --no-cachetells pipnot to look in its local download cache. You use this option just to illustrate a live download from PyPI since it’s likely you do have a sixcache somewhere. I mentioned earlier that a wheel file is essentially a .zip archive. You can take this statement literally and treat wheels as such. For instance, if you want to view a wheel’s contents, you can use unzip: $ unzip -l six*.whl Archive: six-1.14.0-py2.py3-none-any.whl Length Date Time Name --------- ---------- ----- ---- 34074 01-15-2020 18:10 six.py 1066 01-15-2020 18:10 six-1.14.0.dist-info/LICENSE 1795 01-15-2020 18:10 six-1.14.0.dist-info/METADATA 110 01-15-2020 18:10 six-1.14.0.dist-info/WHEEL 4 01-15-2020 18:10 six-1.14.0.dist-info/top_level.txt 435 01-15-2020 18:10 six-1.14.0.dist-info/RECORD --------- ------- 37484 6 files six is a special case: it’s actually a single Python module rather than a complete package. Wheel files can also be significantly more complex, as you’ll see later on. In contrast to --only-binary, you can use --no-binary to do the opposite: $ python -m pip download --no-binary :all: --dest . --no-cache six Collecting six Downloading six-1.14.0.tar.gz (33 kB) Saved ./six-1.14.0.tar.gz Successfully downloaded six $ popd The only change in this example is the switch to --no-binary :all:. This tells pip to ignore wheels even if they’re available and instead download a source distribution. When might --no-binary be useful? Here are a few cases: The corresponding wheel is broken. This is an irony of wheels. They’re designed to make things break less often, but in some cases a wheel can be misconfigured. In this case, downloading and building the source distribution for yourself may be a working alternative. You want to apply a small change or patch file to the project and then install it. This is an alternative to cloning the project from its version control system URL. You can also use the flags described above with pip install. Additionally, instead of :all:, which will apply the --only-binary rule not just to the package you’re installing but to all of its dependencies, you can pass --only-binary and --no-binary a list of specific packages to apply that rule to. Here are a few examples for installing the URL library yarl. It contains Cython code and depends on multidict, which contains pure C code. There are several options to strictly use or strictly ignore wheels for yarl and its dependencies: $ # Install `yarl` and use only wheels for yarl and all dependencies $ python -m pip install --only-binary :all: yarl $ # Install `yarl` and use wheels only for the `multidict` dependency $ python -m pip install --only-binary multidict yarl $ # Install `yarl` and don't use wheels for yarl or any dependencies $ python -m pip install --no-binary :all: yarl $ # Install `yarl` and don't use wheels for the `multidict` dependency $ python -m pip install --no-binary multidict yarl In this section, you got a glimpse of how to fine-tune the distribution types that pip install will use. While a regular pip install should work with no options, it’s helpful to know these options for special cases. The manylinux Wheel Tag Linux comes in many variants and flavors, such as Debian, CentOS, Fedora, and Pacman. Each of these may use slight variations in shared libraries, such as libncurses, and core C libraries, such as glibc. If you’re writing a C/C++ extension, then this could create a problem. A source file written in C and compiled on Ubuntu Linux isn’t guaranteed to be executable on a CentOS machine or an Arch Linux distribution. Do you need to build a separate wheel for each and every Linux variant? Luckily, the answer is no, thanks to a specially designed set of tags called the manylinux platform tag family. There are currently three variations: manylinux1is the original format specified in PEP 513. manylinux2010is an update specified in PEP 571 that upgrades to CentOS 6 as the underlying OS on which the Docker images are based. The rationale is that CentOS 5.11, which is where the list of allowed libraries in manylinux1comes from, reached EOL in March 2017 and stopped receiving security patches and bug fixes. manylinux2014is an update specified in PEP 599 that upgrades to CentOS 7 since CentOS 6 is scheduled to reach EOL in November 2020. You can find an example of manylinux distributions within the pandas project. Here are two (out of many) from the list of available pandas downloads from PyPI: pandas-1.0.3-cp37-cp37m-manylinux1_x86_64.whl pandas-1.0.3-cp37-cp37m-manylinux1_i686.whl In this case, pandas has built manylinux1 wheels for CPython 3.7 supporting both x86-64 and i686 architectures. At its core, manylinux is a Docker image built off a certain version of the CentOS operating system. It comes bundled with a compiler suite, multiple versions of Python and pip, and an allowed set of shared libraries. Note: The term allowed indicates a low-level library that is assumed to be present by default on almost all Linux systems. The idea is that the dependency should exist on the base operating system without the need for an additional install. As of mid-2020, manylinux1 is still the predominant manylinux tag. One reason for this might just be habit. Another might be that support on the client (user) side for manylinux2010 and above is limited to more recent versions of pip: In other words, if you’re a package developer building manylinux2010 wheels, then someone using your package will need pip 19.0 (released in January 2019) or later to let pip find and install manylinux2010 wheels from PyPI. Luckily, virtual environments have become more common, meaning that developers can update a virtual environment’s pip without touching the system pip. This isn’t always the case, however, and some Linux distributions still ship with outdated versions of pip. All that is to say, if you’re installing Python packages on a Linux host, then consider yourself fortunate if the package maintainer has gone out of their way to create manylinux wheels. This will almost guarantee a hassle-free installation of the package regardless of your specific Linux variant or version. Caution: Be advised that PyPI wheels don’t work on Alpine Linux (or BusyBox). This is because Alpine uses musl in place of the standard glibc. The musl libc library bills itself as “a new libc striving to be fast, simple, lightweight, free, and correct.” Unfortunately, when it comes to wheels, glibc it is not. Security Considerations With Platform Wheels One feature of wheels worth considering from a user security standpoint is that wheels are potentially subject to version rot because they bundle a binary dependency rather than allowing that dependency to be updated by your system package manager. For example, if a wheel incorporates the libfortran shared library, then distributions of that wheel will use the libfortran version that they were bundled with even if you upgrade your own machine’s version of libfortran with a package manager such as apt, yum, or brew. If you’re developing in an environment with heightened security precautions, this feature of some platform wheels is something to be mindful of. Calling All Developers: Build Your Wheels The title of this tutorial asks, “Why Should You Care?” As a developer, if you plan to distribute a Python package to the community, then you should care immensely about distributing wheels for your project because they make the installation process cleaner and less complex for end users. The more target platforms that you can support with compatible wheels, the fewer GitHub issues you’ll see titled something like “Installation broken on Platform XYZ.” Distributing wheels for your Python package makes it objectively less likely that users of the package will encounter issues during installation. The first thing you need to do to build a wheel locally is to install wheel. It doesn’t hurt to make sure that setuptools is up to date, too: $ python -m pip install -U wheel setuptools The next few sections will walk you through building wheels for a variety of different scenarios. Different Types of Wheels As touched on throughout this tutorial, there are several different variations of wheels, and the wheel’s type is reflected in its filename: A universal wheel contains py2.py3-none-any.whl. It supports both Python 2 and Python 3 on any OS and platform. The majority of wheels listed on the Python Wheels website are universal wheels. A pure-Python wheel contains either py3-none-any.whlor py2.none-any.whl. It supports either Python 3 or Python 2, but not both. It’s otherwise the same as a universal wheel, but it’ll be labeled with either py2or py3rather than the py2.py3label. A platform wheel supports a specific Python version and platform. It contains segments indicating a specific Python version, ABI, operating system, or architecture. The differences between wheel types are determined by which version(s) of Python they support and whether they target a specific platform. Here’s a condensed summary of the differences between wheel variations: As you’ll see next, you can build universal wheels and pure-Python wheels with relatively little setup, but platform wheels may require a few additional steps. Building a Pure-Python Wheel You can build a pure-Python wheel or a universal wheel for any project using setuptools with just a single command: $ python setup.py sdist bdist_wheel This will create both a source distribution ( sdist) and a wheel ( bdist_wheel). By default, both will be placed in dist/ under the current directory. To see for yourself, you can build a wheel for HTTPie, a command-line HTTP client written in Python, alongside a sdist. Here’s the result of building both types of distributions for the HTTPie package: $ git clone -q git@github.com:jakubroztocil/httpie.git $ cd httpie $ python setup.py -q sdist bdist_wheel $ ls -1 dist/ httpie-2.2.0.dev0-py3-none-any.whl httpie-2.2.0.dev0.tar.gz That’s all it takes. You clone the project, move into its root directory, and then call python setup.py sdist bdist_wheel. You can see that dist/ contains both a wheel and a source distribution. The resulting distributions get put in dist/ by default, but you can change that with the -d/ --dist-dir option. You could put them in a temporary directory instead for build isolation: $ tempdir="$(mktemp -d)" # Create a temporary directory $ file "$tempdir" /var/folders/jc/8_kd8uusys7ak09_lpmn30rw0000gk/T/tmp.GIXy7XKV: directory $ python setup.py sdist -d "$tempdir" $ python setup.py bdist_wheel --dist-dir "$tempdir" $ ls -1 "$tempdir" httpie-2.2.0.dev0-py3-none-any.whl httpie-2.2.0.dev0.tar.gz You can combine the sdist and bdist_wheel steps into one because setup.py can take multiple subcommands: $ python setup.py sdist -d "$tempdir" bdist_wheel -d "$tempdir" As shown here, you’ll need to pass options such as -d to each subcommand. Specifying a Universal Wheel A universal wheel is a wheel for a pure-Python project that supports both Python 2 and 3. There are multiple ways to tell setuptools and distutils that a wheel should be universal. Option 1 is to specify the option in your project’s setup.cfg file: [bdist_wheel] universal = 1 Option 2 is to pass the aptly named --universal flag at the command line: $ python setup.py bdist_wheel --universal Option 3 is to tell setup() itself about the flag using its options parameter: # setup.py from setuptools import setup setup( # .... options={"bdist_wheel": {"universal": True}} # .... ) While any of these three options should work, the first two are used most frequently. You can see an example of this in the chardet setup configuration. After that, you can use the bdist_wheel command as shown previously: $ python setup.py sdist bdist_wheel The resulting wheel will be equivalent no matter which option you choose. The choice largely comes down to developer preference and which workflow is best for you. Building a Platform Wheel (macOS and Windows) Binary distributions are a subset of built distributions that contain compiled extensions. Extensions are non-Python dependencies or components of your Python package. Usually, that means your package contains an extension module or depends on a library written in a statically typed language such as C, C++, Fortran, or even Rust or Go. Platform wheels exist to target individual platforms primarily because they contain or depend on extension modules. With all that said, it’s high time to build a platform wheel! Depending on your existing development environment, you may need to go through an additional prerequisite step or two to build platform wheels. The steps below will help you to get set up for building C and C++ extension modules, which are by far the most common types. On macOS, you’ll need the command-line developer tools available through xcode: $ xcode-select --install On Windows, you’ll need to install Microsoft Visual C++: - Open the Visual Studio downloads page in your browser. - Select Tools for Visual Studio → Build Tools for Visual Studio → Download. - Run the resulting .exeinstaller. - In the installer, select C++ Build Tools → Install. - Restart your machine. On Linux, you need a compiler such as gcc or g++/ c++. With that squared away, you’re ready to build a platform wheel for UltraJSON ( ujson), a JSON encoder and decoder written in pure C with Python 3 bindings. Using ujson is a good toy example because it covers a few bases: - It contains an extension module, ujson. - It depends on the Python development headers to compile ( #include <Python.h>) but is not otherwise overly complicated. ujsonis designed to do one thing and do it well, which is to read and write JSON! You can clone the project from GitHub, navigate into its directory, and build it: $ git clone -q --branch 2.0.3 git@github.com:ultrajson/ultrajson.git $ cd ultrajson $ python setup.py bdist_wheel You should see a whole lot of output. Here’s a trimmed version on macOS, where the Clang compiler driver is used: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g ... ... creating 'dist/ujson-2.0.3-cp38-cp38-macosx_10_15_x86_64.whl' adding 'ujson.cpython-38-darwin.so' The lines starting with clang show the actual call to the compiler complete with a trove of compilation flags. You might also see tools such as MSVC (Windows) or gcc (Linux) depending on the operating system. If you run into a fatal error after executing the above code, don’t worry. You can expand the box below to learn how to deal with this problem. This setup.py bdist_wheel call for ujson requires the Python development header files because ujson.c pulls in <Python.h>. If you don’t have them in a searchable location, then you may see an error such as this one: fatal error: 'Python.h' file not found #include <Python.h> To compile extension modules, you’ll need the development headers saved somewhere your compiler can find them. If you’re using a recent version of Python 3 and a virtual environment tool such as venv, then it’s likely that the Python development headers will be included in compilation and linking by default. If not, then you may see an error indicating that a header file can’t be found: fatal error: 'Python.h' file not found #include <Python.h> In this case, you can tell setup.py where else to look for header files by setting CFLAGS. To find the header file itself, you can use python3-config: $ python3-config --include -I/Users/<username>/.pyenv/versions/3.8.2/include/python3.8 This tells you that Python development headers are located in the directory shown, which you can now use with python setup.py bdist_wheel: $ CFLAGS="$(python3-config --include)" python setup.py bdist_wheel More generally, you can pass any path you need: $ CFLAGS='-I/path/to/include' python setup.py bdist_wheel On Linux, you may also need to install the headers separately: $ apt-get install -y python3-dev # Debian, Ubuntu $ yum install -y python3-devel # CentOS, Fedora, RHEL If you inspect UltraJSON’s setup.py, then you’ll see that it customizes some compiler flags such as -D_GNU_SOURCE. The intricacies of controlling the compilation process through setup.py are beyond the scope of this tutorial, but you should know that it’s possible to have fine-grained control over how the compiling and linking occurs. If you look in dist, then you should see the created wheel: $ ls dist/ ujson-2.0.3-cp38-cp38-macosx_10_15_x86_64.whl Note that the name may vary based on your platform. For example, you’d see win_amd64.whl on 64-bit Windows. You can peek into the wheel file and see that it contains the compiled extension: $ unzip -l dist/ujson-*.whl ... Length Date Time Name --------- ---------- ----- ---- 105812 05-10-2020 19:47 ujson.cpython-38-darwin.so ... This example shows an output for macOS, ujson.cpython-38-darwin.so, which is a shared object ( .so) file, also called a dynamic library. Linux: Building manylinux Wheels As a package developer, you’ll rarely want to build wheels for a single Linux variant. Linux wheels demand a specialized set of conventions and tools so that they can work across different Linux environments. Unlike wheels for macOS and Windows, wheels built on one Linux variant have no guarantee of working on another Linux variant, even one with the same machine architecture. In fact, if you build a wheel on an out-of-the-box Linux container, then PyPI won’t even accept that wheel if you try to upload it! If you want your package to be available across a range of Linux clients, then you want a manylinux wheel. A manylinux wheel is a particular type of a platform wheel that is accepted by most Linux variants. It must be built in a specific environment, and it requires a tool called auditwheel that renames the wheel file to indicate that it’s a manylinux wheel. Note: Even if you’re approaching this tutorial from the developer rather than the user perspective, make sure that you’ve read the section on the manylinux wheel tag before continuing with this section. Building a manylinux wheel allows you to target a wider range of user platforms. PEP 513 specifies a particular (and archaic) version of CentOS with an array of Python versions available. The choice between CentOS and Ubuntu or any other distribution doesn’t carry any special distinction. The point is for the build environment to consist of a stock Linux operating system with a limited set of external shared libraries that are common to different Linux variants. Thankfully, you don’t have to do this yourself. PyPA provides a set of Docker images that give you this environment with a few mouse clicks: - Option 1 is to run dockerfrom your development machine and mount your project using a Docker volume so that it’s is accessible in the container filesystem. - Option 2 is to use a CI/CD solution such as CircleCI, GitHub Actions, Azure DevOps, or Travis-CI, which will pull your project and run the build on an action such as a push or tag. The Docker images are provided for the different manylinux flavors: To get started, PyPA also provides an example repository, python-manylinux-demo, which is a demo project for building manylinux wheels in conjunction with Travis-CI. While it’s common to build wheels as a part of a remote-hosted CI solution, you can also build manylinux wheels locally. To do so, you’ll need Docker installed. Docker Desktop is available for macOS, Windows, and Linux. First, clone the demo project: $ git clone -q git@github.com:pypa/python-manylinux-demo.git $ cd python-manylinux-demo Next, define a few shell variables for the manylinux1 Docker image and platform, respectively: $ DOCKER_IMAGE='quay.io/pypa/manylinux1_x86_64' $ PLAT='manylinux1_x86_64' The DOCKER_IMAGE variable is the image maintained by PyPA for building manylinux wheels, hosted at Quay.io. The platform ( PLAT) is a necessary piece of information to feed to auditwheel, letting it know what platform tag to apply. Now you can pull the Docker image and run the wheel-builder script within the container: $ docker pull "$DOCKER_IMAGE" $ docker container run -t --rm \ -e PLAT=$PLAT \ -v "$(pwd)":/io \ "$DOCKER_IMAGE" /io/travis/build-wheels.sh This tells Docker to run the build-wheels.sh shell script inside the manylinux1_x86_64 Docker container, passing PLAT as an environment variable available in the container. Since you used -v (or --volume) to bind-mount a volume, the wheels produced in the container will now be accessible on your host machine in the wheelhouse directory: $ ls -1 wheelhouse python_manylinux_demo-1.0-cp27-cp27m-manylinux1_x86_64.whl python_manylinux_demo-1.0-cp27-cp27mu-manylinux1_x86_64.whl python_manylinux_demo-1.0-cp35-cp35m-manylinux1_x86_64.whl python_manylinux_demo-1.0-cp36-cp36m-manylinux1_x86_64.whl python_manylinux_demo-1.0-cp37-cp37m-manylinux1_x86_64.whl python_manylinux_demo-1.0-cp38-cp38-manylinux1_x86_64.whl In a few short commands, you have a set of manylinux1 wheels for CPython 2.7 through 3.8. A common practice is also to iterate over different architectures. For instance, you could repeat this process for the quay.io/pypa/manylinux1_i686 Docker image. This would build manylinux1 wheels targeting 32-bit (i686) architecture. If you’d like to dive deeper into building wheels, then a good next step is to learn from the best. Start at the Python Wheels page, pick a project, navigate to its source code (on a place like GitHub, GitLab, or Bitbucket), and see for yourself how it builds wheels. Many of the projects on the Python Wheels page are pure-Python projects and distribute universal wheels. If you’re looking for more complex cases, then keep an eye out for packages that use extension modules. Here are two examples to whet your appetite: lxmluses a separate build script that’s invoked from within the manylinux1Docker container. ultrajsondoes the same and uses GitHub Actions to call the build script. Both of these are reputable projects that offer a great examples to learn from if you’re interested in building manylinux wheels. Building Wheels in Continuous Integration An alternative to building wheels on your local machine is to build them automatically within your project’s CI pipeline. There are myriad CI solutions that integrate with the major code hosting services. Among them are Appveyor, Azure DevOps, BitBucket Pipelines, Circle CI, GitLab, GitHub Actions, Jenkins, and Travis CI, to name just a few. The purpose of this tutorial isn’t to render a judgment as to which CI service is best for building wheels, and any listing of which CI services support which containers would quickly become outdated given the speed at which CI support is evolving. However, this section can help to get you started. If you’re developing a pure-Python package, the bdist_wheel step is a blissful one-liner: it’s largely irrelevant which container OS and platform you build the wheel on. Virtually all major CI services should enable you to do this in a no-frills fashion by defining steps in a special YAML file within the project. For example, here’s the syntax you could use with GitHub Actions: 1name: Python wheels 2on: 3 release: 4 types: 5 - created 6jobs: 7 wheels: 8 runs-on: ubuntu-latest 9 steps: 10 - uses: actions/checkout@v2 11 - name: Set up Python 3.x 12 uses: actions/setup-python@v2 13 with: 14 python-version: '3.x' 15 - name: Install dependencies 16 run: python -m pip install --upgrade setuptools wheel 17 - name: Build wheels 18 run: python setup.py bdist_wheel 19 - uses: actions/upload-artifact@v2 20 with: 21 name: dist 22 path: dist In this configuration file, you build a wheel using the following steps: - In line 8, you specify that the job should run on an Ubuntu machine. - In line 10, you use the - In line 14, you tell the CI runner to use the latest stable version of Python 3. - In line 21, you request that the resulting wheel be available as an artifact that you can download from the UI once the job completes. However, if you have a complex project (maybe one with C extensions or Cython code) and you’re working to craft a CI/CD pipeline to automatically build wheels, then there will likely be additional steps involved. Here are a few projects through which you can learn by example: Many projects roll their own CI configuration. However, some solutions have emerged for reducing the amount of code specified in configuration files to build wheels. You can use the cibuildwheel tool directly on your CI server to cut down on the lines of code and configuration that it takes to build multiple platform wheels. There’s also multibuild, which provides a set of shell scripts for assisting with building wheels on Travis CI and AppVeyor. Making Sure Your Wheels Spin Right Building wheels that are structured correctly can be a delicate operation. For instance, if your Python package uses a src layout and you forget to specify that properly in setup.py, then the resulting wheel might contain a directory in the wrong place. One check that you can use after bdist_wheel is the check-wheel-contents tool. It looks for common problems such as the package directory having an abnormal structure or the presence of duplicate files: $ check-wheel-contents dist/*.whl dist/ujson-2.0.3-cp38-cp38-macosx_10_15_x86_64.whl: OK In this case, check-wheel-contents indicates that everything with the ujson wheel checks out. If not, stdout will show a summary of possible issues much like a linter such as flake8. Another way to confirm that the wheel you’ve built has the right stuff is to use TestPyPI. First, you can upload the package there: $ python -m twine upload \ --repository-url \ dist/* Then, you can download the same package for testing as if it were the real thing: $ python -m pip install \ --index-url \ <pkg-name> This allows you to test your wheel by uploading and then downloading your own project. Uploading Python Wheels to PyPI Now it’s time to upload your Python package. Since a sdist and a wheel both get put in the dist/ directory by default, you can upload them both using the twine tool, which is a utility for publishing packages to PyPI: $ python -m pip install -U twine $ python -m twine upload dist/* Since both sdist and bdist_wheel output to dist/ by default, you can safely tell twine to upload everything under dist/ using a shell wildcard ( dist/*). Conclusion Understanding the pivotal role that wheels play in the Python ecosystem can make your life easier as both a user and developer of Python packages. Furthermore, increasing your Python literacy when it comes to wheels will help you to better understand what’s happening when you install a package and when, in increasingly rare cases, that operation goes awry. In this tutorial, you learned: - What wheels are and how they compare to source distributions - How you can use wheels to control the package installation process - What the differences are between universal, pure-Python, and platform wheels - How to create and distribute wheels for your own Python packages You now have a solid understanding of wheels from both a user’s and a developer’s perspective. You’re well equipped to build you own wheels and make your project’s installation process quick, convenient, and stable. See the section below for some additional reading to dive deeper into the rapidly-expanding wheel ecosystem. Resources The Python Wheels page is dedicated to tracking support for wheels among the 360 most downloaded packages on PyPI. The adoption rate is pretty respectable at the time of this tutorial, at 331 out of 360, or around 91 percent. There have been a number of Python Enhancement Proposals (PEPs) that have helped with the specification and evolution of the wheel format: - PEP 425 - Compatibility Tags for Built Distributions - PEP 427 - The Wheel Binary Package Format 1.0 - PEP 491 - The Wheel Binary Package Format 1.9 - PEP 513 - A Platform Tag for Portable Linux Built Distributions - PEP 571 - The manylinux2010Platform Tag - PEP 599 - The manylinux2014Platform Tag Here’s a shortlist of the various wheel packaging tools mentioned in this tutorial: pypa/wheel pypa/auditwheel pypa/manylinux pypa/python-manylinux-demo jwodder/check-wheel-contents matthew-brett/delocate matthew-brett/multibuild joerick/cibuildwheel The Python documentation has several articles covering wheels and source distributions: Finally, here are a few more useful links from PyPA:
https://realpython.com/python-wheels/
CC-MAIN-2021-17
refinedweb
7,271
62.98
I’m trying to write an exporter, and I’m having problems figuring out how to loop through all actions in code to be able to export the bone poses. I can get each action from context.blend_data.actions, but this only gives me the individual F-curves. If I want to get the individual bone poses, I can loop through each frame and look at the posebones at each frame. However, I can’t figure out how to do this for each action, only the current action. I’m looking through the API documentation and I can’t find how to do this, the closest I can is each datablock stores its animdata which in turn stores the action, but it’s all read only and I can’t change it. Any ideas, or will I have to resort to manually changing the action and exporting each pose to a different file, as I’ve seen in some other exporters? I don’t think my intent was clear. Basically, what I’m trying to do is output the bone pose at each frame marker, using the following code: for i in range(int(start), int(end+1)): bpy.ops.anim.change_frame(frame = i) for posebone in armature.pose.bones: do something to output the pose here However, this only works on the current action. For example, say I have a run cycle and a walk cycle, and I want to export them both. Right now, I have no way of switching between the run and walk action, so whichever one I have selected in the action editor is the one that gets outputted. I can switch between run and walk and run the script once for each time, creating two files, but I’d like to be able to do it in one call of the script. However, one thing I realized after I wrote the initial post is that even for one action at a time, my code isn’t working. The pose doesn’t get updated when I change the frame, so it outputs whatever the value of the pose is when the script is run. I know it’s correctly changing the frame because after the script is run, the frame number is set to whatever the end frame should be, and if I going into the console and print the rotation_quaternions for the posebones after running the script, the pose values have changed. For whatever reason though, the posebones remain the same as what they were before the loop was run. Anyone have ideas why this is happening? for the last question you could try bpy.context.scene.frame_set(frame) instead and see if it works…? Thanks liero, that fixed that issue Doesn’t seem like anyone knows how to do this, so I’ll give this one final bump. If it helps any, the tool tip that pops up when I manually switch actions says “Browse action to be linked”, but unlike virtually every other button, it doesn’t give the underlying python command as a subtitle. Searching through the API documentation, I’ve been unable to find any way to link an action. try this… import bpy for a in bpy.context.screen.areas: if a.type == 'DOPESHEET_EDITOR': x = a.spaces.active z = bpy.data.actions.get('CubeAction') x.action = z or this… import bpy a = bpy.context.area.type bpy.context.area.type = 'DOPESHEET_EDITOR' x = bpy.context.area.spaces.active x.action = bpy.data.actions.get('CubeAction') bpy.context.area.type = a I’m kind of going through the same thing only with a camera animated via constraints. Anyone have ideas why this is happening? Are you applying the world matrix to the bone? That solved my problem, applying the world_matrix. Here are a couple new defs I put together to deal with actions if you know their name. def fetchIfAction (passedName= ""): try: result = bpy.data.actions[passedName] except: result = None return result def fetchFcurveFromAction (passedAction, passedName= ""): try: result = passedAction.fcurves[passedName] except: result = None return result Thanks everyone for your help, you’ve solved my problem. My final code, for those interested: original_area_type = bpy.context.area.type for action in bpy.data.actions: a = bpy.context.area a.type = "DOPESHEET_EDITOR" x = bpy.context.area.active_space x.action = action bpy.context.area.type = "VIEW_3D" bpy.ops.object.mode_set(mode="POSE") bpy.ops.pose.select_all(action="SELECT") bpy.ops.pose.transforms_clear() bpy.ops.screen.frame_jump() start = context.scene.frame_current bpy.ops.screen.frame_jump(end=True) end = context.scene.frame_current for frame in range(int(start), int(end+1)): bpy.context.scene.frame_set(frame) for posebone in parent.pose.bones: #DO YOUR EXPORTING HERE bpy.context.area.type = original_area_type Alright, one final thing. I thought I had it solved, and it was working, but now it seems to have broken, and I have no idea why since I haven’t changed anything. What’s happening is that the x.action = action line isn’t doing anything, x.action is a NoneType and remains so. If I copy that code verbatim from my export file and just run it inside a text file, it works perfectly. So the action never gets changed, and instead of exporting all actions, it only exports the action that the action editor had initially loaded, albeit over and over again for as many actions as there are. I’m baffled by this. I ma not getting what exactly this coding is all about ?
https://blenderartists.org/t/how-to-change-the-active-action/509441
CC-MAIN-2021-10
refinedweb
913
66.23
We know that the MAC address is a hardware address which means it is unique for the network card installed on our PC. It is always unique that means no two devices on a local network could have the same MAC addresses. The main purpose of MAC address is to provide a unique hardware address or physical address for every node on a local area network (LAN) or other networks. A node means a point at which a computer or other device (e.g. a printer or router) will remain connected to the network. Using uuid.getnode() In this example getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module. import uuid print (hex(uuid.getnode())) 0x242ac110002L Using getnode() + format() [ This is for better formatting ] import uuid # after each 2 digits, join elements of getnode(). print ("The formatted MAC address is : ", end="") print (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff) for elements in range(0,2*6,2)][::-1])) The formatted MAC address is : 3e:f8:e2:8b:2c:b3 Using getnode() + findall() + re()[ This is for reducing complexity] import re, uuid # after each 2 digits, join elements of getnode(). # using regex expression print ("The MAC address in expressed in formatted and less complex way : ", end="") print (':'.join(re.findall('..', '%012x' % uuid.getnode()))) The MAC address in expressed in formatted and less complex way : 18:5e:0f:d4:f8:b3
https://www.tutorialspoint.com/extracting-mac-address-using-python
CC-MAIN-2021-17
refinedweb
239
63.29
Nudged elastic band¶ ‘Classical and Quantum Dynamics in Condensed Phase Systems’, edited by B. J. Berne, G. Cicotti, and D. F. Coker, World Scientific, 1998 [standard formulation] - ‘Improved Tangent Estimate in the NEB method for Finding Minimum Energy Paths and Saddle Points’, G. Henkelman and H. Jonsson, J. Chem. Phys. 113, 9978 (2000) [improved tangent estimates] - ‘A Climbing-Image NEB Method for Finding Saddle Points and Minimum Energy Paths’, G. Henkelman, B. P. Uberuaga and H. Jonsson, J. Chem. Phys. 113, 9901 (2000) - ‘Improved initial guess for minimum energy path calculations.’, S. Smidstrup, A. Pedersen, K. Stokbro and H. Jonsson, J. Chem. Phys. 140, 214106 (2014) The NEB class¶ This module defines one class: - class ase.neb. NEB(images, k=0.1, climb=False, parallel=False, remove_rotation_and_translation=False, world=None, method='aseneb')[source]¶ Nudged elastic band. Paper I: - Henkelman and H. Jonsson, Chem. Phys, 113, 9978 (2000). Paper II:G. Henkelman, B. P. Uberuaga, and H. Jonsson, Chem. Phys, 113, 9901 (2000). Paper III:E. L. Kolsbjerg, M. N. Groves, and B. Hammer, J. Chem. Phys, submitted (2016) - images: list of Atoms objects - Images defining path from initial to final state. - k: float or list of floats - Spring constant(s) in eV/Ang. One number or one for each spring. - climb: bool - Use a climbing image (default is no climbing image). - parallel: bool - Distribute images over processors. - remove_rotation_and_translation: bool - TRUE actives NEB-TR for removing translation and rotation during NEB. By default applied non-periodic systems - method: string of method Choice betweeen three method: - aseneb: standard ase NEB implementation - improvedtangent: Paper I NEB implementation - eb: Paper III full spring force implementation Example of use, between initial and final state which have been previously saved in A.traj and B.traj: from ase import io from ase.neb import NEB from ase.optimize import MDMin # Read initial and final states: initial = io.read('A.traj') final = io.read('B.traj') # Make a band consisting of 5 images: images = [initial] images += [initial.copy() for i in range(3)] images += [final] neb = NEB(images) # Interpolate linearly the potisions of the three middle images: neb.interpolate() # Set calculators: for image in images[1:4]: image.set_calculator(MyCalculator(...)) # Optimize: optimizer = MDMin(neb, trajectory='A2B.traj') optimizer.run(fmax=0.04) Be sure to use the copy method (or similar) to create new instances of atoms within the list of images fed to the NEB. Do not use something like [initial for i in range(3)], as it will only create references to the original atoms object. Notice the use of the interpolate() method to obtain an initial guess for the path from A to B. Interpolation¶ NEB. interpolate('idpp')[source] From a linear interpolation, create an improved path from initial to final state using the IDPP approach [4]. NEB. idpp_interpolate()[source]¶ Generate an idpp pathway from a set of images. This differs from above in that an initial guess for the IDPP, other than linear interpolation can be provided. Only the internal images (not the endpoints) need have calculators attached. See also ase.optimize: - Information about energy minimization (optimization). Note that you cannot use the default optimizer, BFGSLineSearch, with NEBs. (This is the optimizer imported when you import QuasiNewton.) If you would like a quasi-newton optimizer, use BFGS instead. ase.calculators: - How to use calculators. Note If there are \(M\) images and each image has \(N\) atoms, then the NEB object behaves like one big Atoms object with \(MN\) atoms, so its get_positions() method will return a \(MN \times 3\) array. Trajectories¶ The code: from ase.optimize import BFGS opt = BFGS(neb, trajectory='A2B.traj') will write all images to one file. The Trajectory object knows about NEB calculations, so it will write \(M\) images with \(N\) atoms at every iteration and not one big configuration containing \(MN\) atoms. The result of the latest iteration can now be analysed with this command: ase gui A2B.traj@-5:. For the example above, you can write the images to individual trajectory files like this: for i in range(1, 4): opt.attach(io.Trajectory('A2B-%d.traj' % i, 'w', images[i])) The result of the latest iteration can be analysed like this: $ ase gui A.traj A2B-?.traj B.traj -n -1 Climbing image¶). To use the climbing image NEB method, instantiate the NEB object like this: neb = NEB(images, climb=True) Note Quasi-Newton methods, such as BFGS, are not well suited for climbing image NEB calculations. FIRE have been known to give good results, although convergence is slow. Parallelization over images¶ Some calculators can parallelize over the images of a NEB calculation. The script will have to be run with an MPI-enabled Python interpreter like GPAW’s gpaw-python. All images exist on all processors, but only some of them have a calculator attached: from ase.parallel import rank, size from ase.calculators.emt import EMT # Number of internal images: n = len(images) - 2 j = rank * n // size for i, image in enumerate(images[1:-1]): if i == j: image.set_calculator(EMT()) Create the NEB object with NEB(images, parallel=True). For a complete example using GPAW, see here. Analysis of output¶ A class exists to help in automating the analysis of NEB jobs. See the Diffusion Tutorial for some examples of its use. - class ase.neb. NEBTools(images)[source]¶ Class to make many of the common tools for NEB analysis available to the user. Useful for scripting the output of many jobs. Initialize with list of images which make up a single band. get_barrier(fit=True, raw=False)[source]¶ Returns the barrier estimate from the NEB, along with the Delta E of the elementary reaction. If fit=True, the barrier is estimated based on the interpolated fit to the images; if fit=False, the barrier is taken as the maximum-energy image without interpolation. Set raw=True to get the raw energy of the transition state instead of the forward barrier.
https://wiki.fysik.dtu.dk/ase/dev/ase/neb.html
CC-MAIN-2018-39
refinedweb
989
50.02
In this assignment, you'll be using QIIME 2 version 2019.1 to analyze two data sets. First, you'll read and complete the QIIME 2 Moving Pictures of the Human Microbiome tutorial, which contains a few thousand sequences from four different human body sites collected over a few days. This will familiarize you with running QIIME 2 through the Jupyter Notebook, and interpreting QIIME 2 output. You'll then adapt the commands from that tutorial to analyze a real-world data set, where human-associated microbial communities were shown to have forensic potential, potentially allowing investigators to determine who touched an object based on the "microbial fingerprint" they leave behind. Before starting this assignment, you should read Fierer et al (2010), where this forensic study was initially published. This will help you understand the study. Then, as you work through the assignment, any time you use a QIIME 2 command you should either look up that command in the QIIME 2 plugin index, or call it with its --help parameter to understand what it does and how to use it. IMPORTANT: This assignment includes some steps that will take some time to run (possibly up to 20 minutes). You should avoid starting this assignment close to the deadline as the server may be slow at that time if a lot of people are running their analyses at the last minute. You are responsible for starting this in a timely manner! If your assignment is late because it did not complete in time, that is your fault, not ours! The QIIME 2 Moving Pictures of the Human Microbiome illustrates how to use QIIME 2 through the command line interface, or in other words using bash shell commands. To run the commands in the Jupyter Notebook, you can preface each command with an !. For example, to run the bash shell command ls through the Jupyter Notebook, you would do the following: !ls ls For example, you need to be familiar with the bash shell commands ls, cd, and pwd. Use the cells below to be sure you understand how to navigate around the file system and ensure you are in the right place to run your code. pwd shows you your current working directory. pwd ls shows you what files and directories are in your current working directory. ls cd allows you to change to a directory. cd .. allows you to change out of the directory that you're currently in to the directory that contains the directory that you're currently in. In the cells below use ls to find a directory. (If you don't have one, run mkdir test-dir to create a new directory called test-dir.) cd into that directory, run ls to view the files and directories it contains (if any), and then return to the original directory using cd ... Finally, run pwd to show that you are back where you started. If you're comfortable with Python 3 programming, you may want to use the QIIME 2 Aritfact API instead of the command line interface for running QIIME 2 in the Jupyter Notebook. This is a bit underdocumented at the moment however, so if you're not comfortable with Python 3 you should stick with running the bash shell commands for this assignment. You can use an sftp client to connect to the Jupyter server. We recommend using Cyberduck, which is free and works well on macOS, Windows, and Linux. However, if you have an sftp client that you're already comfortable with, it should work fine for this. QIIME 2 results are always in .qza or .qzv files, which you can learn about by reading QIIME 2 core concepts. You can view .qza and .qzv files at view.qiime2.org. To do this, you'll: .qzaor .qzvfile using either the scp command or an sftp client; .qzaor .qzvfile from your computer to the view.qiime2.org. Start reading the QIIME 2 Moving Pictures of the Human Microbiome, which will introduce you to using QIIME 2, and will teach you about the commands that you'll need to complete parts 2 and 3 of this assignment. Begin by running the commands in the Sample metadata section of the tutorial in this Jupyer Notebook. When downloading files, you should use either the wget or curl options. The first few commands will look like the following. First, you'll download the sample metadata using the wget command. Then, view the resulting file by downloading it from the Jupyter server. Before downloading, make sure you understand where you are on the file system because that is where files will be downloaded to. Use the pwd command to find your current working directory. pwd wget -O "sample-metadata.tsv" "" Next, create a directory and download the two sequence data files to that directory. mkdir emp-single-end-sequences wget -O "emp-single-end-sequences/barcodes.fastq.gz" "" wget -O "emp-single-end-sequences/sequences.fastq.gz" "" Now, we'll load the QIIME 2 program so we can run the QIIME 2 commands. Note: If you are disconnected from the notebook, you will need to rerun this command and change to the directory that you're working in to continue your analyses. module load qiime2/2019.1 You can now run your first QIIME 2 command, which will import the sequence data that we just downloaded into a QIIME 2 artifact. qiime tools import \ --type EMPSingleEndSequences \ --input-path emp-single-end-sequences \ --output-path emp-single-end-sequences.qza Try downloading the resulting .qza file, and then uploading it to view.qiime2.org. You'll primarily use view.qiime2.org to view QIIME 2 visualizations (i.e., .qzv files), but take a minute to look at the Provenance tab for the emp-single-end-sequences.qza artifact on view.qiime2.org. This provides information on all of the QIIME 2 commands that were run to get to this artifact, as well as some additional information. For example, you can see how long each command took to run. How long did the import command take to run? Work through the rest of the Moving Pictures of the Human Microbiome tutorial in this notebook. As you go, answer the questions that are presented in the tutorial. (You don't need to turn those answers in, but spending time on them now will make parts 2 and 3 of this assignment simple.) Next, you'll adapt the commands above to perform another analysis and answer some questions. The commands will be largely the same as above, but adapted to the following data files. Note: you will not need to run the bioenv or ancom steps of the Moving Pictures Tutorial to answer the questions for parts 2 or 3 of this assignment. You should begin by creating a new directory for your new data set. It is reccommended that you name this directory forensic to set it apart from your moving pictures data. mkdir forensic To work with files that you create in the forensic directory, you'll generally want to be in that directory. If you get error messages indicating things like "no such file or directory", or "file not found", you are most likely in the wrong directory. cd forensic Use these commands to get the appropriate files for your analysis. wget -O "forensic-rep-seqs.qza" wget -O "forensic-table.qza" wget -O "forensic-sample-metadata.tsv" You will need a different trained feature classifier to assign taxonomy to the forensic data. Use the command below to download that classifier. Note you must change the classifer .qza file that is being provided to the qiime feature-classifier classify command to be the classifier that you are downloading here. wget -O "gg-13-8-99-full-length-nb-classifier.qza" "" Answer all of the questions below in the notebook, and turn in a copy of your notebook along with the qzv files that support each answer. In each answer, mention which qzv file(s) that you've turned in support your answer. All of these questions refer to the forensic data set, not the moving pictures data set! Question 1: What was the minimum number of sequences per sample? What was the maximum number of sequences per sample? What even sampling depth did you choose when running qiime diversity core-metrics, and why? Answer Question 1 in this cell. Question 2: How long did qiime alignment mafft take to run (to the microsecond)? Review any of the produced artifacts' or visualizations' Provenace to find that information. How long did qiime phylogeny fasttree take to run (to the microsecond)? Answer Question 2 in this cell. Question 3: The focus of the Fierer 2010 paper was to show that it is possible to match an individual to the objects they touch based on the microbial communities that the individual leaves behind. Based on your analysis results, match the individuals to the keyboard they touched, and explain how you came to this answer. There is one right answer to this question, and you should support your answer with references to more than one .qzv file. Answer Question 3 in this cell. To turn in: .qzvfiles referenced in your answers to Part 2: Questions. This section will focus on working with the results generated by the commands that you ran above. For this section, you will write a 2.5 to 3 page paper describing your analysis. Your paper should not be any shorter than 2.5 pages nor any longer than 3 pages. It must have 1.5 line spacing, 1.25" margins, and be written in 12 point Times New Roman font. Figures and tables are included in the page count, though the total space taken by these should be a maximum of one page. Write this as if you’re submitting to a journal, so your paper should contain: You should address several specific questions in your Results and Conclusions:
https://nbviewer.jupyter.org/github/gregcaporaso/2017.04-bio450-qiime2-assignment/blob/master/qiime2-assignment.ipynb
CC-MAIN-2019-26
refinedweb
1,659
65.32
/* * OutputElement>OutputElement</code> object represents an XML element. * Attributes can be added to this before ant child element has been * acquired from it. Once a child element has been acquired the * attributes will be written an can no longer be manipulated, the * same applies to any text value set for the element. * * @author Niall Gallagher */ class OutputElement implements OutputNode { /** * Represents the attributes that have been set for the element. */ private OutputNodeMap table; * This is the namespace map that contains the namespaces. */ private NamespaceMap scope; * Used to write the start tag and attributes for the document. private NodeWriter writer; * This is the parent XML element to this output node. */ private OutputNode parent; * This is the namespace reference URI associated with this. private String reference; * This is the comment that has been set on this element. private String comment; * Represents the value that has been set for the element. private String value; * Represents the name of the element for this output node. private String name; * This is the output mode that this element object is using. private Mode mode; * Constructor for the <code>OutputElement</code> object. This is * used to create an output element that can create elements for * an XML document. This requires the writer that is used to * generate the actual document and the name of this node. * * @param parent this is the parent node to this output node * @param writer this is the writer used to generate the file * @param name this is the name of the element this represents public OutputElement(OutputNode parent, NodeWriter writer, String name) { this.scope = new PrefixResolver(parent); this.table = new OutputNodeMap(this); this.mode = Mode.INHERIT; this.writer = writer; this.parent = parent; this.name = name; } * This is used to acquire the prefix for this output node. This * will search its parent nodes until the prefix that is currently * in scope is found. If a prefix is not found in the parent * nodes then a prefix in the current nodes namespace mappings is * searched, failing that the prefix returned is null. * @return this returns the prefix associated with this node */ public String getPrefix() { return getPrefix(true); } *. * @param inherit if there is no explicit prefix then inherit public String getPrefix(boolean inherit) { String prefix = scope.getPrefix(reference); if(inherit) { if(prefix == null) { return parent.getPrefix(); } } return prefix; * public String getReference() { return reference; * public void setReference(String reference) { this.reference = public NamespaceMap getNamespaces() { return scope; * OutputNode getParent() { return parent; * Returns the name of the node that this represents. This is * an immutable property and cannot be changed. This will be * written as the tag name when this has been committed. * * @return returns the name of the node that this represents */ public String getName() { return name; * Returns the value for the node that this represents. This * is a modifiable property for the node and can be changed, * however once committed any change will be irrelevant. * * @return the name of the value for this node instance public String getValue() {() { return writer.isRoot(this); * */ public OutputNodeMap getAttributes() { return table; *; * This is used to set a text value to the element. This should * be added to the element if the element contains no child * elements. If the value cannot be added an exception is thrown. * @param value this is the text value to add to this element public void setValue(String value) { this.value = will return the attribute that was just set public OutputNode setAttribute(String name, String value) { return table.put(name, value); * { writer.remove(this); * public void commit() throws Exception{ writer.commit(this); * This is used to determine whether this node has been committed. * If the node is committed then no further child elements can * be created from this node instance. A node is considered to * be committed if a parent creates another child element or if * the <code>commit</code> method is invoked. * @return true if the node has been committed public boolean isCommitted() { return writer.isCommitted(this); * This is the string representation of the element. It is * used for debugging purposes. When evaluating the element * the to string can be used to print out the element name. * @return this returns a text description of the element public String toString() { return String.format("element %s", name); }
http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.stream.OutputElement.html
CC-MAIN-2018-05
refinedweb
699
57.87
> On Sun, Aug 21, 2011 at 04:53:19PM +0200, Vitor Sessak wrote: > %macro BUTTERF 3 > movhlps %2, %1 > movlhps %2, %1 pshufd would reduce number of uops, although I haven't checked what it would do to number of uops on the bottlenecked execution unit(s) or latency. > xorps %2, [ps_p1p1m1m1] Can you xorps %1 instead to reduce dependency chain? > addps %1, %2 > mulps %1, %3 > mova %2, %1 > shufps %1, %1, 0xb1 pshufd again > xorps %2, [ps_p1m1p1m1] > addps %1, %2 > %endmacro > %macro SWAP_64BITS 2 > %ifdef ARCH_X86_64 > SWAP %1, %2 > %endif > %endmacro What good is this doing? There's no %else, so the code must also work (with no extra instructions) if you don't swap...? A bunch of mova (maybe all of them) could be eliminated in avx. On Sat, 27 Aug 2011, Michael Niedermayer wrote: > The main optimization i see is to interleave a few blocks so as to > simplify the shuffling of data Agreed. --Loren Merritt
http://ffmpeg.org/pipermail/ffmpeg-devel/2011-August/114231.html
CC-MAIN-2015-06
refinedweb
160
70.77
Definition of Python Object to String Python object in python refers to the object which is used by the other functions in order to get the direct conversion of one data type present within the object into another data type present in the other object. Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string. Syntax: Initialize an object first : an_obj = 5; Need to perform Typecasting in order to get the object for converting into a string. object_strng = str(an_obj) Convert `an_obj` to a string Need to print the object for getting the details about the data type present within the object. print(object_strng) Need to make the final casting into object_strng for getting the final value of string. print(type(object_strng)) How to Convert Object to String in Python? There are ways to convert object into string in Python with some of the rules and regulations. The working flow includes many of the constraints as mentioned: - Python is a programming language which mainly deals and play around with objects. - Conversion of an object to string in Python plays a pivotal role in determining the object data type and string present within the object. - It comprises many in build functions that are exclusively used for converting the object into string in Python. - It mainly makes use of objects that need to be used for overloading or manipulation with respect to values present within the object or field value. - If while assigning variable it gets concatenated with the extra variable, then it will throw a typo error based on which the rectification needs to be performed. - Also, if in case direct a value has been assigned to a variable then it will get executed successfully as by default the value considered is an integer type. - Some cases also include object gets converted into a string with the help of str() method present in the Python library. - Another way to convert object into string is using repr() method which comes into the picture whenever there is some type of complex object that needs to be decoded and get the string value with the custom methods as well. - There are times when developers need to get the complex object to be dealt with at that scenario retrieving the string value from the object and then return the value as per requirement. - Simultaneous type casting also plays a significant role in conversion of object to string in the sense that the objects containing data type in one format cannot be used to retrieve the value as required from the other object. Thus, the need is to get the actual value as per requirement. - Overloading of the string class also needs to be taken care of as an aspect when object present is in terms of objects present within the class. -. Parameters by default includes encoding or encoded value and errors that specifies what needs to be done in case encoding fails. Examples Let us discuss examples of Python Object to String. Example #1 This program demonstrates the conversion of a variable being assigned with an integer directly into the string type object as shown. With an error which says that if in case the variable assigned includes text will result in a type error. Code: var_t = 8 print(var_t) Output: Example #2 This program demonstrates the code where if we incorporate the string with an object and then perform a typecast it will return the required string from the object defined as shown in the output. Code: var_w = 9 print('I am trying-to convert ' + str(var_w) + ' into_String object.') Output: Example #3 This program demonstrates the conversion of object to string using str() method as shown in the output. Code: int_a = 9 float_c = 9.3 str_2 = str(int_a) print(str_2) print(type(str_2)) str_4= str(float_c) print(str_4) print(type(str_4)) Output: Example #4 This program demonstrates the conversion of a class Object into a String with memory address and assignment of object with object name as shown in the output but still, it needs to get converted by typecasting it into a proper object. Code: class Car: name = "" model = 0 def __init__(self, car_name, car_model): self.name = car_name self.model = car_model c = Car('BMW', 250) print(c) Output: Example #5 This program demonstrates the conversion of object to string and based on that overloading of the string function is performed as shown in the output. Code: class Car: name = "" model = 0 def __init__(self, car_name, car_model): self.name = car_name self.model = car_model def __str__(self): return self.name + ' is with ' + str(self.model) + ' model name.' c = Car('Prsche', 435) print(c) Output: Example #6 This program demonstrates the repr() method for conversion of an object to string as shown in the output. Mostly it will contain complex and custom objects to be decoded into string. Code: print(repr({"a_0": 2, "b_0": 3})) print(repr([4, 6, 8])) class Clss(): def __repr__(self): return "This is a custom Clss" print(repr(Clss())) Output: Conclusion A conclusion can be made with the fact that objects in python play a vital role as it contains all the necessary information regarding the class and once decoded gives the string format of the entire details which gives an overview about the actual class and its implementation. Str() method in python plays an important role whenever it is needed to be retrieved with the value. Recommended Articles This is a guide to Python Object to String. Here we also discuss the Definition and How Convert Object to String in Python? along with different examples and its code implementation. You may also have a look at the following articles to learn more –
https://www.educba.com/python-object-to-string/?source=leftnav
CC-MAIN-2021-39
refinedweb
986
59.03
#include <berryState.h> A piece of state information that can be shared between objects, and might be persisted between sessions. This can be used for commands that toggle between two states and wish to pass this state information between different handlers. This state object can either be used as a single state object shared between several commands, or one state object per command – depending on the needs of the application. Clients may instantiate or extend this class. Definition at line 42 of file berryState.h. Adds a listener to changes for this state. Definition at line 18 of file berryState.cpp. References berry::IStateListener::Events::AddListener(), and stateEvents. Definition at line 23 of file berryState.cpp. References berry::Message2< T, U, A >::AddListener(), berry::IStateListener::Events::stateChanged, and stateEvents. Notifies listeners to this state that it has changed in some way. Definition at line 38 of file berryState.cpp. References berry::IStateListener::Events::stateChanged, and stateEvents. Referenced by SetValue(). Returns the identifier for this state. null. Definition at line 43 of file berryState.cpp. The current value associated with this state. This can be any type of object, but implementations will usually restrict this value to a particular type. Definition at line 48 of file berryState.cpp. Removes a listener to changes from this state. Definition at line 28 of file berryState.cpp. References berry::IStateListener::Events::RemoveListener(), and stateEvents. Definition at line 33 of file berryState.cpp. References berry::Message2< T, U, A >::RemoveListener(), berry::IStateListener::Events::stateChanged, and stateEvents. Sets the identifier for this object. This method should only be called by the command framework. Clients should not call this method. Definition at line 53 of file berryState.cpp. Sets the value for this state object. Definition at line 58 of file berryState.cpp. References FireStateChanged(). Definition at line 113 of file berryState.h. Referenced by AddListener(), FireStateChanged(), and RemoveListener().
http://docs.mitk.org/nightly/classberry_1_1State.html
CC-MAIN-2020-16
refinedweb
312
54.08
Deploying Managed Code Applies To: Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012 Visual Studio Tools lets developers automatically deploy the output of their managed code projects. For example, if you have a class library project, deployment involves copying the assembly to the correct locations. To enable the deployment features, you must first add your project to the model store in Microsoft Dynamics AX. For more information, see Adding a Visual Studio Project to the AOT and How to: Add a Visual Studio Project to the AOT. This topic describes how the deployment of managed code for Microsoft Dynamics AX works. For more information about how to deploy code, see How to: Configure Deployment of Managed Code Assemblies. The general sequence of events for deploying managed code is as follows: Build the project and add it to the model store. Set the deployment properties for the project. Right-click the project and then click Deploy. When the managed code is actually deployed depends on the deployment options that you select. Project Properties for Deployment After you add a project to the Application Object Tree (AOT), project properties are enabled that let you define where the project should be deployed. Deploy to Server Deploy to Client Deploy to EP The managed code deployment properties are available at the project level. To view these properties in Visual Studio, select the project in Solution and Explorer and then click View > Properties Window. Tip Not all deployment properties are available for all project types. For example, Enterprise Portal Web projects and SSRS projects do not have any deployment properties. The system will automatically deploy the output of those projects to the appropriate locations. Deploy to Server When you add a managed code project to the model store, the project files (including the source code) as well as the output, are stored in the model store. If the Deploy to Server property is set to Yes, the system deploys the project output (a DLL, for example) by copying it to the server Bin directory. The server Bin directory could be located at C:\Program Files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\Bin\VSAssemblies\. After you deploy the assembly to the server, you must restart the AOS. This is so that the assembly can be loaded by the AOS. If you have hot swapping enabled, you do not have to restart the AOS. Assemblies are deployed to the server based on how you configure hot swapping. Hot swapping should only be enabled in development scenarios. For more information, see How to: Enable Hot Swapping of Assemblies. Deploy to Client When you add a managed code project to the model store, the project files as well as the output, are stored in the model store. If the Deploy to Client property is set to Yes, the system deploys the project output (a DLL, for example) by copying it to the client Bin directory. The client Bin directory could be located at C:\Users\ <YourUserName> \AppData\Local\Microsoft\Dynamics AX\VSAssemblies\. When you deploy to the client, the assembly is copied to the client the first time it is needed. If you deploy an assembly and you want it to download to a client computer, you must first close the client (if it is open), deploy the assembly, and then start the client again. When the assembly is needed by code running on the client, it is downloaded to the client computer. An assembly is copied to the client under these circumstances: When a call is made from the client to managed code that is contained in the assembly. When you access IntelliSense (at design time). When you compile code that references the managed code assembly. Deploy to Enterprise Portal If the Deploy to EP property is set to Yes, the system deploys the compiled project output to the Bin folder for the Enterprise Portal server. Typically, the Bin folder is located here: C:\intetpub\wwwroot\wss\VirtualDirectorys\80\ If the Deploy to EP property is set to Proxies, only the .cs files for the project are deployed to the Proxies folder within the App_Code folder for the Enterprise Portal server. Typically, the App_Code folder is located here: C:\intetpub\wwwroot\wss\VirtualDirectories\80\ Deploying only the .cs files is the standard practice for deploying proxies to Enterprise Portal, because it reduces the chance of namespace issues when you use objects from the proxy. Use the Deploy command in Visual Studio to deploy the proxies or compiled assembly for the managed code to the Enterprise Portal server. The AxUpdatePortal utility can also be used to deploy the files. Important When creating a proxy project to use with Enterprise Portal, the default namespace is important. In Solution Explorer, right-click the project and then click Properties. Display the Application properties. Set the Default namespace to: Microsoft.Dynamics.Portal.Application.Proxy and save the changes. See also Adding a Visual Studio Project to the AOT How to: Add a Visual Studio Project to the AOT Feedback
https://docs.microsoft.com/en-us/dynamicsax-2012/developer/deploying-managed-code
CC-MAIN-2019-30
refinedweb
843
62.38
Hello, I am samith. I am interested to learn about OSM editing. Normally OSM satellite map is not a higher resolution image. So, I have difficulty to digitize buildings with higher accuracy. So, I got a new Lidar image with 1 m resolution. That image is a georeferenced image. Now I want to import that image into OSM. then I can take good resolution and good accuracy of the building layer. Plz explain the process that we can import our images into OSM asked 09 Mar '20, 06:28 Samith Madus... 11●1●1●1 accept rate: 0% Hello, first we do not import imagery in OpenStreetMap, we use it as a background layer to trace data. Second, when you buy a license to use an image, you don't necessarily buy to right to do everything with it, I think you should check that. One of the most tricky point is that people sell OSM data, and the license allow this. So they will sell data coming from your interpretation of this imagery. I see three results possible : If 1., then I think you best bet would be to upload it to OpenAerialMap, so that anybody will be able to use it also. This platform is meant for UAV imagery, but I think Lidar could fit as well. There might be other platforms. If 2., the problem is that you'll be able to trace from your imagery, but nobody will be able to check your work. If you use it to fine-tune geometry of objects visible on other imagery, that should be fine. But if you add objects, other people might delete them. Disclaimer, I'm no lawyer, I might be wrong on my interpretation of the license. If you need help for the technical part, please tell at least the file format of your data. JOSM should be able to open most geo-referenced image, for example with this plugin. Regards. answered 09 Mar '20, 17:16 H_mlet 3.1k●12●49 accept rate: 14% Realy appreciate your valuable answer sir. The format of the image is tif. it is a georeferenced Lidar image. i want to use it as a background image to edit map. Plz, guide me to know this process, sir. Are you familiar with JOSM ? You can use the previously mentioned plugin if your tif is not WGS84. Otherwise, I think you just have to open your file with JOSM, and it will load as a background layer. Unfortunately I don't have access to geotiff files, so I can't test. If you can share a sample of your files, or one of the same source, it would be easier to help you. Best regards. You will need permissions from the owners of the images before they can used for OSM mapping see answered 09 Mar '20, 09:02 andy mackey 12.5k●80●134●274 accept rate: 4% Yes. I have bought it Sir. I have ownership of that. But I can not sell it again. Then how I can import it. That may not be good enough. But hopefully it is. Someone with better legal knowledge can answer it for you. The JOSM editor may have a plugin that can use the image, but i haven't used it. Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: editing ×334 import ×187 satellite-images ×23 question asked: 09 Mar '20, 06:28 question was seen: 794 times last updated: 13 Mar '20, 15:04 How to import indoor mapping .osm files in Vespucci? What is the best way to edit using up to date local imagery? How can I use a plan generated from a CAD package as an overlay? Editing OSM maps, viewing within 24 hrs then importing to my own server? How can I edit all ways with certain tag in an area? How can I edit GPX tracks in Potlatch 2? What is the difference between live and with save mode in map edit (with Potlatch)? How do I add/edit/remove Presets in JOSM? What should I do about vandalism? How do I import map data from a .dwg file to OpenStreetMap? First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/73442/how-to-import-higher-resolution-image-into-osm
CC-MAIN-2021-39
refinedweb
728
84.78
Important: Please read the Qt Code of Conduct - Return QObject * objects to be used both in QML and Javascript Hi, I am a little bit confused. I have a JSWrapperObject inheriting from QObject with a test method. This method must return (in some way) a QObject * to the JS engine and the QML engine depending on who called it. What type should I return precisely and how should I add it to the engines? For the moment: - Returning a QJsonObject works but is useless for me as I need to call methods on the returned object; - Returning a QJSValue wrapping my object works in the JS engine but not in the QML engine; - doing qmlEngine->rootContext()->setContextProperty("test", new JSWrapperObject); works in QML, but not in JS. Ultimately, I would like the GUI (QML) to call JS methods which in turn call my C++ methods. Thanks for your help. Some updates. I did some tests. So: - Returning a QVariant object to QML engine works; - Returning my custom C++ object to QML does NOT work. The type is correctly registered because I can do something like: qmlEngine->rootContext()->setContextProperty("testObj", new namespace::JSWrapperObject()); I can access testObj and check that the type is correctly registered. Any idea why I could use this type by creating it directly from C++ into QML with the previous line but not by returning it from Q_INVOKABLE methods?
https://forum.qt.io/topic/42956/return-qobject-objects-to-be-used-both-in-qml-and-javascript
CC-MAIN-2021-10
refinedweb
232
59.13
: | | > Fair enough. *You* are the person who first made the assumption, | > in, that | > an implementation might just the function only as a macro: | | That's because I was under the impression you had mis-understood the | problem, The only sensible problem we've been faced is that of having a function implemented both as a macro and a real function. The solution to that problem is to #undef the macro and introduce a corresponding declaration for an external function with C linkage declaration in namespace std. Is that what you're questioning? If yes, then I don't think I misunderstood. Because the following has to evaluate to true: ::mblen == std::mblen And it is also the library requirement 17.4.1.2/7 which diretly refers to Annexe D/2 Each C header, whose name has the form name.h, behaves as if each name placed in the Standard library namespace by the corresponding cname header is also placed within the namespace scope of the namespace std and is followed by an explicit using-declaration (7.3.3). Am I still being dense? | ... We'd | lose the optimization opportunity that the header files of the system Is optimization more important than correctness? My opinion is: No. But I can understand you may disagree. | attempt to offer, and failing to work in case the name is only | available as a macro (which is not the case at hand, but it might be | on other systems). So, again you're pointing out an imaginary implementation which offers only the macro name. No comment. | ... These two problems are absent with the | implementation in my latest patch, as proposed by Ben. | | But, if you have a good argument against the patch I last proposed, | here's one that does it as you suggest. Ok to install? Yes. -- Gaby CodeSourcery, LLC
http://gcc.gnu.org/ml/libstdc++/2000-12/msg00325.html
crawl-001
refinedweb
307
62.68
The mbrtowc() function is defined in <cwchar> header file. mbrtowc() prototype size_t mbrtowc( wchar_t* pwc, const char* s, size_t n, mbstate_t* ps ); The mbrtowc() function converts the multibyte character represented by s to a wide character and is stored in the address pointed to by pwc. - If s is not a null pointer, a maximum of n bytes starting from the byte pointed to by s are examined in order to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the next n multibyte character in s is complete and valid, the function converts it to the corresponding wide character and is stored in the location pointed to by pwc. - If s is a null pointer, the parameters n and pwc has nothing to do with the function call and the call is equivalent to std::mbrtowc(NULL, "", 1, ps). - If the wide character produced is a null character, the conversion state stored in *ps is the initial shift state. mbrtowc() Parameters - pwc: Pointer to the memory address where the converted wide character is stored. - s: Pointer to the multibyte character to convert. - n: Maximum number of bytes in s to examine. - ps: Pointer to the conversion state used when interpreting the multibyte string mbrtowc() Return value The mbrtowc() function returns the first of the following that is valid: - 0 if the wide character converted from s is null (if pwc is not null). - The number of multibyte character successfully converted from s. - -2 if the next n bytes doesn't represent a complete multibyte character. - -1 is encoding error occurs, errno is set to EILSEQ. Example: How mbrtowc() function works? #include <cwchar> #include <clocale> #include <iostream> using namespace std; void test_mbrtowc(const char *s, size_t n) { mbstate_t ps = mbstate_t(); wchar_t wc; int retVal = mbrtowc(&wc, s, n, &ps); if (retVal == -2) wcout << L"Next " << n << L" byte(s) doesn't represent a complete multibyte character" << endl; else if (retVal == -1) wcout << L"Next " << n << L" byte(s) doesn't represent a valid multibyte character" << endl; else if (retVal == 0) wcout << L"The converted wide character is a null wide character" << endl; else { wcout << L"Next " << n << L" byte(s) hold " << retVal << L" bytes of multibyte character, "; wcout << L"Resulting wide character is " << wc << endl; } } int main() { setlocale(LC_ALL, "en_US.utf8"); char str1[] = "\u00b5"; char str2[] = "\0"; test_mbrtowc(str1, 1); test_mbrtowc(str1, 5); test_mbrtowc(str2, 5); return 0; } When you run the program, the output will be: Next 1 byte(s) doesn't represent a complete multibyte character Next 5 byte(s) hold 2 bytes of multibyte character, Resulting wide character is µ The converted wide character is a null wide character
https://cdn.programiz.com/cpp-programming/library-function/cwchar/mbrtowc
CC-MAIN-2021-04
refinedweb
450
52.83
import "cloud.google.com/go/translate" Package translate is a client for the Google Translation API. See for details. const Scope = raw.CloudPlatformScope Scope is the OAuth2 scope required by the Google Cloud Vision API. Client is a client for the translate API. NewClient constructs a new Client that can perform Translation operations. You can find or create API key for your project from the Credentials page of the Developers Console (console.developers.google.com). Close closes any resources held by the client. Close should be called when the client is no longer needed. It need not be called at program exit. DetectLanguage attempts to determine the language of the inputs. Each input string may be in a different language. Each slice of Detections in the return value corresponds with one input string. A slice of Detections holds multiple hypotheses for the language of a single input string. SupportedLanguages returns a list of supported languages for translation. The target parameter is the language to use to return localized, human readable names of supported languages. func (c *Client) Translate(ctx context.Context, inputs []string, target language.Tag, opts *Options) ([]Translation, error) Translate one or more strings of text from a source language to a target language. All inputs must be in the same language. The target parameter supplies the language to translate to. The supported languages are listed at. You can also call the SupportedLanguages method. The returned Translations appear in the same order as the inputs. type Detection struct { // Language is the code of the language detected. Language language.Tag // Confidence is a number from 0 to 1, with higher numbers indicating more // confidence in the detection. Confidence float64 // IsReliable indicates whether the language detection result is reliable. IsReliable bool } Detection represents information about a language detected in an input. Format is the format of the input text. Used in Options.Format. Constants for Options.Format. type Language struct { // Name is the human-readable name of the language. Name string // Tag is a standard code for the language. Tag language.Tag } A Language describes a language supported for translation. type Options struct { // Source is the language of the input strings. If empty, the service will // attempt to identify the source language automatically and return it within // the response. Source language.Tag // Format describes the format of the input texts. The choices are HTML or // Text. The default is HTML. Format Format // The model to use for translation. The choices are "nmt" or "base". The // default is "base". Model string } Options contains options for Translate. type Translation struct { // Text is the input text translated into the target language. Text string // Source is the detected language of the input text, if source was // not supplied to Client.Translate. If source was supplied, this field // will be empty. Source language.Tag // Model is the model that was used for translation. // It may not match the model provided as an option to Client.Translate. Model string } Translation contains the results of translating a piece of text. Package translate imports 8 packages (graph) and is imported by 9 packages. Updated 2019-03-16. Refresh now. Tools for package owners.
https://godoc.org/cloud.google.com/go/translate
CC-MAIN-2019-13
refinedweb
524
61.53
Help on buildind to Windows 10 Hi, guys. I'm i developer from a company that is actually porting some codes from actionscript and java to C++, and we recently have choosen Qt. I've already installed Qt Creator at some machines: in Mac and Windows 7 it´s working ok, very nice. But in some Windows 10 machines, even with fresh OS install, I can´t neither run the simplest console application: #include <QCoreApplication> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); return a.exec(); } This error always happens: Starting C:\Users\carlo\OneDrive\Documentos\build-untitled2-Desktop_Qt_5_9_0_MinGW_32bit-Debug\debug\untitled2.exe... The program has unexpectedly finished. C:\Users\carlo\OneDrive\Documentos\build-untitled2-Desktop_Qt_5_9_0_MinGW_32bit-Debug\debug\untitled2.exe crashed. I llok at some forums, and many people thinks that it seems to be caused by an abscence of some dll file. Well, I'd appreciate it for some help. Thanks a lot. Hi, just a quick guess, but try placing your program somewhere else than in the OneDrive folder. Thanks for the reply. At this machine, i'm using the OneDrive folder. But the same occurs at other installations at 2 other Windows 10 PCs. In both cases, the projects are located at "normal" folders. Ok another quick guess: have you tried building in Release instead of Debug? I´ve just tried Released and the machine crashed (freezed). I tried at other machine, the same code. The console window doens´t present the QCoreApplication standard message. Nothing happens. Both release and debug. When a close console, it returns this error: C:\Users\cranoya\Documents\build-untitled2-Desktop_Qt_5_9_0_MinGW_32bit-Release\release\untitled2.exe exited with code -1073741510 I've tried again at the crashed PC and release built worked. The console window shows the message "Press <RETURN> to close this window..." But debugg built still not works.... Are you trying just to run the app you created, or are you trying to develop on all those machines? If going for just running it, have you gone thru the windeployqt command? Hi Xyrer. I'm just trying a very simple thing: I install Qt Creator, crete a new project (console application), press the "build and run" button, and this happens. I did it many times (including reinstalling Qt) and the same happens in two of my PCs. With my Windows 7 PC at home i'm working fine (i'm working with Qt just now). With my parter's Mac it's ok too. I don't know if it's a coincidence, by these two Windows 10 PCs are giving the this headache... Thanks for replying. - JKSH Moderators @carlos-ranoya said in Help on buildind to Windows 10: I install Qt Creator, crete a new project (console application), press the "build and run" button, and this happens. What do you see if you click "Start Debugging" instead of "Build and Run" (using a Debug build)? Also, which version of Qt did you install on each PC? Are they all Qt 5.9.0 for MinGW 32-bit?
https://forum.qt.io/topic/78998/help-on-buildind-to-windows-10
CC-MAIN-2017-22
refinedweb
509
67.15
FULL PRODUCT VERSION : java version "1.6.0" Java(TM) SE Runtime Environment (build 1.6.0-b105) Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode, sharing) ADDITIONAL OS VERSION INFORMATION : Linux matthew-desktop 2.6.20-15-generic #2 SMP Sun Apr 15 07:36:31 UTC 2007 i686 GNU/Linux A DESCRIPTION OF THE PROBLEM : I believe that Pattern.split() and String.split() are implemented incorrectly for the case where the input is an empty string, and the pattern can match zero-length subsequences. For example: Pattern.compile(".*").split("") returns an array containing an empty string. The correct behaviour would be for it to return an empty array. Rationale: the API docs promise that, "trailing empty strings will be discarded" -- always in the one-argument version of split(), or when the limit is zero in the two argument version. This is not happening in the above case. While the API docs do also say that, "If this pattern does not match any subsequence of the input then the resulting array has just one element, namely the input sequence in string form", this is not the case here, because the pattern does match the input (as shown in test case). Looking at the source code for Pattern.split(), it would seem that the test for "no match was found" is incorrect for this particular case. This is not the most earth-shatteringly critical bug, of course ;-) STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : Run test case. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - Regex matches: 1 Number of split() results: 1 split() result 0: "" ACTUAL - Regex matches: 1 Number of split() results: 0 REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- import java.util.regex.Matcher; import java.util.regex.Pattern; public class SplitTest { public static void main(String[] args) { int count = 0; Pattern pattern = Pattern.compile(".*"); Matcher matcher = pattern.matcher(""); while (matcher.find()) count++; System.out.println("Regex matches: " + count); String[] strings = pattern.split(""); System.out.println("Number of split() results: " + strings.length); for (int i = 0; i < strings.length; i++) System.out.println("split() result " + i + ": \"" + strings[i] + "\""); } } ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : Can't think of any, barring avoiding doing wacky things like attempting to split empty strings with weird delimiters.
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6559590
CC-MAIN-2021-21
refinedweb
378
59.6
CGI::Simple - A Simple totally OO CGI interface that is CGI.pm compliant This document describes CGI::Simple version 1.113. use CGI::Simple; $CGI::Simple::POST_MAX = 1024; # max upload via post default 100kB $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads $q = new CGI::Simple; $q = new CGI::Simple( { 'foo'=>'1', 'bar'=>[2,3,4] } ); $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' ); $q = new CGI::Simple( \*FILEHANDLE ); $q->save( \*FILEHANDLE ); # save current object to a file as used by new @params = $q->param; # return all param names as a list $value = $q->param('foo'); # return the first value supplied for 'foo' @values = $q->param('foo'); # return all values supplied for foo %fields = $q->Vars; # returns untied key value pair hash $hash_ref = $q->Vars; # or as a hash ref %fields = $q->Vars("|"); # packs multiple values with "|" rather than "\0"; @keywords = $q->keywords; # return all keywords as a list $q->param( 'foo', 'some', 'new', 'values' ); # set new 'foo' values $q->param( -name=>'foo', -value=>'bar' ); $q->param( -name=>'foo', -value=>['bar','baz'] ); $q->param( 'foo', 'some', 'new', 'values' ); # append values to 'foo' $q->append( -name=>'foo', -value=>'bar' ); $q->append( -name=>'foo', -value=>['some', 'new', 'values'] ); $q->delete('foo'); # delete param 'foo' and all its values $q->delete_all; # delete everything <INPUT TYPE="file" NAME="upload_file" SIZE="42"> $files = $q->upload() # number of files uploaded @files = $q->upload(); # names of all uploaded files $filename = $q->param('upload_file') # filename of uploaded file $mime = $q->upload_info($filename,'mime'); # MIME type of uploaded file $size = $q->upload_info($filename,'size'); # size of uploaded file my $fh = $q->upload($filename); # get filehandle to read from while ( read( $fh, $buffer, 1024 ) ) { ... } # short and sweet upload $ok = $q->upload( $q->param('upload_file'), '/path/to/write/file.name' ); print "Uploaded ".$q->param('upload_file')." and wrote it OK!" if $ok; $decoded = $q->url_decode($encoded); $encoded = $q->url_encode($unencoded); $escaped = $q->escapeHTML('<>"&'); $unescaped = $q->unescapeHTML('<>"&'); $qs = $q->query_string; # get all data in $q as a query string OK for GET $q->no_cache(1); # set Pragma: no-cache + expires print $q->header(); # print a simple header # get a complex header $header = $q->header( -type => 'image/gif' -nph => 1, -status => '402 Payment required', -expires =>'+24h', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00' ); # a p3p header (OK for redirect use as well) $header = $q->header( -p3p => 'policyref="' ); @cookies = $q->cookie(); # get names of all available cookies $value = $q->cookie('foo') # get first value of cookie 'foo' @value = $q->cookie('foo') # get all values of cookie 'foo' # get a cookie formatted for header() method $cookie = $q->cookie( -name => 'Password', -values => ['superuser','god','my dog woofie'], -expires => '+3d', -domain => '.nowhere.com', -path => '/cgi-bin/database', -secure => 1 ); print $q->header( -cookie=>$cookie ); # set cookie print $q->redirect(''); # print a redirect header dienice( $q->cgi_error ) if $q->cgi_error; at the end. In practical testing this module loads and runs about twice as fast as CGI.pm depending on the precise task. Here is a very brief rundown on how you use the interface. Full details follow. Before you can call a CGI::Simple method you must create a CGI::Simple object. You do that by using the module and then calling the new() constructor: use CGI::Simple; my $q = new CGI::Simple; It is traditional to call your object $q for query or perhaps $cgi. Once you have your object you can call methods on it using the -> arrow syntax For example to get the names of all the parameters passed to your script you would just write: @names = $q->param(); Many methods are sensitive to the context in which you call them. In the example above the param() method returns a list of all the parameter names when called without any arguments. When you call param('arg') with a single argument it assumes you want to get the value(s) associated with that argument (parameter). If you ask for an array it gives you an array of all the values associated with it's argument: @values = $q->param('foo'); # get all the values for 'foo' whereas if you ask for a scalar like this: $value = $q->param('foo'); # get only the first value for 'foo' then it returns only the first value (if more than one value for 'foo' exists). Most CGI::Simple routines accept several arguments, sometimes as many as 10. Several routines are commonly called with just one argument. In the case of these routines you can provide the single argument without an argument name. header() happens to be one of these routines. In this case, the single argument is the document type. print $q->header('text/html'); Sometimes methods expect a scalar, sometimes a reference to an array, and sometimes a reference to a hash. Often, you can pass any type of argument and the routine will do whatever is most appropriate. For example, the param() method can be used to set a CGI parameter to a single or a multi-valued value. The two cases are shown below: $q->param(-name=>'veggie',-value=>'tomato'); $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']); For convenience a functional interface is provided by the CGI::Simple::Standard module. This hides the OO details from you and allows you to simply call methods. You may either use AUTOLOADING of methods or import specific method sets into you namespace. Here are the first few examples again using the function interface. use CGI::Simple::Standard qw(-autoload); @names = param(); @values = param('foo'); $value = param('foo'); print header(-type=>'image/gif',-expires=>'+3d'); print header('text/html'); Yes that's it. Not a $q-> in sight. You just use the module and select how/which methods to load. You then just call the methods you want exactly as before but without the $q-> notation. When (if) you read the following docs and are using the functional interface just pretend the $q-> is not there. When you use the functional interface Perl needs to be able to find the functions you call. The simplest way of doing this is to use autoloading as shown above. When you use CGI::Simple::Standard with the '-autoload' pragma it exports a single AUTOLOAD sub into you namespace. Every time you call a non existent function AUTOLOAD is called and will load the required function and install it in your namespace. Thus only the AUTOLOAD sub and those functions you specifically call will be imported. Alternatively CGI::Simple::Standard provides a range of function sets you can import or you can just select exactly what you want. You do this using the familiar use CGI::Simple::Standard qw( :func_set some_func); notation. This will import the ':func_set' function set and the specific function 'some_func'. If you do not have a AUTOLOAD sub in you script it is generally best to use the '-autoload' option. Under autoload you can use any method you want but only import and compile those functions you actually use. If you do not use autoload you must specify what functions to import. You can only use functions that you have imported. For comvenience functions are grouped into related sets. If you choose to import one or more ':func_set' you may have potential namespace collisions so check out the docs to see what gets imported. Using the ':all' tag is pretty slack but it is there if you want. Full details of the function sets are provided in the CGI::Simple::Standard docs If you just want say the param and header methods just load these two. use CGI::Simple::Standard qw(param header); Where you see global variables being set using the syntax: $CGI::Simple::DEBUG = 1; You use exactly the same syntax when using CGI::Simple::Standard. The first step in using CGI::Simple is to create a new query object using the new() constructor: $q = new CGI::Simple; This will parse the input (from both POST and GET methods) and store it into an object called $q. If you provide a file handle to the new() method, it will read parameters from the file (or STDIN, or whatever). open FH, "test.in" or die $!; $q = new CGI::Simple(\*FH); open $fh, "test.in" or die $!; $q = new CGI::Simple($fh); The file should be a series of newline delimited TAG=VALUE pairs. Conveniently, this type of file is created by the save() method (see below). Multiple records can be saved and restored. IO::File objects work fine. If you are using the function-oriented interface provided by CGI::Simple::Standard and want to initialize from a file handle, the way to do this is with restore_parameters(). This will (re)initialize the default CGI::Simple object from the indicated file handle. restore_parameters(\*FH); In fact for all intents and purposes restore_parameters() is identical to new() Note that restore_parameters() does not exist in CGI::Simple itself so you can't use it. You can also initialize the query object from an associative array reference: $q = new CGI::Simple( { 'dinosaur' => 'barney', 'song' => 'I love you', 'friends' => [qw/Jessica George Nancy/] } ); or from a properly formatted, URL-escaped query string: $q = new CGI::Simple( 'dinosaur=barney&color=purple' ); or from a previously existing CGI::Simple object (this generates an identical clone including all global variable settings, etc that are stored in the object): $old_query = new CGI::Simple; $new_query = new CGI::Simple($old_query); To create an empty query, initialize it from an empty string or hash: $empty_query = new CGI::Simple(""); -or- $empty_query = new CGI::Simple({}); @keywords = $q->keywords; If the script was invoked as the result of an <ISINDEX> search, the parsed keywords can be obtained as an array using the keywords() method. @names = $q-). @values = $q->param('foo'); -or- $value = $q->param('foo'); Pass the param() method a single argument to fetch the value of the named parameter. If the parameter is multi-valued by default as an empty string. If you set the global variable: $CGI::Simple::NO_UNDEF_PARAMS = 1; Then value-less parameters will be ignored, and will not exist in the query object. If you try to access them via param you will get an undef return value. $q->param('foo','an','array','of','values'); This sets the value for the named parameter 'foo' to an array of values. This is one way to change the value of a field. param() also recognizes a named parameter style of calling described in more detail later: $q->param(-name=>'foo',-values=>['an','array','of','values']); -or- $q->param(-name=>'foo',-value=>'the value'); If POSTed or PUTed data is not of type application/x-www-form-urlencoded or multipart/form-data, then the data will not be processed, but instead be returned as-is in a parameter named POSTDATA or PUTDATA. To retrieve it, use code like this: my $data = $q->param( 'POSTDATA' ); -or- my $data = $q->param( 'PUTDATA' ); (If you don't know what the preceding means, don't worry about it. It only affects people trying to use CGI::Simple for REST webservices) You nay also use the new method add_param to add parameters. This is an alias to the _add_param() internal method that actually does all the work. You can call it like this: $q->add_param('foo', 'new'); $q->add_param('foo', [1,2,3,4,5]); $q->add_param( 'foo', 'bar', 'overwrite' ); The first argument is the parameter, the second the value or an array ref of values and the optional third argument sets overwrite mode. If the third argument is absent of false the values will be appended. If true the values will overwrite any existing ones . This method was silly, non OO and has been deleted. You can get all the params as a hash using Vars or via all the other accessors. $q->delete('foo'); This completely clears a parameter. If you are using the function call interface, use Delete() instead to avoid conflicts with Perl's built-in delete operator. If you are using the function call interface, use Delete() instead to avoid conflicts with Perl's built-in delete operator. $q->delete_all(); This clears the CGI::Simple object completely. For CGI.pm compatibility Delete_all() is provided however there is no reason to use this in the function call interface other than symmetry. For CGI.pm compatibility Delete_all() is provided as an alias for delete_all however there is no reason to use this, even in the function call interface. This method is provided for CGI.pm compatibility only. It returns an array ref to the values associated with a named param. It is deprecated. $params = $q->Vars; # as a tied hash ref print $params->{'address'}; @foo = split "\0", $params->{'foo'}; %params = $q->Vars; # as a plain hash print $params{'address'}; @foo = split "\0", $params{'foo'}; %params = $q->Vars(','); # specifying a different separator than "\0" @foo = split ',', $params{'foo'};. Because this hash ref is tied changing a key/value changes the underlying CGI::Simple object. Called in a list context, it returns the parameter list as an ordinary hash. Changing this hash will not change the underlying CGI::Simple object When using Vars(), the thing you must watch out for are multi-valued CGI parameters. Because a hash cannot distinguish between scalar and list context, multi-valued. You can change the character used to do the multiple value packing by passing it to Vars() as an argument as shown. The url_param() method makes the QUERY_STRING data available regardless of whether the REQUEST_METHOD was 'GET' or 'POST'. You can do anything with url_param that you can do with param(), however the data set is completely independent. Technically what happens if you use this method is that the QUERY_STRING data is parsed into a new CGI::Simple object which is stored within the current object. url_param then just calls param() on this new object. When the REQUEST_METHOD is 'POST' the default behavior is to ignore name/value pairs or keywords in the $ENV{'QUERY_STRING'}. You can override this by calling parse_query_string() which will add the QUERY_STRING data to the data already in our CGI::Simple object if the REQUEST_METHOD was 'POST' $q = new CGI::Simple; $q->parse_query_string; # add $ENV{'QUERY_STRING'} data to our $q object If the REQUEST_METHOD was 'GET' then the QUERY_STRING will already be stored in our object so parse_query_string will be ignored. This is a new method in CGI::Simple that is not available in CGI.pm $q->save(\*FILEHANDLE) This will write the current state of the form to the provided filehandle. You can read it back in by providing a filehandle to the new() method.(). open FH, "test.in" or die $!; $q1 = new CGI::Simple(\*FH); # get the first record $q2 = new CGI::Simple(\*FH); # get the next record Note: If you wish to use this method from the function-oriented (non-OO) interface, the exported name for this method is save_parameters(). Also if you want to initialize from a file handle, the way to do this is with restore_parameters(). This will (re)initialize the default CGI::Simple object from the indicated file handle. restore_parameters(\*FH); File uploads are easy with CGI::Simple. You use the upload() method. Assuming you have the following in your HTML: <FORM METHOD="POST" ACTION="" ENCTYPE="multipart/form-data"> <INPUT TYPE="file" NAME="upload_file1" SIZE="42"> <INPUT TYPE="file" NAME="upload_file2" SIZE="42"> </FORM> Note that the ENCTYPE is "multipart/form-data". You must specify this or the browser will default to "application/x-www-form-urlencoded" which will result in no files being uploaded although on the surface things will appear OK. When the user submits this form any supplied files will be spooled onto disk and saved in temporary files. These files will be deleted when your script.cgi exits so if you want to keep them you will need to proceed as follows. The upload() method is quite versatile. If you call upload() without any arguments it will return a list of uploaded files in list context and the number of uploaded files in scalar context. $number_of_files = $q->upload; @list_of_files = $q->upload; Having established that you have uploaded files available you can get the browser supplied filename using param() like this: $filename1 = $q->param('upload_file1'); You can then get a filehandle to read from by calling upload() and supplying this filename as an argument. Warning: do not modify the value you get from param() in any way - you don't need to untaint it. $fh = $q->upload( $filename1 ); Now to save the file you would just do something like: $save_path = '/path/to/write/file.name'; open FH, ">$save_path" or die "Oops $!\n"; binmode FH; print FH $buffer while read( $fh, $buffer, 4096 ); close FH; By utilizing a new feature of the upload method this process can be simplified to: $ok = $q->upload( $q->param('upload_file1'), '/path/to/write/file.name' ); if ($ok) { print "Uploaded and wrote file OK!"; } else { print $q->cgi_error(); } As you can see upload will accept an optional second argument and will write the file to this file path. It will return 1 for success and undef if it fails. If it fails you can get the error from cgi_error You can also use just the fieldname as an argument to upload ie: $fh = $q->upload( 'upload_field_name' ); or $ok = $q->upload( 'upload_field_name', '/path/to/write/file.name' ); BUT there is a catch. If you have multiple upload fields, all called 'upload_field_name' then you will only get the last uploaded file from these fields. The upload_info() method is a new method. Called without arguments it returns the number of uploaded files in scalar context and the names of those files in list context. $number_of_upload_files = $q->upload_info(); @filenames_of_all_uploads = $q->upload_info(); You can get the MIME type of an uploaded file like this: $mime = $q->upload_info( $filename1, 'mime' ); If you want to know how big a file is before you copy it you can get that information from uploadInfo which will return the file size in bytes. $file_size = $q->upload_info( $filename1, 'size' ); The size attribute is optional as this is the default value returned. Note: The old CGI.pm uploadInfo() method has been deleted. CGI.pm has a default setting that allows infinite size file uploads by default. In contrast file uploads are disabled by default in CGI::Simple to discourage Denial of Service attacks. You must enable them before you expect file uploads to work. When file uploads are disabled the file name and file size details will still be available from param() and upload_info respectively but the upload filehandle returned by upload() will be undefined - not surprising as the underlying temp file will not exist either. You can enable uploads using the '-upload' pragma. You do this by specifying this in you use statement: use CGI::Simple qw(-upload); Alternatively you can enable uploads via the $DISABLE_UPLOADS global like this: use CGI::Simple; $CGI::Simple::DISABLE_UPLOADS = 0; $q = new CGI::Simple; If you wish to set $DISABLE_UPLOADS you must do this *after* the use statement and *before* the new constructor call as shown above. The maximum acceptable data via post is capped at 102_400kB rather than infinity which is the CGI.pm default. This should be ample for most tasks but you can set this to whatever you want using the $POST_MAX global. use CGI::Simple; $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads $CGI::Simple::POST_MAX = 1_048_576; # allow 1MB uploads $q = new CGI::Simple; If you set to -1 infinite size uploads will be permitted, which is the CGI.pm default. $CGI::Simple::POST_MAX = -1; # infinite size upload Alternatively you can specify all the CGI.pm default values which allow file uploads of infinite size in one easy step by specifying the '-default' pragma in your use statement. use CGI::Simple qw( -default ..... ); If you are using CGI::Simple be sure to call binmode() on any handle that you create to write the uploaded file to disk. Calling binmode() will do no harm on other systems anyway. In HTML the < > " and & chars have special meaning and need to be escaped to < > " and & respectively. $escaped = $q->escapeHTML( $string ); $escaped = $q->escapeHTML( $string, 'new_lines_too' ); If the optional second argument is supplied then newlines will be escaped to. This performs the reverse of escapeHTML(). $unescaped = $q->unescapeHTML( $HTML_escaped_string ); This method will correctly decode a url encoded string. $decoded = $q->url_decode( $encoded ); This method will correctly URL encode a string. $encoded = $q->url_encode( $string ); @keywords = $q->parse_keywordlist( $keyword_list ); This method returns a list of keywords, correctly URL escaped and split out of the supplied string CGI.pm alias for print. $q->put('Hello World!') will print the usual CGI.pm alias for print. $q->print('Hello World!') will print the usual. If the "secure" attribute is set, the cookie will only be sent to your script if the CGI request is occurring on a secure channel, such as SSL. The interface to HTTP cookies is the cookie() method: $cookie = $q->cookie( -name => 'sessionID', -value => 'xyzzy', -expires => '+1h', -path => '/cgi-bin/database', -domain => '.capricorn.org', -secure => 1 ); print $q->header(-cookie=>$cookie); cookie() creates a new cookie. Its parameters include: The name of the cookie (required). This can be any string at all. Although browsers limit their cookie names to non-whitespace alphanumeric characters, CGI.pm removes this restriction by escaping and unescaping cookies behind the scenes. The value of the cookie. This can be any scalar value, array reference, or even associative array reference. For example, you can store an entire associative array into a cookie this way: $cookie=$q->cookie( -name => 'family information', -value => \%childrens_ages ); The optional partial path for which this cookie will be valid, as described above. The optional partial domain for which this cookie will be valid, as described above. The optional expiration date for this cookie. The format is as described in the section on the header() method: "+1h" one hour from now If set to true, this cookie will only be used within a secure SSL session. The cookie created by cookie() must be incorporated into the HTTP header within the string returned by the header() method: print $q->header(-cookie=>$my_cookie); To create multiple cookies, give header() an array reference: $cookie1 = $q->cookie( -name => 'riddle_name', -value => "The Sphynx's Question" ); $cookie2 = $q->cookie( -name => 'answers', -value => \%answers ); print $q->header( -cookie => [ $cookie1, $cookie2 ] ); To retrieve a cookie, request it by name by calling cookie() method without the -value parameter: use CGI::Simple; $q = new CGI::Simple; $riddle = $q->cookie('riddle_name'); %answers = $q->cookie('answers'); Cookies created with a single scalar value, such as the "riddle_name" cookie, will be returned in that form. Cookies with array and hash values can also be retrieved. The cookie and CGI::Simple = $q->cookie( -name=>'answers', -value=>[$q->param('answers')] ); # vice-versa $q->param( -name=>'answers', -value=>[$q->cookie('answers')] );::Simmple::Cookie module.. print $q->header; -or- print $q->header('image/gif'); -or- print $q->header('text/html','204 No response'); -or- print $q-. Recognized parameters are -type, -status, -cookie, -target, -expires, -nph, -charset and -attachment. Any other named parameters will be stripped of their initial hyphens and turned into header fields, allowing you to specify any HTTP header you desire. For example, you can produce non-standard HTTP header fields by providing them as named arguments: print $q->header( -type => 'text/html', -nph => 1, -cost => 'Three smackers', -annoyance_level => 'high', -complaints_to => 'bit bucket' ); This will produce the following non-standard HTTP header: HTTP/1.0 200 OK Cost: Three smackers Annoyance-level: high Complaints-to: bit bucket Content-type: text/html Note that underscores are translated automatically into hyphens. This feature allows you to keep up with the rapidly changing HTTP "standards". The -type is a key element that tell the browser how to display your document. The default is 'text/html'. Common types are: text/html text/plain image/gif image/jpg image/png application/octet-stream The -status code is the HTTP response code. The default is 200 OK. Common status codes are: 200 OK 204 No Response 301 Moved Permanently 302 Found 303 See Other 307 Temporary Redirect 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 405 Not Allowed 408 Request Timed Out 500 Internal Server Error 503 Service Unavailable 504 Gateway Timed Out The -expires parameter lets you indicate to a browser and proxy server how long to cache pages for. special format that includes interesting attributes such as expiration time. Use the cookie() method to create and retrieve session cookies. The -target is for frames use'. Most browsers will not cache the output from CGI scripts. Every time the browser reloads the page, the script is invoked anew. However some browsers do cache pages. You can discourage this behavior using the no_cache() function. $q->no_cache(1); # turn caching off by sending appropriate headers $q->no_cache(1); # do not send cache related headers. $q->no_cache(1); print header (-type=>'image/gif', -nph=>1); This will produce a header like the following: HTTP/1.0 200 OK Server: Apache - accept no substitutes Expires: Thu, 15 Nov 2001 03:37:50 GMT Date: Thu, 15 Nov 2001 03:37:50 GMT Pragma: no-cache Content-Type: image/gif Both the Pragma: no-cache header field and an Expires header that corresponds to the current time (ie now) will be sent. The somewhat ill named cache() method is a legacy from CGI.pm. It operates the same as the new no_cache() method. The difference is/was that when set it results only in the Pragma: no-cache line being printed. Expires time data is not sent. print $q-. You can also use named arguments: print $q->redirect( -uri=>'', -nph=>1 ); The -nph parameter, if set to a true value, will issue the correct headers to work with a NPH (no-parse-header) script. This is important to use with certain servers, such as Microsoft ones, which expect all their scripts to be NPH. There are a number of pragmas that you can specify in your use CGI::Simple statement. Pragmas, which are always preceded by a hyphen, change the way that CGI::Simple functions in various ways. You can generally achieve exactly the same results by setting the underlying $GLOBAL_VARIABLES. For example the '-upload' pargma will enable file uploads: use CGI::Simple qw(-upload); In CGI::Simple::Standard Pragmas, function sets , and individual functions can all be imported in the same use() line. For example, the following use statement imports the standard set of functions and enables debugging mode (pragma -debug): use CGI::Simple::Standard qw(:standard -debug); The current list of pragmas is as follows: If a value is not given in the query string, as in the queries "name1=&name2=" or "name1&name2", by default it will be returned as an empty string. If you specify the '-no_undef_params' pragma then CGI::Simple ignores parameters with no values and they will not appear in the query object. This makes CGI.pm produce a header appropriate for an NPH (no parsed header) script. You may need to do other things as well to tell the server that the script is NPH. See the discussion of NPH scripts below.. Separate the name=value pairs in CGI parameter query strings with ampersands rather than semicolons. This is the default. ?name=fred&age=24&favorite_color=3 This is only available for CGI::Simple::Standard and uses AUTOLOAD to load functions on demand. See the CGI::Simple::Standard docs for details. This turns off the command-line processing features. This is the default. This turns on debugging. At debug level 1 CGI::Simple will read arguments from the command-line. At debug level 2 CGI.pm will produce the prompt "(offline mode: enter name=value pairs on standard input)" and wait for input on STDIN. If no number is specified then a debug level of 2 is used. See the section on debugging for more details. This sets the default global values for CGI.pm which will enable infinite size file uploads, and specify the '-newstyle_urls' and '-debug1' pragmas Disable uploads - the default setting Enable uploads - the CGI.pm default Only allows headers to be generated once per script invocation Carp when cgi_error() called, default is to do nothing Croak when cgi_error() called, default is to do nothing. You can set NPH mode in any of the following ways: Simply add the "-nph" pragma to the use: use CGI::Simple qw(-nph) Call nph() with a non-zero parameter at any point after using CGI.pm in your program. $q->nph(1) in the header() and redirect() statements: print $q->header(-nph=>1); The Microsoft Internet Information Server requires NPH mode. CGI::Simple. CGI.pm provides four simple functions for producing multipart documents of the type needed to implement server push. These functions were graciously provided by Ed Jordan <ed@fidalgo.net> with additions from Andrew Benham <adsb@bigfoot.com> You are also advised to put the script into NPH mode and to set $| to 1 to avoid buffering problems. Browser support for server push is variable. Here is a simple script that demonstrates server push: #!/usr/local/bin/perl use CGI::Simple::Standard(-boundary=>$boundary); Initialize the multipart system. The -boundary argument specifies what MIME boundary string to use to separate parts of the document. If not provided, CGI.pm chooses a reasonable boundary for you. multipart_start(-type=>$type) Start a new part of the multipart document using the specified MIME type. If not specified, text/html is assumed. multipart_end() End a part. You must remember to call multipart_end() once for each multipart_start(), except at the end of the last part of the multipart document when multipart_final() should be called instead of multipart_end(). multipart_final() End all parts. You should call multipart_final() rather than multipart_end() at the end of the last part of the multipart document. Users interested in server push applications should also have a look at the CGI::Push module.). Before you do this you will need to change the debug level from the default level of 0 (no debug) to either 1 if you want to debug from @ARGV (the command line) of 2 if you want to debug from STDIN. You can do this using the debug pragma like this: use CGI::Simple qw(-debug2); # set debug to level 2 => from STDIN or this: $CGI::Simple::DEBUG = 1; # set debug to level 1 => from @ARGV At debug level 1 you can pass keywords and name=value pairs like this: your_script.pl keyword1 keyword2 keyword3 or this: your_script.pl keyword1+keyword2+keyword3 or this: your_script.pl name1=value1 name2=value2 or this: your_script.pl name1=value1&name2=value2 At debug level 2 you can feed newline-delimited name=value pairs to the script on standard input. You will be presented with the following prompt: (offline mode: enter name=value pairs on standard input) You end the input with your system dependent end of file character. You should try ^Z ^X ^D and ^C if all else fails. The ^ means hold down the [Ctrl] button while you press the other key. When debugging, you can use quotes and backslashes to escape characters in the familiar shell manner, letting you place spaces and other funny characters in your parameter=value pairs: your_script.pl "name1='I am a long value'" "name2=two\ words" The Dump() method produces a string consisting of all the query's object attributes formatted nicely as a nested list. This dump includes the name/value pairs and a number of other details. This is useful for debugging purposes: print $q->Dump The actual result of this is HTML escaped formatted text wrapped in <pre> tags so if you send it straight to the browser it produces something that looks like: $VAR1 = bless( { '.parameters' => [ 'name', 'color' ], '.globals' => { 'FATAL' => -1, 'DEBUG' => 0, 'NO_NULL' => 1, 'POST_MAX' => 102400, 'USE_CGI_PM_DEFAULTS' => 0, 'HEADERS_ONCE' => 0, 'NPH' => 0, 'DISABLE_UPLOADS' => 1, 'NO_UNDEF_PARAMS' => 0, 'USE_PARAM_SEMICOLONS' => 0 }, '.fieldnames' => { 'color' => '1', 'name' => '1' }, '.mod_perl' => '', 'color' => [ 'red', 'green', 'blue' ], 'name' => [ 'JaPh,' ] }, 'CGI::Simple' ); You may recognize this as valid Perl syntax (which it is) and/or the output from Data::Dumper (also true). This is the actual guts of how the information is stored in the query object. All the internal params start with a . char Alternatively you can dump your object and the current environment using: print $q->Dump(\%ENV); You can get a similar browser friendly dump of the current %ENV hash using: print $q->PrintEnv; This will produce something like (in the browser): $VAR1 = { 'QUERY_STRING' => 'name=JaPh%2C&color=red&color=green&color=blue', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'REGRESSION_TEST' => 'simple.t.pl', 'VIM' => 'C:\\WINDOWS\\Desktop\\vim', 'HTTP_REFERER' => 'xxx.sex.com', 'HTTP_USER_AGENT' => 'LWP', 'HTTP_ACCEPT' => 'text/html;q=1, image/gif;q=0.42, */*;q=0.001', 'REMOTE_HOST' => 'localhost', 'HTTP_HOST' => 'the.restaurant.at.the.end.of.the.universe', 'GATEWAY_INTERFACE' => 'bleeding edge', 'REMOTE_IDENT' => 'None of your damn business', 'SCRIPT_NAME' => '/cgi-bin/foo.cgi', 'SERVER_NAME' => 'nowhere.com', 'HTTP_COOKIE' => '', 'CONTENT_LENGTH' => '42', 'HTTPS_A' => 'A', 'HTTP_FROM' => 'spammer@nowhere.com', 'HTTPS_B' => 'B', 'SERVER_PROTOCOL' => 'HTTP/1.0', 'PATH_TRANSLATED' => '/usr/local/somewhere/else', 'SERVER_SOFTWARE' => 'Apache - accept no substitutes', 'PATH_INFO' => '/somewhere/else', 'REMOTE_USER' => 'Just another Perl hacker,', 'REMOTE_ADDR' => '127.0.0.1', 'HTTPS' => 'ON', 'DOCUMENT_ROOT' => '/vs/www/foo', 'REQUEST_METHOD' => 'GET', 'REDIRECT_QUERY_STRING' => '', 'AUTH_TYPE' => 'PGP MD5 DES rot13', 'COOKIE' => 'foo=a%20phrase; bar=yes%2C%20a%20phrase&;I%20say;', 'SERVER_PORT' => '8080' }; Errors can occur while processing user input, particularly when processing uploaded files. When these errors occur, CGI::Simple); print "<H2>$error</H2>; exit; } $version = $q->version(); The version() method returns the value of $VERSION $q->nph(1); # enable NPH mode $q->nph(0); # disable NPH mode The nph() method enables and disables NPH headers. See the NPH section. @all_parameters = $q->all_parameters(); The all_parameters() method is an alias for param() $charset = $q->charset(); # get current charset $q->charset('utf-42'); # set the charset The charset() method gets the current charset value if no argument is supplied or sets it if an argument is supplied. $crlf = $q->crlf(); The crlf() method returns the system specific line ending sequence. $globals = $q->globals('FATAL'); # get the current value of $FATAL $globals = $q->globals('FATAL', 1 ); # set croak mode on cgi_error() The globals() method gets/sets the values of the global variables after the script has been invoked. For globals like $POST_MAX and $DISABLE_UPLOADS this makes no difference as they must be set prior to calling the new constructor but there might be reason the change the value of others. $auth_type = $q->auth_type(); The auth_type() method returns the value of $ENV{'AUTH_TYPE'} which should contain the authorization/verification method in use for this script, if any. $content_length = $q->content_length(); The content_length() method returns the value of $ENV{'AUTH_TYPE'} $content_type = $q->content_type(); The content_type() method returns the content_type of data submitted in a POST, generally 'multipart/form-data' or 'application/x-www-form-urlencoded' as supplied in $ENV{'CONTENT_TYPE'} $document_root = $q->document_root(); The document_root() method returns the value of $ENV{'DOCUMENT_ROOT'} $gateway_interface = $q->gateway_interface(); The gateway_interface() method returns the value of $ENV{'GATEWAY_INTERFACE'} $path_translated = $q->path_translated(); The path_translated() method returns the value of $ENV{'PATH_TRANSLATED'} $referer = $q->referer(); The referer() method returns the value of $ENV{'REFERER'} This will return the URL of the page the browser was viewing prior to fetching your script. Not available for all browsers. $remote_addr = $q->remote_addr(); The remote_addr() method returns the value of $ENV{'REMOTE_ADDR'} or 127.0.0.1 (localhost) if this is not defined. $remote_host = $q->remote_host(); The remote_host() method returns the value of $ENV{'REMOTE_HOST'} if it is defined. If this is not defined it returns $ENV{'REMOTE_ADDR'} If this is not defined it returns 'localhost' $remote_ident = $q->remote_ident(); The remote_ident() method returns the value of $ENV{'REMOTE_IDENT'} $remote_user = $q->remote_user(); The remote_user() method returns the authorization/verification name used for user verification, if this script is protected. The value comes from $ENV{'REMOTE_USER'} $request_method = $q->request_method(); The request_method() method returns the method used to access your script, usually one of 'POST', 'GET' or 'HEAD' as supplied by $ENV{'REQUEST_METHOD'} $script_name = $q->script_name(); The script_name() method returns the value of $ENV{'SCRIPT_NAME'} if it is defined. Otherwise it returns Perl's script name from $0. Failing this it returns a null string '' $server_name = $q->server_name(); The server_name() method returns the value of $ENV{'SERVER_NAME'} if defined or 'localhost' otherwise $server_port = $q->server_port(); The server_port() method returns the value $ENV{'SERVER_PORT'} if defined or 80 if not. $server_protocol = $q->server_protocol(); The server_protocol() method returns the value of $ENV{'SERVER_PROTOCOL'} if defined or 'HTTP/1.0' otherwise $server_software = $q->server_software(); The server_software() method returns the value $ENV{'SERVER_SOFTWARE'} or 'cmdline' If the server software is IIS it formats your hard drive, installs Linux, FTPs to, installs Apache, and then restores your system from tape. Well maybe not, but it's a nice thought. $user_name = $q->user_name(); Attempt to obtain the remote user's name, using a variety of different techniques. This only works with older browsers such as Mosaic. Newer browsers do not report the user name for privacy reasons! Technically the user_name() method returns the value of $ENV{'HTTP_FROM'} or failing that $ENV{'REMOTE_IDENT'} or as a last choice $ENV{'REMOTE_USER'} $ua = $q->user_agent(); # return the user agent $ok = $q->user_agent('mozilla'); # return true if user agent 'mozilla' The user_agent() method returns the value of $ENV{'HTTP_USER_AGENT'} when called without an argument or true or false if the $ENV{'HTTP_USER_AGENT'} matches the passed argument. The matching is case insensitive and partial. $virtual_host = $q->virtual_host(); The virtual_host() method returns the value of $ENV{'HTTP_HOST'} if defined or $ENV{'SERVER_NAME'} as a default. Port numbers are removed. $path_info = $q->path_info(); The path_info() method returns additional path information from the script URL. E.G. fetching /cgi-bin/your_script/additional/stuff will result in $q-. $Accept = $q->Accept(); The Accept() method returns a list of MIME types that the remote browser accepts. If you give this method a single argument corresponding to a MIME type, as in $q->Accept('text/html'), it will return a floating point value corresponding to the browser's preference for this type from 0.0 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept list are handled correctly. $accept = $q->accept(); The accept() Method is an alias for Accept() $http = $q->http(); Called with no arguments the http() method returns the list of HTTP or HTTPS: $requested_language = $q->http('Accept-language'); $requested_language = $q->http('Accept_language'); $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE'); $https = $q->https(); The https() method is similar to the http() method except that when called without an argument it returns the value of $ENV{'HTTPS'} which will be true if a HTTPS connection is in use and false otherwise. $protocol = $q->protocol(); The protocol() method returns 'https' if a HTTPS connection is in use or the server_protocol() minus version numbers ('http') otherwise. $full_url = $q->url(); $full_url = $q->url(-full=>1); $relative_url = $q->url(-relative=>1); $absolute_url = $q->url(-absolute=>1); $url_with_path = $q->url(-path_info=>1); $url_with_path_and_query = $q->url(-path_info=>1,-query=>1); $netloc = $q->url(-base => 1); url() returns the script's URL in a variety of formats. Called without any arguments, it returns the full form of the URL, including host name and port number You can modify this format with the following named arguments: If true, produce an absolute URL, e.g. /path/to/script.cgi Produce a relative URL. This is useful if you want to reinvoke your script with different parameters. For example: script.cgi Produce the full URL, exactly as if called without any arguments. This overrides the -relative and -absolute arguments. Append the additional path information to the URL. This can be combined with -full, -absolute or -relative. -path_info is provided as a synonym. Append the query string to the URL. This can be combined with -full, -absolute or -relative. -query_string is provided as a synonym. Generate just the protocol and net location, as in $self_url = $q->self_url(); The self_url() method returns the value of: $self->url( '-path_info'=>1, '-query'=>1, '-full'=>1 ); $state = $q->state(); The state() method is an alias for self_url() To make it easier to port existing programs that use cgi-lib.pl all the subs within cgi-lib.pl are available in CGI::Simple. Using the functional interface of CGI::Simple::Standard porting is as easy as: OLD VERSION require "cgi-lib.pl"; &ReadParse; print "The value of the antique is $in{'antique'}.\n"; NEW VERSION use CGI::Simple::Standard qw(:cgi-lib); &ReadParse; print "The value of the antique is $in{'antique'}.\n"; CGI:Simple's ReadParse() routine creates a variable named %in, which can be accessed to obtain the query variables. Like ReadParse, you can also provide your own variable via a glob. Infrequently used features of ReadParse(), such as the creation of @in and $in variables, are not supported. You can also use the OO interface of CGI::Simple and call ReadParse() and other cgi-lib.pl functions like this: &CGI::Simple::ReadParse; # get hash values in %in my $q = new CGI::Simple; $q->ReadParse(); # same thing CGI::Simple::ReadParse(*field); # get hash values in %field function style my $q = new CGI::Simple; $q->ReadParse(*field); # same thing Once you use ReadParse() under the functional interface , you can retrieve the query object itself this way if needed: $q = $in{'CGI'}; Either way it allows you to start using the more interesting features of CGI.pm without rewriting your old scripts from scratch. Unlike CGI.pm all the cgi-lib.pl functions from Version 2.18 are supported: ReadParse() SplitParam() MethGet() MethPost() MyBaseUrl() MyURL() MyFullUrl() PrintHeader() HtmlTop() HtmlBot() PrintVariables() PrintEnv() CgiDie() CgiError() I has long been suggested that the CGI and HTML parts of CGI.pm should be split into separate modules (even the author suggests this!), CGI::Simple represents the realization of this and contains the complete CGI side of CGI.pm. Code-wise it weighs in at a little under 30% of the size of CGI.pm at a little under 1000 lines. A great deal of care has been taken to ensure that the interface remains unchanged although a few tweaks have been made. The test suite is extensive and includes all the CGI.pm test scripts as well as a series of new test scripts. You may like to have a look at /t/concur.t which makes 160 tests of CGI::Simple and CGI in parallel and compares the results to ensure they are identical. This is the case as of CGI.pm 2.78. You can't make an omelet without breaking eggs. A large number of methods and global variables have been deleted as detailed below. Some pragmas are also gone. In the tarball there is a script /misc/check.pl that will check if a script seems to be using any of these now non existent methods, globals or pragmas. You call it like this: perl check.pl <files> If it finds any likely candidates it will print a line with the line number, problem method/global and the complete line. For example here is some output from running the script on CGI.pm: ... 3162: Problem:'$CGI::OS' local($CRLF) = "\015\012" if $CGI::OS eq 'VMS'; 3165: Problem:'fillBuffer' $self->fillBuffer($FILLUNIT); .... CGI::Simple is strict and warnings compliant. There are 4 modules in this distribution: CGI/Simple.pm supplies all the core code. CGI/Simple/Cookie.pm supplies the cookie handling functions. CGI/Simple/Util.pm supplies a variety of utility functions CGI/Simple/Standard.pm supplies a functional interface for Simple.pm Simple.pm is the core module that provide all the essential functionality. Cookie.pm is a shortened rehash of the CGI.pm module of the same name which supplies the required cookie functionality. Util.pm has been recoded to use an internal object for data storage and supplies rarely needed non core functions and/or functions needed for the HTML side of things. Standard.pm is a wrapper module that supplies a complete functional interface to the OO back end supplied by CGI::Simple. Although a serious attempt has been made to keep the interface identical, some minor changes and tweaks have been made. They will likely be insignificant to most users but here are the gory details. The list of global variables has been pruned by 75%. Here is the complete list of the global variables used: $VERSION = "0.01"; # set this to 1 to use CGI.pm default global settings $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS; # see if user wants old CGI.pm defaults do{ _use_cgi_pm_global_settings(); return } if $USE_CGI_PM_DEFAULTS; # no file uploads by default, set to 0 to enable uploads $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS; # use a post max of 100K, set to -1 for no limits $POST_MAX = 102_400 unless defined $POST_MAX; # do not include undefined params parsed from query string $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS; # separate the name=value pairs with ; rather than & $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS; # only print headers once $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE; # Set this to 1 to enable NPH scripts $NPH = 0 unless defined $NPH; # 0 => no debug, 1 => from @ARGV, 2 => from STDIN $DEBUG = 0 unless defined $DEBUG; # filter out null bytes in param - value pairs $NO_NULL = 1 unless defined $NO_NULL; # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak $FATAL = -1 unless defined $FATAL; Four of the default values of the old CGI.pm variables have been changed. Unlike CGI.pm which by default allows unlimited POST data and file uploads by default CGI::Simple limits POST data size to 100kB and denies file uploads by default. $USE_PARAM_SEMICOLONS is set to 0 by default so we use (old style) & rather than ; as the pair separator for query strings. Debugging is disabled by default. There are three new global variables. If $NO_NULL is true (the default) then CGI::Simple will strip null bytes out of names, values and keywords. Null bytes can do interesting things to C based code like Perl. Uploaded files are not touched. $FATAL controls the behavior when cgi_error() is called. The default value of -1 makes errors silent. $USE_CGI_PM_DEFAULTS reverts the defaults to the CGI.pm standard values ie unlimited file uploads via POST for DNS attacks. You can also get the defaults back by using the '-default' pragma in the use: use CGI::Simple qw(-default); use CGI::Simple::Standard qw(-default); The values of the global variables are stored in the CGI::Simple object and can be referenced and changed using the globals() method like this: my $value = $q->globals( 'VARNAME' ); # get $q->globals( 'VARNAME', 'some value' ); # set As with many CGI.pm methods if you pass the optional value that will be set. The $CGI::Simple::VARNAME = 'N' syntax is only useful prior to calling the new() constructor. After that all reference is to the values stored in the CGI::Simple object so you must change these using the globals() method. $DISABLE_UPLOADS and $POST_MAX *must* be set prior to calling the constructor if you want the changes to have any effect as they control behavior during initialization. This is the same a CGI.pm although some people seem to miss this rather important point and set these after calling the constructor which does nothing. The following globals are no longer relevant and have all been deleted: $AUTOLOADED_ROUTINES $AUTOLOAD_DEBUG $BEEN_THERE $CRLF $DEFAULT_DTD $EBCDIC $FH $FILLUNIT $IIS $IN $INITIAL_FILLUNIT $JSCRIPT $MAC $MAXTRIES $MOD_PERL $NOSTICKY $OS $PERLEX $PRIVATE_TEMPFILES $Q $QUERY_CHARSET $QUERY_PARAM $SCRATCH $SL $SPIN_LOOP_MAX $TIMEOUT $TMPDIRECTORY $XHTML %EXPORT %EXPORT_OK %EXPORT_TAGS %OVERLOAD %QUERY_FIELDNAMES %SUBS @QUERY_PARAM @TEMP Notes: CGI::Simple uses IO::File->new_tmpfile to get tempfile filehandles. These are private by default so $PRIVATE_TEMPFILES is no longer required nor is $TMPDIRECTORY. The value that were stored in $OS, $CRLF, $QUERY_CHARSET and $EBCDIC are now stored in the CGI::Simple::Util object where they find most of their use. The $MOD_PERL and $PERLEX values are now stored in our CGI::Simple object. $IIS was only used once in path_info(). $SL the system specific / \ : path delimiter is not required as we let IO::File handle our tempfile requirements. The rest of the globals are HTML related, export related, hand rolled autoload related or serve obscure purposes in CGI.pm There are some new pragmas available. See the pragmas section for details. The following CGI.pm pragmas are not available: -any -compile -nosticky -no_xhtml -private_tempfiles Unlike CGI.pm which tries to accept all filehandle like objects only \*FH and $fh are accepted by CGI::Simple as file accessors for new() and save(). IO::File objects work fine. %hash = $q->Vars(); # pack values with "\0"; %hash = $q->Vars(","); # comma separate values You may optionally pass Vars() a string that will be used to separate multiple values when they are packed into the single hash value. If no value is supplied the default "\0" (null byte) will be used. Null bytes are dangerous things for C based code (ie Perl). All the cgi-lib.pl 2.18 routines are supported. Unlike CGI.pm all the subroutines from cgi-lib.pl are included. They have been GOLFED down to 25 lines but they all work pretty much the same as the originals. Here is a complete list of all the CGI::Simple methods. _initialize_globals _use_cgi_pm_global_settings _store_globals import _reset_globals new _initialize _read_parse _parse_params _add_param _parse_keywordlist _parse_multipart _save_tmpfile _read_data param add_param param_fetch url_param keywords Vars append delete Delete delete_all Delete_all upload upload_info query_string parse_query_string parse_keywordlist _init_from_file save save_parameters url_decode url_encode escapeHTML unescapeHTML put print cookie raw_cookie header cache no_cache redirect multipart_init multipart_start multipart_end multipart_final read_from_cmdline Dump as_string cgi_error _shift_if_ref ReadParse SplitParam MethGet MethPost MyBaseUrl MyURL MyFullUrl PrintHeader HtmlTop HtmlBot PrintVariables PrintEnv CgiDie CgiError version nph all_parameters charset crlf # new, returns OS specific CRLF sequence globals # get/set global variables auth_type content_length content_type document_root gateway_interface path_translated referer remote_addr remote_host remote_ident remote_user request_method script_name server_name server_port server_protocol server_software user_name user_agent virtual_host path_info Accept accept http https protocol url self_url state There are a few new methods in CGI::Simple as listed below. The highlights are the parse_query_string() method to add the QUERY_STRING data to your object if the method was POST. The no_cache() method adds an expires now directive and the Pragma: no-cache directive to the header to encourage some browsers to do the right thing. PrintEnv() from the cgi-lib.pl routines will dump an HTML friendly list of the %ENV and makes a handy addition to Dump() for use in debugging. The upload method now accepts a filepath as an optional second argument as shown in the synopsis. If this is supplied the uploaded file will be written to there automagically. _initialize_globals() _use_cgi_pm_global_settings() _store_globals() _initialize() _init_from_file() _read_parse() _parse_params() _add_param() _parse_keywordlist() _parse_multipart() _save_tmpfile() _read_data() add_param() # adds a param/value(s) pair +/- overwrite upload_info() # uploaded files MIME type and size url_decode() # decode s url encoded string url_encode() # url encode a string parse_query_string() # add QUERY_STRING data to $q object if 'POST' no_cache() # add both the Pragma: no-cache # and Expires/Date => 'now' to header _shift_if_ref() # internal hack reminiscent of self_or_default :-) MyBaseUrl() MyURL() MyFullUrl() PrintVariables() PrintEnv() CgiDie() CgiError() crlf() # returns CRLF sequence globals() # global vars now stored in $q object - get/set content_length() # returns $ENV{'CONTENT_LENGTH'} document_root() # returns $ENV{'DOCUMENT_ROOT'} gateway_interface() # returns $ENV{'GATEWAY_INTERFACE'} Here is a complete list of what is not included in CGI::Simple. Basically all the HTML related stuff plus large redundant chunks of the guts. The check.pl script in the /misc dir will check to see if a script is using any of these. initialize_globals() compile() expand_tags() self_or_default() self_or_CGI() init() to_filehandle() save_request() parse_params() add_parameter() binmode() _make_tag_func() AUTOLOAD() _compile() _setup_symbols() new_MultipartBuffer() read_from_client() import_names() # I dislike this and left it out, so shoot me. autoEscape() URL_ENCODED() MULTIPART() SERVER_PUSH() start_html() _style() _script() end_html() isindex() startform() start_form() end_multipart_form() start_multipart_form() endform() end_form() _textfield() textfield() filefield() password_field() textarea() button() submit() reset() defaults() comment() checkbox() checkbox_group() _tableize() radio_group() popup_menu() scrolling_list() hidden() image_button() nosticky() default_dtd() CGI::Simple uses anonymous tempfiles supplied by IO::File to spool uploaded files to. private_tempfiles() # automatic in CGI::Simple tmpFileName() # all upload files are anonymous uploadInfo() # relied on FH access, replaced with upload_info() previous_or_default() register_parameter() get_fields() _set_values_and_labels() _compile_all() asString() compare() read_multipart() readHeader() readBody() read() fillBuffer() eof() Nothing. Originally copyright 2001 Dr James Freeman <jfreeman@tassie.net.au> This release by Andy Armstrong <andy@hexten.net> This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see) Address bug reports and comments to: andy@hexten.net. When sending bug reports, please provide the version of CGI::Simple, the version of Perl, the name and version of your Web server, and the name and version of the operating system you are using. If the problem is even remotely browser dependent, please provide information about the affected browsers as well. Address bug reports and comments to: andy@hexten.net Lincoln D. Stein (lstein@cshl.org) and everyone else who worked on the original CGI.pm upon which this module is heavily based Thanks for patches to: Ewan Edwards, Joshua N Pritikin, Mike Barry, Michael Nachbaur, Chris Williams, Mark Stosberg, Krasimir Berov, Yamada Masahiro This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic. CGI, CGI::Simple::Standard, CGI::Simple::Cookie, CGI::Simple::Util, CGI::Minimal
https://metacpan.org/pod/release/ANDYA/CGI-Simple-1.113/lib/CGI/Simple.pm
CC-MAIN-2014-23
refinedweb
8,839
53.41
v0.59 of React Native is a big deal. It... - Adds support of hooks - Is a big push towards the "Lean Core" initiative - Improves developer tooling With that, I wanted to spend some time walking through how to upgrade (it's easy!), how to upgrade in the future, and handling changes. This post was originally published at React Native School. If you’re interested in learning more about React Native be sure to visit! New articles weekly! How to Upgrade React Native is putting it's foot down on what the proper way to upgrade React Native is and I'm happy to see the community unifying around one solution. To upgrade you'll want to use rn-diff-purge. This tool will allow you to view the differences between your current version of React Native and your target version. For example, here are all the changes necessary to upgrade from 0.58.3 to 0.59.2. Once you've done that and you're running v0.59+ you can then use the react-native upgrade tool. Speaking of the react-native CLI tool... CLI Has Been Moved Out of React Native Core This is a great thing to happen. Why? Because Facebook (who has the final say in what is merged into React Native) wasn't using the React Native CLI internally. That made it a lower priority and thus the CLI was a bit stagnant. With this moving to the community it means it can improve independently of core React Native. We're already benefiting from this one! Learn more about the CLI improvements. Moving Core Packages to the Community If you upgrade to React Native v0.59+ you may start getting some Yellowbox warnings saying that certain APIs are being deprecated. Don't be alarmed! Just like the CLI, this is going to be a great thing for the React Native community as a whole because these package can now be updated and managed independently of a React Native release. Learn which APIs and why they're being moved to the community. Handling Deprecation Warnings in v0.59+ Okay, you've upgraded to React Native v0.59+ (or you're considering it and want to know what it's like to handle those deprecation warnings). How do I take care of the warnings? Let's say we're seeing this warning: The code that causes this warning: import React, { Component } from 'react'; import { StyleSheet, Text, View, Button, AsyncStorage } from 'react-native'; export default class App extends Component { get = () => { AsyncStorage.getItem('item').then(result => alert(result)); }; write = () => { AsyncStorage.setItem('item', Math.random().toString()).then(() => alert('set!') ); }; render() { return ( <View style={styles.container}> <Button title="Get" onPress={this.get} /> <Button title="Set" onPress={this.write} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, }); The Wrong Way The easiest way is to use Yellowbox.ignoreWarnings, like this: import React, { Component } from 'react'; import { StyleSheet, Text, View, Button, AsyncStorage, Yellowbox, } from 'react-native'; Yellowbox.ignoreWarnings(['Warning: Async Storage has been extracted...']); // ... Why is this wrong? Because when you upgrade React Native in the future and the API is actually removed you're going to be confused why things don't work. No bueno - let's fix it now. The Right Way After upgrading React Native (via rn-diff-purge) you can quickly handle each deprecation error. Find the effected APIs and their new home. Terminal yarn add @react-native-community/async-storage react-native link @react-native-community/async-storage Then update your code: import React, { Component } from 'react'; import { StyleSheet, Text, View, Button } from 'react-native'; import AsyncStorage from '@react-native-community/async-storage'; // ... Sure you may have to do it in a handful of places but it's for the best! Conclusion If I've learned anything working with React Native it's to update often. I know it can be tiring but it'll pay dividends. Spending an hour or two each month upgrading to the next version (even if it's a version behind the latest!) wins over having to go from v0.48 -> v0.59. That's going to hurt, take a ton of time, and likely break things. Don't be afraid to upgrade to v0.59! Gotta get them hooks 🎣 (and all the other fantastic updates included). If you want to learn more about React Native be sure to visit reactnativeschool.com! Discussion (0)
https://dev.to/spencercarli/upgrading-to-react-native-0-59-handling-deprecation-warnings-3d07
CC-MAIN-2021-21
refinedweb
737
58.99
Raspberry Pi was synonymous with single-board Linux computers. No longer. The $4 Raspberry Pi Pico board is their attempt to break into the crowded microcontroller module market. The microcontroller in question, the RP2040, is also Raspberry Pi’s first foray into custom silicon, and it’s got a dual-core Cortex M0+ with luxurious amounts of SRAM and some very interesting custom I/O peripheral hardware that will likely mean that you never have to bit-bang again. But a bare microcontroller is no fun without a dev board, and the Raspberry Pi Pico adds 2 MB of flash, USB connectivity, and nice power management. As with the Raspberry Pi Linux machines, the emphasis is on getting you up and running quickly, and there is copious documentation: from “Getting Started” type guides for both the C/C++ and MicroPython SDKs with code examples, to serious datasheets for the Pico and the RP2040 itself, to hardware design notes and KiCAD breakout boards, and even the contents of the on-board Boot ROM. The Pico seems designed to make a friendly introduction to microcontrollers using MicroPython, but there’s enough guidance available for you to go as deep down the rabbit hole as you’d like. Our quick take: the RP2040 is a very well thought-out microcontroller, with myriad nice design touches throughout, enough power to get most jobs done, and an innovative and very hacker-friendly software-defined hardware I/O peripheral. It’s backed by good documentation and many working examples, and at the end of the day it runs a pair of familiar ARM MO+ CPU cores. If this hits the shelves at the proposed $4 price, we can see it becoming the go-to board for many projects that don’t require wireless connectivity. But you want more detail, right? Read on. The Specs and the Luxuries In many ways, the Pico is a well-appointed “normal” microcontroller board. It has 26 3.3 V GPIOs, a standard ARM Serial Wire Debug (SWD) port, USB host or device capabilities, two UARTs, two I2Cs, two SPIs, and 16 PWM channels in eight groups. (The PWM unit can also measure incoming PWM signals, both their frequency and duty cycle.) The Pico has a 12-bit ADC, although it’s connected to only four three pins, so you’ve got to be a little careful there. (Ed note: the RP2040 has four ADCs, but the fourth isn’t available on the Pico.) The twin ARM M0+ cores run off of PLLs, and are specced up to 133 MHz, which is pretty fast. There are separate clock dividers for nearly every peripheral, and they can be turned on and off individually for power savings, as with most other ARM microcontrollers. It runs full-out at around 100 mA @ 5 V, and has full-memory-retention sleep modes under 1 mA. As the ESP8266 and ESP32 modules do, it uses external flash ROM to store programs, and can run code directly from the flash as if it were internal memory. The Pico board comes with a decent 2 MB QSPI flash chip, but if you’re handy with a soldering iron, you can fit up to 16 MB. It has 264 kB of SRAM, which is certainly comfy. The RAM is divided up internally into four striped 64 kB banks for fast parallel access, but they’re also accessible singly if you’d like. Two additional 4 kB banks are non-striped and suggest using themselves as per-core stack memory, but nothing forces you to use them that way either. There are numerous minor hardware-level conveniences. All of the configuration registers are 32 bits wide, and so you might not want to have to specify all of them, or maybe you want to avoid the read-modify-write dance. Like many of the STM32 chips, there is a special memory map that lets you set, clear, or XOR any bit in any of the config registers in a single atomic command. There are also 30 GPIOs, so they all fit inside a single 32-bit register — none of this Port B, Pin 7 stuff. This also means that you can read or write them all at once, while setting individual pins is easy through the above atomic access. An internal mask ROM contains the UF2 bootloader, which means that you can always get the chip back under control. When you plug the Pico in holding down the BOOTSEL button, it shows up as a USB mass storage device, and you can just copy your code across, with no programmer, and Raspberry even provides an all-zeros file that you can copy across to completely clean-slate the machine. If you copy the Pico’s MicroPython binary across, however, you’ll never need the bootloader again. The mask ROM also contains some fast routines that support integer and floating point math, and all of the contents are open source as mentioned above. The power regulation onboard is a boost-buck configuration that takes an input from 1.8 V to 5 V. This is a good range for lithium batteries, for instance, which can be a hassle because they run both above and below the IC’s 3.3 V, so it’s nice to have a boost-buck regulator to squeeze out the last few milliamp-hours. Or you could run your project on two AAs. That’s nice. So the Pico/RP2040 is a competent modern dev board with some thoughtful touches. But it gets better. The PIO: Never Bitbang Again The real standout peripheral on the RP2040 and the Pico is the Programmable I/O (PIO) hardware, which allows you to define your own digital communication peripheral. There are two of these PIO units, and each one has four programmable state machines that run sequential programs written in a special PIO assembly language. Each of the state machines has its own clock divider, register memory, IRQ flags, DMA interface, and GPIO mapping. These allow essentially arbitrary cycle-accurate I/O, doing the heavy lifting so that the CPU doesn’t have to. If you want to program another UART, for instance, it’s trivial. But so is Manchester-encoded UART, or a grey code encoder/decoder, or even fancier tricks. One of the example applications is a DPI video example, with one state machine handling the scanline timing and pixel clock, while another pushes out the pixel data and run-length encodes it. These are the sort of simple-but-fast duties that can bog down a CPU, leading to timing glitches, so dedicated hardware is the right solution. The PIOs are meant to have a lot of the flexibility of a CPLD or FPGA, but be easier to program. Each state machine can only take a “program” that is 32 instructions long, but the “pioasm” language is very dense. For instance, the command to set pin states also has an argument that says how long to wait after the pins are set, and additional “side-set” pins can be twiddled in the same instruction. So with one instruction you can raise a clock line, set up your data, and hold this state for a defined time. A basic SPI master TX implementation is two lines. Or take the example of the WS2812 LED protocol. To send a logical 1, you hold the self-clocked data line high for a long period and low for a short period. To send a logical 0, the data line is held high for a short period and low for a long one. Creating the routines to do this with reasonable speed in the CPU, without glitches, required a non-trivial shedding of hacker tears. With the PIO peripheral, writing a routine to shift out these bits with absolute cycle accuracy is simple, and once that’s done your code can simply write RGB values to the PIO and the rest is taken care of. To run PIO code from C, the assembler is called at compile time, the program is turned into machine language and stored as a matrix in a header file, and then this can be written to the PIO device from within main() to initialize it. In Python, it’s even easier — the @asm_pio decorator turns a function into PIO code. You just have to write the “Python” function using the nine PIO assembly instructions and then hook it up to GPIO pins. After that, you can call it from your code as if it were a normal peripheral. Having played around with it only a little bit, the PIO is the coolest feature of the Pico/RP2040. It’s just a little bit of cycle-correct programmable logic, but most of the time, that’s all you need. And if you don’t feel like learning a new assembly language — although it’s only nine instructions — there are a heaping handful of examples already, and surely folks will develop more once the boards hit the streets. IDEs and SDKs: C and MicroPython The Raspberry Pi single-board computers (SBCs), when combined with their documentation and examples, usually manage a nice blend of being simple enough for the newbie while at the same time not hiding too much. The result is that, rather than having the underlying system’s Linuxiness abstracted away, you get introduced to it in a friendly way. That seems to be what the Raspberries are aiming at with the Pico — an introduction to microcontrollers that’s made friendly through documentation and MicroPython’s ease of use, but that’s also not pulling any punches when you turn to look at the C/C++ code. And having a Raspberry Pi SBC on hand makes a lot of the most hardcore microcontrollering simpler. For instance, if you want to do debugging on-chip, you’ll need to connect over the SWD interface, and for that you usually need a programmer. But of course, you can also bit-bang a SWD controller with the GPIOs of a Raspberry Pi SBC, but you’ll have to configure OpenOCD just right to do so. If that all sounded like gibberish, don’t worry — all of this is taken care of by a simple pico_setup.sh script. It not only installs all of the compilation and debugging environment, it also (optionally) pulls down VScode for you. Nice. And you will want to program it over the SWD eventually. The cycle of unplugging USB, holding down a button, and re-plugging USB gets old real fast. If you’re a command-line junkie, the C SDK’s build system is based on CMake and runs just fine from the command line if you’ve already got the ARM toolchain installed. And as with all SDKs, there’s a certain amount of boilerplate necessary to start up a new coding session. This is taken care of by the pico project generator, so you don’t have to. In the “Getting started” guides, you’ll find instructions for setting up your environment on a Raspberry Pi SBC, Windows, Mac, or desktop Linux machine. If you prefer Eclipse as an IDE, there are integration instructions as well. Two Cores: Here be Dragons If there’s one area that strikes me as not yet fully developed, it’s the dual-core aspect of the system. Right now, if you write either C or Python code, it’s running on Core 0, while Core 1 is simply sitting idle. Both the C and Python SDK documentation tell you how to start up a thread on the other core, and there’s example code available as well, but the instructions are sparse. In C, there’s a pico/multicore.h and even mutex, semaphore, and queue libs for you to include, but the documentation warns that most of the stdlib functions aren’t thread-safe. In Python you import _thread and call the start_new_thread() method, but I don’t know how much fine-grained control you have. If all of the above sounds scary, well, it is a little. The truth about coding for multiprocessor systems is that it opens up new ways for things to go wrong, as one CPU changes values out from under the other, or they both try to write out to the UART at the same time. We wrote the Raspberries and asked if they were planning to port over an RTOS, which provides a little more structure to the problem, and they replied that that was actually first on their plate after they get through the release. So unless you know what you’re doing, you might not get the full benefit of the dual-core chip just yet. But we’re honestly looking forward to an RTOS getting the Raspberry Pi documentation-and-tutorial treatment when it happens. Deep Thoughts It’s not every day that you see a new player enter the microcontroller market, let alone one with the hacker-friendly qualifications of Raspberry Pi. For that alone, this board is notable. But the feature set is also solid, there are many creature comforts in both the silicon and the support, and it brings one truly new capability to the table in the form of the PIO units. Add to all this a price tag of $4, and you can imagine it becoming folks’ go-to board — for those times when you don’t need wireless connectivity. Indeed, the only real competitor for this board in terms of price/performance ratio are the various ESP32 boards. But they’re also very different animals — one offers fewer GPIOs but has extensive wireless features, and the other has more (and more flexible) GPIO, device and host USB, but no radio. Power consumption while running full-out, with wireless turned off, is a slight advantage for the ESP32, but the sleep modes of the Pico are slightly thriftier. Both SDKs get the job done in C, and both run MicroPython. ESP32’s dual cores run FreeRTOS, but we imagine it won’t be very long before that playing field is levelled. So basically it’s down to WiFi vs USB. Of course, for slightly less money, one can pick up one of the STM32-based “Black Pill” boards, with yet another set of pros and cons. Choices, choices! With the Pico, Raspberry Pi is entering a crowded field. They’ve got the name recognition, a cool hardware trick, a great value proposition, and a track record of solid documentation. If I were coding up a GPIO-heavy application without the need for wireless, the Pico would be a solid choice, especially if I could make use of the extra core. I’ll leave you with a teaser: On page 9 of the RP2040 datasheet, they lay out what “2040” stands for: two cores, type M0+, more than 256 kB RAM, and zero kB flash. Does that mean we’ll eventually see models with more RAM, onboard flash, or different ARM cores? RP2050? RP2048? Speculate wildly in the comments. 351 thoughts on “Raspberry Pi Enters Microcontroller Game With $4 Pico” Will you actually be able to buy more than one of them at that price, or is this just doomed to be another repeat of the Pi Zero fiasco? You can buy 100,000 of them at that price if you want! As long as there’s hardware meant to be sold as cheaply as possible, there will always be scalpers and hoarders. This is not why Pi Zero supplies were (and still are) supply constrained. It’s because of their rather eccentric approach to manufacturing. Zeroes are supply constrained? I’ve never not seen them available at Microcenter when I rummage around the Hobby section. When they were first released, the scalpers were everywhere! Totally spitballing here, but the price is very fair, but not totally out of whack either. The board has the chip, power, flash, a crystal, an LED, and a button: seven parts that aren’t caps or resistors. B/c the USB is handled on-chip, there’s no USB-UART chip, and all-in-all, it’s a much smaller BOM than on an ESP32 board, for instance, and they run $4-$5. I’m glad they splashed out on a nice boost-buck power section, but other than that, there’s only the flash chip that separates this from the $2 blue pill boards. I haven’t seen pricing on the RP2040 bare chips yet. Anyone? I’d guess their margin is very tight, but I don’t think they’re losing money. The Pi Foundation is probably fine (They mention debugging one with another one, so clearly they plan to support you buying at least two), but scalpers could still trash the whole thing to thee point where we’re paying $12 for a full kit with crappy laser cut cases we don’t even want. plus an arm and a leg for shipping and you can only order 1 in each order. Hey Statler and Waldorf, is that really you? ;-) You can connect the debug with a Raspberry Pi Linux computer, no need to use another RPi pico. And it is two M0+ cores, with a special small CPU for IO, so you don’t need to bit bang other protocols, like for those popular leds and other easy protocol. They can also produce interrupts to the main CPU:s Yes, it is a nice and well though through for what it is designed for. Both the chip and the break out board it sits on. The RP2040 chips are 40nm, and 2mm^2 in size – they have a lot of room to manoeuvre in bare chip pricing as they might get 10,000 per wafer (assuming 8″ wafer). There are several third party boards already designed, and listed on the RPi website, including an Arduino with Wifi+BT. You can get a free Pico with a magazine as well this month. I think they’ve made enough (in Japan, this time, not UK). Magazine name?? Wait.. nevermind, I found all the info and realized what you’re saying a bit better. The Pico’s are made in japan, but the magazine is hackspace magazine, which is only affordable in the uk. £90 for a subscription which starts at issue 40, when the pico comes with issue 39 is also quite tricky when they suggest you can get the pico with a subscription on the raspberry pi blog. Super disappoint. John, there’s a free Pico on the front of Issue 39 of Hackspace, but their subscriber offer is also now a free Pico (it used to be a Pi Zero). So if you were able to start your subscription at issue 39 you’d get two boards, one freebie on 39’s cover, and one as part of your subscription. 39 seems to be out of stock now, unfortunately. Shoe, thanks for the update, but still £90 is a lot for a pico and some magazines. I’ll try to find a single issue of 39. Dang, I think Hackspace is available at the big Walmarts that have overpriced Pi and related robot and STEM kits in the electronics section. But I’m not near enough any of them. thanks for the headsup Shoe. We’re under heightened covid restrictions here though atm so I can’t really troll a bunch of stores looking for it. Though I’ll certainly check for it at stores I need to go to anyway over the next month. ESP32 boards are $4-5 retail. If you buy 1,000 of them they are $2. RP2040 is still $4 if you buy 1,000. Damn Elliot, you got a phrasebook that’s called “Hello Fellow Kids” or what? I was originally referring to the “one per household” policy on the OG Pi Zero per the RPi foundation that is still in place, not the supply issues at launch. The supply issues were fixed long ago, but I still can’t buy more than one from official distribution channels in the same order. Pimoroni have a “3 per customer” limit for Pico sales in the UK. Limits will be relaxed for Pico once the sales pipeline is filled. Adafruit has them bouncing in and out of stock. Limit 3/order. IDK if you can submit multiple orders/day. The basic Zero $5 price is a subsidised educational price. You can buy multiple ZeroW or ZeroWH but they are more expensive. You can also buy multiple basic Zero’s but you will pay more as they won’t have the educational subsidy. You can’t. ZeroW are similarly restricted. ZeroWH are supposed to be unrestricted but are often restricted just the same. Go and look on e.g. Adafruit. The thing about scalpers is the nearest microcenter sells pi zero W for $10 and cheapest Amazon is $18.48 so scalpers with their 84.8% profit margin amirite? However, when you actually run the numbers, the nearest microcenter is 100 miles away so figure at least 50 cents per mile, plus sales tax plus highway tolls and I can buy one pi zero and be home in three hours for maybe $125 or so. The scalper only wants $20 and 60 seconds on amazon. On the other hand, a USPS flat rate priority mail box is $8.30. That means the “scalper” on amazon is pocketing a staggering eighteen cents of corrupt profit for the privilege of printing out a shipping label and tossing a pi in a box and tossing it in a mailbox. So if I participate in the scam economy and buy from the scalper I save myself three hours of driving and about a hundred bucks of wear and tear on the car which is nothing to laugh at. Also you can’t freely swap between billable hours and hobby hours but if you could then driving out to get the pi is going to cost me a couple hundred bucks lost in billable hours. Now if some guy living in Chicago is “scalping” 100 pi at a time every day as a side hustle, I can respect that and it multiplies out to paying for the guys lunch every day, and I’m good with that. It saves me a lot of money and is very convenient. And you can get a RPi pico (and could get a RPi zero W) for about $90 AND a year subscription for a magazine, sent home to you. “I couldn’t get one of a massively in demand item instantly, so I’m gonna be salty about it forever” Hope that’s working out for you. Here in Australia they literally have 2500 units ready to go, and we’re the arse end of the world. More importantly, the product’s Australia tax is quite reasonable. No, more like “The Raspberry Pi Foundation’s official policy is that you are only supposed to be able to purchase one Pi Zero, and all official distributors limit to one per household” I’d appreciate if someone could provide a link to a supplier in the US where one can purchase more than one Pi Zero (non-W) from for close to $5/each? Because the fact that I can’t buy them for anywhere close to $5 due to having to have them shipped individually is honestly is what has kept me ftom building projects using them so far. The PI zero slower than death anyway. I bought one a while back because it sounded cool, but dozens of project later I’ve yet to find one that’s not better suited to a regular pi or a microcontroller. I guess the low price is cool, but if I’m going to spend 10 hours getting something working I can afford to spend 10 dollars on the MCU instead of 5. I saw many stories of people going to Micro Centre and getting a bunch at a time. When I go to Micro Center, I can buy (1) Pi 4, 1 Pi Zero, 1 Pi ZeroW, and maybe a Pi 3, (per day) if they are in stock. What can you build with it? I’m totally new and have no idea what toys I can make. Anything you can make with a Pi, only it’ll run slower and require more effort on your part. You can go thru the motions, challenges, and thrills of setting up a very small cheap and portable compute cluster, very educational. The various bus options are easy to interface to. Buy some stereotypical weather sensors like the $3 BME280. Lets say ten of each. Then solder them together and scatter thru the house and do some data science magic to graph how humidity flows thru the house when you boil up some pasta in the kitchen or how you can actually measure the speed of the furnace air in the ducts as the house slowly warms when the furnace is on etc etc etc. Its hilarious to stick a $5 magnetometer or $2 light sensor on a pi and try to do presence detection across ten or so pi scattered thru the house. You can learn a lot about AWS and IOT by turning them into IOT devices that uplink to amazon and do all your data analysis in the cloud. You certainly don’t have to, to handle five temperature sensors, LOL. But the whole point is learning to play with AWS and IOT tools. I mean its not really a pi project at that point its a project that uses pi. Even if you only buy two or three you can learn a lot about I2C by making them talk to each other over I2C. Or for the more ambitious try to reimplement IRDA infrared networking. Pi make halfway decent digital picture frames or magic mirror drivers. The only thing better than one digital picture frame is maybe four synchronized-to-each-other frames. Also e-ink status displays are kinda cool. You can have a lot of fun with about five or so pi. Alone with bare hardware you can’t do much more than make a cluster but attach almost any sensor and multiple devices will be fun. Anything you can do with any other cheaper micro-controller (AVR, STM32F1 and thousands more) This arrives a little late to the game. yet if I want to buy a Pi zero, I can still only buy one at a time, and then pay shipping on top of it. so I am paying 25 for each and everyone I use. I am in Melbourne, so this is a 100% attack on the way it works here. Sparkfun: “We have an order limit of 100 per customer on this product.” Price: $4. Sparkfum on Thu., 21-Jan-2020, 21:35 EST: “BACKORDER. We have 1328 incoming. We do not have an estimated date yet. Incoming stock values are estimates, and subject to change without warning. Note: We have an order limit of 100 per customer on this product.” Yeah, typical Raspberry Pi unobtainium syndrome. Adafruit too! “And we have plenty, so don’t worry about it. We’re not gonna run out in like…two minutes. There’s a lot of supply […] we got many thousands of these so I’m not concerned about it” – Adafruit livestream @ ~02:00 CST “IN STOCK” – Adafruit twitter 13:49 CST “OUT OF STOCK. Please enter email to be notified when this product is back in stock” – Adafruit website at 20:48 CST I placed my order on Sparkfun within 15 minutes of this article getting posted, so hopefully I’m at least at the front of the line, but it still hasn’t shipped, so who knows! Just bought 3 of them on sparkfun with no problems. The total was like 20 bucks with shipping and tax. i just purchased 5 to play with and give to friends. So yup no restrictions that i could see. As far as I can tell it’s impossible to actually buy it for $4 133mhz dual core M0+ with 265k of sram That’s rather impressive and quite compeditive even at twice the cost I have been relying on bluepill clones for my goto cheap ARM boards It’s no M4F but it would still be very very useful Nice to have two cores, but since they are M0+: no I-cache. It basically means that one can run from flash, the other from ram. If both run from flash it will basically means that it will be faster to run one core. There is a 16K (separate from the SRAM) two way cache for the XIP flash, so many programs will be fine out of the box. You can move any C function into RAM via a decorator macro, and of course the floating point routines are in ROM, so no contention there. Also the SRAM is striped to minimize contention. They could have done it that way but it seems like they did not. I welcome corrections on this comment… The spec mentions a 4:10 crossbar. (see page 14, the pic helps) The 4 bus masters (both cpu’s and dma) can all access the 10 slaves simultaneously (not the same slave) the memory is broken into 5 banks so you should be able to run one core from one bank and another from another bank without slowing down. matrix has 2GB/sec BW. Now the rom looks like it is single slave port so maybe some occasional arbitration there. Same if the cores are accessing the same bank for some shared code or data.. I would probably load from the flash into sram and go. Maybe it allows one core to run xip from the flash and the other from sram… The spi is QSPI , not sure the speed they are running at for slowdown.. I need to read more details and see if there are app notes. If you have a big program that’s a whole different thing, dma in/out chunks etc.. Hoping there is an m33 version with I$/D$ in the works. Note also the M0+ is executing mostly 16 bit instructions, but does 32 bit fetches. There is a lot less contention than you would expect and you can get two cores plus DMA going flat out without much trouble. The two smaller memories contain the two stacks by default, which is a decent fraction of your load/store bandwidth pointed at memories that are by convention core private (although this isn’t enforced in hardware, you can do whatever you want with your RAM). You can also stash some core-private hot code in those memories if you need guaranteed access, and there are macros to do this in the SDK. Some thought went into this! > there is a special memory map that lets you set, clear, or XOR any bit in any of the config registers in a single atomic command That isn’t uncommon on microcontroller ARM chips. Which was pretty much stated in the other half of the sentence you conveniently left off. Sure, it’s not limited to STM32, but it’s not like Elliot was claiming it’s a novel feature either. Is it a standard ARM feature? I haven’t dug really deep into any of the ARMs outside of ST’s offering. ARM provides bitbanding as an option for most (all?) of the Cortex-M cores. Interestingly it looks like it’s definitely “most” – M0 and M7 don’t have it, and the RP2040 has what must be a custom implementation specifically for the peripheral register regions. Note bitbanding is entirely useless on a system with two cores. The access might be atomic from the software point of view, but it’s still a read-modify-write on the _bus_, so the accesses still race. Doesn’t a mutex implemented in hardware let you use bitbanding on a multicore chip. All you need is an atomic instruction to test a bit and leave it set after testing. Then each core can test that bit and use it as a gate before starting a read-modify-write sequence. I can’t believe any modern multi-core chip would lack that instruction. Oops, last comment was hasty, bitbanding is implemented as read-modify-write on the bus but is safe if your vendor bus fabric implements bus locking correctly (which is part of the required bus standard) Anyway M0+ does not have bit banding natively, though some vendors choose to hack it on with a wrapper around the processor. On RP2040 all the registers support set/clear/xor of the entire register, and this is a native function of the actual register blocks. It’s a bit more general than bitbanding, makes it easier to update multiple fields at once. @pelrun said: “ARM provides bitbanding as an option for most (all?) of the Cortex-M cores.” @Luke Wren said: “Note bitbanding is entirely useless on a system with two cores. The access might be atomic from the software point of view, but it’s still a read-modify-write on the _bus_, so the accesses still race.” In the ARM Cortex M3/M4, bit-banding read or write operations are not Read-Modify-Write (RMW). Indeed the whole purpose of bit-banding is to avoid using multiple instruction cycles to read or write from/to a register bit, like needed with RMW operations. The problem solved by bit-banding is that with RMW, something might change between one of the instructions (e.g. pin-change interrupt), this can potentially cause a race condition. A bit-banding read or write operation is atomic and takes place in a single instruction cycle. All M3/M4 cores on die are clock coherent, so during a bit-banding operation nothing can change. Regardless, I believe bit-banding is only available on the ARM Cortex M3/M4 chips. So unless the ARM Cortex M0 IP being used on Rapberry Pi’s RP2040 chip has bit-banding added to it (not likely), then there must be another mechanism in-place to prevent race conditions from occurring between the two M0 cores. That would be a good question for the RP2040 designers. Maybe there’s a commutator between the two cores, or some mutex/semaphore magic might be happening. Here are a couple of bit-banding links: 1. Bit-banding – An Elegant Approach to Setting & Clearing Bits 2. Cortex-M3 Embedded Software Development – AppsNote179, Sec.-2.5 Bit-Banding Bitbanding only allows you access to a single bit at a time. This allows you access to 32bits at a time *and* allows you to and/or/xor any of them; with bitbanding you can only set or clear in a single instruction and you will need to do the address calculation for each bit to be modified somehow. there is an alliance Arduino: Adafruit: and Sparkfun: Dang, the Maker-Industrial Complex is real! ;-) Pimoroni: This looked nice but not really interesting to add to my giant pile of microcontroller boards until I saw that PIO feature… dang. More skulls for the skull throne! No, no. PIO experimentation from the MicroPython REPL! I think this’ll be really interesting for a whole bunch of really strange use cases. Stoked. Realtime hardware decoding of cheap digital calipers for use as position encoders on servo-based CNC machines comes to mind. no need for PIO, calipers are only 10Hz output, 50Hz for the ones that support fast mode, hardly a realtime issue. Yeah. I went from “meh another microcontroller” to “I WANT ONE NOW”. Most people just drive Canon EF lenses with a normal SPI controller, ignoring the possibility the lens might try to insert busy states. But the real Canon EF protocol is a variant of SPI where the lens can hold the clock line low to stop data transfer. PIO would be perfect for this. It sound a bit like I2C clock stretching. Micro-USB? Really? USB-C would have been a much better option :-( Good thing nobody is forcing you to buy it! :-) Someone must, otherwise there wouldn’t be a market for scalpers*, and hence complaints. *In general. Not this board specifically. Adafruit have a RP2040 based “feather” board that uses an USB-C connector I hate USB-C, the cables are either fully featured, and become too thick and stiff, or the cables are not fully featured, and don’t work when you expect them to. Meanwhile, I can tie a knot with my USB micro cables and it’ll still work. except there are power only and data also style micro-USB cables around. The former are abundant when coupled with a power supply with USB-A socket. I would have preferred USB-C too but it isn’t that much of a deal breaker to me. I got plenty of both cables lying around. Oh my. This is going to take a minute or two to digest. Thanks, Elliot, I didn’t have enough to think about already! “The Pico has a 12-bit ADC, although it’s connected to only four pins, so you’ve got to be a little careful there.” Eliot, care to show where the 4th ADC input is on the Pico? The fourth pin goes to an internal temperature sensor. Depending on phrasing… There are 4 ADC-capable pins on RP2040, and all are used on Pico, but only 3 are broken out on the edge pins. The fourth RP2040 ADC pin can be used to measure the VSYS voltage via a resistive divider. There is a fifth ADC input on RP2040 which connects to the internal temperature sensor. The fourth external input also goes to a testpoint on the back, and pico can be surface mount soldered as a module, which lets you break out these test points onto your board. That lets you use the fourth external input. Dual-core seems like a crazy idea, it only invites endless complexity and nightmares… I’d rather have a little faster M4 core! It also sounds like they have not paid much attention to power consumption if it burns more than an esp32… On the price front, doesn’t an esp32-s2 pack more performance, a lower price, usb, and wifi, and bluetooth? ESP32-S2 doesn’t do Bluetooth and doesn’t have anything comparable to PIO. The ESP32-S2 does have the “ultra low power” co-processor, which on that device you can run in RISC-V mode. Taking a quick look, it can run while the main CPU is running, not just only while in sleep mode. The s2 doesn’t have bluetooth and is single core. I think you are wrong on the multiple cores (though I agree I’ve been writing for multiple cores for quite a few decades) – it is really really really useful to have. And it isn’t that hard to do safely – ie thread safe queues are your best friend, as are thread safe events :-). The power comparison might not be totally fair. I should really do that right. The numbers from the Pico are with it running basically flat out on both cores: doing video and I2S audio. I fear I might have been comparing a max value to an average value in my mind. The ESP32s are actually pretty good with power, considering clock speed and peripheral load, once you turn the radio off. With the radio on, you can kiss your batteries goodbye. :) Neither of them have very good sleep power draws, in my book. When an AVR sleeps, for instance, it’s a handfull of microamps, but when an ESP32 / RP2040 sleeps, it’s 100-200 uA. Throw in some support circuitry that stays powered up, and there you go. Is it just the difference between 2 kB RAM and 264 kB RAM? 10x sleep power draw? Could be. It’d be fun to do a low-power shootout and get all the numbers in one place. From what I understand from the chip guys/gals, RAM is a big part of it, as SRAM costs a certain amount of current per KB to keep ‘alive’. AVRs only have a few K of it, an ESP32 has a few hundred K. Note that in deep sleep, where you only get the 8K of RTC RAM to store your persistent info, the ESP32 also only sips a few uA. Yes. Some chips have the option to disable part of the SRAM in sleep for that reason. I highly doubt the SRAM has anything to do with it. Of all the ram types that require power to retain their contents, SRAM is one of the more power efficient. In the 90’s before flash memory was popular, we had SRAM PCMCIA cards. These were battery backed with a CR2025/32 coin cell or two and the battery would last for a year or more with the card outside of the host system. I can only imagine SRAM has gotten more power efficient since the 90’s The ESP32-S2 in deep sleep is specced for about 25uA, and Adafruit has confirmed that in practice: see the several most recent Desk of Lady Ada videos. My MagTag, which lacks a few of the low power tweaks from the videos due to being first generation, lasts about a week on 420mAh, waking up to run a circuit python program to grab some json, parse it, and update an eink display daily, with an always on 20uA power left. I wonder if you could simplify the utility of it by basically writing your code in 2 parts with no common variables and segregate what pages of memory they are allowed to touch and then have a shared set of variables and memory area and a token that gets past back and forth for explicit control of which core can touch the memory (read and write only when holding the token) That’s one way. But there are HW spinlocks and intercore mailboxes to do proper core cooperation. Yup, that’s the way to go. Use one core for handling digital and analog inputs / devices, and use the other core for UI functions, and you’ve got a winner. Remember Multibus? This is exactly the way I architected a multiprocessor / shared memory anesthesia monitoring system in 1980 :-) This device is going to give the Colour Maximite 2 a run for its money. If you think having two cores is a pain, wait til you have both code that can’t be interrupted and interrupts that are time critical :) Often you can write pretty simple firmware with two polling loops that would otherwise have a bunch of exciting context switches. Dual core can be a savior. It is hard to get microsecond-precise timings in a scenario where you, say, collect data from a few SPI devices and ADCs at high frequency, process it and send at very specific time up the UART. Any interrupt-driven design would screw timing in a single core scenario. Having two cores polling explicitly all the lines is cleaner and far more predictable for a hard real time. Given you can avoid locks. I wonder how many samples per second it can do. Apart from the PIO, why bother? The esp32 has more ram (better organised too, which is really saying something as it’s something the esp32 has to do better..), has wifi & bluetooth, and is the same or cheaper cost… And why didn’t they put RTOS on this? “Apart from all the things this does differently to , this is pointless and you should just buy “. The PIO isn’t the only novel thing in there, I’m only partway through the datasheet and just hit the section on the integrator. WOW. An RTOS is just software, nobody’s stopping you from writing one if you need it (although the Pi Foundation has said they’re already writing/porting one – it just didn’t need to hold up the launch.) There are actually a _ton_ of cool microcontroller design choices here. The Pi folks had the chance to do a ground-up ARM design, and they took it. I read through the whole datasheet (663 pages!) and there are little helpful tidbits scattered throughout. I’m not a DSP nerd, but the accumulator and the fast math routines in the ROM should be interesting for those folks. But I also remember thinking the same on the ESP32 release. The parallel I2S peripheral in particular blew my mind. (And we’ve seen some really awesome hacks that use it since then.) I wanted to pick one standout new thing about this chip, that will be of maximum interest to the Hackaday crowd (read: creative thinkers) and that’s the PIOs. But to answer Ian’s question: USB, more GPIOs, the PIOs, and we can argue about ARM vs Tensilica. Trade that against wireless, more flash, and some of the other crazy features of the ESP32, like that I2S and the odd flexibility of the RTC low-power CPU. They’ve got different strengths. And at these prices, you can buy one of each! without wifi or bluetooth, how are you going to get it to talk to anything? And yes, I could put RTOS on it. But it is a bit silly releasing it without that done. I also posted above that the ram of 264K in banks is a bit of a strange decision… Ram (and the way it is organised) is one of the main issues with the esp32, and it has more – better organised – than this pico. This would have been a fantastic board 5 years ago, but no wifi means it has to plug into something else – and maybe that is the whole plan, for this to always be the daughterboard of a full PI. In that case, once RTOS is out, I can see it being useful – and it might end up as a daughterboard on quite a few esp32 projects as well… What exactly is the problem with the RAM organization here? Causes? Consequences? (Serious question.) I hope that there is no crossing boundaries issues like there is on freescale/NXP MK64F, 256KB total but 192+64kB banks. So you must take care that a data access doesn’t lie between both as it will not end well. @mac012345, the linker script (GCC talk) or the memory map of your compiler would take care not to allocate arrays/data structures straddle across the boundary. As for indirect access e.g. pointers or DMA src/des, you are on your own coding practice with some boundary checks. You seem to have a highly limited view of what microcontrollers are used for, and your only reference point is the ESP32. Microcontrollers have been used in hundreds of thousands of applications that *do not* involve wifi or bluetooth anywhere. Other controllers don’t have “poorly organised ram” only because it’s different to how the ESP32 does it. You might want to consider that the embedded world is wider than just *your* use cases. yes, and I’ve used a number chips to do them. BUT this is not meant for all those many (but falling) devices that need no connections, it is meant for consumer level programming. That, now days, means connecting via wifi or bluetooth. I’ve got into the 8266 and esp32 because I had a son who I wanted to teach some stuff to. He now uses them a lot – as does his friends at school – and does c++ on them. He looked at the pico and his first comment was ‘useless, I can’t put it on the network’ – and he is one of the key demographics targeted by PI.. So you simultaneously think you know what this is “meant for”, and also think it’s completely misdesigned for that purpose. Ever considered that you’re completely wrong? Whats the point of yet another half baked device that can’t operate standalone and can’t communicate with the outside world unless hard wired to something else in host mode? Do I need to spend $4 in order to blink an LED? Will this drive relays out of the box? No. Useless. At least they didn’t force another SD card dependant device on their users. @not spam Just because you can only think of IOT application, doesn’t mean every applications are IOT. There are a lot of applications (especially industrial ones) that does not rely on a wireless link. If history has anything to go by, I am sure at some point there will be a version with Wifi added at some point. people forget that the pi foundation primary role is education. the fact that the boards have been a commercial success is just a happy coincidence. They are not competing against arduino or ESP32, they are creating a product that can be used to teach uC programming. The fact there is a myriad of possible uses is just a testament to the design team In a few weeks – Arduino Nano RP2040 Connect >They are not competing against arduino or ESP32, they are creating a product that can be used to teach uC programming I think some people are missing this, a load of people on Reddit are all “but this other chip has way more features!” It’s much easier to write good teaching resources when you have control over the firmware and hardware releases too, with your own distinct boards rather than trying to wrestle with an endless line of “sort of compatibles”. Arduino is really aimed at an older audience than the kids the Pi Foundation normally works with, and branching from software and physical computing to microcontrollers is fairly logical. I’m fairly sure Upton has said in the past that there aren’t enough good electronics resources for kids, so maybe this is the first step in that. I guess that if you’re the kind of person who can critically assess the specs, compare it with alternatives off the top of your head, and question if this is an optimal solution, then you’re already way beyond the market this is designed for. the pi foundation have themselves forgot their primary role is education. closed blobs, compute modules, and dual display outputs are purely for commercial interests. speaking of missing education: rpi400 EU kit with US keyboard layout ?! The US is on another continent. The UK on the other hand is still located in Europe.. No matter how many Brexit’s the hold. “rpi400 EU kit with US keyboard layout ?!” yes, many Europeans – and in particular coders – prefer a US keyboard layout. US layout is the best. I prefer metric layout. The same anyone made other microcontrollers without BT and wireless did before the ESP chips. Those chips did not exist at one point and the world still had BT and wireless connectivity. Wow you must be very new to micros. Before wifi we connected to micros via USB or two wire serial. Both work and are easy to use. How can it talk to anything? *IOT intensifies* You have a limited perception of what MCUs are for. Honestly cannot think of too many cases in the past few years of professional embedded development where I needed an MCU to have any wireless connecrivity. And most of the designs had more than one MCU anyway, doing different things. Also, why WiFi or Bluetooth when, say, LoRa is far more practical in an industrial environment? Cheap and not made in china is probably the best reason. “not made in China” is not a selling point at all, because that’s just for now, and subject to change without notice. I really wish they had done a branded ESP32 board with their own software support and the extra hardware features, but this still looks like the perfect choice for building USB peripherals. I assume this has proper native USB, it’s cheap, from a trusted brand, and that buck-boost regulator really makes it all worth it. Assuming it can handle Vin and USB at the same time, that feature lets you make a UPS with just an LTO battery or ultracap, a 2.5v regulator, a resistor, and some diodes. Maybe we can see better cheap USB interfaces for things like NFC and DMX, that traditionally cost a lot. The newer ESP32-S2 chip has native USB. No WiFi? All my remote $4 Nodemcus are programmed wirelessly and use a web page for a HMI. Search “Nodemcu12E” for the projects. it looks like there is going to be a board from arduino with wifi/bluetooth, no price of availability listed yet All those RTOSes are not really that RT to start with, unless you’re super careful in your designs. And dual core allows to do far more stuff without an RTOS, having a simple FSM polling all the devices at 100% predictable time intervals. Every time I can get away without having to use an RTOS, with just a bare metal single process, no interrupts, I do. And I personally find this coding style much simpler than relying on any RTOS scheduler. Because I can get the Pico from a reliable supplier for $4. (Well, I’ll be able to when production catches up with demand.) Show me where I can get ESP32 boards for that price that isn’t a sketchy small producer in China. Will the microcontroller itself be available to buy from our favourite shops? so we can design custom boards for it. Yes. Well, depends on where you favourite shop is, but the chips will be available to purchase! Yup, cross marketing deal with liquor stores in association with JD4kidz training whiskey. “After a hard days coding, get rekt.” :-D Another bogus announcement… sorry. Rpi 4 compute with 8 gb ram and the rpi4CM expansion boards are nowhere to be found, meaning there are no facilities able to manufacture them…. and they launch another dream product – which will also be nowhere to find? Pretty simple. These are available now from most resellers. CM4 stuff is being produced as fast as possible, but demand has been much higher than expected. Note that the Pico and the CM4 comes from different factories (Japan and Wales respectively), so there is no conflict in production. Have you even bothered to look at the availability? I just picked up one of these from sparkfun this morning. No issues with stock. im curious about that boot rom. if it is masked or simply a onboard eeprom. The uf1 seems to be different from the linked repo. And its a bit odd to mask a debug build. But if it is a custom chip, certainly a possibility! More info please ;) From the datasheet: A 16kB read-only memory (ROM) is at address 0x00000000 . The ROM contents are fixed at the time the silicon is manufactured. It contains: • Initial startup routine • Flash boot sequence • Flash programming routines • USB mass storage device with UF2 support • Utility libraries such as fast floating point Yup; boot rom is in ROM, no EEPROM .. it is what it is :-) What is stored in flash is entirely user program/data – there is no “bootrom” in flash – i.e. you can’t brick the board. Most things (including MicroPython impl itself) link against the C/C++ SDK runtime which provides transparent support for use of the ROM/hardware or floating point operations, integer fast divide etc. Thanks for both your replies, but I meant also, the fit repo, is that the source of the masked ROM?! I would hope and assume so then, but it is very unusual for a coorp to that. Also if you look at the pi and those bootrom shenanigans. Either way, if it truely is (reproducible build?) Kudos to the pi foundation on that one. Points scored. It’s explicitly mask rom. And debug builds just add debug sections to the elf, it doesn’t change the code itself. >a friendly introduction to microcontrollers using MicroPython But why?? Like if you ever want to do “serious” things on microcontrollers you have to go with C/C++ anyways. Why Python? Yes, things are hard. Why not teach them, but throw massive amounts of abstraction at people? Agreed. The main downside of c and c++ is the exact reason they’re good for microcontrollers: they’re close to bare metal. because there is a lot of stuff that doesn’t meet your criteria of “serious” that’s useful, and if MicroPython lowers the learning curve, you can get useful stuff done easily. I guess you are right. Maybe I am some sort of boomer when it comes to handling with microcontrollers, but I literally enjoyed the journey a lot. Learning about bare metal and handling with register FIRST before using abstraction things like Arduino or STM32 HAL. Imo that just gives you just a better understanding of the whole system, but apparently that’s not fun for everyone and I kinda have to accept that. When ESP8266 appeared I started playing with Lua first and once I got comfortable with the platform I started gradually moving to C. All this even though I didn’t know Lua at the time and had 10+ years experience in embedded C programming. So I’m glad that there are multiple choices with Pico. I see it as the same reason those old microcontroller training kits where you entered your program by hand in machine code using the included hex keyboard went away. When your new user doesn’t have good ways to tell if their program logic is wrong, or if the implementation is wrong it adds a lot of friction. Starting them in python where it’s syntax is less picky compared to C++ and hopefully you have fewer chunks of pass this byte sequence to do magic (to say nothing of the mess of library naming) is very similar to moving from hand entering hand made machine code vs compiling in an IDE that is checking for errors before you flash. Big thing (in my mind) with Python is there is nothing to install on your host system. All you need is a text editor to write a Python script to do things. Then drop that ‘ascii’ file onto the controller and it runs (or not). Sure it isn’t bare metal ‘fast’… But you can still get a lot of useful work (fun) done quickly. With ‘C’, I had to download the tool chain, the SDK, the examples, setup a SDK path, Then run cmake, then ‘make’ before I had a file to ‘drop’ onto the board (that’s just to get a sample program running). This was on my Ubuntu system. Not quite as straight forward to get started. Now, I don’t mind as I ‘understand’ being an old embedded real-time ‘C’ programmer. To me this was actually ‘easy’ (But there was a LOT of upfront work already done to make it this easy!!!! That said, Python has it’s place. I personally won’t knock it. Use it where applicable, and drop to ‘C’ if I need the performance edge or dig deeper into the guts of the controller. Like Arduino ecosystem acting as a shim between Artists and Hackers You misspelled “shiv” B^) Or “ship” in the sense of continued efforts at “shipping” them together. (From fanfic term for relationshipping, i.e. the fan written torrid “love” scenes between Riker/Crusher (either of them) Riker/warmbody that we never saw on TV, aka “slash” because of the / between names, though slash would probably have the all sexual connotation where plain “shipping” might have the odd bit of sappy dialogue.) I laughed. It doesn’t lower the learning curve if you’ve been programming in C for 30+ years! The Pi Foundation have always done this: Python is the standard language for the Pi, but they’ve also released C++ resources for those who want to explore that. I’d expect the same approach here, get people on board with an easier language and then give them a path to something more advanced if they want it. In their blog announcement they actually talk about C++ resources before MicroPython. I’d say that bodes well for C++ resources. Exactly, The C SDK was developed first, and has had a huge amount of work and documentation done on it. MicroPython was then ported using that. C is a couple of orders of magnitude faster in some tests. Say you want to do something that isn’t super time critical, like read a temperature or lidar signal every 50ms. You can easily play around in the Micropython REPL and do live registers set up and reads of I2C or SPI sensors. Is threads support any good on micropython? If it is, I could see that making it easy for people to get beyond Arduino single-thread limitations who aren’t ready for FreeRTOS and STM32 CMSIS. If it’s going to use FreeRTOS, it better have a JTAG connector and debugging support. I only see a placeholder documentation page for threads, it might be a work in progress. Go check yourself, the page for the _thread module literally only has a sentence saying that it’s an experimental API. I don’t know what that really means. Would love to see it for multicore systems, maybe this is the moment when there will be some focus on it. There’s SWD pins for debug it looks like. There are some instructions on turning a second pico into a debug probe. The garbage collector is a godsend for complex code if you don’t have tight timing constraints. And even if you have tight timings, I have been putting that stuff inside C and recompiling them as python modules right inside the MicroPython firmware. Sometimes you need to run embedded code that has a bunch of arrays and matricies and need to join them and mix types and still want it to be somewhat readable to non-coders This programmable IO peripheral sounds very interesting, reminds me of a hybrid between the NXP SCT (State Configurable Timer) and a DMA capable I/O port where the timer/statemachine can control when you read and write. This opens up possibilities, what if you had a cortexM4 single core with 4 or even 8 of these units? And no peripherals like uart/spi and such? Like the parallalax propellor. Interesting that now a smaller player is making custom silicon that seems to be developed by makers for makers. A bit like how Atmel positioned itself as the “to go” makers microcontroller with the AVR. From the beginning with the AT90 series controllers and the GCC port that was maintained by volunteers. This resulted in the “Killer app” the Arduino series of boards, and the rest is history. Now we get a device with a lot of flexibility and focus to run micropython, unique features and low cost. Maybe the raspberry foundation has a new “AVR” on their hands? I am interesting if RISC-V will be an option in the future? Great stuff anyhow, what a time to be alive in, especially if I remember the time that I got my hands on some ATMega8’s and a parallel port programmer. Anyone who has tried to talk to a slow (4MHz) microcontroller bus using a fast-clocked Cortex-M knows it’s a lot harder than it looks. Even though the ARM has a clock speed ten times faster than an AVR and 40 times faster than the 4MHz bus, interrupt latency is similar to the AVR at about a microsecond, which is a full four clocks on the slow bus! It is sometimes possible, but you need to be clever (tight loops with halts on events rather than interrupts, abusing peripherals in various ways) which is a shock to anyone who normally thinks of ARM microcontrollers being essentially fast enough to do almost everything. There’s a whole bunch of tasks that normally aren’t considered possible except on an FPGA (or with a bunch of external logic), and this PIO module suddenly makes a big chunk of them not just possible, but potentially trivially easy. The Raspberry Pi foundation are not the only people in the maker/educational market to have made their own chip. Most notably there is Parallax with their Propeller chips. That being said, Parallax’s least expensive chip is more expensive than this complete dev board, and they run on their own ISA that makes the things you develop rather difficult to port to less expensive hardware. When I saw this post, I was excited to see what the RPi folks had come up with for $4. With the Pi Zero selling for $5, I was expecting something special. I am disappointed. Its general capabilities seem unremarkable. The PIO capability and the second core could be of interest when libraries are available to exploit them but, the meantime, I plan to stick with XIAO, ESP8266, ESP32, STM32 and Teensy boards. Am I missing something? I think it could make a great board for cnc machines, using those 2 pio chips to drive the steppers, hopefully someone will port grbl across. The beaglebone had something similar with its piu’s but that’s a much more expensive board running LinuxCNC with a lot more effort required. Grbl is much easier to setup but the old Arduinos it runs on are slow with limited io. Also could be great for generating IR & RF pulse trains to mimic remote controls. grblHAL. Ready to easily port. Already runs on just about every ARM out there including ARM M0. Libraries are already in place for the PIO and the second core. Note that there are also custom HW PWM blocks, HW interpolators, and HW dividers which can greatly increase the performance (enough to generate DVI…) Yes. Nobody said this was supposed to replace all other things that ever existed. It’s a new thing, it does some things different, and you’re free to not have a use for it. Not sure if it was already mentioned but it is not just this board, if you read their blog post there are several boards with this chip made by adafruit, sparkfun, arduino … I am slightly surprised then did not went with risc-v but it is quite understandable, they have lot of ARM experience inhouse. I saw that also. Adafruit, Sparkfun, Arduino, Pimoroni,…. Not often you you see a brand new chip introduced in-house with products from other vendors already building around it and products ready to go. Will have to get one (or two) and spin it’s wheels. is possible run unix on this device? No MMU? So only a minix type or ELKS derivative, dig up and reanimate μClinux. It’s a microcontroller. generally, they don’t need MMUs. There is a port of 2.11BSD for the Microchip PIC32 (MIPS) – linux yes, linux work fine on 286 I have asked the devs of FrostedOS (mostly made by belgian hackers) if they could port it to this board, and have busybox. FrostedOS could run Doom, but need an M4 style processor. How about something smaller? How Long until NES emulation ;’) . I give it 3 months. Keep watching our Twitter account. ;-) how long mac os 7 ? Yeah surely even emulating a 6502 from the 80s is no challenge to this processor, I’d say something tells me this chip could approach the capabilities of something between a SNES and an Atari Jaguar, maybe natively, not emulated. Try as I might I couldn’t see it competing with a PS1 in sheer horsepower, especially against its 3D capabilities, but its £3.60!!! Incredible! And I’d love to be proven wrong! This looks perfect for a tilt compensated compass I’ve been working on …. An Arduino doesn’t have enough program space or power for the calibration data and even a Pi Zero is a bit of overkill and not very power efficient. Most commercial designs I’ve seen use ARM M0 devices For me no WiFi makes this a no-go. Pity, as it looks so promising otherwise. Bring on the PicoW :) Speaking as a microcontroller newbie, I like the sound of it showing up as a USB device for programming. I’ve lost track of the number of hours I have wasted wrestling with flaky USB-to-serial drivers. That’s why I settled on the Arduino clones with the 32u4 chip, Pro Micro etc, which are amazing for USB support. That is until this thing came along!, he’ll its even cheaper than the clones! I am certain that I have seen this apparently revolutionary PIO on microcontrollers before, maybe NXP? There have certainly been other micros with very configurable universal communication modules on them before. Yeah Microchip also implement Configurable Logic Cells (CLC) on their micros too Maybe you’re thinking of the Cypress PSoC chips? They’ve been doing stuff like this for a long time. 2x 200MHz PRU (Programmable Real-Time Units) in TI’s AM3358 SoC (Beagle boards). It is fast enough to make a 100MHz logic analyzer. Various other microcontrollers have had some configurable logic peripherals, from the tiny GAL-like CLC in Microchip chips, to the significant FPGA-like fabric on Cypress PSoC chips. But you’ve had a choice of “very simple and not very well-connected” (the CLC/CCL from Microchip usually has 3-4 bits of input, one bit of storage, and the only connection to the data bus is via “pins”) or “very complex” (PSoC, PRU, etc.) The RPi PIO seems to be better organized for doing the sorts of things that I’d really want such things to DO (FIFOs to the bus, shift logic, etc.)… Are you sure? I haven’t seen an IDE as simple and complete as the one used for PSoC (for example the 5LP) Pretty sure. I went to a PSoC class offered by Cypress, back when the PSoC-3 was new (8051 core instead of the cypress proprietary core!) One of the other attendees pointed out that they had “mixed” the Hardware/FPGA and Software parts of system development in a way that was likely to break many traditional companiies, where those parts were probably done by separate people, and maybe even separate groups. I think PSoC designer still does the UDB part with schematic-like entry of logic gates and such (I haven’t looked in a while, actually.) That’s OK for the subset of people who fancy themselves as having a good understand of both hardware and software design, but that seems to be fewer people than you’d expect.) (I guess the PSoC IDE also has pre-created UDB-based peripherals that you can just drag and drop (more or less.) Seems nice. But IMO they should get on with producing the compute module 4 XD Mentioned this above, but they come from different factories, so there is no production conflict. The CM4 shortages are simply down to massive demand for all 2711 based products, we simply cannot make them fast enough. This should improve soon. AFAIK Cortex M0+ does not have MPU and Floating co-processor and absence of any of them is a total deal-breaker for any of my projects. “This microcontroller doesn’t have a jet engine, it’s completely useless for my rocket car project” This made my day, LOL Then you should probably not buy it. it’s not like ST, Microchip, NXP, TI, Cypress and other lacks parts that will fit your project… It does have an MPU (8 protection regions) There are M0+-optimised floating point routines in the mask ROM which are significantly faster than the standard soft float libraries. These are used by default in your code. Do the optimized floating point routines make use of the specialized math hardware (divide assist, etc) on the RPi chip? (oops: answering my own question. From the qfplib page: “The Raspberry Pi RP2040 microcontroller includes a version of this library, slightly modified to take advantage of special hardware available on that device. “) Your statement about 4 pins for ADC is misleading… it only has 3 ADC inputs. “2 × SPI, 2 × I2C, 2 × UART, 3 × 12-bit ADC, 16 × controllable PWM channels” There are 5 pins to connect, 1 GND, 1 SRC, and 3 actual inputs. The MCU has 4 muxed ADCs, GP[26:29]. Seems like the board doesn’t have GP29 available for use though. It’s not misleading — it’s a mistake. And that’s what you get from reading across seventeen different datasheets! I had 3 in mind, and then I saw 4 in the RP2040 datasheet. Will fix. There are 4 channels for ADC, but one is allocated to the onboard temperature sensor. There are 5 ADCs if you count the internal temperature ADC. The board uses 1 of the 4 externally pinned for input voltage measurement. I wonder if it’s possible to sacrifice input voltage measurement, and use it as a general purpose ADC. I said “watch your pin allocations” in the article — if you’re using the I2S peripheral, it eats up the ADC pins. Of course, then you just go and code up I2S in the PIOs… Poor execution and non-existent vision. Purely a profit-driven product. The “new” chip is no competition to… well, anyone really. I am giving it a pass, just like everything else from the brand I’d like to subscribe to your blog about all the things you won’t be buying! You are subscribed now, thanks for your interest! But it is not much of a blog – stuff with the brand ‘Raspberry’ and stuff that runs Linux… that’s pretty much all :) Yeah… I’m sure they’ll consult you on their next product to make sure you’ll be 100″% satisfied with it. I’m also interested in your blog about things you don’t buy, these kind of comments are very useful. Wow, didn’t know so many people wanted me to keep them updated. Hence, I created a page for everyone to visit and stay informed :) You are welcome! :) Epilepsy warning This PIO is very good. That was one of Paduk strength, and now one can have it with a powerful re-programmable micro-controler. The only deception came from the core choice. The Pi Fundation have the power, knowledge and name brand to help the HiFive. It would have been a very nice opportunity. But, hey, ARM are well known, so I thing it’s not a bad choice in itself. Will I get one? Maybe, that is if I can find one at $4… if i can get these things for $4 actual (considering they would need to make enough of them to meet demand like every other pi, and not screw me in shipping like adafruit loves to do) then they will probably become a fixture in my ever growing and seldom used dev board collection. Well it looks equivalent to products selling from $2 to $7 so it should be good there. Unlike the zero which looked like $15 worth so it always seemed like there was gonna be a catch. Waste of time – no Wifi, no Bluetooth, questionable driver support, and twice the price of an ESP32 which has all those things, is well supported, is also dual core, and runs twice as fast. Questionable driver support? Really? What makes you think that? And I suspect once you take the PIO, HW interpolators, HW PWM, HW dividers etc in to account, the RP2040 will be faster. We can bitbang 2 DVI displays over the GPIO once you use all that stuff…. Are you f’ing serious?!!!! The Pi foundation has some of the best support out there. There are countless SBCs out there that come out all the time and the only I can think of that I can find guaranteed support for for sure is from the Pi guys because they have such a huge following and people behind it. Not to mention free too! How did anything ever get done before any chips were out with built-in WiFi or BT?!!! You connected it to other things that could. What’s next? You’re not going to use any MCU’s for your projects that require GPS because there are no MCUs out there with GPS built into it? What a joke, hahahaha One question for me is considering it has no ethernet (wired or wireless) connection what is going to be the best way to connect it to a larger device such as normal pi? Will SPI be suitable for this, or can we do it via the USB in some way? USB would be the fastest. The TinyUSB stack is incorporated in to the SDK. But it also has a number of UARTS, I2C (host or slave), SPI etc so you have a choice of what to use. If UART, you could use PiPiPi ;^) I would love to see the Raspberry Pi (SBC) to Pico interface. “Getting Started with Pico” document, page 12, they show how to use a Pi SBC as the host computer, using USB CDC (serial port). Which brings up a question for me: if you are using serial port emulation at both ends of a USB connection, I don’t think there’s anything that limits the connection speed to what the emulators are told it is, because it never gets throttled through an actual UART. So even if you tell your terminal program 1200 bits/sec, a) it doesn’t matter what the serial emulator at the other end is set at, and b) it will run at “full speed” USB. Is this correct? @BrightBlueJim – yes, that’s correct. Existing “native USB” Arduino-like boards (SAMD, etc) achieve ~6Mbps “Serial.print()” rate. (Thereby confusing users, and breaking all manner of program that were counting (unconciously) on the serial port providing throttling.) The closest thing to the PIO I have used in the past is the FlexIO (with Teensy 4.x’s mcu from NXP), which has timmers, shifters and is DMA capable. I think FlexIO is more powerfull than the PIO, but FlexIO is a PITA to program, and its documentation doesn’t help. I really like this type of generic interfaces, where any pin in the MCU can act as the peripheral you need instead of the ones you are given. Pretty much sums up NXP, amazing chips with terrible documentation and support… At least we have Teensy giving amazing support for them. I’m getting a “The specified key does not exist.” error on the datasheet link, but found this one which isn’t in the pico directory but the rp2040 directory. Will fix. Had a ton of pre-press links in the article. Here’s what I like about it immediately… we’ve got a ton of boards that are “almost good” for emulating 8 bits and early 16bit machines… the arduinos are a bit too slow, some faster boards have too little RAM, and the ESP series, while of a decent speed is hurting for I/O for these applications (Less so for gameboys, more so for computers). Here we have a useful amount of RAM, useful amount of I/O and we can use those PIO state machines for the drudgery of interface emulation so as not to tie up the CPU. While not many applications will have these specific requirements, it definitely has a niche betwixt and between boards we are familiar with, that were “almost good” for doing some things with, if there was a bit more RAM, if there was a bit more I/O, if there was a bit more CPU, if you didn’t have to tie up the CPU doing dumb repetitive things. I know there’s thing they say with boats and RVs, “Two-foot-itis” just 2 feet longer would be perfect, whatever you currently have, and we can get into this with SBCs and dev boards, only need 20 more Mhz, only need 20 more kB, only need 2 more I/O pins… but I think this board has a nice balance. There was plenty you could do that would have you going for the grunty SBCs and lamenting the waste of CPU power and actual power, making them desktop queens addicted to wall warts, or needing to be >50% battery pack. Also you’d have the OS to fight with for doing things at inconvenient times. So these let you shrink those kind of apps back to a 3rd the board, 3rd the battery, and make them that much more portable. Your traditional Arm microcontroller vendors are pretty good at that. They sell enough volume to the industrial customers to make these options available. They have different families of Arm chipos for specific market from really low end to high end, variants that target peripherals and different packages to accomodate the I/O needs. The board level modules allow for easier breakout, but you won’t get the same up/down sizing options. I won’t want to hold my breath to see this board with 2X GPIO or more processing power e.g. M4. But this is also one of the reasons I’m REALLY glad to see this: there are so many options in building ARM chips, if you design with a certain set of options/peripherals, and your supplier stops making that chip, you have a lot of work to do. You can’t just buy a Cortex M0+ that runs at X MHz with Y amount of Flash and Z amount of RAM, because there’s no standard bus architecture to get data into/out of the CPU. With RPi supporting this chip, I have some confidence, and I think the PIOs are especially good for making a single chip flexible. Of course I assume that there will be other variants of the RP2040, but I don’t expect it will be like any of the big vendors that have dozens of different ARM-based microcontrollers. Are there peripherals / support for safety class software planned? Certain products need that sort of thing. I think the progression from regular Pi -> Pi Zero -> Pico makes the future obvious, and it’s only a matter of time. How long before the Raspberry PiFiveFive is released to compete with the Trollduino? I expect it on April 1st. Now if the Raspberry Pi Foundation also starts producing 555’s they will have all bases covered. The Pi555. too small ram , no power directly from AAA, LiPo, 9V battery etc. Are you deliberately ignoring the Adafruit board that has a lipo connector? Did you read the article? You _can_ power the Pico from 2xAAAs or a LiPo — it has a buck/boost regulator. Not 9V though. (What century is this?) 264 kB should be enough for anyone. (It’s kind of the century AFTER 9V batteries were a thing.) “If I don’t read the specs I can claim it doesn’t do anything!” An issue that keeps biting me is a lack of 5V IO.There’s a ton of peripherals that use five volts and it’s a pain and additional components to connect to then. Is this chip (or board, with additional components) at least 5V tolerant? Maybe you should upgrade, 3.3 volt peripherals weigh much less than a ton. It’s not as simple—there just aren’t many 3.3V 10 atm pressure transducers. Hmmm, aren’t they a resistance bridge type thing? Put in 3.3V and calibrate to that. At least the 3 bar transducers I’ve played with would work like that. They sayyyy 5V input and ground and voltage out, but really you’re just feeding the top of a pressure variable resistor, like a potentiometer that the pressure turns, so you won’t get 0ish to 5V ish output voltages, you’ll get 0ish to 3.3ish output voltages instead. Scaling analog voltages is basic stuff with voltage dividers. They’re called level shifters. The getting started manual says : VBUS 5 volts power A source of 5 V power taken from your Pico’s micro USB port, and used to power hardware which needs more than 3.3 V. Oh, you were talking 5V GPIO. Whoops. Says in the datasheet that they’re NOT 5V tolerant. (emphasis mine) Yeah, that was a little sad to see, but not at all unreasonable. It’s not their fault I want to plug it into a 80’s computer bus, and level translators exist. I’m actually very curious about this board. I’m not very familiar with microcontrollers, but I know ESP32 and the Mega 2650 are commonly used in 3D printing mainboards. I wonder if the PIOs make this board more flexible for that purpose that those boards, as well as if the onboard storage would be enough to hold Marlin. Yes, but. The Mega2650 is used for RAMPs both b/c of the extra memory, but also b/c of the extra GPIO pins. The ESP32 _can_ be used with some CNCs, but honestly you run out of pins pretty quick. Which is why, e,g, Bart Dring made his own ESP32 motor driver breakout board with shift registers to buy himself the extra pins (frinstance). This board has the speed, has more than enough code space, and enough GPIOs. The PIO bit is just icing on the cake AFAIK, b/c most of the time you’re not limited by how quickly bits can be toggled — exceptions would be high resolution motors geared way down or going way fast.. Directly from their site: “Raspberry Pi Pico is designed as our low-cost breakout board for RP2040,” And that’s really all it is – another ARM-based microcontroller with peripherals designed for the needs of a particular market. I don’t know how this warrants the 250 comments here. The features appear to be good, the price, great. But it’s not at all intended to do the work of the chipset in all of the previous Raspberry Pi products. No surprise – it needs more power than the typical 8-bit MCU, and (shocking!) won’t have a Linux distro customized for it. As for the board aside from the MCU, I think having a more flexible power regulator than most teensy-size boards do is a good thing, and having the boot memory un-brickable is also nice. Done. But you know, people won’t be happy until it has every interface previously invented by mankind, run kernel 5.8+, include GPS, a laser cannon, and a jet engine in it. Oh, and it needs to consume only 10uA while running that jet engine in deep sleep mode. Sigh. I totally forgot about jet engines. frankly a QFP or high pich BGA would be better. QFN is probably the worse thing to solder, just behind QFN with thermal central pad. QFN aren’t that hard to solder if you have a $50 hot air tool or used reflow. For hand soldering, you can get better access with the soldering iron if you extend the pads out a bit more. Some people make a large plate through hole on the ground center pad so that they can solder from the other side. The ground pad in some cases are for heatsinking to ground layers by design. I’ll neven have to deal with bent pins with QFN or wicked solder between pins. The package is better for very high frequency as it eliminates the inductance of the long leads with a QFP. The downside is that it takes up more area around the package for breaking out the pads to a different layer if there is a ground pad. For QFP, some of the break out can be done under the pakage. No question about the immunity from lead bending. But you’ve contradicted yourself with the inductance argument. I have the same problem with QFN as with BGA packages: by the time you get all the signals you need fanned out from the part (by way of the six or eight layers you need to do that), they take up as much area as the equivalent QFP package. Talk about entry level. I guess they need to start somewhere. Really curious to see their Raspberry Pi 4 version of this in a few years. ARMv8-M Mainline or beyond? Competing with Teensy 4.1? Probably because of this: >The Cortex-M0 is now available under a $40k simplified fast track license making it easier for SoC developers to design, develop, and commercialize Cortex-M0 based products. After completing a simple registration process, ARM will contact you to fast-track your route to Cortex-M0 based SoCs. >The package includes: > Cortex-M0 processor > Cortex-M0 System Design Kit (with system IP, peripherals, test bench and software) > ARM Keil® MDK development tools It is considered “cheap” compared to the rest of the chip fabiraction process. Interesting, off to start a kickstarter for the Jolly Wrencher M0000000000000000 herd, or as many M0 cores as we can get on a 10mm square chunk of silicon at a cheap fab… :-D The Cortex-M cores aren’t just there as a starting point. They’re there because everything is a compromise, and a simple core costs less and burns less power than a more complex one. The biggest, fastest CPU isn’t the best one for every job. That said, I wouldn’t be the least bit surprised if this chip becomes successful enough to warrant adding at least an M4 core chip to the product line in the not-too-distant future.. They are/will be selling the chips on their own. The designs from that PDF are also online: In my field (power electronics research), people often need to run very fast control loops (up to the MHz range, although ~100 kHz would be enough for me) with very tight timing control and super high resolution PWM. The most basic application is a discrete time controller which takes an analog sample at a specific point in time during a converter switching cycle, takes one or two cycles to compute the control implications of that fresh sample using PID or similar, and then updates its control timing. The PIOs seem good for this. FPGAs and DSPs are commonly used, but they are difficult to program and expensive. Could this device be suitable for such an application? Your average Arm microcontrollers can be triggered ADC from hardware timer *without* requiring PIO. Triggering ADC isn’t the issue. Keeping a fast, very high resolution PWM going and controlling it in real time basically cycle by cycle is the hard part. PIO seems good for the high resolution PWM part. You typically don’t need to run the control loop at PWM frequency. i.e. a more realistic fraction like 1/6 or lower. Digital PWM is a trade off for Speed vs Resolution limited by the clock frequency. There are faster way and simplier control scheme than PWM. e.g. Hysteretic It all depends on the type of SMPS being controlled. In some applications, it might be desirable to have an SMPS that achieves zero voltage switching (ZVS), which means the switching transistors only turn on when the voltage across them has resonated to zero. A control strategy often used for ZVS is model-based control. Essentially take a measurement or two every switching cycle, feed them into a model of the SMPS being controlled, and use that model to predict when the voltage across a FET will be zero so it can be turned on with minimal loss (turn off loss is generally of least concern when dealing with MOSFETs). This can be pretty computationally intensive. I’ve ordered a couple of these boards and hope to see how much they can do in such a hard realtime control application (can’t turn down $4 a pop). PIO is extremely accurate, but there is also HW PWM that is also very accurate. read the datasheet for more information on them both. That is very good to hear, thank you. I wonder if the processor and PIO communication will be fast enough to update PWM every single cycle. I guess I will need to check the datasheet then. There is usually a buffered option for Timer Compare value for hardware timers. i.e. the timer will update with that value at the beginning of the new PWM cycle – useful for synchronization without needing PIO. Oooooh, perfect. Look at the Parallax Propeller. it’s 8 32-bit cores are coupled extremely closely to the IO pins. So while each core only has 20MIPS, it’s fairly easy to get sub 1uS response times in a simple PID loop. (as long as you use powers of 2 for gains.) Having 8 cores means you can dedicate 1-7 cores to your high-speed task and still have a core for setup, debug, and housekeeping tasks. Hey, decent write-up. A an embedded C guy, the question of “whether to RTOS” is actually the wrong question. C++ stdlib has incorporated into the standard lib all the threading primitives. I read with horror that there is a “multi.h” header that’s different from the C++ primitives, different from FreeRTOS. Any time a hardware company writes systems code, it all goes horribly horribly wrong. C and C++ have atomics, mutexes, threads, etc – the language moved forward. The RPI people should embrace the modern language primitives, instead of writing their own, instead of using FreeRTOS. I’ve done a fair amount of ESP32 multicore, you can check my repos on github, and fighting with the RTOS isn’t easy. There’s a lot you need, why is why Espressif had to fork FreeRTOS and is stuck on FreeRTOS 9-whatever. A stripped down system that simply relies on the C++ language primitives (and C where they exist) is better than trying to roll into FreeRTOS – and it’s even OK if their implementation is FreeRTOS at the beginning, or roll-your-own. Don’t do a new API. Ooops, too late, now it needs to be supported forever. I hope it has _all the things_. But here are my questions on your article. Is $4 the _dev board_ price or the _chip_ price. With ESP32 my _dev board_ price is $4, and that includes USB programming, and BT and Wifi. For $10 to $8 I can get a well made board from a major manufacture, and include all the lipo battery regulation. For $20 I can get a really well made board with bells and whistles like extra PSRAM, an APA102 LED, external antenna connector, or similar. What remains to be seen is whether this MCU can support all the background processing of Wifi. And, what about malloc() from different memory pools? Will that be required? It seems very, very clear that RPI folks looked hard at the problems of ESP32 and have attempted to come up with a better chip. The idea of an “assembly language” for pins is frankly brilliant if implemented even slightly plausibly – it removes the RMT and I2S shenannigans, or pushes the shenanigans to one programmer who will make it good for the rest of us. By the way, I would bet this chip, at 133Mhz, would outperform an ESP32 at 240Mhz. When the ESP32 has to load from executable flash, it slows down. A lot. While this chip has the same problem, it might well have more RAM. The ESP32-S3 has more RAM for this reason. And you didn’t discuss floating point. The ESP32 floating point subsection is not good. You also didn’t mention RISC-V. There’s a deep-think bit here where the RPI open source people are coming out with a MCU that fights with the RISC-V line, which is where espressif has gone (the RISC-V ESP-IDF code hit their repo just recently – what, last week – so boards must be out there). C does NOT provide multithreading capabilities. Mutexes, threads, semaphores,etc are provided by runtime libraries or maybe even hardware level preprocessor macros, but C itself has no threading features. And this is why C is such a lousy language, Rust is what people should be running on this chip. Rust Actually Does have proper threading support. Is there already a Rust for the Cortex M0+? Actually yes, the whole Cortex-M lineup is very well supported: The real thing that will be missing for this chip is the HAL libraries, that will be written pretty quickly, no doubt. I’d say this makes C a ‘great’ language for these small apps. Only bring in the libraries you need to get the job done. With C and assembly, keep the program as tight as you need it to be. Flexible without the ‘overhead’ and ‘pain’ of using Rust. I’ve done some programming in Rust just to see what the hoopla was about and don’t care for it. Of course, I’ve only been programming C since the early 80s for applications and embedded real-time projects, so what do I know. This. Very much this. That’s very much a case of you’ve already learned to avoid many of the C pitfalls and are comfortable and fast working in it, so learning a new language that has major improvements but you have to go back to feeling like a novice developer seems like a failure. That’s not Rust’s problem, and not pandering to the greybeards like us means they’re free to improve things for the next generation of developers. One day I’ll make myself fluent in Rust, one day… No, it’s not like that at all. Programming paradigms, such as structured programming, object-oriented programming, functional programming, and so on, are all about trying to make certain pitfalls of programming difficult to fall into. But each paradigm has a price for this, and in Rust, it’s that the programmer is forced into a certain way of thinking about pointers and memory allocation, and that programs must accept the overhead that the language requires for this. Does any of this make assembly-level programming obsolete? They would like you to think so, but no, it does not. In microcontrollers specifically, we accept certain performance limitations in exchange for benefits in system cost, or power requirements, or something else. And it’s similar with programming languages, where the more levels of abstraction we are away from the underlying hardware, the more it costs us in other considerations. What has made C something that Just Won’t Go Away, is that C was developed to maximize performance while minimizing dependence on a particular architecture, so that we could reuse work we’ve done in the past without having to recode from scratch for every new architecture, and it does so by staying close to the hardware, with C statements being about as close as they can be to machine instructions. If it turns out that Rust, or Go, or whatever else gets written by someone who got tired of making the same mistakes over and over again, rather than learning the discipline not to make those mistakes, actually does a better job than C without adding on layers of inefficiency, THEN I might change. $4 is the Pico board — a minimalistic (but just fine) breakout for the RP2040. It’s cool to see other firms already putting out their own maximalistic takes. RTOS. I’m with you. Many times, you can get away with an RTOS, but “guaranteed to run within 100 us” is also the same as saying “up to 100 us jitter”. I tend to think that there are also many applications where simply dedicating a single core to the timing sensitive stuff is the right way to go — purely determinstic. One core for the grunt-work, one core for input from the outside and other slow stuff. No RTOS needed. The assembly language for the PIOs is cute, and very dense. Read all about it in the datasheet. I didn’t look into floating point very hard. I actually almost never use FP. RISC-V. Yeah, they could have. I would bet that given the RPi SBCs are all ARM procs, they have a lot of ARM experience. And they’re just down the street from ARM HQ. Sometimes you do what you know. At the time RP2040 chip dev started, the RISCV ISA was OK, but the ancillary stuff (interrupt blocks etc) were not yet good enough. Many people have connected AVR microcontrollers to Raspberry Pi SBCs, just to eliminate that uncertainty. If you have a CPU core that has only one job, you can count clocks if you need to. I’m hoping that the dual M0+ cores in the RP2040 will also help with this sort of thing. Oh, and the PIOs. This is great but wish the Sony CXD5602 based Spresense was available at somewhere close to this price. I will probably pass this even the PIO is not as cool the Parallax Propeller (Propeller 2) is even better. For most projects this will do quite well. It’s also dirt cheap so it’s worth picking up a few just to road test them. Of course it won’t appeal to everyone. But for hobbyists it’s a good buy. It’s very well documeneted and supported by mulitple vendors and already has development tools in place. How is it still a RaspberyPI? Only by brand name, eh? I’d like to hear the thinking of why dual uCores (and symmetric at it)? What’s the intended use case for a uC? Contrast that with Parallax Propeller? Also, as for tinker toys, this strangly positioned: the buck/boost regulator is superp, the build-in USB alsmost standar nowadays, IO are Arduino-comparable, processing power overwhellming and so is power consumption. All in all in my projects I seek an Arduino-Nano w/ radio (wifi or other convinient wireless). Normally I end up splicing Nano with ESP8266/Esp-link. I wish there was a single board w/ such combination (ESP in general lack IO/ADCs, and PIZW has no ADCs). So this does not solve the remote access? Answering my own request: Arduino Nano RP2040 Connect (if offered <$10 it woudl be fantastic hit). Look for RF Nano on your favourite online marketplaces. It’s an Atmega328p and an NRF24L01+ in nano-ish formfactor. Like here: (fifth and sixth option) Sounds like a strong contender, but for $10 I could get the NanoPi Neo, which gives me Linux, USB, Ethernet, audio and various I/O interfaces on its GPIO pins on a board not much bigger than the connectors it hosts. For $2 I can get a nice strong cup of coffee with all the caffeine I need, and a reusable cup! For $10 I can buy a belt that does a much better job of holding up my pants than this thing! The biggest complainers I’ve noticed are all hurt because it doesn’t do wifi or ethernet. Well sorry kiddies most embedded systems don’t need them. So move on to consumer appliance that does make you happy. Then there is the next best thing that I read in an article: “…speculation on the potential for a Raspberry Pi 5 with a built-in RP2040.” :) I would put money on it. The real questions are when, what will it cost and how easy is it to actually use combined with how stripped down will it be versus how feature rich? Plus to a certain extent what the software support will be and how easy it will be to debug at low levels if needed but also how easy it is to program for users who are not really experts in multiple fields. I would think it would just as easy as now except now the ‘connection/power’ is internal to the board. They are two ‘separate’ processors after all. Internally they could be connected serially or maybe even a folder to drop your python programs in or both. Get your data out serially with a /dev/tty (or whatever)…. You wouldn’t need to expose some pins because you already have 3.3, 5.0, GND and probably a few others already on RPI. I’d be satisfied with a new row of 20 pins (the analogs, and remainder interruptible fast GPIO). Have your ‘real-time’ side and ‘general purpose’ side all rolled into one. And the Pi Zero with this extra chip and set of pins as well…. The RP2040 MCU used on the Raspberry Pi Pico follows the naming scheme shown in Figure 2. “While dual-core Cortex-M MCUs are not uncommon these days, they usually don’t have two Cortex-M0+ inside but rather use the more powerful Cortex-M4, Cortex-M7, or the newer Cortex-M33 cores.” Has to start somewhere. Now that is when it gets interesting! I often use microcontrollers to interface real time peripherals to SBCs to ensure system resilience and consistent performance. Integrating the two could make for a smpler implementation. Other SBCs, such as the Intel Curie, have done something similar but it failed for other reasons. I always wondered why Beaglebone black did not put more focus on advertising it’s PRU. That was (and still is) huge advantage over other SBCs but seems like on the beginning it was not easy task to program. Which is why I think Pico will succeed – they will provide enough material for beginners to start. What I’d rather see is a few of those PIO peripherals *inside* the next Raspberry Pi Maybe the Pi5 or Pi6 gets a RP2040 onboard as a PiColot * *or Co-Pi-lot?? but then we lost the pico IDK Please be kind and respectful to help make the comments section excellent. (Comment Policy)
https://hackaday.com/2021/01/20/raspberry-pi-enters-microcontroller-game-with-4-pico/
CC-MAIN-2022-33
refinedweb
17,790
69.92
From: Matthias Troyer (troyer_at_[hidden]) Date: 2003-10-28 15:37:49 On Oct 28, 2003, at 4:35 PM, John Maddock wrote: >> Can anybody explain the reason for the following lines in >> boost/config/platform/macos.hpp? >> >> >> # ifndef __APPLE_CC__ >> >> // GCC strange "ignore std" mode works better if you pretend >> everything >> // is in the std namespace, for the most part. >> >> # define BOOST_NO_STDC_NAMESPACE >> # endif >> >> >> With this BOOST_NO_STDC_NAMESPACE some parts of ublas fail to compile >> under MacOS if a non-Apple GNU compiler such as gcc-3.3.2 is used. Why >> is BOOST_NO_STDC_NAMESPACE defined on MacOS for non-Apple gcc >> compilers? > > No idea, but it looks wrong for gcc3 series compilers in any case... > > would: > > # if (__GNUC__ < 3) && !defined( __APPLE_CC__) > > be any better? Yes, that would be much better, all my codes will then compile then but some will give a linking error (see my recent post regarding ublas). As far as I can see this linking error might be a gcc-3.3.2 bug that needs investigating. In any case the proposed change is definitely needed and should not lead to any incompatibility as far as I can see. Matthias Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2003/10/55368.php
CC-MAIN-2020-50
refinedweb
213
67.96
Hello , I’ve been thinking about what should be my next post. I’d like to talk about WCF RIA, where I have had some encounters, but it’s like too soon to write about it. On the other hand, I won a raffle and the prize was a book about Windows Phone 7 Game Development (Thanks to 101FreeTechbook and additionally there is going to be a free workshop about XNA 4.0 development at gamedevelopedia (Starting at 17-Jan-2010). Thus, I’ve decided to write a set of tutorials about XNA and WP7 for those who wants to start as well as I want. If everything goes well the series will have the following tag XNAWP7, and I’ll try to post every week about the every new topic. So, lets get started. WP7: Windows Phone 7 Development Windows Phone 7‘s the platform Microsoft has release to create new experiences on Windows Phone development. This new platform is based on managed code, so it’s backed on .NET Compact Framework. At this time it’s possible to write application C#. There are two main framework available for WP7 development: XNA: Xna is Not an Acronym XNA is a high-performance game framework. It’s over DirectX and it allows to create application taking advantage of high performance on Graphics, sounds, networking and input devices. Additionally, it can take advantage of Microsoft Live to have a customized game experience. The only drawback of this platform is that you have to create most of the components almost from scratch or get a third party framework instead. SL: Silverlight Silverlight is framework build on .NET and it allows to create rich interactive applications by using a declarative language (XAML). Xaml uses XML to describe how the UI is drawn, and the C# to details on logic and interaction. This framework also supports game development, this framework is fairly enough for games which does not have high-performance graphics nor have tons of elements. Event though, SL4 is already in the market and SL5 is on feature request on Jan-2011, WP7 uses an special flavor of Silverlight 3. This special flavor of SL3 has removed not related feature of mobile such as System.Window.Browse namespace, and it has added specific new namespaces in order to take advantage of the platform specific items. Windows Phone 7 and its hardware Microsoft has defined very specific hardware in order to be able to run properly WP7 Operative System (WP7 OS). - 1 Ghz CPU processor - WVGA (480×800) or HVGA (480,320) - Accelerometer sensor. This sensor helps to detect the orientation of the device, this means it allows to detect if the device is point up, down, left right, etc.. - GPS sensor This sensor helps to detect the position around the world by detecting the latitude and longitude Development on WP7 At lats but not least, let see what it’s required to develop on WP7 platform. The SDK is free and it can be downloaded at AppHub If you have Visual Studio already installed the WP7 tools will integrate with VS automatically. If you don’t have Visual Studio, then you can get the Visual Studio Express version for free at Visual Studio Express. If you wan to run you application in you phone, then you’ll need to get a XNA creators account to being able to deploy your application into your phone. Additionally by acquiring an account you’ll be able to publish your game in the Market place, at this time (Jan-2011) only US and Europe are available to publish content, it’s planned to open more countries during the next years. Don’t get worried if you don’t have a Windows Phone 7, you can start coding using the emulator which is already included with WP7 SDK, however it’s strongly recommended to use a physical WP7 to perform final tests. An initial application As traditional, the hello world application. So, on this little sample you it’s possible to appreciate the basis to display text and sprites. The Main Game loop If haven’t worked with game frameworks before, let me point out a concept known as game loop. Traditional programing models are event based, this means that a certain functionality is executed by a given trigger. But the most common video game frameworks does not work on this scheme, instead they use the game loop which is a “infinite” cycle where the application performs an update and then draw the scene. Frameworks such as XNA have methods invoked before and after the game loop is executed to perform initialization tasks, or free resources. This main loop game is implemented by the Game class of XNA. BTW there is a particularity of using XNA on WP7. Normally an application has an entry point such as the main function, and you can clearly see this function on a WP7 template project. However WP7 loads looks for instances of Game in your projects and handles them such a contract to define the execution of your application. A sprite The word sprite is an term which hasn’t changed from its origin. During the age of 8-bits the very first images that were drawn on a screen were called sprites. So, an sprite a two dimensional rendered figure ;-). Sprites have become a great resource because much of the game frameworks does not have a graphic interface library (GUI), thus sprites provides a good-alternative mechanism. On XNA an sprite is represented by the Texture2D class. Sprite font Particularly XNA has decide to draw text by using sprites. Which means that all the charset is backed by images. A font on XNA is associated to an spritefont. On XNA an sprite is represented by the SpriteFont class. Drawing sprites XNA defines a tool for drawing sprites (or spritefonts). XNA helps you to deal with the resources of you application by providing a content loader. This content loader is able to load the sprites, fonts, audio files that you application will consume. some csharp code With all the previous things said I’m attaching what it would be the first post (hopefully of many more posts). Source code is at
https://hmadrigal.wordpress.com/category/xna/
CC-MAIN-2020-24
refinedweb
1,041
61.36
>> Boston (MA) - A former Massachusetts state worker has been vindicated of child pornography charges after investigators said a computer virus was responsible for automatically downloading dozens of illegal pictures. Michael Fiola, formerly of the Department of Industrial Accidents, was fired in 2007 after department IT staff found child porn on his work laptop. Later in the year, he was charged with possession of child pornography. Back in November 2006, Fiola was issued a laptop with Windows XP SP2 installed. The laptop had the typical anti-virus software installed, but Tami Loehrs, a computer forensic investigator hired by the defense, said the laptop was improperly configured. This prevented virus definition updates from installing which eventually led to the laptop’s infection. Apparently a shoddy laptop setup was the main catalyst to this infection. The laptop had been used by another employee and according to Loehrs, the laptop name was simply changed when it was given to Fiola. This caused the laptop to stop receiving virus and software updates via the department’s update server. According to Loehrs, a computer virus caused the laptop to scan approximately 40 sites every minute and riddled the browser’s cache file with hundreds of images. Prosecution investigators concurred with Loehrs and all charges were dropped. Source : Tom's Hardware US Related news Related Deals - Can I install a second antivirus [Windows 95/98/ME] - Can A Windows Virus spread to a backup drive in Fedora Live CD? [Linux/Free BSD] - First 64-bit AMD64 Windows virus emerges [CPU & Components] - would a router fix this problem? [General Networking] - Second Take: The Future of Mac Gaming [Bestofmedia's Site Feedback] Questions? Ask Tom's community! Sponsored links Related forums topics - Recommend me a new motherboard - Extremely slow computer - Best virus prevention? - dual core or quad core? - Only one core working on Q6600 - Bios problem with HCL laptop - HOWTO: Overclock C2Q (Quads) and C2D (Duals) - Guide v1.6.1 - FSB lower than it should be ? - Best pc pranks - PC Turning On.. Overheating? - No display 8800gtx (i think its the motherboard not sure) - booting harddrive to install windows - FSB 133 gets stuck at 100 - GA-M57SLI-S4 - Bad SATA controller? And this is the main reason why even if ISP's find that someone's computer is downloading CP, they should not automatically jump to the conclusion that their CUSTOMER is downloading CP, especially if they have a wireless router (even if it is passworded, it can STILL be broken into given enough time) or more than one person in their home. Even with an anti-virus software installed on your computer and an anti-malware software installed, it is still very possible for a computer to be infected by malware/spyware/viruses that are not on the list yet. To be blunt, it is just impossible to prove whether someone whose computer was downloading CP or anything else illegal was doing it by their command or by the command of a virus that was unknown or unknown at the time that the CP downloading supposedly took place. God, what a nightmare for that guy! I'm glad he was vindicated and can sleep well now, even if he is out of a job. Anyone should be responsible for their computer. If someone else takes over your computer and hacks a government (or anyone else's) system through it, you should be liable (at least partially) for the damage caused, because of your negligence. It's like if someone took your gun and shot someone (self) because it was improperly secured. If he just got a computer that was administrated by the company's IT department, it's their fault that they didn't care enough to secure the computer they should look after. They should get fired in the end. That's like saying if someone steals your car and runs over people, you're in the §hit. so if that was you, your response in court etc would be "I done it" and get sent off to prison for some virus maker's idea of a joke? If anything like that happened to you i don't think you'd want to be responsible for it So you say that you may hack whatever you want, download and distribute porn etc. from your computer, then just install some virus on it and claim it wasn't your fault at all? That's just ridiculous! If anything the person responsible for making the virus should be prosecuted, who would make a virus to do such a thing. And i am against piracy etc but you don't always get a virus from that just a dodgy web page is enough Where exactly do you think he got the virus from if not on a porn site. From what i've learned, viruses on web pages don't come from legit sites like google and msn... Only "underground" sites with suspicious content try to hack into your computer to get a return ($) for their content. In the end, this wouldn't have happened if he had used Firefox. ZOMG! With sudden surge of XSS compromised sites recently, not to mention it has been going on for years, people are just plain stupid to even think that by avoiding "underground"/"bad" sites they are immune. From what rock did this people crawl out from? Another ZOMG! True, your chances of being compromised are a lot smaller. But that's all. FF still has bugs. Heck any software has bugs. "Hackers" knows a lot more bugs/loopholes about a certain software than the developers of that software. I'm betting this kind of people are already infected, only they are so full of themselves to think they are above the problem. I suspect it was a virus in his brain. Seatrotter, I understand what you are saying but what I was implying is that the probability of this happening with firefox were pretty thin. Considering this : -How likely is it to have your computer infected by a virus that downloads child pornography, not likely. -How likely it is if you use Firefox, even less likely. So less likely than not likely, is pretty close to not happen no ? I'm a bit sensitive to semantics(?) today so although you didn't mention the words "never"/"impossible"/etc, "wouldn't have happened" is pretty much clear on where it stands. While we're at it, I'd like to rephrase about "Hackers" and bugs: "Hackers" can compromise a software/system in ways developers couldn't have thought of or thought highly unlikely. As for the possibility of being in a situation you mentioned, "close to" is what it is. Let's put it in another perspective. Let's say that the chances it can happen is 1:1,000,000. Almost unlikely to happen but when you consider the population w/ a computer connected to the net, you're talking about a great deal of people getting screwed. I think a lot of people are just too wrapped-up on the concept that a virus "downloading" p3d0 p0rn on someone's computer would only happen if that person is being blackmailed. Seriously, has anyone who thought so, also considered that the virus is not "downloading" it but "storing" it (yeah, semantics) for distribution. Why? Do you want to get caught distributing something illegal? If you have a brain, you wouldn't want it traced back to you. Solution? Use zombie computers to distribute your wares. poor windows users. linux rocks linux... as long as you don't completely trust your linux setup, know how to probe deeply into your system and know how look for "anomalies", frequently doing so, and have a bootable cd loaded w/ security tools to frequently scan your setup for god-like rootkits (in case you've gotten too complacent/arrogant), then I guess your all set. but then again, you can also do these w/ other platforms. Well said. +2 I'm stuck with my "not happening" thing. In addition of getting infected by a child pron downloading trojan, and using Firefox, the event itself was pretty unlikely. I explain. So, from what the story tells : The infected computer was inside a corporate site.. So, tell me, how many guys are in this situation ? 1 million ? Probably more like 100 to be generous. Considering there are 1,173,109,925 Internet users in the world. [...] rnet_users 100/1,000,000,000(I rounded)* 1/1,000,000 = 1/10,000,000,000,000 So to me, i'ts pretty unlikely. To be fair, the probability of that specific event happening was already small. And the story doesn't even say if he was actually using Firefox. I was just stating firefox in my initial text because I just downloaded the new version. 1. Why the hell did they go through his browser cache? 2. Why the hell did he not goto Tools > Options > Privacy > Check "Always clear my private data..." ? Oh man! People are just trying to be know-all. First of let's make things simple by focusing on getting infected, by just browsing, w/ a malware that turns your computer into a zombie (a lot of people just can't seem to separate their "this-person-is-guilty" emotions w/ other facts). Being inside a corporate network means jack-sh!t nothing if people inside these corporate netowrks can browse the internet. Remember that numerous legitimate sites are being compromised daily, to serve malware. To date, FireFox, like any software, has a history of bugs/security issues that has allowed it to be compromised w/o the user knowing it. It is more secure than some other browsers but that doesn't mean there isn't a way to compromise it in a practical manner (as opposed to just theoretical). That is just FireFox. What about the other software that is commonly used that is integrated to a browser, such as Adobe Flash? You turn off your flash plugin and disables javascript? So what? Javascript and Flash alone are so heavily used today in services and websites that a lot of people just can't afford to completely turn them off, even manage when to turn it on/off. And how did you come to that computation 1/1,000,000 scaled to 1,000,000,000 isn't 1/10,000,000,000,000. When you're scaling up (from 1,000,000 to 1,000,000,000) the result will be more not less. Conversely, scaling down will result to less not more. Also the example probability (1/1,000,000), will always be the same no matter what the actual number is. Think of it as percentage. 50% will always be 50%. Why? because it is the result of a computation from a given set of data. If the sample data is 100 out of 200, and you use a bigger sample data, you'll still get roughly the same proportion. 10,000 out of 20,000. Going back, 1/1,000,000 will always be that. What you will get if you include an actual sample data is an actual data, not some new proportion. 1,000,000,000? Out of that population, you'll get 1,000. True? 1,000/1,000,000,000 = 1/1,000,000. That's 1,000 users infected out of 1,000,000,000. As for the antivirus, improperly configured means more than outdated virus definition. If that AV has some protection against tampering w/ the system, an improperly configured AV could also mean that it wasn't enabled. Even if you have an updated AV, all it takes is a new/variation type of packing/encrypting for malware (plus an anti-debug mechanism) to defeat signature and behavioural detection. And if its payload is a hardened rootkit, you're screwed. I don't care if the guy is actually guilty or not (though just because someone d/l'd pr0n doesn't unequivically mean that person d/l's ch!ld pr0n. simple logic. also, if you've been around the corner for some time you'll notice that not all perverts are turned on by ch!ld pr0n), but saying that he can not be a victim of malware is just living in a fantasy (especially when "use firefox" gets thrown a lot so easily). I understand that you're not a big Firefox fan and that you like to argue. You're probably also one of thoses "People how are trying to know-all", as I am. Just to make it clear. I did not scale 1/1,000,000 to 1,000,000,000. Because considering there might be only 100 person ( I understand that this is purely an impression, make it 10 000 if you want) in the world that conrespond to those criterias : The infected computer was inside a corporate site( behind a good firewall I assume). It means that the probability of you (or me) being one of them is 10 000/1 000 000 000. Now regardless of me (or you) being one of these 10 000 unlucky persons, you have a probability of 1/1,000,000 of being infected by a virus that downloads child porn while using firefox. So to fit in these 3 categories at once you have to multiply the probablities. If you have 100 people, 50% of them are blond, 30% of them are women and 25% have blue eyes. What's the probability of finding a Blond woman with blue eyes ? 50/100*30/100*25/100 = 37500/1,000,000 or 3,75% That said, I completely agree with you that it's a dream to think that using firefox would prevent all malware. It's just that the guy has already so unlucky to be caught in this situation that all he needed was little more luck (like 0,00001%) and maybe this wouldn't have happened at all. It's been nice, arguing with you. Good day. I may also be "People how are trying to know-all", but at least I set a clearer boundary on what I know and up to what point. Let's take for example the stance on browser. I'm an Opera user. Although I rarely suggest to people to use Opera, I wouldn't say something like "In the end, this wouldn't have happened if he had used Opera." I'd say something like "Try Opera, it's more secure." or "With Opera, he could have avoid being infected." Also I wouldn't confuse "pretty unlikely" to "not happening". Remember, your target audience are those who aren't that conscious about security or "tech-savvy" (otherwise, you wouldn't need to say such statements) and those choice of words will seed arrogance. To them "not happening" is the same as "never gonna happen". . Yeah, the guy was pretty unlucky (to be caught, since no doubt a lot are in the same situation as he is, only the employer is not that vigilant in persuing an investigation). For the probabilty arguement, I guess I was wrong to say that you scaled. Unfortunately for you, you made a fatal mistake of broadening the scope of the probability beyond what the initial argument was. Remember, the initial arguement (where the example 1/1,000,000 prob was used) was about a specific malware and while using FF. You then mixed that up w/ things completely irrelevant to getting infected, such as getting caught, fired, and accused in court. W/o those irrelevant parameters, you be getting something much, much higher/bigger. Now, if the initial arguement was about the guy, then it would make sense. And while at it, people will I agree when I say that we both are guilty of using fantasy-level optimism in getting infected. The chances are actually much higher than what were given as examples. So it has to end, huh? Sorry it was you that I had to argue w/ (I'm not much into arguing anyway, as I find it too tedious to register just to post a comment) since I've got too light of a load of work these days To other readers, when it comes to the browser, yes, use FireFox. Use Opera. Safari? Apple refused to fix a bug so, no. Both are more secure than IE, just don't get too complacent. Always stay vigilant, even if browsing just "safe" sites. Thanks for keeping your cool and being a sport. Have a nice day too Tons of people could be infected with this virus and storing pedo pron. The difference would only be that the infected systems haven't been detected by the company, nor would this one if there wasn't the excessive traffic but not all traffic is as closely monitored.
http://www.tomshardware.com/news/computer-windows-virus,5686.html
crawl-002
refinedweb
2,825
70.94
hi guys, I know how LinkedList works, but I've been given classes and methods headers to implement LinkedList, and I need a bit of help with this. Basically consist of three classes Students(which contains student attributes and methods... no help needed here), and the other two classes, which I'm showing below. The Node class. I implemented the constructor; however, I don't see what's the point of having "public Student value" here, or am I missing something? Code : public class Node { //construct student object public Student value; public Node next; //constructor public Node(Student s) { this.next = new Node(s); } } And here's the Class LinkedList. My main concern here is how to implement the constructor Code : public class LinkedList { private Node first; public LinkedList() { } //add students to the list public void add(Student s) { } //remove duplicate records (return true if duplicate found) public boolean remove(String fn, String ln) { } //display list of student public void display() { } } Thanks
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/16028-need-help-implementing-linkedlist-printingthethread.html
CC-MAIN-2014-41
refinedweb
162
60.75
0 So, I'm really frustrated with this problem. I desperately need some good explanation about this. Why does the calling function does not reflect the change done in the called function? despite the fact that I pass the variable via pointer. Any explanations please. Thanks in advance. #include <iostream> using namespace std; void foo(int *x) { int *y = new int(999); x = y; } int main(void) { int *x = new int(1); foo(x); cout << *x << endl; cin.get(); return 0; } In main: x = 1; In foo: x = 999; In main: x = 1; Why ? and How will I reflect the change on the calling function (without using RETURN) ? THANKS.
https://www.daniweb.com/programming/software-development/threads/212786/need-help-about-passing-pointers-in-a-function-and-reflecting-any-changes
CC-MAIN-2017-26
refinedweb
109
85.39
Machine Learning has found its application across a number of domains that involve mimicking the complexities and senses of human beings. Computer Vision and Speech synthesis have been around since the late 1960s and have exponentially improved over time — especially in the last few years. Today, we will focus on Speech Synthesis which is one of the growing research areas with a number of real-world applications. Register for Data & Analytics Conclave>> Speech synthesis as a technology has already entered the common households as a powerhouse for many voice-operated devices including virtual assistants like Alexa, Google Assistant, Cortana and Siri. Voice assistants today are more than just audio encyclopedias — they can also bark, meow and whine like cute animals. But how does this technology work? As complicated as it seems, speech synthesis is backed by many complex algorithms that do more than just synthesis, but analyse the sound and produces insights. One good application is the sound classification. Machines today are capable of classifying different sounds. Visualising Sounds “Sound is a vibration that propagates as an audible wave of pressure, through a transmission medium such as a gas, liquid or solid” This textbook explanation of sound is self-explanatory, as to how humans and most inhabitants of earth perceive sound. But how does a machine do it? Machines are good pretty with vision, so we convert sounds into numbers and images. This is what we will do in this hands-on session. The exponential advancement in ML and the number of researches being done in the field has given rise to many tools and software kits that make it effortless to implement complex tasks in just a few lines of codes. In one of our previous articles, we learned how to convert a simple text classifier into a fully functional speech classifier just by adding a few lines of code. In this tutorial, we will discuss some of the various aspects to determine the characteristics of a sound and we will learn to visualize any sound as a beautiful wave. You will learn to effortlessly load audio files and play it in Python notebooks and also to convert audio files into spectrograms in just 5 lines of code. And for fun, we will also compare the spectrograph of different songs. Ready Set Code We will use the IPython module to load the audio file and a popular library called Librosa to visualize it. The following example has been done on Google Colab and given below are the environment details: - Python 3.6.9 - Librosa 0.6.3 Installing Librosa LibROSA is a python package that helps us analyse audio files and provides the building blocks necessary to create audio information retrieval systems. We will install the librosa library using the following command: !pip install librosa Assuming that your Google drive has some audio files in it, we will proceed to load the file. But before that let’s mount the google drive on Colab. Mounting Google Drive Execute and authenticate using the following code block to access your Google Drive on colab. from google.colab import drive drive.mount('/GD') Importing The Libraries import IPython.display as ipd import librosa import librosa.display import matplotlib.pyplot as plt We will now load our audio file in just a one liner. Type and execute the following code. ipd.Audio('/GD/.../audio/numb.m4a') On executing the above code you will get an inline audio player which can be used to play the audio as shown below. Spectrograms We can now use the librosa library to plot the spectrogram for an audio file in just 4 lines of code. First, we will initialize the plot with a figure size. plt.figure(figsize=(15,4)) We will then load the audio file using librosa and will collect the data array and sampling rate for the audio file. filename = '/GD/My Drive/.../audio/numb.m4a' data,sample_rate1 = librosa.load(filename, sr=22050, mono=True, offset=0.0, duration=50, res_type='kaiser_best') Sampling Sound is a continuous wave. We can digitise sound by breaking the continuous wave into discrete signals. This process is called sampling. Sampling converts a sound wave into a sequence of samples or a discrete-time signal. The load functions loads the audio file and converts it into an array of values which represent the amplitude if a sample at a given point of time. Sampling Rate The sampling rate is the number of samples per second. Hz or Hertz is the unit of the sampling rate. 20 kHz is the audible range for human beings. We can now plot the spectrogram using the waveplot method as shown below: librosa.display.waveplot(data,sr=sample_rate1, max_points=50000.0, x_axis='time', offset=0.0, max_sr=1000) Fun Time: Linkin Park Vs Micheal Jackson Vs Blue Lets compare the Spectrograms for three very popular songs: Complete Code What’s Ahead Keeping in mind the Machine Learning context, the above example has great importance. This is especially true when we are dealing with sound data in creating intelligent machines such as recommendation engines or machine that can classify music into genres or security systems such as voice recognition systems. Subscribe to our NewsletterGet the latest updates and relevant offers by sharing your email. Join our Telegram Group. Be part of an engaging community A Computer Science Engineer turned Data Scientist who is passionate about AI and all related technologies. Contact: [email protected]
https://analyticsindiamag.com/step-by-step-guide-to-audio-visualization-in-python/
CC-MAIN-2021-43
refinedweb
908
55.64
Now this is a multipurpose project. Use it as a party light OR as a gig booster. Adding colors and manipulating the light sequence is easy thing to do. Check the video to see the project in work. If there is a VOTE patch on the right side of the project site, throw me a vote if you want :) Step 1: Components First thing first. Components. Consider that this project can be done much smaller with Arduino nano or any small programming board. I made this with Arduino Uno for two reasons. 1. At the time i did not have any smaller programming board available and 2. I't is easier for beginner to make use of the Uno board by copying the work. You will need: Arduino board (anything you have, even a copy one). 10 kOhm resistor. Two female plugs for audio in and audio out. Neopixel led strip. Mine is 1 meter long and has got 30 led's. Optional Case (printable files in project) Prototype shield. Just to keep everything nice looking. Step 2: Desing Step 3: Printing The case was printed with Printrbot makers kit. Basic and cheap printer. Settings for printer was 0.4mm nozzle, 0.2mm layer height, 40mm/s print speed. Holes for the case are made in the printing. If the fit is snug in the holes just use file to make it fit. Step 4: Testing and Coding The connections are pretty simple. Put a resistor between GND and A0 to make the analog 0 by default. This helps Arduino to sense real thing and not just some interference made by radio signals etc. Ground the ground from the plug to make it a part of Arduino. Put left or right channel from the plug to Arduino A0 Put the led strip's +5 to VCC and GND to GND. Data cable goes to Arduino pin 6. If you have any questions, just ask. Note that you will need NeoPixel.h library. Find it from GitHub. #include <Adafruit_NeoPixel.h> #include <avr/power.h> #define PIN 6 Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, PIN, NEO_GRB + NEO_KHZ800); void setup() { Serial.begin(9600); strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { int sensorValue = analogRead(A0); Serial.println(sensorValue);//Just for the calipration if(sensorValue > 10) { rainbowCycle(0); } if(sensorValue >30){ theaterChase(strip.Color(255,0,0),10); theaterChase(strip.Color(255,0,0),10); theaterChase(strip.Color(0,0,255),10); } if(sensorValue >40){ colorWipe(strip.Color(255,0,0),10); colorWipe(strip.Color(0,255,0),10); colorWipe(strip.Color(0,0,255),10); } } //this makes the rainbow equally distributed throughout void rainbowCycle(uint8_t wait) { uint16_t i, j; for(j=0; j<256*1; j++) { // 1 cycle of all colors on wheel for(i=0; i< strip.numPixels(); i++) { strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255)); } strip.show(); delay(wait); } } //Theatre-style crawling lights. void theaterChase(uint32_t c, uint8_t wait) { for (int j=0; j<5; j++) { //do 5 Step 5: Test Fit Solder pins to the shield if you use one. Drop the Arduino in to the case to see it fits. If it fits continue to next step. If you use different Arduino than Uno. (Smaller or bigger does not matter.) And need a design for the case. I can make one on my free time and send it to you via email. Unfortunately i really can't make the real print and send it to you because sending something from here Finland to some other country is really expensive. Step 6: Soldering Solder needed wires and hook up the shield to Arduino and hope for best. The plugs are meant to keep the Arduino down in the case as seen in picture 4. Step 7: Final Assembly Insert the "Hook" if needed to the back side of the case. Use hot glue to keep it in place. Then glue the bottom lid on to the bottom. Step 8: Done Now the project is done. This is pretty much there is to make. Now you will just have to thing where to use it. Next few steps are just examples where to use it. Power the board from USB or a Battery. Any battery works great. 9V battery lasts about an hour. Step 9: Option One Use the box to enchant your speaker setup. Light looks really nice. Making you favorite colors is easy by just changing the (R-G-B) from the code. Where 0 is no light on and 255 is full light. Step 10: Option Two Make a awesome gig enchanter. Just sew the led strip on the guitar/bass strap and rock on! Or for drummers, throw this inside the bass drum and wait for the applause. Musicians benefits are guaranteed ;) Thanks for reading :) If you have any questions i will try to answer them :)
http://www.instructables.com/id/Arduino-Party-Lights/
CC-MAIN-2017-17
refinedweb
813
77.74
TheExchangeMAPI (“Program Files (x86)” on a 64 bit machine). We also renamed Exchange’s mapi32.dll binary. It’s now called ExMAPI32.dll. Some notes: - If you’ve installed an earlier version of this download on a machine and wish to upgrade, you must uninstall the earlier version first. It will not upgrade in place, and may even claim to have successfully installed. - Mapi32.dll in the system directory should be version 1.0.xxxx. If it’s 6.5.xxxx, then the stub is not in place. Use FixMAPI.exe to correct this before installing the updated MAPI download. - The version number of the Windows Server 2008/Vista compatible download is 06.05.8022.0. - MAPI and CDO are still 32 bit only – it will install and work on a 64 bit machine, but only when used from a 32 bit program. - MAPISVC.inf in the system directory will be updated with Exchange’s providers, but the date may not be changed. I just noticed this when testing the installer on a machine here. - The installer adds the MAPI install directory to the PATH statement. This MUST NOT be removed. It is required to allow DLL dependencies to work correctly. - Session 0 Isolation causes problems with our fix to the deleted profile issue. With that fix in place, a normal user (who lacks SeCreateGlobalPrivilege) wouldn’t be able to use MAPI at all. So we modified the fix to attempt the global namespace first (which will fail for a normal user), then fall back to a local namespace. This means it is possible for a normal user to log on to a server twice with Terminal Services and delete a profile from one session that is in use under another session. To help identify this scenario, there’s a new error code which will be seen by MAPI applications if this happens: MAPI_E_PROFILE_DELETED (0x80040204). - The download enters Extended Support in April 2009. That doesn’t mean the download will be removed then, but don’t expect updates to it. Update: Looks like the Ehlo blog picked this up. Welcome Ehlo readers! I was involved in getting this update done, so lemme know if you have any questions. Stephen, Any time period for 64 bit MAPI release ?? Regards Sridhar There have been no announcements regarding a 64 bit MAPI. Has anything else changed in this update or is it just introducing Windows Server 2008/Vista support? In addition to the session 0 isolation issue, we also fixed an unreported crash scenario. The move from system32 to program files is a fairly large and potentially destabilizing move though. You should definitely test your applications with this update. Well, that didn’t take long. We just released of the latest MAPI download this weekend and yesterday It appears that one of the new dll’s is changing the current working directory of the loading process to "C:Program FilesExchangeMAPI" and breaking some applications. Also, adding this directory to the path will not work in all/most cases since windowssystem32 precedes it. Uninstalling the previous version (7974) did not remove the dll’s from the windowssystem32 directory… perhaps that is why the current working directory is changed? I didn’t think we were changing the working directory, but I’ll check on that. On the uninstall, if an application was using the DLLs then they’d have to be scheduled for deletion on reboot – perhaps that’s why the uninstall failed? I just did a quick test program and its MAPIInitialize() that’s changing the directory. is there a new version of MERGEINI that would work with WS 08? Wow – haven’t seen that tool in ages. All it does is simple text manipulation. In fact, since mapisvc.inf is nothing more than a .ini file, the Windows INI functions work (). See HrSetProfileParameters in the MFCMAPI code. I just installed Backup Exec 12 on my 2008 server running Exchange 2007. I have been bouncing back and forth between Microsoft and Symantec trying to get v12 to restore mail boxes. Symantec is blaming MAPI and Microsoft insists MAPI is configured properly. Based on your notes everything appears correct, but Symantec believes that having MAPI32.DLL and MAPISTUB.DLL (both v1.0.2536) in the SysWOW64 folder is an issue. I am stuck in the middle with no clue what to do. Send me a mail with your case number and I can check on the status from our side. Sorry for not posting this sooner – I just found out about it today. As I noted previously , we recently We recently released a downloadable Exchange System Manager (ESM) for Exchange 2003 which can be installed The ESM for Vista won’t install on a W2K8/x64 machine. It complains "You are not running Vista". Will there be an update to correct his? Thanks……………..Chuck The ESM for Vista is just that – it’s a version of ESM designed to install and run on Vista. For W2k8 you can just install the regular ESM from the Exchange CD. ESM 2003 won’t install on W2K8/x64. It complains: "Program is Blocked due to compatibility issues". I have not found any info on M/S site (yet) about this issue. Exchange 2003 isn’t compatible with Windows 2008. But Exchange 2007 is. See. Any issue installing this on Exchange 2007 mailbox servers, to enable a vb script that was developed before MRM to be run on the local server? I am trying to install "Microsoft Exchange Server MAPI Client and Collaboration Data Objects 1.2.1" () on 2008 SBS, and getting the error: "Collaboration Data Objects 1.2.1 cannot be installed unless Microsoft Office Outlook 2007 is also installed". The reason I ask is because my Symantec Backup Jobs are failing with: "e0001207 – To support individual mailbox message and folder restores from Information Store backups, you must download and install the Microsoft Exchange Server MAPI Client and Collaboration Data Objects package version 06.05.7888 or later on the Exchange 2007 server …" Does anyone know of a way to install MAPI/CDO without installing Outlook 2007? Joe – what you tried to install was ExchangeCdo.EXE and did not come from that link. You tried to install the CDO only package, which requires Outlook 2007. Redownload ExchangeMapiCdo.EXE and try it again. installed onto windows 2003 standard 64bit. the mapi extensions installed just fine but it did not register cdo. manually registering c:"Program Files (x86)ExchangeMapi"cdo.dll fixed that. RE Not registering CDO: I’ve not run across that in my testing. I’m apparently having issues with MAPICDO 1.2.1 on a Windows 2008 x64 SP2 / BES 5.0 installation (problem with calendar synchronization). According to the Blackberry Engineer I have to reinstall MAPI/CDO, but he proceeded to leave me high and dry because I’m running on a W2K08 x64 SP2 server. I tried moving the MAPI32.dll out of the SYSTEM32 and SYSWOW64 (at least that’s the way I’ve interpreted it from your Blog) and reinstalled MAPICDO 1.2.1, but as soon as I do that the Blackberry MailStorage service fails as it is looking for the MAPI32.DLL in the SYSWOW64 directory. What should I be doing? Jeff – I didn’t mean to imply you should be manually moving binaries. I would suggest you: 1 – Uninstall the MAPI download 2 – Run FixMAPI 3 – Check that the version of MAPI in syswow64 is 1.0.xxxx. If it isn’t there or is some version like 6.5, find that copy you manually moved and put it back. If you can’t find it – get it from another similar system. 4 – Reinstall the MAPI download. I had an issue with Symantec backup for single mailbox recovery, the error saying need to install CDO1.2.1 on exchange server 2007. After installing CDO1.2.1 on exchange server i could able to take backup, but the problem is i could not able to configure MAPI for new users. Is this issue because of CDO1.2.1 on Exchange 2007 or something else making this problem. What do you mean by "configure MAPI for new users"? It’s not clear what your issue is. Hi stephen Am having Exchange 2008 x64 with Exchange 2007 sp1 running on it. for backup am using Syamntec backup exec 12.8 on a DELL Tape drive. Wen i try to take ordinary Exchange backup its works good, but wen i go for individual mailbox backup by check Granular restore technology there was error which shows to install Microsoft Mapi and CDO 1.2.1. after installing it too i faced the same problem with individual mailbox backup. I went through all the requisites of syamntec regarding this issue and i met it and still problem exists. What are the congiguration still i need to do on the Exchange side. I faced problems in configuring MAPI for new users. so i again uninstalled ExchangeMapicdo1.2.1 from Mailbox server. Kindly look into this issue. Suggest me the solution What should i do to take individual mailbox backup. is this problem related to Microsoft or Symantec? If no one will tell me what they mean by "configuring MAPI for new users", I cannot help. I suggest contacting Symantec if you’re having problems with their backup solution. Hi stephen configuring mapi for new users in the sense Configuring outlook 2007 for new users. Outlook won’t run? What does Outlook have to do with Symantec’s backup solution? I am having problems with Symantec seeing the Exchange 2007 information store on a Server 2003 64 bit server. After talking with Symantec, they are stating that mapi is not configured correctly. If I go to system information, software environment and loaded modules, mapi32 module is not loading. I have loaded Microsoft Mapi and CDO 1.2.1. Any ideas? Go back to Symantec and ask them to resolve the issue. They say it’s not their problem since mapi32 module is not loading. They state it’s a Windows mapi issue. And telling their customers to go away and figure it out on their own is wrong. If Symantec needs help getting their application to work with MAPI, then Symantec needs to open a case with us. I’m just wondering why the mapi module will not load. I have another server with the same setup and the module is loading fine. Symantec will need to answer that – it’s their process and I don’t know anything about it. For instance, I can’t tell you if they’re even trying to load it – maybe they’re not even trying. I’ll tell you that mapi32 is the wrong module to look for – it’s called exmapi32 in the Exchange MAPI download. The exmapi maodule isn’t loaded either. Symantec states that it not their module but a windows module. The module that loads correctly on another server is mapi32 1.0.2536.0 (srv03_sp1_rtm.050324-1447) from that it looks like something that was loaded with SP1 and not by symantec. Whoever you’re talking to is clearly confused. You should ask to have your case escalated. It already has been escalated. They are stating this is a Microsoft issue and cannot go any further without Microsoft involvement. Is there a way for me to test if mapi is functioning correctly on this server? I have not seen postings here since Jan, so I hope this blog is still active. I am running Windows 2008 and I have installed CDO/Mapi 1.2.1 and it all went well. However, I am running Redemption and when I start a Mapi Session with Redemption, I get an error message stating that the sessions cannot be opened. I've got a couple of questions: 1- After installing the mapi libraries, do I need to create a profile of some sort in order to get Mapi working? 2- Is there any other setup that has to be done in order for the mapi interface to work? Thanx Thatch Thatch – The 27 other posts I've put up this year so far don't count? You're asking a question about Redemption. You should ask the maker of Redemption about his product. We have installed MAPI CDO 1.2.1 using administrator account, we then logon using Besadmin account to install BlackBerry Enterprise Server Express. We are having issue creating mapi profile with error: "An error occurred while initializing a MAPI session" . When i logon using administrator account, i am able to create mapi profile just fine. We then uninstall MAPI CDO 1.2.1, rename all the mapi32.dll file to mapi32.old and logon using besadmin account to re-install it. Installation completed, however mapi32.dll file did not get created even after we ran the fixmapi.exe. And we are still unable to create mapi profile. Then we logon using administrator account to re-install MAPI CDO 1.2.1, mapi32.dll get created. However we still have the same issue creating mapi profile using besadmin account. I also notice that MAPISVC.inf does not exist in system32 folder it older exist in syswow64 We checked the exchangemapi folder, all files are there including exmapi32.dll Windows SBS standard 2008 x64 BES 5.0.2 Express UAC Off Can anyone please advise what might be wrong? Stephen, Thanks for taking the time to work on this and to post your findings. I think I can say that Symantec Backup Exec needs to figure out a better way to connect to Exchange if they want to keep their customers. We're looking for a suitable replacement due to issues just like this. Thanks again, Carl Windows 7 x64 with Outlook 2007 installed; "Messaging API and Collaboration Data Objects 1.2.1 cannot be installed with Microsoft Outlook" Same if I try setting compatibility of the installer to anything other than Windows 7. Steven – this is expected. The MAPICDO package cannot be installed on a machine with Outlook on it. If you wanted CDO there's a different installer for that which includes just CDO. Just want to repeat Sridhar's question: is there (will there be) a 64 bit MAPICDO release, i.e. being able to talk MAPI to Exchange from a 64 bit program (without using a 64 bit version of Outlook)? Lars – there are no plans for a 64 bit MAPICDO. stephen – after installing latest mapicdo i am getting following error while accessing MAPI.sessionclass System.Runtime.InteropServices.COMException MSG:Retrieving the COM class factory for component with CLSID {3FA7DEB3-6438-101B-ACC1-00AA00423326} failed due to the following error: 80040154 RAM – we didn't make any changes in an area that would explain that. Try uninstalling and reinstalling. stephen-I am getting following error whie creating instance for MAPI.Sessionclass — >Collaboration Data Objects TYPE:System.Runtime.InteropServices.COMException MSG: [Collaboration Data Objects – [MAPI_E_NOT_FOUND(8004010F)]] Whr as its working fine in windows 2003 machine and not working on win 20008 Stephan – if we create object objSession = Server.CreateObject("MAPI.Session") its throwing below error [Collaboration Data Objects – [MAPI_E_NOT_INITIALIZED(80040605)]] In the registry key file is thr Hi Stephan, currently we are using ExchangeServer 2003 in seperate machine and win server 2003 and Cdo.1.0x in seperate machine for communication. As per Servers upgrade we need to change our win server 2003 to win 2008 R2 so we installed latest ExchangeMAPICDO.exe. we followed below steps for fresh win server 2008 machine 1. Installed ExchangeMAPICdo.exe 2. verified new files in C:Program Files (x86)ExchangeMapi 3. CDO Latest dll & EXMAPI32.dll version its displaying is 6.5.8353.0 4. deployed our application by adding reference latest CDO.dll -in the bin folder its displaying Ineterop.MAPI.dll 5.while accessing MAPI.SessionClass instance its throwing NULL reference error. 6.so its displaying [Collaboration Data Objects – [MAPI_E_NOT_INITIALIZED(80040605)] error Pls let me know ur thoughts on this. Thanks Sush Stephen, I'm trying to install Acronis Server Backup on a server running SBS 2008 and the Acronis installer wants me to upgrade from MAPI 6.x to 1.2.1. Well, I tried installing the MAPI software without first running the FixMAPI solution you mentioned (I just now came across this blog entry) and afterwards when trying to install Acronis again it is still showing version 6.x installed despite the new version installing without any errors (as you hinted to in this post). Now that I've read your blog post all of this is pretty much a given at this point but my question is the following: Does the FIXMAPI protocal still apply? I only ask because I clicked on the link only to find Microsoft doesn't recommend using that method any longer…? Thanks for your help! Restarting the server worked. No need to use FixMAPI protocol.
https://blogs.msdn.microsoft.com/stephen_griffin/2008/06/02/this-just-in-mapi-and-windows-server-2008-now-get-along/
CC-MAIN-2016-07
refinedweb
2,827
67.15
Agenda See also: IRC log Steven: the latest editor's draft is built nightly, not yet uploaded to W3C site ... please take a look and give us feedback ... the area we're having problems with still is blank nodes ... we want to create anonymous nodes and give them names independent of URLs ... for this one little edge case it seems a new naming and referencing mechanism needs to be created ... e.g. aboutblank and hrefblank ... and we need a way to give a (blank) name to an element ... in RDF/A there was a proposed XPointer framework for referring to blank nodes and a naming mechanism ... the problem with this XPointer framework solution was that we'd have to create a spec for it, as it's not defined anywhere Mark: we could simply define that XPointer framework as in the RDF/A draft -- we don't have to go all the way back to XPointer ... the framework makes use of the XPointer architecture ... we could define this in our spec, don't need to go back to XPointer WG Jeremy: I didn't like the RDF/A XPointer solution ... I found it "ugly" ... one nodeID attribute is sufficient; no need for extra hrefblank ... what's hard is providing text for an HTML author who is not RDF-aware to motivate this nodeID attribute Steven: you're suggesting a nodeID attribute that simultaneously defines and references? Jeremy: yes ... in the [October] RDF/A proposal, if there was not a subject in the triple then it was inherited from the context ... if nodeID expresses the subject it's possible to default the object and vice-versa ... while clunky, this achieves the goal of being able to express all of RDF without making things too complicated for an HTML author ... [the spec is] affected by the complexity of the mapping rules from the XHTML attributes to RDF ... I felt the [October] RDF/A mapping rules were a bit too complex Mark: I came up with the XPointer solution because I'm pretty sure we do need two attributes ... RDF/XML does not need two attributes due to its striping syntax ... in the XHTML mechanism we've tried to make it possible to write a complete triple in a single element ... Jeremy's suggested defaulting mechanism may work but I'm pretty sure there are cases where you still need two attributes ... it's also an aesthetic problem for bnodes to have URIs that are not supposed to be considered as URIs Ben: is the bnode section in this editor's draft yet? Steven: no. the document I cited has RDF/A transformed into XHTML2 style except for the bnode material ... we've been struggling with finding some mechanism for bnodes that is more aesthetic and that is explicable to HTML authors without referring to the term "bnode" Jeremy: I agree with that objective Mark: why would an author use anything other than id="A" and id="B" to refer to anonymous nodes? ... why should I [as a document author] be worried about any outside use of those names? ... e.g. I use those names locally, but why should I prevent them from use outside? ... I think this is a concern more to RDF folk than to an HTML author Ben: let's move this discussion to e-mail Jeremy: at the March face-to-face, Steven suggested that XHTML2 would go to Last Call without addressing this particular issue ACTION: Ben to move bnode discussion to email list. [recorded in] Steven: we don't expect any given XHTML spec to have addressed all open issues; we simply have to freeze a document and count remaining open issues as Last Call issues ... if we didn't do this we'd never get a document out the door; people are always reading new drafts and bringing new issues Ralph: are the words in the editors' draft now fairly stable? would a careful review be a waste of time? Steven: not a waste of time ... people are fixing schema errors now ... but up to publication there is always the chance of changes ACTION: Steven to send email about latest draft of RDF/A included in XHTML 2 [recorded in] Steven: the editors' draft cited above has dealt with all the issues from the HTML WG F2F ACTION: BenA to Examples in RDF/XHTML and RDF/XML - use cases [recorded in] [reworded below] Ben: any specific examples you'd like to see, or just use cases? Steven: use cases good Mark: it is OK to give RDF/XML examples and we'll translate them ... most of the larger examples I've done have been based on RSS and FOAF. These might not express everything ACTION: BenA Provide RDF/XML examples and english description to Steven and Mark (use cases) [recorded in] [CONTINUES] ACTION: Tom Baker and Gavin to get feedback about use of RDF in XHTML in their respective communities [recorded in] [CONTINUES] ACTION: DanBri RDF schema for new XHTML2 namespace elements [recorded in] [CONTINUES] Ben: let's plan to meet weekly, even if it's a short meeting next meeting: 12 April, 1400 UTC Ben: discussing f2f feedback; do we need to address a pre-XHTML2 solution? Jeremy: I'll take an action to get HP feedback ACTION: Jeremy to ask HP about need for pre-XHTML 2 solution to RDF-in-HTML problem [recorded in] Ben: Dan and Dom did a new editor's draft for GRDDL Ralph: I read the new draft but didn't look at the diffs Ben: what I gleaned from the ... and specifying what happens if more than one transform is given within a document Ralph: Dave Beckett announced an implementation ... Dave asked if multiple tranformations yield a single graph ... Dom answered in the affirmative Ben: what communities do we need to approach? ACTION: Ben to ask Tom, Gavin and CC about opinion on GRDDL and pre-XHTML2 [recorded in] Ralph: Creative Commons and Dublin Core are still in the top of our list. ... we could grow the list but at least we need those two responses <Zakim> Jeremy, you wanted to summarize changelog and to discuss possible questions to users Jeremy: I see only editorial changes in the GRDDL changelog ... should I be asking HP "Is GRDDL useful" or "Do we need a solution to embedding RDF before XHTML2"? Ben: I think the latter; do we need a solution before XHTML2 and if so, is GRDDL a good way to do this? Jeremy: the vast majority of HTML on the web is ill-formed, not XML ... if we're seeking user feedback, it's up to them to define the scope Ben: I think it's good to cast a wide net to find out user expectations ... this task force may not last long enough to provide every solution, but please ask Ralph: Dave Beckett's GRDDL implementation partly answers some questions that Ivan Herman raised in a hallway conversation at the March F2F ... note that the GRDDL spec says transformations SHOULD be XSLT, not MUST ... so implementations have to be careful
http://www.w3.org/2005/04/05-swbp-minutes.html
CC-MAIN-2013-48
refinedweb
1,184
65.56
NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | ATTRIBUTES | SEE ALSO | NOTES cc [ flag ... ] file ...[ -ltnfprobe ] [ library ... ] #include <tnf/probe.h>TNF_DECLARE_RECORD(c_type, tnf_type); This macro interface is used to extend the TNF (Trace Normal Form) types that can be used in TNF_PROBE(3TNF). There should be only one TNF_DECLARE_RECORD and one TNF_DEFINE_RECORD per new type being defined. The TNF_DECLARE_RECORD should precede the TNF_DEFINE_RECORD. It can be in a header file that multiple source files share if those source files need to use the tnf_type being defined. The TNF_DEFINE_RECORD should only appear in one of the source files. The TNF_DEFINE_RECORD macro interface defines a function as well as a couple of data structures. Hence, this interface has to be used in a source file (.c or .cc file) at file scope and not inside a function. Note that there is no semicolon after the TNF_DEFINE_RECORD interface. Having one will generate a compiler warning. Compiling with the preprocessor option -DNPROBE (see cc(1B)), or with the preprocessor control statement #define NPROBE ahead of the #include <tnf/probe.h> statement, will stop the TNF type extension code from being compiled into the program. The c_type argument must be a C struct type. It is the template from which the new tnf_type is being created. Not all elements of the C struct need be provided in the TNF type being defined. The tnf_type argument is the name being given to the newly created type. Use of this interface uses the name space prefixed by tnf_type. If a new type called "xxx_type" is defined by a library, then the library should not use "xxx_type" as a prefix in any other symbols it defines. The policy on managing the type name space is the same as managing any other name space in a library; that is, prefix any new TNF types by the unique prefix that the rest of the symbols in the library use. This would prevent name space collisions when linking multiple libraries that define new TNF types. For example, if a library libpalloc.so uses the prefix "pal" for all symbols it defines, then it should also use the prefix "pal" for all new TNF types being defined. The tnf_member_type_n argument is the TNF type of the nth provided member of the C structure. The tnf_member_name_n argument is the name of the nth provided member of the C structure. The following example demonstrates how a new TNF type is defined and used in a probe. This code is assumed to be part of a fictitious library called "libpalloc.so" which uses the prefix "pal" for all it's symbols. #include <tnf/probe.h> typedef struct pal_header { long size; char * descriptor; struct pal_header *next; } pal_header_t; TNF_DECLARE_RECORD(pal_header_t, pal_tnf_header); TNF_DEFINE_RECORD_2(pal_header_t, pal_tnf_header, tnf_long, size, tnf_string, descriptor) /* * Note: name space prefixed by pal_tnf_header should not be used by this * client anymore. */ void pal_free(pal_header_t *header_p) { int state; TNF_PROBE_2(pal_free_start, "palloc pal_free", "sunw%debug entering pal_free", tnf_long, state_var, state, pal_tnf_header, header_var, header_p); . . . } See attributes(5) for descriptions of the following attributes: prex(1), tnfdump(1), TNF_PROBE(3TNF), tnf_process_disable(3TNF), attributes(5) It is possible to make a tnf_type definition be recursive or mutually recursive e.g. a structure that uses the "next" field to point to itself (a linked list). If such a structure is sent in to a TNF_PROBE(3TNF), then the entire linked list will be logged to the trace file (until the "next" field is NULL). But, if the list is circular, it will result in an infinite loop. To break the recursion, either don't include the "next" field in the tnf_type, or define the type of the "next" member as tnf_opaque. NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | ATTRIBUTES | SEE ALSO | NOTES
https://docs.oracle.com/cd/E19683-01/817-0712/6mgganadb/index.html
CC-MAIN-2018-13
refinedweb
614
63.39
In preparation for two Ruby on Rails workshops in Sydney, Australia in a few weeks, I’ve discovered a few testing tidbits. Test Timer Some of my tests were very slow, but I didn’t know which ones were the slowest. I wrote a minor hack to Test::Unit that prints a report of how long each test takes to run. Require it after Test::Unit in any test and you’ll know what you need to work on. sudo gem install test_timer require 'test_timer' # Output looks like this 0.857 test_bar_graph_set_colors(TestGruffBar) 0.909 test_wide(TestGruffArea) 0.982 test_many_areas_graph_small(TestGruffArea) 1.081 test_set_legend_box_size(TestGruffBar) 1.114 test_many_datapoints(TestGruffArea) 1.152 test_tall_graph(TestGruffBar) 1.191 test_wide_graph(TestGruffBar) 1.744 test_area_graph(TestGruffArea) 2.119 test_custom_theme(TestGruffBar) 2.652 test_bar_graph(TestGruffBar) 4.511 test_y_axis_increment(TestGruffBar) Faster ActiveRecord callback tests I noticed that some very simple tests were taking more time than they should. I looked into using Mocha but couldn’t find a good way to hook into the saving process. It turns out that you can just call the callbacks directly without hitting the database at all: article = Article.new(:title => "Soggy Bacon") article.send(:before_create) assert_equal 'soggy-bacon', article.permalink Test Rails Layouts Alone I’m using Test::Rails from ZenTest for a few projects. I wanted to be able to test layout templates apart from their contents. But Test::Rails::ViewTestCase looks at the name of the test and the name of the test methods to find what controller and template to use. The solution was to create a temporary controller for layouts so they could be tested alone. # Fake controller so bare layouts can be tested class LayoutsController < ApplicationController; end class LayoutsViewTest < Test::Rails::ViewTestCase # Tests layouts/application.rhtml alone def test_application # Set instance variables for the template assigns[:article] = Article.new(:title => "Soggy Bacon") render assert_... end end One note on the 'Faster ActiveRecord callback tests': this only works if you have: class Thing < ActiveRecord::Base def before_create #do something end end ...defined in your model. If you use: class Thing < ActiveRecord::Base before_create :some_method private def some_method # do something end end ...it doesn't seem to actually call all the before_create methods. Anyone know anyway around this?
http://www.oreillynet.com/ruby/blog/2006/10/test_tidbits.html
crawl-002
refinedweb
371
61.22
Not find an interesting phenomenon occurring in the world nowadays. What happens when a software development department turns into a secondary entity not closely related to the company's basic area of activity? A forest reserve appears. However significant and critical the company's area of activity may be (say, medicine or military equipment), a small swamp appears anyway, where new ideas get stuck and 10-year old technologies are in use. Here you are a couple of extracts from the correspondence of a man working in the software development department at some nuclear power plant: And then he says, "What for do we need git? Look here, I've got it all written down in my paper notebook." ... And do you have any version control at all? 2 men use git. The rest of the team use numbered zip's at best. Though it's only 1 person with zip's I'm sure about. Don't be scared. Software developed at nuclear power plants may serve different purposes, and no one has abolished hardware security yet. In that particular department, people collect and process statistical data. Yet the tendency to swamping is pretty obvious. I don't know why it happens, but the fact is certain. What's interesting, the larger the company, the more intense the swamping effect. I want to point it out that stagnation in large companies is an international phenomenon. Things are quite the same abroad. There is an article on the subject, but I don't remember its title. I spent quite a time trying to find it, but in vain. If somebody knows it, give me the link please so that I could post it. In that article, a programmer is telling a story about him having worked at some military department. It was - naturally - awfully secret and bureaucratic - so much secret and bureaucratic that it took them several months to agree on which level of access permissions he could be granted to work on his computer. As a result, he was writing a program in Notepad (without compiling it) and was soon fired for inefficiency. Now let's get back to our ex-colleague. Having come to his new office, he was struck with kind of a cultural shock. You see, after spending so much time and effort on studying and working with static analysis tools, it's very painful to watch people ignore even compiler warnings. It's just like a separate world where they program according to their own canons and even use their own terms. The man told me some stories about it, and most of all I liked the phrase "grounded pointers" common among the local programmers. See how close they are to the hardware aspect? We are proud of having raised inside our team a skilled specialist who cares about the code quality and reliability. He hasn't silently accepted the established situation; he is trying to improve it. As a start, he did the following. He studied the compiler warnings, then checked the project with Cppcheck and considered preventing typical mistakes in addition to making some fixes. One of his first steps was preparing a paper aiming at improving the quality of the code created by the team. Introducing and integrating a static code analyzer into the development process might be the next step. It will certainly not be PVS-Studio: first, they work under Linux; second, it's very difficult to sell a software product to such companies. So, he has chosen Cppcheck for now. This tool is very fine for people to get started with the static analysis methodology. I invite you to read the paper he has prepared. It is titled "The Way You Shouldn't Write Programs". Many of the items may look written pretty much in the Captain Obvious style. However, these are real problems the man tries to address. Ignoring compiler warnings. When there are many of them in the list, you risk easily missing genuine errors in the lately written code. That's why you should address them all. In the conditional statement of the 'if' operator, a variable is assigned a value instead of being tested for this value: if (numb_numbc[i] = -1) { } The code is compiled well in this case, but the compiler produces a warning. The correct code is shown below: if (numb_numbc[i] == -1) { } The statement "using namespace std;" written in header files may cause using this namespace in all the files which include this header, which in turn may lead to calling wrong functions or occurrence of name collisions. Comparing signed variables to unsigned ones: Keep in mind that mixing signed and unsigned variables may result in: The foregoing code sample incorrectly handles the situation of the 'ba' array being empty. The expression "ba.size() - 1" evaluates to an unsigned size_t value. If the array contains no items, the expression evaluates to 0xFFFFFFFFu. Neglecting usage of constants may lead to overlooking hard-to-eliminate bugs. For example: The '=' operator is mistakenly used instead of '=='. If the 'str' variable were declared as a constant, the compiler would not even compile the code. Pointers to strings are compared instead of strings themselves: Even if the string "S" is stored in the variable TypeValue, the comparison will always return 'false'. The correct way to compare strings is to use the special functions 'strcmp' or 'strncmp'. Buffer overflow: memset(prot.ID, 0, sizeof(prot.ID) + 1); This code may cause several bytes of the memory area right after 'prot.ID' to be cleared as well. Don't mix up sizeof() and strlen(). The sizeof() operator returns the complete size of an item in bytes. The strlen() function returns the string length in characters (without counting the null terminator). Buffer underflow: In this case only N bytes will be cleared instead of the whole '*ptr' structure (N is the pointer size on the current platform). The correct way is to use the following code: Incorrect expression: if (0 < L < 2 * M_PI) { } The compiler doesn't see any error here, yet the expression is meaningless, for you will always get either 'true' or 'false' when executing it, the exact result depending on the comparison operators and boundary conditions. The compiler generates a warning for such expressions. The correct version of this code is this: if (0 < L && L < 2 * M_PI) { } Unsigned variables cannot be less than zero. Comparing a variable to a value it can never reach. For example: The compiler produces warnings against such things. Memory is allocated with the help of 'new' or 'malloc', while forgotten to be freed through 'delete'/'free' correspondingly. It may look something like this:: Memory is allocated through 'new[]' and freed through 'delete'. Or, vice versa, memory is allocated through 'new' and freed through 'delete[]'. Using uninitialized variables: In C/C++, variables are not initialized to zero by default. Sometimes code only seems to run well, which is not so - it's merely luck. A function returns a reference or pointer to local objects: On leaving the function, 'FileName' will refer to an already freed memory area, since all the local objects are created on the stack, so it's impossible to handle it correctly any further. Values returned by functions are not checked, while they may return an error code or '-1' in case of an error. It may happen that a function returns an error code, us continuing to work without noticing and reacting to it in any way, which will result in a sudden program crash at some point. Such defects take much time to debug after that. Neglecting usage of special static and dynamic analysis tools, as well as creation and usage of unit-tests. Being too greedy for adding some parentheses in math expressions, which results in the following: D = ns_vsk.bit.D_PN_ml + (int)(ns_vsk.bit.D_PN_st) << 16; In this case, addition is executed in the first place and only then left-shift is. See "Operation priorities in C/C++ ". Judging by the program logic, the order the operations must be executed in is quite reverse: shift first, then addition. A similar error occurs in the following fragment: The error here is this: the programmer forgot to enclose the TYPE macro in parentheses. This results in first executing the 'type & A' expression and only then the '(type & A ) | B' expression. As a consequence, the condition is always true. Array index out of bounds: The 'mas[3] = 4;' expression addresses a non-existing array item, since it follows from the declaration of the 'int mas[N]' array that its items can be indexed within the range [0...N-1]. Priorities of the logical operations '&&' and '||' are mixed up. The '&&' operator has a higher priority, so in this condition: if (A || B && C) { } 'B && C' will be executed first, while the rest part of the expression will be executed after that. This may not conform to the required execution logic. It's often assumed that logical expressions are executed from left to right. The compiler generates warnings for such suspicious fragments. An assigned value will have no effect outside the function: The pointer 'a' cannot be assigned a different address value. To do that, you need to declare the function in the following way: void foo(int *&a, int b) {....} or: void foo(int **a, int b) {....} I haven't drawn any specific and significant conclusions. I'm only sure that in one particular place the situation with software development is beginning to improve. And that's pleasant. On the other hand, it makes me sad that many people haven't even heard of static analysis. And these people are usually responsible for serious and important affairs. The area of programming is developing very fast. As a result, those who are constantly "working at work" fail to keep track of contemporary tendencies and tools in the industry. They eventually grow to work much less efficiently than freelance programmers and programmers engaged in startups and small companies. Thus we get a strange situation. A young freelancer can do his work better (because he has knowledge: TDD, continuous integration, static analysis, version control systems, and so on) than a programmer who has worked for 10 years at Russian Railways/nuclear power plant/… (add your variant of some large enterprise). Thank God, it's far not always like that. But still it happens. Why am I feeling sad about this? I wish we could sell PVS-Studio to them. But they don't even have a slightest suspicion about existence and usefulness of such tools. :)
http://www.cplusplus.com/articles/91wTURfi/
CC-MAIN-2015-06
refinedweb
1,763
64.41
hi its the first time i have had to install a package not included in default netbeans and cant get it to work im using ubuntu and downloaded jsoup from software center so it is defo installed correctly as it was taken care of by the good people in debian but i cant use it in netbeans Document doc = Jsoup.connect("").get(); String title = doc.title(); both these commands show red lines under and i can fix imports and if i type import org.jsoup.Jsoup; manually this allso has red line under it . is there anythig else im suppossed to do thanks ?
http://www.javaprogrammingforums.com/whats-wrong-my-code/27119-how-install-pakcage.html
CC-MAIN-2014-15
refinedweb
103
68.5
In a previous post, I talked about Elixir's pattern matching in general. Today, I want to focus on binary matching. Briefly, binary matching can have a number of uses, but the most obvious is when dealing with binary data from, say, a file or a socket. As an example, a PostgreSQL message generally takes the shape of 1 byte (to identify the type of message), followed by a 4-byte big-endian encoded length, followed by data. Assuming that we've read such a message from a socket, we could use binary pattern matching as such: def process(<<?D, length::big-32, row::binary>>) do // row represents a row of data end def process(<<?C, length::big-32, tag::binary>>) do // now more rows, command completed, tag has some meta // information on the result that was just returned end ... ( ?D and ?C returns the codepoint of the C and D characters; we could have just as easily used 68 and 67 respectively). The key to binary matching is being able to specify the size of each part. In the above code, we see three different ways to specify the size: an individual byte, a numeric encoding (big/little 16/32/64) and globbing up anything else via ::binary. It's important to note that globbing can only happen at the end of the pattern, as we're doing here. That might seem like a huge limitation, but binary data typically follows some type of deterministically sized header followed by N bytes; so, in most cases, it shouldn't be a problem. Another common length specifier is bytes-size(n) which matches n bytes: <<x::bytes-size(2), rest::binary>> = <<1, 2, 3>> // x == <<1, 2>> // y == <<3>> Finally, you can match individual bits. For example, we could extract the two most significant bits from a byte with: <<a::2, _::6>> = <<200>> // a == 3 Notice that we weren't able to gobble the rest of the data via the ::binary specifier. Why? because the rest of the data isn't a binary: 6 bits does not a binary make. The type of code that relies on binary matching is often performance sensitive, how does all this perform? First, because globbing is only allowed at the end, the deterministic size of each part shouldn't (and doesn't appear to) add much/any overhead. The real performance implications come from how strings and substrings are handled. And, for a runtime not known for its raw performance, Erlang has a few nice tricks up its sleeve. First, and not really related, binaries larger than 64 bytes aren't stored on process heaps, but rather a shared space that processes can reference. Reference counting is used to garbage collect these. Very much related to our conversation about binary matching is the fact that Erlang can create sub binaries which, for anyone familiar with Go, are like slices. That is to say that creating one binary from another doesn't necessarily involve any copying. Erlang can take this a step further and defer the creation of sub binaries if it can tell that a sub binary will be created from a sub binary. This is common when parsing binary data which often happens in a loop or recursively. And, while sub binaries are very small and efficient (if Go's anything to go by, it's a pointer and a length), in a tight loop, creating 1 sub binary is obviously going to be faster than creating a thousand. Erlang isn't always able to optimize binary matching. Sometimes, that's fines. Sometimes, that'll be unavoidable. Still, it's always helpful to understand what's going on. To this end, we can pass the ERL_COMPILER_OPTIONS=bin_opt_info environment variable when compiling our code to get information about what is and isn't being optimized. Consider the following code: defmodule Parser do def parse(%{first: false}, <<type, length::big-32, data::binary>>) do # ... end end When compiled with the special environment variable, we'll get: warning: INFO: matching anything else but a plain variable to the left of binary pattern will prevent delayed sub binary optimization; SUGGEST changing argument order sample.ex:12 So, the first thing we learn is that we'll only get optimized binary matching if we have a simple variable being matched before our binary (or if the binary is the first parameter). In this case, we could just switch the parameter order. Consider this second case: def parse(<<type, length::big-32, data::binary>>) do case byte_size(data) == length do true -> # we have enough data false -> # we need more data end end This will give us NOT OPTIMIZED: sub binary is used or returned. If you look at the code above, this should be obvious. The creation of the data sub binary can't be deferred because we need to know its length then and there. You could say that the call to byte_size/1 actualizes the value. In this case, we can re-write our code easily enough: def parse(<<type, length::big-32, data::binary>>) do case data do <<data::bytes-size(length), rest::binary>> -> process(data) # we have enough data # we should probably process the leftover data "rest" too _ -> # we need more data end end You can see here that the actual value of data doesn't need to be known. You might be thinking: What does deferring buy us? At some point, we'll need to extract meaning from the data!. But, if we can defer that until the point where we convert the binary data to, say, a boolean or integer or string, then we've potentially avoided creating intermediary sub binaries. If we stick with our PostgreSQL example, data which represents a row, would itself begin with an integer (representing the number of columns) and then for each of those columns there'd be more meta data embedded in the binary. Eventually we'll turn the data into a value, but the ability to do this while deferring object creation, and, much more significantly, avoiding copying data, is significant. The erlang documentation has a well-written section on binaries and matching which is worth reading. And you can learn a lot by experimenting and while using the ERL_COMPILER_OPTIONS environment variable to see what is and isn't optimized and why.
https://www.openmymind.net/Elixir-Binary-Matching-Performance/
CC-MAIN-2019-13
refinedweb
1,058
58.72
by Jim Bray (editor's note: this article refers to software aimed at the Canadian market) Get ready to send that kilo of flesh to Ottawa! And while you're at it, why not try to ensure that the flesh you send is your fair and adequate share - that you get the breaks you need so you don't end up dipping even deeper into your pocket than is necessary. After all, why give them more than is absolutely required? They'll just blow it on some billion dollar boondoggle anyway, so better it stays in your pocket where it can do some good. But I digress... The good news is that today's tax preparation computer software can turn the ordeal of poring over those darn sheets and tables into a relatively painless experience. Relatively. TAXWIZ offers a range of "less taxing" products including an online version that lets you fill out and file your return using a Web Browser and the Internet. I haven't actually tried this method, though my son did and he said it was about as pleasant an experience as doing your taxes could be. Some people undoubtedly wonder about the security aspects of putting all your personal poop onto the Internet, but this is really a paper tiger. The only time you'd really have to worry about your info being stolen would be at the destination end, which in this case is Taxwiz, and it depends on their security. But the same can be said for the government's computers that'll end up storing your data - and given the current government's woeful record on just about anything I wouldn't think their systems are any more secure than Taxwiz's - or yours. Speaking of yours, your hard drive could be hacked over an open Internet connection, too, so you could also be as much of a security risk as Taxwiz, the government, or whomever. So don't sweat the security aspects excessively. And there are advantages to filling out the forms online, including these: It's cheaper if you're ony doing one return ($12.95), you don't have to worry about installing software or having it take up hard disk drive space all year while you aren't using it - and you don't have to update it every year. But it was the CD version that I tried. TAXWIZ Deluxe ($24.95, Windows CD), starts with a splash screen offering you choices that range from a "first time users introduction" to the famous "interview" preparation method for beginners and more experienced "returners" alike. You can also access the tax forms directly, convert last year's return or open an existing return. If you choose "First time users," you're taken to another screen, Browser-like in appearance, that offers the choices for if you've never done a tax return before, if you've done returns before by hand, or if you're used tax preparation software before. Taxwiz includes a selection of videos, too, though the ones I sat through amounted basically to just a talking head (albeit an attractive one) who appeared to be reading (rather dryly) from a TelePrompTer. But it's a bit of welcome humanity among all the numbers and tables. I usually do these reviews by taking the "newcomer" route, since it's the best test of the software's ease of use. Taxwiz's interface looks and acts like a Web Browser, so it should be familiar to most computer-savvy people. Down the left side is a series of topics you can access directly. It begins with a little background advice and then sends you off to collect all your info together (T4's, receipts, RRSP contributions etc.) before heading fearlessly into the realm of the "H and R bloc" via the "Taxes" icon at the top of the screen. Entering the data is fill-in-the-blanks easy (though the calendar by which you enter your birthdate is unnecessarily complex: why not just type in the numbers?) and when a particular form (for example, your T4) is required it comes up on screen looking like the real McCoy. The forms appear to have been designed for resolutions lower than the 1280x1024 pixels I use, however, because they're very small and I found them hard to read even with my glasses on. Fortunately, you can easily follow the layout from the print version from which you're transcribing the figures. Navigating the forms is done by either clicking on the next field or pressing the "Tab" key. The Help system isn't as good, alas, forcing you to search the help section for the particular item on which you're working. If only there were a context-sensitive place to click that would take you to help that relates to whatever particular section is confusing you (in my case it was "Name.") Fortunately, you can access the tutorial, "tax center" or the CCRA guide whenever you want or need to, which helps. All in all, the process is reasonably straightforward and if your return is also straightforward it doesn't take long to get through the interview and end up with a completed return (and the software will check it over for you, too). And when you've finished you can just click on the "your tax form" link to see your information, clicking through the pages to find your personal bottom line (to give yourself an early heart attack!) Taxwiz Deluxe 2002 lets you prepare and file up to 6 income tax returns on one computer for the $24.95 price of admission. The company also has provision for unlimited returns to be prepared by taxpayers who earn under $25,000 a year. Spousal returns are integrated and you can Netfile the finished result. Taxwiz is set up for all Provinces and Territories, includes RRSP and charitable donations entries, and an auto expense worksheet. You can also switch between your return and the spousal one, select individual forms without fuss, and there are some popup hints that appear throughout the experience including many tips from "Taxes for Dummies for Canadians". On the whole I think I liked last year's Taxwiz slightly better than this year's, though only slightly. While some things are easier in the interview method this time around, you're now limited to six returns (last year's was unlimited) - though that probably isn't a big deal. Still, overall it's easy to use and if your return is very basic you can probably do your return in little more than half an hour once your ducks are all in a row before you begin. More complicated returns require more work, and more conscious thought, of course but the software does a good job of walking you through the ins and outs regardless.
http://www.technofile.com/articles/taxwiz2003.html
crawl-001
refinedweb
1,151
64.64
I'm on 5/7 Pulling it together where you add Hotel_costs, plane_ride_costs, and rental_car_costs. It doesnt appear to be summing the hotel_costs and rental_car_costs properly Oops, try again. trip_cost('Tampa', 4) returned 220 instead of the correct value 920 it should have added them up. The functions have all worked individually but dont seem to work together. def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 else: return 'Wrong' def rental_car_cost(days): if days == 1 or days == 2: return 40 * days elif days >= 3 and days <= 6: return (40 * days) - 20 elif days >= 7: return (40 * days) - 50 else: return 0 def trip_cost(city,day): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city)
https://discuss.codecademy.com/t/cant-pull-it-together-on-5-7/50615
CC-MAIN-2018-51
refinedweb
134
54.97
Recording an error message does not necessarily have to be fast. I am not saying you should ignore sound design practices and provide a sloppy means of error logging. What I am saying is that your exception handling should concentrate on providing the best options for recording errors and not necessarily the fastest means of handling them. When an application fails and it begins to throw exceptions, its performance takes a back seat to that of dealing with the error itself. This is not always the case, because there are systems that require fast failing. However, the majority of the systems I have built required that the framework allow the best means of solving the problem. The first and best option for solving the problem is discovering what the problem is. Unless you are the user of the application, this may not be possible without a log and/or tracing mechanism. Logging allows anyone to read the state of the system at any time. One of the best places to log is in the exception class itself because the exception has the necessary information to record. Logging can be done in one shot, usually in the final catch block of what could be multiple levels of exception handlers. Another option is to log in real time. Real-time logging is the recording of information while the system is running. This is also referred to as tracing. This helps eliminate the more difficult runtime problems that may occur and that one-time logging may not help to solve. The trick is to capture as much information as possible in the one-time log event so that tracing isn't always necessary in production. Why? Aside from slowing down performance (which you can minimize, as we will see), tracing forces the developer periodically to add tracing function throughout the code, thus cluttering it up. Before we go into how you can architect a robust and flexible tracing system, let's first show how we can build one-time logging into our exception handling. You saw in the FtpException example how the user had the option of logging by passing in true as the last parameter (bLog). However, all of this functionality was passed onto the base class. Because logging usually conforms to a universal standard in your architecture, this can be implemented in your base exception handling class, as shown below: Listing 2.3 The beginning of a real base exception class. public class BaseException : System.ApplicationException { private int m_nCode; public BaseException(){;} public BaseException(string sMessage, bool bLog) : this(sMessage, null, bLog){;} public BaseException(string sMessage, System.Exception oInnerException, bool bLog) : this(null, 0, sMessage, oInnerException, bLog){;} public BaseException(object oSource, int nCode, string sMessage, bool bLog) : this(oSource, nCode, sMessage, null, bLog){;} public BaseException(object oSource, int nCode, string sMessage, System.Exception oInnerException, bool bLog) : base(sMessage, oInnerException) { if (oSource != null) base.Source = oSource.ToString(); Code = nCode; // need to add logic to check what log destination we // should logging to e.g. file, eventlog, database, remote // debugger if (bLog) { // trace listeners should already initialized, this // is called to be prudent Utilities.InitTraceListeners(); // log it Dump(Format(oSource, nCode, sMessage, oInnerException)); } } /// <summary> /// Writes the entire message to all trace listeners including /// the event log /// </summary> /// <param name="oSource"></param> /// <param name="nCode"></param> /// <param name="sMessage"></param> /// <param name="oInnerException"></param> private void Dump(string sMessage) { // write to all trace listeners Trace.WriteLineIf(Config.TraceLevel.TraceError, sMessage); // see Utilities.InitTraceListeners() // record it to the event log if error tracing is on // The EventLog trace listener wasn't added to the // collection to prevent further traces // from being sent to the event log to avoid filling up the // eventlog if (Config.TraceLevel.TraceError) EventLog.WriteEntry("PMException", sMessage); } public static string Format(object oSource, int nCode, string sMessage, System.Exception oInnerException) { StringBuilder sNewMessage = new StringBuilder(); string sErrorStack = null; // get the error stack, if InnerException is null, // sErrorStack will be "exception was not chained" and // should never be null sErrorStack = BuildErrorStack(oInnerException); // we want immediate gradification Trace.AutoFlush = true; sNewMessage.Append("Exception Summary \n") .Append("-------------------------------\n") .Append(DateTime.Now.ToShortDateString()) .Append(":") .Append(DateTime.Now.ToShortTimeString()) .Append(" - ") .Append(sMessage) .Append("\n\n") .Append(sErrorStack); return sNewMessage.ToString(); } /// <summary> /// Takes a first nested exception object and builds a error /// stack from its chained contents /// </summary> /// <param name="oChainedException"></param> /// <returns></returns> private static string BuildErrorStack(System.Exception oChainedException) { string sErrorStack = null; StringBuilder sbErrorStack = new StringBuilder(); int nErrStackNum = 1; System.Exception oInnerException = null;(); } else { sErrorStack = "exception was not chained"; } return sErrorStack; } public int Code { get {return m_nCode;} set {m_nCode = value;} } The logging logic in Listing 2.3 is simple. When throwing an exception, the developer has the option of logging by passing in true for the log flag, as shown in this FTP client code snippet: Listing 2.4 Applying our base exception child class. FtpWebResponse = FtpWebResponse.Create(ControlStreamReader); switch(FtpWebResponse.Code) { case Constants.POSITIVE_COMPLETION_REPLY_CODE: { // success - 200 // this reply is ok break; } case Constants.SERVICE_NOT_AVAILABLE_CODE: case Constants.PERMANENT_NEGATIVE_COMPLETION_REPLY_CODE: case Constants.SYNTAX_ERROR_IN_ARGUMENTS_CODE: case Constants.NOT_LOGGED_IN_CODE: { throw new FtpException (this, FtpWebResponse.Code, FtpWebResponse.GetOriginalMessage(), false); } default: { throw new FtpException (this, FtpWebResponse.Code, NotValidReplyCodeMessage(FtpWebResponse.Code, "PORT"), true); // log this error!!!!! } Here I show a custom FTP exception class passing in the response code, an appropriately returned code description, and the source of the error. In the default section of the switch case statement, the developer wishes to log this exception. In the case statement directly above the default, the FtpException (for whatever reason) does not log. This is an imaginary scenario, but it quickly shows how to specify which exceptions are logged and which ones aren't. The logging itself is handled by the exception, as we have seen. But where does the error actually get logged? Challenge 2.2 How can you globally control where logging output is sent? A solution appears in the next section. Determining Where to Log (Using the Trace Object) In the BaseException class, logging output is eventually written to one or more log targets using the statement Trace.WriteLineIf(). Here I use the tracing capabilities of the FCL to determine where to send the output. You can easily write to the Windows event log, a log file, or another target directly but I wanted to leverage what I consider one of the more elegant features of .NET—tracing. // write to all trace listeners Trace.WriteLineIf(Config.TraceLevel.TraceError, sMessage); The .NET Trace class methods can be used to instrument any debug or release build of your application. Tracing can be used to monitor the health of any system during runtime but it can also act as logging mechanism. Whether you use it for logging, monitoring, or both, tracing can be great way to diagnose problems without affecting or even recompiling your application. The Trace.WriteLineIf method above takes only two arguments. The first is a boolean parameter where I use what is called a TraceSwitch to determine whether I want to trace a message and at what level. Don't worry about the TraceSwitch just yet if you haven't worked with them; I will explain them in the upcoming technology backgrounder. The second parameter is simply the message I want to trace. Trace.WriteLineIf() is called from within the Dump method. The Dump method is, in turn, called from within the overloaded BaseException constructor. Listing 2.5 Sample Base Exception logging routine. if (bLog) { // trace listeners should already initialized, this // is called to be prudent Utilities.InitTraceListeners(); // log it Dump(Format(oSource, nCode, sMessage, oInnerException)); } You'll also notice a few other goodies in the BaseException class. In Listing 2.5, you see that the Dump method calls the Format method. This method is used to prepare the output format of the error message. How you format your messages and what information is included is completely design-specific. Here my formatted message prepares a string that includes three main parts. The first part is the source of the error, usually passed in as this so that I can access the fully qualified type as well as other elements of the calling object. The second part is the error code that will be ultimately included in the recorded message. The third part is an error summary, which is the description of the error provided by the thrower. This is one set in the exception thrown that will actually be logged. The final parameter is the chained exception, which is usually the one just caught. This will be used to build our error stack because it will contain any previously caught and chained errors. The .NET framework provides the mechanism to chain and even a stack trace to use but it does not provide a formatted error stack. This is your job. Providing a full error stack each time you log is optional but it will help determine the cause of the error. This is in case the high-level error does not provide enough clues as to the cause. In fact, I'm sure you have already found that it typically doesn't. Determining What to Log Provide Enough Information When building your application exception classes, especially your base exception class, you will need to determine how much information to provide. Determining this completely depends on the audience. When providing error information to users, you want to give them enough information to determine that there is a problem without inundating them with terse language or technical details that they may not understand. However, this does not mean you forgo technical information as part of your exception. This only means you do not want to display it by default. For example, when displaying an error dialog, you should show only a high-level version of the problem. Optionally, you can also add a Details button to allow the more technically savvy user get more detailed error information if he or she so chooses. You want to provide the option of information without intimidation. Providing a high-level error description is typically the job of the last handler of the exception. This is referred to as the exception boundary. This could be an ASP.NET page or a GUI catching the final exception and displaying it to the user. Again, this does not in any way mean you forgo providing rich information; in fact, you should side on providing more rather than too little. Just hide the complexity from the user. One of the great things about .NET is that you don't have to provide rich information through extensive custom development. The FCL takes care of providing you with helper objects and methods that will give you as much relevant data as you can handle. The following table shows some of the informational items you can easily access using the FCL: Table 2.1. Environmental information: Some examples of information providers from the FCL You'll notice in Table 2.1 that a couple of the items are retrieved using .NET Reflection. Reflection services allow you introspect the public members of almost any class, including the System.Exception class. This can come in very handy when displaying detailed information during logging or display and should be explored. For more information on Reflection services, please refer to the technology backgrounder on Reflection in Chapter 4. Building an Error Stack One of the first things I typically provide is an error stack. This is not to be confused with a call stack; something the System.Exception class provides “out of the box.” As mentioned earlier, the error stack is built around another nice feature of .NET called exception chaining. This is actually a well-known design pattern that the .NET System.Exception class provides for free. All you have to do is take advantage of it. This means making sure during each throw of your BaseException that you pass in the exception class initially caught, as in the following snippet: catch(FtpException ftpe) { throw new BaseException(this, 1234, "FTP Error: " + ftpe.Message, ftpe, true); } Here I am throwing a new exception, passing in a source object (this), an error code (1234), an error description, and what is now the inner exception. In this case, that inner exception is an FtpException. The last parameter (true) will tell this exception to log itself. This will eventually lead to the BuildErrorStack method being called. This is the heart of this method. The BuildErrorStack method simply loops through each chained exception, using the inner exception property of the BaseException class, as shown in Listing 2.6. The format and additional items you place here are, again, up to you. The point is that you leverage the FCL chaining facility by building a useful display medium that will hopefully help solve the issue. Listing 2.6 Sample stack builder used in our base exception class.(); } Challenge 2.3 When throwing exceptions from Web services, what other steps are required? How does SOAP affect exception handling? A solution appears in the upcoming technology backgrounder on SOAP Faults (page 65). Throwing System Exceptions Once you've built your base exception class and all of its helpers, you are probably going to want to leverage it as much as possible. That said, you may also want to take advantage of some of the system exception classes (e.g., System.IOException) that the FCL has to offer. How does one leverage the features of both? The answer is that you use both by employing exception wrapping. When you want to throw a system exception and still want to take advantage of your base exception features, you simply create a new system exception class and pass that as the inner exception of your base exception class constructor. This in effect “wraps” the system exception, allowing it to appear neatly as part of your error stack. This can all be with one (albeit long) line of code: throw new BaseException(this, 120, GetMessage(120), new System.IOException(), true); Here I want to throw the system exception IOException. However, I still want to use my BaseException class features, such as error stacks, message formatting, and logging. Using exception wrapping, I get both.
http://www.informit.com/articles/article.aspx?p=102315&seqNum=3
CC-MAIN-2018-47
refinedweb
2,353
56.05
Use of RTC with XTAL and deepsleep I have a few questions regarding use of the RTC (real time clock). - Is there a difference in accuracy and power consumption when using the RTC with XTAL_32KHZ vs. INTERNAL_RC - Will the RTC need to be reinitalized after a deepsleep to make it use XTAL_32KHZ or INTERNAL_RC - Will deep sleep have any affect on the accuracy of the RTC? @robert-hh I have the same impression. I had a 15 minutes deep sleep cycle running the night and the time was ~4 minutes off in the morning. @t0000899 In my test I also had the impression that the external XTAL is not used. I connected one, made it working. At least I believe so. Getting a crystal to oscillate is not easy. It is not just soldering it to the pins. But the time lapse compared to an external RTC clock was still the same. Even injecting a 32kHz signal with an external generator did not change the figure. I have to investigate further. Hi @jmarcelino , Is it still true that one would need a special firmware to use external RTC crystal in machine.deepsleep? If so, could it be possible to select a firmware with a 32768 Hz external cystal enabled in "Advanced Settings" in Firmware Update Tool? Or update deep sleep documentation to remind that external crystal is not used to count machine.deepsleep time? Hi, I'm trying to setup the RTC to use the external XTAL while in deep-sleep. I create an RTC and set its source to XTAL_32KHZ right before entreing the deep-sleep mode. Everything seems to work fine, but accuracy is still a mess (2 seconds diff over a 10-min sleep time), exactly the same as when using the internal RC oscillator. It looks like the ESP32 is still using the internal clock, because if I remove the crystal, it does the same. My test code: import machine import time rtc = machine.RTC() rtc.init(source=rtc.XTAL_32KHZ) time.sleep_ms(1) machine.deepsleep(60000) Any thoughts on this? What am I missing? Thanks, Javi - jmarcelino last edited by You will get better accuracy - including timing deepsleep wake, especially if you're having long sleep times - using an external crystal at the expense of slightly higher power consumption. I don't however have quantitative data on this to share and it'll also vary depending on the crystal used. On the normal firmware you'll need to tell RTC to enable XTAL_32KHZ every time, because the pycom-esp-idf is compiled with CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC=y CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL= so this reverts to the internal clock every deepsleep cycle. If you're using an external crystal I'd recommend compiling a custom firmware with the external crystal enabled: Component config->ESP32-specific->"Timers used for gettimeofday" and "RTC clock source"
https://forum.pycom.io/topic/3162/use-of-rtc-with-xtal-and-deepsleep/
CC-MAIN-2020-24
refinedweb
471
63.29
I'm creating a program that will test a range of temperatures for validity. I have become stuck, in this case am trying to print a message saying invalid input when a user enters a value not in the range of 425 - 435. Code:#include <stdio.h> #define sentinel 999 int main(void) { int temp; double valid; printf ("Enter the number 999 when you are finished entering numbers.\n\n"); printf ("Enter the temperature range :", sentinel); scanf("%d", &temp); while (temp != sentinel ) { valid = 1; while (valid) { if (temp > 425 && temp < 435) valid = 0; } printf("The product cure temperature is good!\n"); break; } return (0); }
https://cboard.cprogramming.com/c-programming/145729-nested-while-loop-help.html
CC-MAIN-2017-39
refinedweb
104
72.36
Writing PHP Git Hooks with Static Review Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 If you’ve been using Git for more than a short length of time, you’ll hopefully have heard of Git hooks. If not, Git hooks, as Andrew Udvare introduced here on SitePoint back in August of last year, are scripts which run, based on certain events in the Git lifecycle, both on the client and on the server. There are hooks for pre- and post-commit, pre- and post-update, pre-push, pre-rebase, and so on. The sample hooks are written in Bash, one of the Linux shell languages. But they can be written in almost any language you’re comfortable or proficient with. As Tim Boronczyk pointed out in September 2013, there are a wide range of meaningful purposes which hooks can be put to. These include linting, spell-checking commit messages, checking patches against accepted coding standards, running composer, and so on. Now, PHP’s a great language, don’t get me wrong, but it’s not necessarily the best language for shell scripting. Admittedly, it’s gotten a lot better than it once was. But compared to languages such as Bash, Python, and Ruby, it hasn’t been quite as suitable for creating Git hooks; that is, until now. Thanks to Static Review, by Samuel Parkinson, you can now write Git hooks with native PHP, optionally building on the existing core classes. In today’s post, I’m going to give you a tour of what’s on offer, finishing up by writing a custom class to check for any lingering calls to var_dump(). Installing the Library Like most, if not all modern PHP libraries and packages, StaticReview is installable via Composer. To install it in your project, run composer require sjparkinson/static-review in the root of your project. With that, let’s get going. A Working Example Like any code, the best way to understand it is to step through a real example, such as the one below, taken from the StaticReview project repository. Firstly, like all shell scripts, it defines what will run the script. In this case, it’s PHP. After that, the Composer autoload script is included, so that the script has access to all the required classes, as well as a warning, should the autoload script not be available. #!/usr/bin/env php <?php $included = include file_exists(__DIR__ . '/../vendor/autoload.php') ? __DIR__ . '/../vendor/autoload.php' : __DIR__ . '/../../../autoload.php'; if (! $included) { echo 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -sS | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL; exit(1); } Next, as with most modern PHP scripts, all of the required classes are imported, and three variables are initialized. These are: a Reporter, a CLImate, and a GitVersionControl object. The Reporter object provides information about the hook, whether the hook succeeded or failed. The CLImate object makes outputting colored text and text formats simple. And the GitVersionControl object simplifies interactions with Git. // Reference the required classes and the reviews you want to use. use League\CLImate\CLImate; use StaticReview\Reporter\Reporter; use StaticReview\Review\Composer\ComposerLintReview; use StaticReview\Review\General\LineEndingsReview; use StaticReview\Review\General\NoCommitTagReview; use StaticReview\Review\PHP\PhpLeadingLineReview; use StaticReview\Review\PHP\PhpLintReview; use StaticReview\StaticReview; use StaticReview\VersionControl\GitVersionControl; $reporter = new Reporter(); $climate = new CLImate(); $Git = new GitVersionControl(); Next, it creates a new StaticReview object, and passes in the types of reviews to run in the hook. In the case below, it adds five. These reviews: - Checks if the file contains any CRLF line endings - Checks if the set file starts with the correct character sequence - Checks if the file contains NOCOMMIT. - Checks PHP files using the built-in PHP linter, php -l. - Checks if the composer.jsonfile is valid. Then, it tells the review to check any staged files. $review = new StaticReview($reporter); // Add any reviews to the StaticReview instance, supports a fluent interface. $review->addReview(new LineEndingsReview()) ->addReview(new PhpLeadingLineReview()) ->addReview(new NoCommitTagReview()) ->addReview(new PhpLintReview()) ->addReview(new ComposerLintReview()); // Review the staged files. $review->review($Git->getStagedFiles()); Similar to other forms of validation, if issues are reported by any of the review classes, each issue is printed out to the terminal, in red, preceded by an ✘, and the commit does not complete. However, if there are no problems, then a success message, ✔ Looking good. Have you tested everything?, is printed out, and the commit is allowed to complete. // Check if any matching issues were found. if ($reporter->hasIssues()) { $climate->out('')->out(''); foreach ($reporter->getIssues() as $issue) { $climate->red($issue); } $climate->out('')->red('✘ Please fix the errors above.'); exit(1); } else { $climate->out('')->green('✔ Looking good.')->white('Have you tested everything?'); exit(0); } So far, nothing you’d be unfamiliar with, if you’ve worked with Git hooks before. But how, specifically, does a review class operate? Every Review class extends AbstractReview, which implements ReviewInterface. This interface requires two methods to be implemented: canReview(), and review(). canReview, as the name implies, determines if a review can be run, and review does the actual review. Take ComposerLintReview.php as an example, which you can see below. canReview() checks if the file being reviewed is called composer.json. If so, review() can be called. This then creates a command which invokes Composer’s validate functionality on composer.json, and passes that to the getProcess method, implemented in AbstractReview, running the process. If the process is not successful, an error message is created, and set on the Reporter object, by passing it to a call to Reporter’s error() method, as well as the file which was reviewed. public function canReview(FileInterface $file) { // only if the filename is "composer.json" return ($file->getFileName() === 'composer.json'); } public function review(ReporterInterface $reporter, FileInterface $file) { $cmd = sprintf('composer validate %s', $file->getFullPath()); $process = $this->getProcess($cmd); $process->run(); if (! $process->isSuccessful()) { $message = 'The composer configuration is not valid'; $reporter->error($message, $this, $file); } } In a nutshell, that’s all that’s required to create a Git hook to validate files on one of the events in the Git lifecycle. A Custom Review If you browse under vendor/sjparkinson/static-review/src/Review/, you’ll see there are quite a number of pre-packaged Review classes available. They cover Composer, PHP, and general purpose reviews. But what if we want to create one ourselves, one to suit our specific use case? What if we’re concerned that we might leave var_dump statements in our code? We wouldn’t, right? But hey, never hurts to be sure, as old habits can sometimes die hard. So what would a custom review look like? Let’s work through one and find out. First, we’ll create a new directory structure to store our PSR-4 compliant code. Use the following command in the project’s root directory. mkdir -p src/SitePoint/StaticReview/PHP Then, in composer.json, add the following to the existing configuration, and run composer dumpautoload: "autoload": { "psr-4": { "SitePoint\\": "src/SitePoint/" } } This will update Composer’s autoloader to also autoload our new namespace. With that done, create a new class, called VarDumpReview.php in src/SitePoint/StaticReview/PHP. In it, add the following code: <?php namespace SitePoint\StaticReview\PHP; use StaticReview\File\FileInterface; use StaticReview\Reporter\ReporterInterface; use StaticReview\Review\AbstractReview; class VarDumpReview extends AbstractReview { public function canReview(FileInterface $file) { $extension = $file->getExtension(); return ($extension === 'php' || $extension === 'phtml'); } public function review(ReporterInterface $reporter, FileInterface $file) { $cmd = sprintf('grep --fixed-strings --ignore-case --quiet "var_dump" %s', $file->getFullPath()); $process = $this->getProcess($cmd); $process->run(); if ($process->isSuccessful()) { $message = 'A call to `var_dump()` was found'; $reporter->error($message, $this, $file); } } } Based off of PhpLintReview.php and ComposerLintReview.php, canReview checks if, based on the extension, the file being checked is a PHP file. If so, review then uses grep to scan the file for any references to var_dump. If any are found, an error is registered, which tells the user that a call to var_dump was found, and the commit fails. If you were to run it, you could expect output as in the screenshot below. Creating the Hook There’s just one last step to go, which is to create a Git hook from our hook class. In a new directory Hooks in my project root, I’ve copied the hook code we worked through at the beginning of the article, making one small change. I added our new Review file to the list of Reviews, as follows: $review->addReview(new LineEndingsReview()) ->addReview(new PhpLeadingLineReview()) ->addReview(new NoCommitTagReview()) ->addReview(new PhpLintReview()) ->addReview(new ComposerLintReview()) ->addReview(new VarDumpReview()); With that done, create a pre-commit hook, by running the following command. ./vendor/bin/static-review.php hook:install hooks/example-pre-commit.php .Git/hooks/pre-commit And with that, if you look in .git/hooks, you’ll now see a symlink created from pre-commit, to our new hooks file. To test the hook, make a call to var_dump() in any PHP file, stage the file, and attempt to commit it. You shouldn’t even be allowed to create a commit message before the error message shows. If you then update the file to remove the call to var_dump(), you should see a success message, before being able to add a commit message as in the image below. Wrapping Up And that’s all it takes to create simple or powerful Git hooks, using one of the most versatile languages around, PHP. I only came across Static Review thanks to the ever vigilant Bruno Skvorc. But I’m really thankful he suggested checking it out. With it, I can now do one more, ever important development task, using my favorite software development language – PHP. Are you already using Static Review? If so, share your experience in the comments. I’m keen to know how people more experienced than myself.
https://www.sitepoint.com/writing-php-git-hooks-with-static-review/
CC-MAIN-2021-31
refinedweb
1,650
56.35
Ask the Pro LANGUAGES: C# TECHNOLOGIES: File I/O | SQL Belay That Delay Precompile your ASP.NET Web sites to avoid first-run slowness. By Jeff Prosise Q. Is there a tool available for precompiling an ASP.NET Web site so the first request for each page suffers no compilation delay? A. Assuming you enjoy access to pages through the local file system (that is, assuming you can run the tool on the Web server where the pages reside or access the pages through a network share), building a precompilation utility is easy using the rich facilities found in the .NET Framework Class Library. Figure 1 contains the source code for such a utility; it's a console application written in C#. To compile it, open a Visual Studio .NET command prompt window, go to the directory where Touch.cs is stored, and type csc touch.cs. The output is an executable named Touch.exe. To precompile the pages in a specified directory and its subdirectories, execute a command of the form touch url path, in which url is the URL of the virtual root directory and path is the physical path to that directory in the file system. For example, to precompile all the .aspx files in wwwroot and its subdirectories, type touch c:\inetpub\wwwroot. This assumes, of course, that wwwroot is located on the C drive. using System; using System.IO; using System.Net; class Touch { static void Main (string[] args) { if (args.Length < 2) { Console.WriteLine ("Syntax: TOUCH url path"); return; } if (!Directory.Exists (args[1])) { Console.WriteLine ("Error: Invalid path"); return; } string url = args[0]; if (!url.ToLower ().StartsWith ("http")) url = "http://" + url; string path = args[1]; TouchFiles (url, path); } static void TouchFiles (string url, string path) { string[] files = Directory.GetFiles (path, "*.aspx"); foreach (string file in files) { int index = file.LastIndexOf ("\\"); string page = url + "/" + file.Substring (index + 1); WebRequest request = WebRequest.Create (page); try { WebResponse response = request.GetResponse (); StreamReader reader = new StreamReader (response.GetResponseStream ()); string content = reader.ReadToEnd (); reader.Close (); Console.WriteLine ("OK: " + page); } catch (WebException) { Console.WriteLine ("Error: " + page); } } string[] dirs = Directory.GetDirectories (path); foreach (string dir in dirs) { int index = dir.LastIndexOf ("\\"); string nextdir = dir.Substring (index + 1); string nexturl = url + "/" + nextdir; string nextpath = path + "\\" + nextdir; TouchFiles (nexturl, nextpath); } } } Figure 1. Touch.cs precompiles ASP.NET applications by submitting an HTTP request for each .aspx file in a virtual directory and its subdirectories. Touch.exe lists all the pages it fetches (see Figure 2). If "OK" appears in front of the filename, the page was retrieved successfully and it compiled without error. If "Error" appears in front of the filename, the page was not retrieved successfully. This could mean the page contains an error that prevents it from compiling, but that's for you to decide after inspecting the page. Figure 2. Touch.exe lists the pages it retrieves and tells you whether the page executed successfully. The word "Error" preceding a filename could indicate that the page contains a syntax error preventing it from compiling. How does Touch.exe work? It uses the .NET Framework Class Library's System.IO.Directory class to enumerate the files and directories in the specified directory and its subdirectories. Then, it uses System.Net.WebRequest to submit an HTTP request for each .aspx file it finds. If a page fetched this way hasn't been compiled into a Dynamic Link Library (DLL) already, ASP.NET compiles it, averting the compilation delay that normally would occur when a user first accesses the page. Note that Touch.exe does not work with pages that disallow anonymous access because it lacks support for Windows authentication protocols. Nor can it fetch pages protected by forms authentication because it has no means for getting past the login page. One solution to the forms authentication problem is to expose pages protected by forms logins temporarily so they can be accessed without logging in. Q. Are there any tricks I can use to post a page containing a runat="server" form to a page other than itself? Adding an action attribute to the A. ASP.NET forbids a runat="server" form from posting back to another page, but you might be able to accomplish what you're after by taking a slightly different approach. It turns out that if you remove runat="server" from the Figure 3. Login.aspx posts back to Welcome.aspx rather than to itself. The secret? Remove runat="server" from the form tag and use HTML controls rather than Web controls. void Page_Load (Object sender, EventArgs e) { Output.Text = "Hello, " + Request["UserName"]; } Figure 4. Upon postback, Welcome.aspx reads the username the user typed into Login.aspx and uses it to display a customized greeting. In real life, login forms often post back to pages that are accessed over HTTPS. Substitute an HTTPS URL for Welcome.aspx in the action attribute, and this form will do just that. Q. I'm using the DataGrid's built-in paging support to allow users to page through a rather lengthy list of records. One concern I have is even though I set the page size to 50, I must query for all the records and provide the entire recordset - which consists of more than 4,000 records - each time the DataGrid is paged. I understand custom paging is more efficient because it allows me to provide the DataGrid with only the 50 records for the current page, but I can't figure out a way to query SQL Server 2000 for only one page worth of records. A. I consulted with fellow asp.netPRO columnist Dino Esposito and SQL Server guru Peter DeBetta, and I learned a technique they use to custom-page DataGrid controls. You can use a query containing multiple SELECT statements and a NOT IN clause to query SQL Server for a specific range of records. The sample page in Figure 5 demonstrates how. It displays records from the Products table of SQL Server's Northwind database, which contains a total of 77 records, using a page size of 10. <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { MyDataGrid.VirtualItemCount = 77; MyDataGrid.DataSource = GetPage (MyDataGrid.CurrentPageIndex, MyDataGrid.PageSize); MyDataGrid.DataBind (); } } void OnPage (Object sender, DataGridPageChangedEventArgs e) { MyDataGrid.CurrentPageIndex = e.NewPageIndex; MyDataGrid.DataSource = GetPage (e.NewPageIndex, MyDataGrid.PageSize); MyDataGrid.DataBind (); } DataSet GetPage (int index, int size) { // Build and execute a command of the following form: // // SELECT * FROM // (SELECT TOP {0} * FROM // {2} ORDER BY {3}) AS t1 // WHERE {3} NOT IN // (SELECT TOP {1} {3} FROM {2} // ORDER BY {3}) // // Where {0} = Page size * page number // {1} = Page size * (page number - 1) // {2} = Table name // {3} = Field name for sorting string command = String.Format ( "SELECT * FROM " + "(SELECT TOP {0} * FROM " + "{2} ORDER BY {3}) AS t1 " + "WHERE {3} NOT IN " + "(SELECT TOP {1} {3} FROM {2} " + "ORDER BY {3})", size * (index + 1), size * index, "Products", "ProductID" ); SqlDataAdapter adapter = new SqlDataAdapter (command, "server=localhost;database=northwind;uid=sa"); DataSet ds = new DataSet (); adapter.Fill (ds); return ds; } Figure 5. SmartPaging.aspx uses the DataGrid control's custom-paging feature to display records from SQL Server's Northwind database. It queries for only one page worth of records at a time. Although 77 is a rather small record count, the technique applies to tables of any size. Simply substitute the values of your choice for {0}, {1}, {2}, and {3} in the statement that formulates the query, per the instructions provided in the GetPage method. And, remember that "page number" is 1-based, not 0-based like page indexes. A final thought to keep in mind when paging a DataGrid is you can improve performance by querying all the records you intend to display simultaneously, caching the resulting DataSet and coding your PageIndexChanged handler to fetch the DataSet from memory. The ASP.NET application cache, which you can access through a page's Cache property, provides an ideal mechanism for caching DataSets. The sample code in this article is available for download. Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (), a software consulting and education firm that specializes in .NET. Have a question for this column? Submit queries to [email protected]. Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.
http://www.itprotoday.com/web-development/belay-delay
CC-MAIN-2018-30
refinedweb
1,405
67.35
Shortcuts are small files containing the location of another file, or the command line required to launch an application. They are commonly placed within the Windows Start Menu as a convenient way to access common functions of your device. By creating and organising your own shortcuts you can customise the features you have quick access to on your device. Creating a shortcut You can create shortcuts directly on the device by using the built in File Explorer application. In order to create a shortcut XYZ” where XYZ was the original file name. By using the standard file rename functionality you can rename the shortcut to a more suitable name. Uses of – as discussed in a previous blog entry shortcuts placed in this folder will appear on the System tab of the Settings application that is accessible via the Start Menu. Early adopters of the Pointui shell replacement for Windows Mobile devices are using similar techniques to customise the functionality of the built in menus to launch phone dialler applications etc. Technical Details Behind the scenes File Explorer is creating a shortcut file (probably via the SHCreateShortcut API). A shortcut is a file that has the extension *.lnk and contains details of the command line or file that the shortcut should open. Pavel Bánský discusses in his blog the technical details on the contents of a *.lnk file. As an alternative to creating the shortcut file manually, you can also utilise an API called SHCreateShortcut as shown below: using System.Runtime.InteropServices; [DllImport("coredll.dll")] public static extern void SHCreateShortcut( string target, string shortcut); // Create a shortcut to tmail.exe within the // windows start menu. SHCreateShortcut( @"\windows\start menu\programs\my email.lnk", @"\windows\tmail.exe"); Shortcuts can also be created as part of a CAB file installation package for your applications, as discussed in the .NET CF Deployment section of the Microsoft Visual Studio 2005 Professional Guided Tour. Shortcuts can also have other purposes, one of these I will discuss in greater depth in a future blog posting… Visual Studio Deployment project cant create a shortcut which includes command line arguments. And if you instead craft your own .lnk file it wont let you deploy it. When you try to add it nothing happens. For some reason it rejects the file extension. The only remaining option is to create it in code using a CE Setup dll. which can’t be managed code. So you can’t use System.Runtime.InteropServices. Well done Microsoft for completely shafting us again. How about a programatic method for removing a shortcut? Hi Cliff, I have not verified it, but have you tried calling DeleteFile (or it’s managed equivalent File.Delete), passing in the path to the shortcut? For example: Shortcuts can be treated as if they were any other file on the filesystem. Hi and thanx a million dude. Keep up the good work. Caio. I was wondering about making a shortcut to a webpage. I was able to do it before but I cant remember how I did it. For example I want to make a shortcut to youtube. Thanks, reg Hello anybody can help me in this issue……I have created auto started windows mobile application.That should work as a back end process means we have written code in the form load but we don’t want to show the screen to the user. i have tried form1.hide() and form1.windowsstate=formstate.minimized. But it’s not orking. If you have the solution it will be very helpful. Regards, Hema Hi Hema, Try adding a line such as BeginInvoke(new Action(() => Hide())); At the end of your Form Load event handler (or even the constructor of your form, directly underneath the call to InitializeComponent). The problem is the form load event handler is called part way through the OS attempting to make your window visible. Even if you request it to hide, your load event handler still returns to the code within the OS that then makes the window visible. Using a code snippet such as the one I mentioned above essentially “queues” up the request to hide the window. Your form load event handler returns, the window is briefly made visible, and then the OS gets around to processing any outstanding window messages, and hence finds your request to hide it. For a similiar reason another method you may see suggested is the use of a timer with a duration of 1 millisecond. The timer tick event triggers after the window is visible, and hence calling Hide() works as expected. Depending upon what you are attempting to do it may even be better to start off with a console project, and only make the window visible when first required. Hope this helps, Christopher Fairbairn Hope this helps, Christopher Fairbairn
http://www.christec.co.nz/blog/archives/213
CC-MAIN-2018-09
refinedweb
802
64.51
From: Brian Barrett (bbarrett_at_[hidden]) Date: 2007-05-28 16:58:06 On May 28, 2007, at 10:59 AM, Jack Howarth wrote: > On MacOS X, the current v1.1.5 and v1.2.2 sources for openmpi > create shared libraries with undefined environ symbols. This > problem on MacOS X and the available workarounds are discussed > on the fink wiki section on Porting Notes... I understand the problem, but am curious how you are running into it. Open MPI's shared libraries are built with a flat namespace and undefined errors suppressed. An application will always have environ defined, so this could only happen when linking a dynamic library against the Open MPI libraries. When testing this, however, I wasn't able to have create a situation where the linker complained that environ wasn't defined unless the new (MPI-using) library also included environ. Do you have an example where Open MPI using environ causes problems? If so, could you send the link command and output from this error? Or even better, a test case? While I agree that long term this wouldn't be a bad thing to fix, I really hate making OS-specific hacks in the Open MPI source code if we don't absolutely have to. Thanks, Brian -- Brian W. Barrett Open MPI Team, CCS-1 Los Alamos National Laboratory
http://www.open-mpi.org/community/lists/devel/2007/05/1591.php
CC-MAIN-2013-20
refinedweb
225
64.91
The Legend of Zelda: Link's Awakening Trading Sequence FAQ by Kaas Version: 1.02 | Updated: 10/20/05 | Search Guide | Bookmark Guide || _||_ | | THE LEGEND OF ______| |_______ ______________ ______ ____ / ____| |__ / \ __ \ / \ "\ \_ \ / / | | / / | | \ | | | |"\ | \ \ /__/ _| |/ / / | | \_| | | | | | | \ / __ / / / | |_/| | | | | | | | \ /_/| / / / | | | | | | | | | /_\ \ |/ / | |_ | | | | | | | ; __ \ / / / | | \/ _| | || | | | / / \ \ / / / | |___/ / |/|| |_/ |/ / \ \ / /| __|______/|____|/______//___\ /___\ / / / | / / / / / | / / LINK'S AWAKENING / / /| |____/ / /_____| |______/ - - - - - - - - - - | | | | Trading Sequence FAQ \ / \/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Introduction 001~~~~~~~~~~~~~~~~~~~~~~~~~ Welcome to this in-depth FAQ for the Legend of Zelda: Link's Awakening on the GameBoy. In this FAQ, I will try to help you complete the trading sequence. The trading sequence is an important part of the game. In it, you will be trading items you receive for other (sometimes better, sometimes worse) items. Your ultimate goal will be the Magnifying Glass, which you'll need to complete the game. Legend of Zelda: Link's Awakening is the first Zelda game ever to feature the trading sequence; it is now part of the Zelda games as much as the bow & arrows. Be warned however, as the following text will have spoilers in them. As always, if you think there's something wrong with this FAQ, have a question for me or simply want to tell me something, just e-mail me at the following adress: Kaas(dot)Bink(at)GMail(dot)com. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Content 002~~~~~~~~~~~~~~~~~~~~~~~~~ In here you can find the different areas of the walkthrough. Press ctrl+f to open the search box, then enter the code you see next to the section to get there faster. Introduction....................001 Content.........................002 Version History.................003 Trading Sequence................004 Uses of the Magnifying Glass....005 Special Thanks..................006 Legal Stuff.....................007 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Version History 003~~~~~~~~~~~~~~~~~~~~~~~~~ 22 June, 2005 - Version 1.0 I began and completed this FAQ today, and I think it's completely done too. If someone mails me important information, I'll make sure to add, though. 20 July, 2005 - Version 1.01 Small mistake corrected and some spelling errors were corrected today. 20 Oktober, 2005 - Version 1.02 Another small mistake has been corrected; the FAQ is done now. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Trading Sequence 004~~~~~~~~~~~~~~~~~~~~~~~~~ During your stay on the Koholint Island, you will receive many items. Some of those you will keep (such as the bow & arrows), some of them you will trade for something else. I'll focus on the latter. If you complete the trading sequence, you'll receive an important item which will aid you in finding the location of the final boss. Sometimes, when you want to trade your item for another one, you'll have to do or have something else first. I've indicated what you need, where to need to use it and the qoute when you receive your new item in this FAQ (thanks to davogones, who let me use his Text Dump FAQ). On a little sidenote, sometimes, when you receive your new item, the game shows a picture of it instead of naming it. In the qoute section I just put the name of the item, as I didn't feel like drawing all those pictures. I'm sure you understand... To make things easier, I've included a handy map to show you where to find every item. This map is the same as the World Map you see on your screen when you press the Select Button. Coordinates are noted like this: (a;1) for the first square, (p;16 for the last square). a b c d e f g h i j k l m n o p 1 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 2 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 3 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 4 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 5 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 6 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 7 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 8 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 9 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 10 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 11 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 12 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 13 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 14 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 15 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 16 |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| Item 1: a Yoshi Doll. Prereqisuites: 10 rupees and a sword. Location: (d;12), it can be found in the building in the southeast part of Mabe Village. How to get: Once you have the sword, go kill some monsters and cut some grass to earn yourself 10 rupees. Once you have ten rupees, go to the location I told you (d;12) and cut away the grass to enter the building. Inside, go talk to man at the right. He'll ask you if you want to play the Trendy Game, so say yes. Now press the B Button to move your crane horizontally so, that the shadow of the crane is above the Yoshi Doll (it's in the middle). Then press the A button to make the crane move vertically. If done correcty, the crane should pick up the Yoshi Doll and deliver it to you. It's pretty easy to catch, so don't worry. Qoute:You got a Yoshi Doll! Recently, he seems to be showing up in many games! Item 2: a Ribbon. Prereqisuites: a Yoshi Doll. Location: (c;9), the Quadruplet's house in the very north of Mabe Village. How to get: Once you've obtained the Yoshi Doll, just go to the house in the northern part of the village. You'll see a woman with a baby there, as well as a man and some beds with kids. Talk to the woman with the baby and she'll ask you if she can have your doll. You should say "Yes" and you'll make one lucky baby very happy (and receive a nice ribbon in return). Qoute: You traded your Yoshi Doll for a Ribbon! Maybe you can trade the ribbon for something else! Item 3: Dog Food. Prereqisuites: a Ribbon. Location: (b;11), the little house right next to Madam MeowMeow's house. In it lives a small, female Chain-chomp. How to get: Go to the small house with your Ribbon. In it, is a small, female Chian-chomp (wow, the second Mario reference; the first one was Yoshi of course). Anyway, it seems she fancies jewelery and accessoires, so talk to her and say "Yes" when she asks for your Ribbon to receive the Dog Food. Qoute: You exchanged Ribbon for Dog Food! It's full of juicy beef! Item 4: Bananas. Prerequisites: Dog Food. Location: (d;15), a little house on the beach. Just go south from Mabe Village, then keep going east to find it (it's just northeast of the place where you found your sword). How to get: make your way to the little house and talk to the big alligator inside. He'll tell you he likes canned food, and practically goes insane when he finds out you have some. Let him have it and he'll give you some bananas in return (after he eats the canned food). Now that was odd, wasn't it? Qoute: MUNCH MUNCH!! ... ... ... ... That was great! I know it's not a fair trade, but here's some bananas! YUM... Item 5: a Stick. Prereqisuites: Bananas. Location: (l;8), there's a little monkey on the bridge. You won't be able to cross the bridge without talking to her, and you'll need to cross to find the 5 Golden Leaves for Richard. How to get: Simply talk to Kiki the monkey (the one on the bridge), and give her your bananas. She'll summon some more monkeys, and they'll build you a bridge you can cross. Luckily, they also leave a stick behind... Qoute: You found a stick a monkey left behind... You take it! Item 6: Honeycomb. Prereqisuites: Stick and having dungeon 3 (Key Cavern) beaten. Location: (h;9), a man next to a tree. He can be found on the prairie, a bit east from Mabe Village. How to get: When you approach the man, you'll probably recognize him. It's Tarin, your savior, up to something stupid! Anyway, just talk to him and say "can" when he asks you if he can borrow your stick. He'll poke the honeycomb and gets chased away by bees. You can pick up the honeycomb (now without bees!) when he's gone. Later, if you check his house, you can find him hurting in his bed. Qoute: The stick became the honeycomb! You're not sure how it happened, but take it! Item 7: Pineapple. Prereqisuites: Honeycomb. Location: (n;14), the house southeast in Animal Village. It's the house next to the fence, with some sort of chimney next to it. How to get: Go inside the house and talk to the chef with the cooking hat there. He'll want your honeycomb, because he's all run out of them, so reply "Yes" when he asks for it. He'll give you a pine-apple in return. Qoute: You exchanged the honeycomb for a pineapple! It's not as sweet, but it is delicious! Item 8: Hibiscus. Prereqisuites: Pine-apple Location: (j;2), the guy who's lost in the mountains. You can reach him by entering and following the cave at (h;2), then when you exit that one, enter the cave at (j;2). When you exit that one, simply go down one screen and left one screen to reach a famished Papahl (you've met him before; he was the dad of the Quadruplets. You even gave your Yoshi away in that house). How to get: Talk to him and he'll tell you he's so famished, he can't even move. He'll ask you for some "Vittles", so give him your pine-apple. He'll give you a nice Hibiscus in return! Qoute: AH! This isn't meant to be a reward... Here, take this flower! It's a hibiscus! Item 9: Letter. Prereqisuites: Hibiscus. Location: (n;13), the house in the northeast corner of Animal Village. How to get: In the house in Animal Village lives a goat who is apparently very fond of nice manners. When you talk to her, she'll just assume the flower is for her, and will ask you for a favor. Say "Yes" and she'll now give you a letter for you to to deliver to Mr. Write. Qoute: You traded the hibiscus for a goat's letter! ...Great!? Item 10: Broom. Prerequisites: The goat's letter. Location: (a;4), a lonely house in left of the swamp. In it you'll find Mr. Write busy writing something. How to get: Just enter the house and talk to Mr. Write. He'll be happy with the letter and will give you a broom in return! Make sure to pay attention to the picture the goat included! Pretty funny scene... Qoute: You got a Broom as your reward from Mr. Write! But that photo was not of... Item 11: Fish Hook Prerequisites: Broom. Location: (b;12), the woman outside Ulrira's house in the southwest corner of Mabe Village. It's granma Ulrira, who was always busy sweeping everything clean! How to get: You'll notice the woman who was always sweeping suddenly is broom- less. Well, we now have one so talk to her and tell her it's for her. She'll give you a fishing hook she found while sweeping by the river bank. After the exchange, you'll find granma Ulrira back in Animal Village (sweeping, of course). Qoute: You exchanged the broom for the fishing hook! What will the fishing hook become? Item 12: Necklace. Prerequisites: Fishing Hook, Flippers. Location: (k;15), under the small bridge, south of dungeon 5 (Catfish's Maw). How to get: When you're in the water, press B to dive down and swim under the bridge. Jump out of the water with your Roc's Feather and enter the boat. Now talk to the fisherman and let him use your hook in trade of his next catch. The fisherman will start fishing immediatelly and it won't be bad. Well, he happens to catch a necklace! Qoute: The fishing hook became a necklace! L-l-lucky! Item 13: Scale. Prerequisites: Necklace. Location: (j;13), the mermaid in the water, just above dungeon 5 (Catfish's Maw). Her name is Martha, not uncoincedentilly the name of this bay! How to get: You'll notice the mermaid in the water, so swim over and talk to her to find out she lost her necklace. She says she's looked all over for it. Well, it looks like we've got it now, so give it back to her and she'll let you take a scale of her tail. Only one piece, though. Qoute: You returned the necklace and got a scale of the mermaid's tail. How will you use this? Item 14: Magnifying Glass. Prerequisites: Scale, Hookshot. Location: (j;15), the statue of a mermaid in Martha's Bay. How to get: use the hookshot to cross the water southwest of Animal Village and follow the path until you see the statue. Walk towards it and you should automatically insert the scale in the statue (it was missing one scale). The statue should move to the left now and you can enter the cave. You'll see nothing in the first area of the cave, but when you start moving, changes are you'll bump into some invisible enemies. Just ignore them and move to the north part of the cave. Take the item you see there to get the Magnifying Glass, which concludes our trading sequence! Qoute: You've got the Magnifying Glass! This will reveal many things you couldn't see before! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Uses of the Magnifying Glass 005~~~~~~~~~~~~~~~~~~~~~~~~~ There are only three ways to use the Magnifying Glass, and they all work automatically. 1) See invisible enemies. The only time you'll use this function is when you just picked it up and go south. You'll see a few emenies there who you couldn't see before, but it's very obvious this isn't the main purpose of the Magnifying Glass. 2) Get the Boomerang. This is more like it. Once you've found the Magnifying Glass, go to the beach at (e;16). There's a cracked wall there, so bomb it to reveal a cave. In it you'll find a friendly monster who will trade you the Boomarang for the item you have equipped in your B Button slot. You can trade back the Boomarang for your own item any time you want. Most people trade their shovel for it, because it gets pretty useless after you've digged up everything worthwhile. Feel free to choose something else to trade, however. The Boomarang itself is a very powerful weapon, stunning and sometimes killing enemies with only one hit! 3) Read the Book "Dark Mysteries and Secrets of Koholint". This is where it's all about. You can find this book in Mabe Village's library (a;12); it's the book in the southeast corner. In it, you can find the way to move in the Windfish's Egg. You should write down this route, as you'll need it when you're going to confront the final boss. When you've made your way to the Windfish's Egg, and played the instruments in front of it, the Egg opens up. When you enter and go north one room, you'll drop down. Now, everywhere you go (except backwards, which takes you back to the beginning) you'll see the same exact room. If you follow the directions you've read in the mysterious book, you should reach the room of the final boss! Good luck with him, as he's pretty hard to defeat. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Special Thanks 006~~~~~~~~~~~~~~~~~~~~~~~~~ CJayC: for hosting this FAQ and keeping an excellent site updated and operational. Nintendo: for making this excellent game. davogones: for letting me use his Text Dump FAQ for some of the quotes in this FAQ. It was very useful! Malcom M.: for pointing out a small mistake in the FAQ. My mom: for buying me this game for my birthday; best present ever! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Legal Stuff 007~~~~~~~~~~~~~~~~~~~~~~~~~ This walkthrough, and all it's content (including the ASCIIs),
https://www.gamefaqs.com/gameboy/563277-the-legend-of-zelda-links-awakening/faqs/37454
CC-MAIN-2017-34
refinedweb
2,907
84.27
The other day, I saw Learn regex the easy way. This is a great resource, but I felt the need to pen a post explaining that regexes are usually not the right approach. Let’s do a little exercise. I googled “URL regex” and here’s the first Stack Overflow result: https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*) This is a bad regex. Here are some valid URLs that this regex fails to match: - - - http://名がドメイン.com (warning: this is a parked domain) - - - - http://[::1] (ipv6 loopback) Here are some invalid URLs the regex is fine with: - - http://–example.org This answer has been revised 9 times on Stack Overflow, and this is the best they could come up with. Go back and read the regex. Can you tell where each of these bugs are? How long did it take you? If you received a bug report in your application because one of these URLs was handled incorrectly, do you understand this regex well enough to fix it? If your application has a URL regex, go find it and see how it fares with these tests. Complicated regexes are opaque, unmaintainable, and often wrong. The correct approach to validating a URL is as follows: from urllib.parse import urlparse def is_url_valid(url): try: urlparse(url) return True except: return False A regex is useful for validating simple patterns and for finding patterns in text. For anything beyond that it’s almost certainly a terrible choice. Say you want to… validate an email address: try to send an email to it! validate password strength requirements: estimate the complexity with zxcvbn! validate a date: use your standard library! datetime.datetime.strptime validate a credit card number: run the Luhn algorithm on it! validate a social security number: alright, use a regex. But don’t expect the number to be assigned to someone until you ask the Social Security Administration about it! Get the picture?
https://drewdevault.com/2017/08/13/When-not-to-use-a-regex.html
CC-MAIN-2017-47
refinedweb
334
75.61
In the enterprise application development world, the buzzwords are Performance, Scalability, and Security. I started my career as a VC++ programmer, and one fine morning, I was transferred to Web development department. Like every C++ programmer, I also was frustrated. I thought every Tom, Dick, and our very own Harry can program in HTML. But, soon I found that the real challenge is to produce high performance, scalable, and reliable applications. And above all that the loosely coupled, stateless nature of web environment is always going to haunt you. In order to produce high performance scalable applications, it is important to use your resources in an optimized manner. One tip is that use your resource as late as you can and free it at the earliest after your use. My intention here is to describe the object cleaning up mechanism used in C#. As we all know, �Destructors� are used to destruct instances of classes. When we are using destructors in C#, we have to keep in mind the following things: The following is a declaration of a destructor for the class MyClass: ~ MyClass() { // Cleaning up code goes here } The programmer has no control on when the destructor is going to be executed because this is determined by the Garbage Collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits. When a destructor executes what is happening behind the scenes is that the destructor implicitly calls the Object.Finalize method on the object's base class. Therefore, the preceding destructor code is implicitly translated to: protected override void Finalize() { try { // Cleaning up . } finally { base.Finalize(); } } Now, let us look at an example of how destructors are called. We have three classes A, B and C. B is derived from A, and C is derived from B. Each class has their own constructors and destructors. In the main of the class App, we create an object of C. using System; class A { public A() { Console.WriteLine("Creating A"); } ~A() { Console.WriteLine("Destroying A"); } } class B:A { public B() { Console.WriteLine("Creating B"); } ~B() { Console.WriteLine("Destroying B"); } } class C:B { public C() { Console.WriteLine("Creating C"); } ~C() { Console.WriteLine("Destroying C"); } } class App { public static void Main() { C c=new C(); Console.WriteLine("Object Created "); Console.WriteLine("Press enter to Destroy it"); Console.ReadLine(); c=null; //GC.Collect(); Console.Read(); } } As we expect, the constructors of base classes will be executed and program will wait for the user to press 'enter'. When this occurs, we set the object of class C to null. But the destructors are not executing ..!!?? As we already said, the programmer has no control on when the destructor is going to be executed because the Garbage Collector determines this. But the destructors are called when the program exits. You can check this by redirecting the o/p of the program to a text file. I have the output here. Notice that the destructors of the base classes are called because behind the scenes base.Finalize() is called. Creating A Creating B Creating C Object Created Press enter to Destroy it Destroying C Destroying B Destroying A So, what do you do if you want to call the destructors once you are finished using the object? There are two ways: Disposemethod of IDisposableinterface. You can force the garbage collector to do clean up by calling the GC.Collect method, but in most cases, this should be avoided because it may result in performance issues. In the above program, remove the comment on GC.Collect(). Compile and run it. Now, you can see the destructors being executed in the console itself. The IDisposable interface contains only one public method with signature void Dispose(). We can implement this method to close or release unmanaged resources such as files, streams, and handles held by an instance of the class that implements this interface. This method is used for all tasks associated with freeing resources held by an object. When implementing this method, objects must seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. class MyClass:IDisposable { public void Dispose() { //implementation } } When we implement IDisposable interface, we require discipline to ensure that Dispose is called properly. Public class MyClass:IDisposable { private bool IsDisposed=false; public void Dispose() { Dispose(true); GC.SupressFinalize(this); } protected void Dispose(bool Diposing) { if(!IsDisposed) { if(Disposing) { //Clean Up managed resources } //Clean up unmanaged resources } IsDisposed=true; } ~MyClass() { Dispose(false); } } Here the overload of Dispose(bool) does the cleaning up, and all the cleaning up code is written only in this method. This method is called by both the destructor and the IDisposable.Dispose(). We should take care that the Dispose(bool) is not called from any where else except from the IDisposable.Dispose() and the destructor. When a client calls IDisposable.Dispose(), then the client deliberately wants to clean up the managed and unmanaged resource, and so the cleaning up is done. One thing you must have noticed is that we called GC.SupressFinalize(this) immediately after we cleaned up the resource. This method tells the Garbage Collector that there is no need to call its destructor because we have already done the clean up. Notice that in the above example, the destructor calls the Dispose with parameter as false. Here, we are ensuring that the Garbage collector collects the managed resources. We only do the cleaning up of unmanaged resource. Even though we have spent some time implementing the IDisposable interface, what if the client doesn�t call them properly? C# has a cool solution for this. The � using� block. It looks like this: using (MyClass objCls =new MyClass()) { } When the control exits from the using block either by running successfully and reaching the closing braces or by throwing an exception, the IDispose.Dispose() of MyClass will be executed. Remember the object you instantiate must implement the System.IDisposable interface. The using statement defines a scope at the end of which an object will be disposed. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/cs/destructorsincs.aspx
crawl-002
refinedweb
1,030
58.18
Hi all, I’ve just been following the Number Wizard videos and it’s all pretty much perfect except it won’t restart properly at the end of the first round and the “Return” button seems to become inactive. Would someone by kind enough to check my code please? using System.Collections; using System.Collections.Generic; using UnityEngine; public class NumberWizard : MonoBehaviour { int max; int min; int guess; // Start is called before the first frame update void Start() { StartGame(); } void StartGame() { max = 1000; min = 1; guess = 500; Debug.Log("Ahoyyyy, Welcome to number wizard me hearty!"); Debug.Log("Polly says that It's time to think of a number, but don't tell me or 'im"); Debug.Log("The lowest number you can pick is: " + min); Debug.Log("The hghest number you can pick is: " + max); Debug.Log("What are you waiting for, go forth Greybeard. Solve the mystery!"); Debug.Log("Ye-arghhh Hurry up!"); Debug.Log("Is yeee number higher or lower than 500"); Debug.Log("Press up = High-arghh, Press Down = Low-arghh, Press Enter = Correct!! Ahoy!! Get the Rum in!"); max = max + 1; } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.UpArrow)) { min = guess; NextGuess(); Debug.Log(guess); } else if (Input.GetKeyDown(KeyCode.DownArrow)) { max = guess; NextGuess(); } else if (Input.GetKeyDown(KeyCode.Return)) { Debug.Log("Yee-arghhhh! get in mate! Let's go again. Is your number high-arghh or low-arghh than 500?"); StartGame(); } } void NextGuess() { guess = (max + min) / 2; Debug.Log("Is the number high-arghh or low-arghh than.." + guess); } }
https://community.gamedev.tv/t/not-restarting-properly/171509
CC-MAIN-2021-25
refinedweb
260
62.14
this is the original assignment : The daily sales amount of a company product for seven days is as follows: 175, 225, 0, 200, 325, 275, 60. Write a program so that the average of sales is increased by x units from the 8th day to the 14th day. x = 1 or 2 or 5 or 10 etc. heres what i got so far: Code : import java.util.Scanner; public class sales2{ public static void main(String[] args){ Scanner user_Input = new Scanner(System.in); double []sales = {175, 225, 0, 200, 325, 275, 60}; double sum = 0, avg; double newSum = 0; int averageIncrease; double newSales = 0; int i, k; for (i = 0; i < 7; ++i){ sum = sum + sales[i]; System.out.println("sales[" + i + "] = " + sales[i]); } avg = sum/i; System.out.println("average = " + avg); for (k = 8; k < 15; k++) { System.out.println("How much would you like to increase average sales by?"); averageIncrease = user_Input.nextInt(); avg = avg + averageIncrease; newSum = avg * k ; newSales = newSum - sum; System.out.println("New sales for day[" + k + "] = " +newSales); } } } Still having a hard time to figure out how to calculate the right amount of sales for days 9-14. I was able to figure out day 8 by subtracting the new sum from the old sum but cant figure out how to get it to subtract the old sum from the first sales array as well as the previous days sorry if this sounds a little confusing.
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/24289-need-some-help-my-code-printingthethread.html
CC-MAIN-2016-30
refinedweb
240
69.92
pthread_atfork(3) BSD Library Functions Manual pthread_atfork(3) NAME pthread_atfork -- register handlers to be called before and after fork() SYNOPSIS #include <pthread.h> int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)); DESCRIPTION The pthread_atfork() function is used to register functions to be called before and after fork(). The prepare handler is called before fork(), while the parent and child handlers are called after fork() in the parent and child process respectively. The prepare handlers are called in reverse order of their registration, while parent and child handlers are called in the order in which they were registered. Any of the handlers may be NULL. Important: only async-signal-safe functions are allowed on the child side of fork(). See sigaction(2) for details. RETURN VALUES If successful, the pthread_atfork() function will return zero; otherwise an error number will be returned to indicate the error. ERRORS pthread_atfork() will fail if: [ENOMEM] The system lacked the necessary resources to add another handler to the list. SEE ALSO fork(2) STANDARDS pthread_atfork() conforms to ISO/IEC 9945-1:1996 (``POSIX.1''). BSD August 12, 2004 BSD Mac OS X 10.9.1 - Generated Thu Jan 9 05:39:22 CST 2014
http://www.manpagez.com/man/3/pthread_atfork/
CC-MAIN-2018-05
refinedweb
201
56.05
I recently needed to use C# to programmatically create a shortcut (.LNK file) to a console executable. This is easily done in native C/C++ using the ShellLink CoClass, the IShellLink interface and their related interfaces. I looked around and couldn’t find a good C# COM interop example for the related native COM interfaces so I wrote one. This was a good excuse for me to learn a litle bit about C# and COM interoperability. You can find the source code here, provided under the Microsoft Permissive License. This first cut provides a set of C# classes and related values for manipulating Windows Shell Links. The public methods, properties and enumerations (or just publics) are C# style – I didn’t let the underlying native names leak through. For example, an important native enumeration is the native SHELL_LINK_DATA_FLAGS enumeration. I’ve seen some interop examples that expose the native names of things publicly in C#. This works, but doesn’t follow the .NET Design Guidelines for Class Library Developers (in hardback on Amazon). Exposing the native names is a bit ugly in .NET languages, and in C# in particular. In the public aspects of my C# I provide the native functionally in a modern C# manner. For example, I provide a .NET enuneration named ShellLinkFlags which provides the values in SHELL_LINK_DATA_FLAGS. These enumerations have C# style names like RunAsUser instead of SLDF_RUNAS_USER. Another important attribute is that all of the publics are CLS compliant. This enables all .NET languages to easily access these classes, not just C#. There are some limitations to this code. I built this so I could create shell links to EXEs – primarily console applications. This code does not yet support the IShellLink.GetIDList() and IShellLInk.SetIDList() methiods. So, it can only be used to link to things in the file system, and not shell objects such as printers. This code is provided in a Visual Studio 2010 project built with C# and .NET 4.0 using the client profile. The actual shell interop code is built in a separate class library named Eidos, which is the name of my general purpose C# library. The namespace is Eidos.Shell. You can use this directly, or easily incorporate it into your own code. I’ve also included a couple of basic unit tests – you can extend these as needed. There is also a simple program that will dump the contents of a Shell link file to the console. The primary public class is ShellLink. This provides a set of properties and methods that provides the functionality of IShellLink but in a C# manner. One of the biggest differences between the C# APIs and the native COM interfaces are how Data Blocks and IShellLinkDataList are treated. These are not exposed in the my .NET classes. instead, they are wrapped using standard properties on the C# ShellLink class. This works really well. It means you can simply get and set property values just like you would with a “normal” .NET class. The IShellLink class handles all the work of creating, writing and reading the data blocks using an internal IShellLinkDataList interface. You can find the source code here, provided under the Microsoft Permissive License.
http://blogs.msdn.com/b/pigscanfly/archive/2010/12/05/c-ishelllink-com-interop-example.aspx
CC-MAIN-2014-41
refinedweb
534
67.25
Ext.fx.animation.Slide is private Ext.fx.animation.Slide is private Ext.fx.animation.Slide is documented as a private class. Seems like that would be a public class. Any chance this is just a documentation error? - Join Date - Mar 2007 - Location - Gainesville, FL - 37,997 - Vote Rating - 978 All of the Ext.fx classes are marked those could be promoted to public classes? It seems like a suite of classes that would be used quite a bit in the animation config in apps. My concern is always that private classes/methods/etc could be changed/nixed in future versions, but other public classes/methods in the framework today point you to use the configs from these private classes (showAnimation, hideAnimation, and so forth).
https://www.sencha.com/forum/showthread.php?257339-Ext.fx.animation.Slide-is-private
CC-MAIN-2015-18
refinedweb
125
59.09
Time::HiRes Actual time resolution to that accuracy is chancy on most platforms. As recommended, Time::HiRes is a good bet, but most platforms will not guarantee any absolute time better than the schedulers time slice, or jiffy. If you need better, check around for 'real time' kernels. After Compline,Zaxo you could use Inline::C. I'm not really a C programmer, but something like this should print the result of that C call. print currentTimeMillis(); use Inline C => <<'END_OF_C_CODE'; #include <sys/time.h> long currentTimeMillis() { long t; struct timeval tv; gettimeofday(&tv, 0); t = tv.tv_usec; return t; } END_OF_C_CODE [download]
http://www.perlmonks.org/index.pl?node_id=286621
CC-MAIN-2015-22
refinedweb
102
68.16
Getting started Brail includes many changes to the way that you normally write code in Boo. Brail views are scripts files that ends with "*.brail" or "*.brailjs". The most significant change is that Brail does not use whitespace to control blocks. This mean that the following statement in Boo: if someCondition: DoAction() Will look like this in Brail: if someCondition: DoAction() end Blocks are controlled starting with a colon and ending by "end". While this is probably the most significant change from Boo, there are many other things that Brail does for you so you would get a scripting experience while working in a compiled langauge. Read on and discover what makes Brail so special. Getting started with Brail First of all you must reference the following assemblies. Copy them to the bin folder if you are not using Visual Studio. - Castle.MonoRail.Views.Brail.dll - Boo.Lang.dll - Boo.Lang.Compiler.dll - Boo.Lang.Parser.dll - anrControls.Markdown.dll The Boo.* files are required for the language support. The anrControl.Markdown.dll is required for support Markdown formatting. Edit your web.config file to include the following line (in the monoRail config section, of course): <viewEngine viewPathRoot="Views" customEngine="Castle.MonoRail.Views.Brail.BooViewEngine, Castle.MonoRail.Views.Brail" /> And that is it, you are now capable of using Boo scripts to write views in MonoRail! Now that you can use it, let's see what you can do with it. Before we get to how to use it, I must send huge thanks to the Boo Community, for being so helpful. Security If your view directory is in the web directory, it's wise to not allow the files to be read through http. So under the system.web/httpHandlers configuration you should add the following: <add verb="*" path="*.brail" type="System.Web.HttpForbiddenHandler"/> <add verb="*" path="*.brailjs" type="System.Web.HttpForbiddenHandler"/> The mandatory 'hello world' First, Brail scripts are not normal Boo programs, they ''require'' that you would have at least one statement at the global namespace, which is what MonoRail will end up calling when your view is invoked. Assuming that you've already have a controller, and that you've setup your environment correctly, you can simply do this: Hello, World! Brail will take this script, compile it and send its output to your browser. The nice thing about it is that if you would change it to say: Hi, World! You will instantly get a the updated view, this is highly important to development scenario. This is a developer feature, meant to ease development. Using it on a production machine would cause recompiling of the scripts and cause an ''assembly leak'' until the application domain is restarted. On a developer machine, this should rarely be a problem, on a production machine, if frequent changes are made to the scripts, this can cause problems. You can also use parameters that the controller has put in the Property Bag or Flash, like this: Hi, ${User}! If you are wondering how does it work behind the scenes: the script is loaded and compiled. There is some magic there that sends anything not wrapped in <% %> directly to the user (which will also expand ${arg} expression to their values). The compiled code is cached, so you pay the compilation cost only once.
http://www.castleproject.org/monorail/documentation/trunk/viewengines/brail/gettingstarted.html
crawl-001
refinedweb
552
63.7
Computer Science Archive: Questions from April 01, 2007 - Anonymous asked1 answer - shwanky asked1 answer - Anonymous asked1 answer - Anonymous asked1. the 4 coefficients of a th... Show morex.øi5PART 1: Your task in Part 1 is to write a program that takes in: 1. the 4 coefficients of a third degree polynomial (ax3 + bx2 + cx + d ), 2. the range of the integral (starting and ending x values), 3. number of bins to be used and calculates the Riemann sum approximation to the integral.Sample Run Enter the coefficients of a 3rd degree polynomial >> 1 -2 1 -1 The polynomial you entered is: (1.00x^3)+(-2.00x^2)+(1.00x)+(-1.00) What is the range to take the integral? >> -1 4 How many bins would you like to use? >> 30 The integral of the polynomial (1.00x^3)+(-2.00x^2)+(1.00x)+(-1.00)in the range [-1.00,4.00] using 30 bins is found as 19.64.PART 2: The Riemann sum only gives an approximation to the integral. We could in fact calculate the actual value using the definition of the integral. For polynomials, the actual value of the integral is found by: 1. For each term raise the power by one, and divide the term with the raised power 2. Plug in (1) the value of the bounding x value on the right 3. Plug in (1) the value of the bounding x value on the left 4. Find the difference between (2) and (3)For instance, we can find the definite integral of x3 − 2x2 + x −1 in the range [−1,4] as: ... etc. Augment the program you wrote in Part 1 to take definite integrals as well. Your program must now calculate both the Riemann sum and the definite integral and tell the user the error made by the approximation. You will upload the augmented version of your program only. Try your program using different polynomials, ranges, and bins. Sample Run 2:? >> 30 The integral of the polynomial (3.20x^3)+(2.90x^2)+(5.30x)+(-12.50) in the range [-5.00,12.00] using 30 bins is found as 19611.76. The actual integral value is found as 17982.88 and the error made by the Riemann sum is 1628.88. Sample Run 3:? >> 18000 The integral of the polynomial (3.20x^3)+(2.90x^2)+(5.30x)+(-12.50) in the range [-5.00,12.00] using 18000 bins is found as 17986.16. The actual integral value is found as 17982.88 and the error made by the Riemann sum is 3.28.o›x.øi5Z°x.øi59Ñpmx.õx.øi5 ›ox.øi5ùøi5pm • Show less0 answers - Anonymous askedYour customer is tired of his employees who keep cominglate from coffee brakes because it takes the... Show more Your customer is tired of his employees who keep cominglate from coffee brakes because it takes them ages to prepare anddrink their coffee and to clean their equipmentafterwards.A company has several departments. Each department has asupervisor and at least one employee. Employ... Show more A company has several departments. Each department has asupervisor and at least one employee. Employees must be assigned toat least one, but possibly more departments. At least one employeeis assigned to a project, but an employee may be on vacation andnot assigned to any projects. The important data fields are thenames of the departments, projects, supervisors and employees, aswell as the supervisor and employee number and a unique projectnumber. 1 answer - IdentifyEntities - FindRelationships - Draw Rough ERD(EntityRelationship Diagram) - Fill inCardinality - Define PrimaryKeys - IdentifyAttributes - Draw Fully Attributed ERDEntity Relationship Diagram) - Cellinda askedWrite the definition of the readAndCount function. Thefunction should... Show morePlease enhance this program. Write the definition of the readAndCount function. Thefunction should read the input line, character by character,counting the number of words (a sequence of letters) and the numberof occurrences of each letter. The array to hold the number of occurrences of each letteris the parameter letterCount. Store the number of occurences of 'a'at index 0, 'b' at index 1, and so forth. Be sure to account forboth upper and lowercase letters. Note that the index can becomputed easily from the character using subtraction of ASCII codes(which are just the 'values' of characters in C++). To count words you need a way of determining when you havecompleted reading a sequence of letters. There are a few differentways to do this.Be sure your method of counting words counts the lastone.• Show less //********************************************************** // // WordLetterCount.cpp // // This program counts the number of words and thenumber // of occurrences of each letter in a line of input. // //********************************************************** #include <iostream> #include <cctype> using namespace std; void readAndCount (int &numWords, int letterCount[]); // Reads a line of input. Counts the words and the number // of occurrences of each letter. void outputLetterCounts (int letterCount[]); // Prints the number of occurrences of each letter that // appears in the input line. // ========================= // main function // ========================= int main() { int numWords; int letterCount[26]; // stores the frequency of eachletter cout << endl; cout << "Enter a line of text.." << endl<< endl; readAndCount (numWords, letterCount); cout << endl; cout << numWords << " words" <<endl; outputLetterCounts(letterCount); return 0; } // ========================= // Function Definitions // ========================= // -------------------------------- // ----- ENTER YOUR CODE HERE ----- // -------------------------------- // -------------------------------- // --------- END USER CODE -------- // -------------------------------- void outputLetterCounts(int letterCount[]) { for (int i = 0; i < 26; i++) { if (letterCount[i]> 0) { cout << letterCount[i] << " " << char('a' +i) << endl; } } }0 answers - Cellinda askedWrite a program that can be used to train the user to use lesssexist language by suggesting alternat... Show moreWrite a program that can be used to train the user to use lesssexist language by suggesting alternative versions of sentencesgiven by the user. The program will ask for a sentence, read thesentence into a string variable, and replace all occurences ofmasculine pronouns with gender-neutral pronouns. For example, itwill replace "he" with "she or he". Thus, the input sentenceSee an adviser, talk to him, and listen to him.should produce the following suggested changed version of thesentence:See an adviser, talk to her or him, and listen to her orhim.Be sure to preserve uppercase letters for the first word ofthe sentence. The pronoun "his" can be replaced by "her(s)"; yourprogram need not decide between "her" and "hers". Allow the user torepeat this for more sentences until the user says she or he isdone.This will be a long program that requires a good deal ofpatience. Your program should not replace the string "he" when itoccurs inside another word, such as "here". A word is any stringconsisting of the letters of the alphabet and delimited at each endby a blank, the end of the line, or any other character that is nota letter. Allow your sentences to be up to 100 characterslong.• Show less0 answers - Anonymous asked1 answer - Anonymous asked1 answer - Anonymous asked(Note: perform only three iteration and... Show more Solve sinx=1+x3 byusing the Newton Raphsonn method.(Note: perform only three iteration and accuracy up tofour places of decimal is required)• Show lessplzzzzzzzzz give me answer in detail2 answers - Cellinda asked#include "stri... Show morePlease debug this program so that it would run on acompiler.// File name checkbk.cpp #include "string" // for a stringclass #include <iostream> // for coutusing namespace std; ////////////// Define class checkBook ////////////// class checkBook { public: // MEMBER FUNCTIONS //--constructors checkBook();checkBook(string initialAcctID, doubleinitialBalance); // post: construct a checkBook object with client suppliedinitial state //--modifiers void check(int checkNumber, double amount); // post: displays the check number, check amount andincrements the number of checksvoid deposit(double amount); // post: displays the deposit amountvoid ATMWithdraw(double amount); // post: displays the ATM withdrawal amount and incrementsthe number of ATMSvoid applyMonthlyCharge(); // post: deduct the monthly bank fee based on localrules // while deducting thatcharge from the balance//--accessor double balance() const; // post: returns the current checkbook balanceprivate: // STATE string my_name; double my_balance; int my_checksWritten; int my_ATMCount; };checkBook::checkBook(string initialAcctID, doubleinitialBalance) { decimals(cout, 2); my_name = "?ID?"; my_balance = 0.0; my_ATMCount = 0; my_checksWritten = 0; }checkBook::checkBook(string initialAcctID, doubleinitialBalance) { decimals(cout, 2); my_acctID = initialAcctID; my_balance = initialBalance; my_ATMCount = 0; my_checksWritten = 0; } void checkBook::check(int checkNumber, double amount) { my_balance = my_balance - amount; my_checksWritten = my_checksWritten + 1; cout.width(7); cout << checkNumber; cout.width(10); cout << amount; cout.width(20); cout << my_balance << endl; }void checkBook::deposit(double amount) { my_balance = my_balance + amount; cout << "Deposit"; cout.width(20); cout << amount; cout.width(10); cout << my_balance << endl; }void checkBook::ATMWithdraw(double amount) { my_balance = my_balance - amount; my_ATMCount = my_ATMCount + 1; cout << "ATM "; cout.width(10); cout << amount; cout.width(20); cout << my_balance << endl; } void checkBook::applyMonthlyCharge() { double fee(0.0); fee = 5.00 + 0.50 * my_ATMCount + 0.25 *my_checksWritten; my_balance = my_balance - fee; cout << "Fee "; cout.width(10); cout << fee; cout.width(20); cout << my_balance << endl; }double checkBook::balance() const• Show less { return my_balance; }1 answer - khattak askedchar *(**b) (v... Show morex.øi5p align=justify>1: What types do the following variables have? int *(**a) [10]; char *(**b) (void); float *(**c(void)) [6]; short *(**d(void)) (int); long *(*(*(*e) (void)) [7]) (void); 2: Maintain a family tree and output family data in correct order. Details To solve this problem you have to: - - ?? Declare structure named Family that has following eight members: Structure Family member of type Description dob Structure Date Date of Birth name character array of size 20 Name father character array of size 20 Father’s name mother character array of size 20 Mother’s name next Structure Family pointer Pointer to next structure previous Structure Family pointer Pointer to previous structure p_to_father Structure Family pointer Pointer to father structure p_to_mother Structure Family pointer Pointer to mother structure Structure Date member of type day integer month integer year integer - - ?? Define a function (say get_personInfo) to take input of family members. Arguments no arguments Return type a pointer to a Family Structure. Within the function Define a pointer to Family type Structure (say temp) and allocate it memory by calling malloc() Take following input from user: Name of Person, Date of Birth, Father’s name, Mother’s name and store this information into temp and return temp. - - ?? Define a function (say related) to fill in pointers to mother or father relationship Arguments two pointers to Family Structure (say first person and second person) Return type true or false Within the function call set_relationship twice to test all possibilities of relationship. That is: return set_relationship(first person, second person) || set_relationship(second person, first person) set_relationship() Arguments two pointers to Family Structure (say first person and second person) Return type true or false Within the function if first person’s father is equal to second person’s name first person’s p_to_father = second person return true if first person’s mother is equal to second person’s name first person’s p_to_mother = second person return true otherwise return false - - ?? The main() functioõl>x.øi5 Declarations: name of type Description first Structure Family pointer Pointer to first person current Structure Family pointer Pointer to current person last Structure Family pointer Pointer to last person input char input character Y or N /* take input from user */ infinite loop printf "Do you want to enter details of a person (Y or N)? " scanf input if input is n break the loop current = get_personInfo() if first == NULL first = current last = current else last->next = current current->previous = last last = current /* check and set the person’s relationships */ Point current to the first loop until current->next is not NULL declare a parent count of type int local to this block point last to current->next loop until last is not NULL if related(current, last) if(++parent == 2) break the inner loop last = last->next current = current->next /* Output family data in correct order */ Iterate through the list and print person’s name, birth day, birth month, birth year and also parent’s information i.e.; name, birth day, birth month, birth year /* Free the memory allocated through malloc() */ Iterate through the list and call free(current) Sample Output Do you want to enter details of a person (Y or N)? y Enter person name: ABC Enter ABC’s date of birth (day month year): 2 2 70 Enter ABC’s father name: DEF Enter ABC’s mother name: GHI Do you want to enter details of a person (Y or N)? y Enter person name: JKL Enter JKL’s date of birth (day month year): 4 4 74 Enter JKL’s father name: MNO Enter JKL’s mother name: PQR Do you want to enter details of a person (Y or N)? y Enter person name: STU Enter STU’s date of birth (day month year): 6 6 96 Enter STU’s father name: ABC Enter STU’s mother name: JKL Do you want to enter details of a person (Y or N)? n ABC was born in 2/2/70, and has DEF and GHI as parents. JKL was born in 4/4/74, and has MNO and PQR as parents. STU was born in 6/6/96, and has ABC and JKL as parents. ABC’s Birth date is 2/2/70 and JKL’s birth date is 4/4/74.Ì>x.øi5ÿ øi5pm • Show less0 answers - Anonymous asked17.2)write a program that copies afile using the source and destination as arguments.the destination
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2007-april-01
CC-MAIN-2014-15
refinedweb
2,187
53.92
Apologies for a newbie question, but I am seeking advice on how to benchmark a pure function that returns an unlifted type. I've heard tell that `criterion` is good for benchmarking, and so I'm using that library (but have no particular allegiance to it, if something else is better). Specifically, I'm comparing a function over unlifted types with the same function written over lifted types, trying to observe how much we pay for the boxing/unboxing. To benchmark the lifted version, I just use criterion's whnf function. That seems to be working splendidly. Of course, whnf doesn't work over unlifted types, so I found its source code and inlined it. This compiles. But it doesn't work! No matter what I do, the unlifted version measures in the nanoseconds. I'm guessing that GHC "cleverly" is avoiding recomputation. How can I stop this? Here is my code: > main :: IO () > main = do > initializeTime > let lifted = whnf fastSumPrimes 100000 > > unlifted = Benchmarkable go > where > go n > | n <= 0 = return () > | otherwise = let x = fastSumPrimes# 100000# in go (n-1) > > benchmark lifted > benchmark unlifted I've tried increasing the argument in the unlifted case, to no avail. I've also tried using `case` instead of `let`. -ddump-simpl suggests that fastSumPrimes# is really being called, but I'm dubious. Can anyone offer advice? Thanks! Richard _______________________________________________ Haskell-Cafe mailing list To (un)subscribe, modify options or view archives go to: Only members subscribed via the mailman list are allowed to post.
http://haskell.1045720.n5.nabble.com/benchmarking-a-function-that-returns-an-unlifted-type-td5853971.html
CC-MAIN-2017-13
refinedweb
251
64
Subject: Re: [linux-audio-dev] anyone interested to develop a new apps ? From: Mario Lang (mlang_AT_delysid.org) Date: Sun Oct 24 2004 - 22:54:55 EEST dubphil_AT_free.fr writes: > I want to setup a sound system with linux. For this, I need an app that > could split an audio file in four tracks in order to add them separately > some effects. > > The ideal application should not be too complex : > > it should be compatible with Jack and could just get a stereo channel > for input and provides 4 stereo channels. The 4 stereo channels would be > the result off a crossover spliting by frequency ranges of the input > stereo channel. > we could give a default preset like this : > > 1st stereo channel : low > 2nd stereo channel : low-mid > 3rd stereo channel : high-mid > 4th stereo channel : high > > of course thoose ranges should also be set manually. > > each channel could have the gain controlled and could have assigned 4 > effects with LADSPA plug-ins. > > each slider or knob should be midi controlled (I know that Jack Rack > already does this). OK, yet another solution, now with my absolute favourite "modular". Since Pd is mentioned on lists so often, I figured I should do some counter-PR for SuperCollider :-) The program below for SuperCoolider will do the splitting for you, channels SuperCollider:out_1 through out_8 will have the 4 stereo channels, and since we are in a modern age, you can control the split points and gain via OSC :-) (MIDI would be possible to do from within SC3 too, its very simple) The SC code: s.waitForBoot { n=SynthDef(\splitter, {|low=300, mid=2000, high=8000, lgain=1.0, lmgain=1.0, mhgain=1.0, hgain=1.0| var signal, l, lm, lmc, mh, mhc, h; signal = AudioIn.ar([1,2]); l = LPF.ar(signal, low, lgain); lmc = low+(mid-low/2); lm = BPF.ar(signal, lmc, (mid-low) / lmc, lmgain); mhc = mid+(high-mid/2); mh = BPF.ar(signal, mhc, (high-mid) / mhc, mhgain); h = HPF.ar(signal, high, hgain); Out.ar(0, [l, lm, mh, h].flat) }).play(s); OSCresponder(nil, '/split', {|time, responder, msg| n.setn(\low, msg[1..7]) }).add; } And here is some little piece of C code using liblo (hey steve, this stuff rocks!) to control the 7 parameters via OSC from command-line (you could as well control them in real-time from within SC itself) #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "lo/lo.h" int main(int argc, char *argv[]) { lo_address t = lo_address_new(NULL, "57120"); if (lo_send(t, "/split", "fffffff", atof(argv[1]), atof(argv[2]), atof(argv[3]), atof(argv[4]), atof(argv[5]), atof(argv[6]), atof(argv[7])) == -1) { printf("OSC error %d: %s\n", lo_address_errno(t), lo_address_errstr(t)); } return 0; } (gcc -o split_client split_client.c -llo) Compile this, and call it like this: ./split_client 120 1200 12000 0.5 1.0 2.0 4.0 > Does this kind of apps should take a long time to be developped ? Took me about 20 minutes :-) Whats left is you need to connect the ports to something like jack-rack, this could also be automated from SC be telling the server which jack ports to connect to. Alternatively, if the effects you need can be implemented with SC3 Unit Generators, you might even be able to do it all inside SC3. -- CYa, Mario This archive was generated by hypermail 2b28 : Sun Oct 24 2004 - 23:00:26 EEST
http://lalists.stanford.edu/lad/2004/10/0109.html
crawl-002
refinedweb
577
73.37
. z! Python’s Innards: Hello, ceval.c! 2010/09/02 § 5 Comments The “Python’s Innards” series owes its existence, at least in part, to hearing one of the Python-Fu masters in my previous workplace say something about a switch statement so large that it was needed to break it up just so some compilers won’t choke on it. I remember thinking then: “Choke the compiler with a switch? Hrmf, let me see that code.” Turns out that this switch can be found in ./Python/ceval.c: PyEval_EvalFrameEx and it switches over the current opcode, invoking its implementation. If I had to summarize all of CPython into one line, I’d probably choose that switch (actually I’d refuse, but humour me by assuming I was at gunpoint or something). This choice is rather subjective, as arguably there are more complex/interesting bits in Python’s object system (explored here and there) or parser/compiler related code. But I can’t help seeing that line, and its surrounding function and file, as the ‘do-work’ heart of CPython. The reason I didn’t start the series from this heart is that I thought it would be too hard (mostly for the author…). Thanks to what we (well, at least I) learned in the previous posts, I think we can now understand it quite well. I’ll try to link backwards as necessary throughout the article, but if you haven’t followed the series so far, you’d probably do much better if you went back and read some of the previous articles before tackling this one. Also, for brevity’s sake in this post, I won’t qualify the file ./Python/ceval.c and the function PyEval_EvalFrameEx in it. Finally, remember that usually in the series when I quote code, I may note that I edited it, and in that case I often prefer clarity and brevity over accuracy; this is true for this post as well, only much more so, excerpts here might bear only slight resemblance to the real code. So, where were we… Ah, yes, monstrous switch statement. Well, as I said, this switch can be found in the rather lengthy file ceval.c, in the rather lengthy function PyEval_EvalFrameEx, which takes more than half the file’s lines (it’s roughly 2,250 lines, the file is about 4,400). PyEval_EvalFrameEx implements CPython’s evaluation loop, which is to say that it’s a function that takes a frame object and iterates over each of the opcodes in its associated code object, evaluating (interpreting, executing) each opcode within the context of the given frame (this context is chiefly the associated namespaces and interpreter/thread states). There’s more to ceval.c than PyEval_EvalFrameEx, and we may discuss some of the other bits later in this post (or perhaps a follow-up post), but PyEval_EvalFrameEx is obviously the most important part of it. Having described the evaluation loop in the previous paragraph, let’s see what it looks like in C (edited): PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { /* variable declaration and initialization stuff */ for (;;) { /* do periodic housekeeping once in a few opcodes */ opcode = NEXTOP(); if (HAS_ARG(opcode)) oparg = NEXTARG(); switch (opcode) { case NOP: goto fast_next_opcode; /* lots of more complex opcode implementations */ default: /* become rather unhappy */ } /* handle exceptions or runtime errors, if any */ } /* we are finished, pop the frame stack */ tstate->frame = f->f_back; return retval; } As you can see, iteration over opcodes is infinite (forever: fetch next opcode, do stuff), breaking out of the loop must be done explicitly. CPython (reasonably) assumes that evaluated bytecode is correct in the sense that it terminates itself by raising an exception, returning a value, etc. Indeed, if you were to synthesize a code object without a RETURN_VALUE at its end and execute it (exercise to reader: how?1), you’re likely to execute rubbish, reach the default handler (raises a SystemError) or maybe even segfault the interpreter (I didn’t check this thoroughly, but it looks plausible). The evaluation loop may look fairly simple so far, but I kept back an important piece: I snipped about 1,450 lines of opcode implementations from within that big switch, all of them presumably more complex than a NOP. In order for you to be able to get a feel for what more serious opcode implementations look like, here’s the (edited) implementation of three more opcodes, illustrating a few more principles: case BINARY_SUBTRACT: w = *--stack_pointer; /* value stack POP */ v = stack_pointer[-1]; x = PyNumber_Subtract(v, w); stack_pointer[-1] = x; /* value stack SET_TOP */ if (x != NULL) continue; break; case LOAD_CONST: x = PyTuple_GetItem(f->f_code->co_consts, oparg); *stack_pointer++ = x; /* value stack PUSH */ goto fast_next_opcode; case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); continue; We see several things. First, we see a typical value manipulation opcode, BINARY_SUBTRACT. This opcode (and many others) works with values on the value stack as well as with a few temporary variables, using CPython’s C-API abstract object layer (in our case, a function from the number-like object abstraction) to replace the two top values on the value stack with the single value resulting from subtraction. As you can see, a small set of temporary variables, such as v, w and x are used (and reused, and reused…) as the registers of the CPython VM. The variable stack_pointer represents the current bottom of the stack (the next free pointer in the stack). This variable is initialized at the beginning of the function like so: stack_pointer = f->f_stacktop;. In essence, together with the room reserved in the frame object for that purpose, the value stack is this pointer. To make things simpler and more readable, the real (unedited by me) code of ceval.c defines several value stack manipulation/observation macros, like PUSH, TOP or EMPTY. They do what you imagine from their names. Next, we see a very simple opcode that loads values from somewhere into the valuestack. I chose to quote LOAD_CONST because it’s very brief and simple, although it’s not really a namespace related opcode. “Real” namespace opcodes load values into the value stack from a namespace and store values from the value stack into a namespace; LOAD_CONST loads constants, but doesn’t fetch them from a namespace and has no STORE_CONST counterpart (we explored all this at length in the article about namespaces). The final opcode I chose to show is actually the single implementation of several different control-flow related opcodes (SETUP_LOOP, SETUP_EXCEPT and SETUP_FINALLY), which offload all details of their implementation to the block stack manipulation function PyFrame_BlockSetup; we discussed the block stack in our discussion of interpreter stacks. Something we can observe looking at these implementations is that different opcodes exit the switch statement differently. Some simply break, and let the code after the switch resume. Some use continue to start the for loop from the beginning. Some goto various labels in the function. Each exit has different semantic meaning. If you break out of the switch (the ‘normal’ route), various checks will be made to see if some special behaviour should be performed – maybe a code block has ended, maybe an exception was raised, maybe we’re ready to return a value. Continuing the loop or going to a label lets certain opcodes take various shortcuts; no use checking for an exception after a NOP or a LOAD_CONST, for instance. That’s pretty much it. I can’t really say we’re done (not at all), but this is pretty much the gist of PyEval_EvalFrameEx. Simple, eh? Well, yeah, simple, but I lied a bit with the editing to make it simpler. For example, if you look at the code itself, you will see that none of the case expressions for the big switch are really there. The code for the NOP opcode is actually (remember this series is about Python 3.x unless noted otherwise, so this snippet is from Python 3.1.2): TARGET(NOP) FAST_DISPATCH(); TARGET? FAST_DISPATCH? What are these? Let me explain. Things may become clearer if we’d look for a moment at the implementation of the NOP opcode in ceval.c of Python 2.x. Over there the code for NOP looks more like the samples I’ve shown you so far, and it actually seems to me that the code of ceval.c gets simpler and simpler as we look backwards at older revisions of it. The reason is that although I think PyEval_EvalFrameEx was originally written as a really exceptionally straightforward piece of code, over the years some necessary complexity crept into it as various optimizations and improvements were implemented (I’ll collectively call them ‘additions’ from now on, for lack of a better term). To further complicate matters, many of these additions are compiled conditionally with preprocessor directives, so several things are implemented in more than one way in the same source file. In the larger code samples I quoted above, I liberally expanded some preprocessor directives using their least complex expansion. However, depending on compilation flags, these and other preprocessor directives might expand to something else, possibly a more complicated something. I can understand trading simplicity to optimize a tight loop which is used very often, and the evaluation loop is probably one of the more used loops in CPython (and probably as tight as its contributors could make it). So while this is all very warranted, it doesn’t help the readability of the code. Anyway, I’d like to enumerate these additions here explicitly (some in more depth than others); this should aid future discussion of ceval.c, as well as prevent me from feeling like I’m hiding too many important things with my free spirited editing of quoted code. Fortunately, most if not all these additions are very well commented -actually, some of the explanations below will be just summaries or even taken verbatim from these comments, as I believe that they’re accurate (eek!). So, as you read PyEval_EvalFrameEx (and indeed ceval.c in general), you’re likely to run into any of these: “Threaded Code” (Computed-GOTOs) Let’s start with the addition that gave us TARGET, FAST_DISPATCH and a few other macros. The evaluation loop uses a “switch” statement, which decent compilers optimize as a single indirect branch instruction with a lookup table of addresses. Alas, since we’re switching over rapidly changing opcodes (it’s uncommon to have the same opcode repeat), this would have an adverse effect on the success rate of CPU branch prediction. Fortunately gcc supports the use of C-goto labels as values, which you can generally pass around and place in an array (restrictions apply!). Using an array of adresses in memory obtained from labels, as you can see in ./Python/opcode_targets.h, we create an explicit jump table and place an explicit indirect jump instruction at the end of each opcode. This improves the success rate of CPU prediction and can yield as much as 20% boost in performance. Thus, for example, the NOP opcode is implemented in the code like so: TARGET(NOP) FAST_DISPATCH(); In the simpler scenario, this would expand to a plain case statement and a goto, like so: case NOP: goto fast_next_opcode; But when threaded code is in use, that snippet would expand to (I highlighted the lines where we actually move on to the next opcode, using the dispatch table of label-values): TARGET_NOP: opcode = NOP; if (HAS_ARG(NOP)) oparg = NEXTARG(); case NOP: { if (!_Py_TracingPossible) { f->f_lasti = INSTR_OFFSET(); goto *opcode_targets[*next_instr++]; } goto fast_next_opcode; } Same behaviour, somewhat more complicated implementation, up to 20% faster Python. Nifty. Opcode Prediction Some opcodes tend to come in pairs. For example, COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE, themselves often followed by a POP_TOP. What’s more, there are situations where you can determine that a particular next-opcode can be run immediately after the execution of the current opcode, without going through the ‘outer’ (and expensive) parts of the evaluation loop. PREDICT (and a few others) are a set of macros that explicitly peek at the next opcode and jump to it if possible, shortcutting most of the loop in this fashion (i.e., if (*next_instr == op) goto PRED_##op). Note that there is no relation to real hardware here, these are simply hardcoded conditional jumps, not an exploitation of some mechanism in the underlying CPU (in particular, it has nothing to do with “Threaded Code” described above). Low Level Tracing An addition primarily geared towards those developing CPython (or suffering from a horrible, horrible bug). Low Level Tracing is controlled by the LLTRACE preprocessor name, which is enabled by default on debug builds of CPython (see --with-pydebug). As explained in ./Misc/SpecialBuilds.txt: when this feature is compiled-in, PyEval_EvalFrameEx checks the frame’s global namespace for the variable __lltrace__. If such a variable is found, mounds of information about what the interpreter is doing are sprayed to stdout, such as every opcode and opcode argument and values pushed onto and popped off the value stack. Not useful very often, but very useful when needed. This is the what the low level trace output looks like (slightly edited): >>> def f(): ... global a ... return a - 5 ... >>> dis(f) 3 0 LOAD_GLOBAL 0 (a) 3 LOAD_CONST 1 (5) 6 BINARY_SUBTRACT 7 RETURN_VALUE >>> exec(f.__code__, {'__lltrace__': 'foo', 'a': 10}) 0: 116, 0 push 10 3: 100, 1 push 5 6: 24 pop 5 7: 83 pop 5 # trace of the end of exec() removed >>> As you can guess, you’re seeing a real-time disassembly of what’s going through the VM as well as stack operations. For example, the first line says: line 0, do opcode 116 (LOAD_GLOBAL) with the operand 0 (expands to the global variable a), and so on, and so forth. This is a bit like (well, little more than) adding a bunch of printf calls to the heart of VM. Advanced Profiling Under this heading I’d like to briefly discuss several profiling related additions. The first relies on the fact that some processors (notably Pentium descendants and at least some PowerPCs) have built-in wall time measurement capabilities which are cheap and precise (correct me if I’m wrong). As an aid in the development of a high-performance CPython implementation, Python 2.4’s ceval.c was instrumented with the ability to collect per-opcode profiling statistics using these counters. This instrumentation is controlled by the somewhat misnamed --with-tsc configuration flag (TSC is an Intel Pentium specific name, and this feature is more general than that). Calling sys.settscdump(True) on an instrumented interpreter will cause the function ./Python/ceval.c: dump_tsc to print these statistics every time the evaluation loop loops. The second advanced profiling feature is Dynamic Execution Profiling. This is only available if Python was built with the DYNAMIC_EXECUTION_PROFILE preprocessor name. As ./Tools/scripts/analyze_dxp.py says, [this] will tell you which opcodes have been executed most frequently in the current process, and, if Python was also built with -DDXPAIRS, will tell you which instruction _pairs_ were executed most frequently, which may help in choosing new instructions. One last thing to add here is that enabling Dynamic Execution Profiling implicitly disables the “Threaded Code” addition. The third and last addition in this category is function call profiling, controlled by the preprocessor name CALL_PROFILE. Quoting ./Misc/SpecialBuilds.txt again: When this name is defined, the ceval mainloop and helper functions count the number of function calls made. It keeps detailed statistics about what kind of object was called and whether the call hit any of the special fast paths in the code. Extra Safety Valves Two preprocessor names, USE_STACKCHECK and CHECKEXC include extra assertions. Testing an interpreter with these enabled may catch a subtle bug or regression, but they are usually disabled as they’re too expensive. These are the additions I found, grepping ceval.c for #ifdef. I think we’ll call it a day here, although we’re by no means finished. For example, I’d like to devote a separate post to exceptions, which is where we can discuss the tail of the evaluation loop (everything after the big switch and before the end of the big for), which we merely skimmed today. I’d also like to devote a whole post to locking and synchronization (including the GIL), which we touched upon before but never covered properly. Last but really not least, there’s about 2,000 other lines in ceval.c which we didn’t cover today; none of them are as important as PyEval_EvalFrameEx, but we need to talk at least about some of them. All these things taken into account, I think we can say that today we finally conquered the evaluation loop. This isn’t the end of the series, far from it, but I do see it as a milestone. “Hooray”, I believe the saying goes. I hope you’re enjoying the show, thanks for the supportive comments (they keep me going), and I’ll see you in the next post. I would like to thank Nick Coghlan for reviewing this article; any mistakes that slipped through are my own.
http://tech.blog.aknin.name/tag/python/
CC-MAIN-2015-48
refinedweb
2,870
57.91
I create videos and blog posts related to test automation and quality assurance. In this post, we'll take a look at what tools/technologies do we need for writing API tests using JavaScript and then we'll also write our first API test. So let's get started... First off, we'll need to get the following dependencies installed to set up our base framework - Note: the above libraries/frameworks are optional to use, you can replace any one or all of them to meet your desired goals. You can watch the installation video below to see how to install all these packages and get your project setup: Once you have your project setup, we will begin to write our API test in the users.js file (created as part of the installation video above). import supertest from 'supertest'; const request = supertest(''); import { expect } from 'chai'; // watch the installation video to create your token const TOKEN = {your_token_here} describe('Users', () => { it('GET /users', (done) => { // make a GET call to the users api request.get(`users?access-token=${TOKEN}`).end((err, res) => { // assertion to ensure data is not empty expect(res.body.data).to.not.be.empty; // done callback to handle async calls done(); }); }); }); Now, its time to run your test, you can do that by running the command or doingcommand or doing mocha which will also run the samewhich will also run the same npm test command if you followed the installation video.command if you followed the installation video. mocha There you go, we just created our first API test and it ran successfully 🙌. Check out this video to see a detailed explanation on how to write your first API test: You can also clone the GitHub repo to access this code To learn more about API testing, check out my free tutorial series here - I hope this post helped you out, let me know in the comments below! Happy testing! 😄 Also published at Create your free account to unlock your custom reading experience.
https://hackernoon.com/if-you-want-to-write-the-1st-api-test-in-javascript-you-can-be-proud-of-read-these-tips-hfg3wck
CC-MAIN-2021-43
refinedweb
335
64.14
New developers have, at one time or another, heard the practice of building software applications likened to building something out of LEGO bricks (I’ve even written about LEGOs and software in the past). A few days ago, it occurred to me that I could sum up my thoughts on this topic in three words, which I might hope would be memorable enough to “stick” in developers’ minds: New is Glue Any time you use the new keyword, you are gluing your code to a particular implementation. You are permanently (short of editing, recompiling, and redeploying) hard-coding your application to work with a particular class’s implementation. That’s huge. That’s like your code’s getting married, forever and ever, until redeployment do us part. Once you’ve said the words (new) and exchanged some vows (type metadata) and exited the church (deployed), changing your code’s chosen partner becomes a very expensive endeavor. This is a big decision for you and your application. You need to be very sure that this is the one and only implementation your code will ever need to work with, or else think about calling the whole thing off. The marriage metaphor is taking things a bit far, I know, but let me add one more bit before we leave it behind us. It’s quite likely that your code is going to need behavior from more than one other class. In fact, it’s quite common that you’ll need to work with other classes in virtually every class within your application. If you go the new route, that’s a lot of overlapping marriages that all need to stay happy for your application to work effectively. But what if the behavior or service you need is only found in one place? Maybe it’s not the perfect, now-and-forever class, but it’s the one that has what you need right now? What am I suggesting, that one forego leveraging any other classes, and just do everything yourself? Not at all, but let’s go with another metaphor now. Favor Contractors over Employees Your application requires certain services to do its job. Think of your application like a small business. There are things your application does, and things it needs to do its job. A small business might need office space, and beyond that, certain utilities like electricity, phone service, internet service, shipping, etc. In a business, relationships you have with service providers and contractors are relatively easy to change, while relationships you have with employees can be somewhat more difficult (for purposes of this analogy, pretend we’re talking about a country where firing people is very difficult/expensive). Now think about which approach to running a small business makes more sense. In the first scenario, your business’s needs are each met by a full-time resource. You have Bob, the electrician, who ensures your electricity works, Joan, the telecom expert, who ensures your phone service is connected, and Joe, the truck driver, who takes care of delivering everything you ever need to send. You also need an office to hold all of these people, which of course you leased with a 5 year lease that’s every expensive to get out of. In the second scenario, your business’s needs are all met by service providers or contractors. You use standard utility companies for electricity, phone, internet, and you can switch from one to another with only a small amount of pain if one fails you. You ship with FedEx, USPS, UPS, etc. based on whichever one fits your needs of the day. Your office space is just big enough for you, and since you’re still growing and aren’t sure how your needs will change, you’re paying month-to-month. Which of these two scenarios provides the greater degree of freedom for the business to adapt to future needs? Which one is locked into a particular implementation and will be hard-pressed to change when needed? Decoupling Services from Providers. Let’s say your code needs send an email, with default code that looks like this: using (var client = new SmtpClient()) using (var message = new MailMessage(fromEmail, toEmail)) { message.Subject = subject; message.Body = bodyHtml; message.IsBodyHtml = true; client.Send(message); } public interface IEmailClient { void SendHtmlEmail(string fromEmail, string toEmail, string subject, string bodyHtml); } Now the code that used to contain the first block of code can be rewritten to simply use the interface: public class SomeService { private readonly IEmailClient _emailClient; public SomeService(IEmailClient emailClient) { } public void DoStuff(User user) { string subject = "Test Subject"; string bodyHtml = GetBody(user); user.EmailAddress, subject, bodyHtml); } } Edited: Please assume that DoStuff() does some useful value-added work, and that sending an email to the user is just something it does as a side effect, perhaps only when it’s successful, and not that it’s the main intent of the method, if that helps you think about the value of removing the dependency on SmtpClient. How many new keywords are in this class, now? Run a search in Visual Studio to find how many instances of new you’re using in your solution, and where. Use ctrl-shift-F to find in files, search for “new”, Entire Solution, Match case, Match whole word, and Look at these file types: *.cs. Have a look at the total numbers, the numbers of files, etc. In one very small ASP.NET MVC application I’m working on now, this search yields 280 matching lines in 25 files out of 47 files searched. Four of the files and 28 of the matches are in my tests project. The lion’s share of the rest of the matches are from SqlHelper.cs. My controllers have a total of 7 matching lines, and all of these relate to creating model/viewmodel types, not services. When is it Acceptable to use New? Using new isn’t wrong, it’s a design decision. Like all design decisions, it should be an informed decision, not a de facto one. Use it when you don’t expect you’ll need flexibility in the future. Use it when it won’t adversely affect the usability of your class by its clients. Consider the transitivity of the dependencies you take on within your class – that is, how the things you depend on in turn become dependencies for classes that use your classes. Consider too how your design decisions and considerations today may change in the future. One common example of this is applications that hard-code dependencies on local system resources like the file system, local memory (session, cache, global collections), and local services like email. When the application needs to scale out to multiple front-end machines, problems ensue. Loosely coupling these resources together would make implementing a webfarm- or cloud-optimized version of these services trivial, but thousands of new statements gluing implementations together can take a long time to fix. One last thing to think about, if you actually do search your code for new, is how many duplicate lines you find. Remember the Don’t Repeat Yourself (DRY) and Single Responsibility (SRP) principles. If you’re instantiating the same class in the same way in more than one place in your code (e.g. 10 places where you new up a new SqlConnection), that’s a DRY violation. If you have ten different classes that all do some kind of work, AND need to know how to create a SqlConnection, that’s an SRP violation. Knowledge of how to talk to the database should be in only one location, the responsibility of a single class. The same is true for any other resource that you find you’re commonly instantiating in many different classes. The exceptions here would be low-level intrinsics like strings, datetimes, and things like exceptions that generally are created only in exceptional cases. Moving Forward Learn to look for new in your code and in code reviews. Question whether it’s appropriate when you see it. Work on pushing the responsibility of choosing which classes your code will work with into as few classes as possible, and see if your code doesn’t start to become more loosely coupled and easier to maintain as a result.
http://ardalis.com/new-is-glue
CC-MAIN-2014-15
refinedweb
1,384
60.35
App-DualLivedList - Perl extension to determine if a module is Dual-Lived. dual-lived <module_name> This script provides an easy way to determine if a module is Dual-Lived or is not Dual-Lived. dual-lived CGI - returns the module name, author, current version on CPAN, installed version number, status as dual-lived or core or not. dual-lived /^CGI/ - returns all the modules on CPAN that start with CGI. dual-lived /CGI/ - returns all the modules on CPAN that have CGI somewhere in the namespace. dual-lived /word/ - searchs the entire CPAN for "word" or parts of that word. Note:: "entire" means just that. For example: dual-lived /hog/ could return hog, ho, hog-tied, etc. dual-lived /^*/ - returns all of the modules on CPAN. You can use one option at a time, or you may bundle them. For example: dual-lived CPAN -f dual-lived CPAN -df dual-lived CPAN -dfu To check the module list and author list: dual-lived // -al -A | --alpha = alphabetical list of authors by CPAN_ID -a | --authors = list of authors by module appearance -d | --distributions = gives the distribution name from which the dual-lived modules derives -f | --filestats = gives file size, line length, and word count -l | --list = DualLivedList of modules -u | --update = installs or upgrades a module -v | --version = App::DualLivedList version number Version 0.01 Kevin W. Henwood <Khen1950fx@yahoo.com> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.5.0 or, at your option, any later version of Perl 5 you may have available.
http://search.cpan.org/~ski/App-DualLivedList-0.02/lib/App/DualLivedList.pm
CC-MAIN-2014-52
refinedweb
270
62.17
Deploy¶ CherryPy stands on its own, but as an application server, it is often located in shared or complex environments. For this reason, it is not uncommon to run CherryPy behind a reverse proxy or use other servers to host the application. Note CherryPy’s server has proven reliable and fast enough for years now. If the volume of traffic you receive is average, it will do well enough on its own. Nonetheless, it is common to delegate the serving of static content to more capable servers such as nginx or CDN. Contents Run as a daemon¶ CherryPy allows you to easily decouple the current process from the parent environment, using the traditional double-fork: from cherrypy.process.plugins import Daemonizer d = Daemonizer(cherrypy.engine) d.subscribe() Note This engine plugin is only available on Unix and similar systems which provide fork(). If a startup error occurs in the forked children, the return code from the parent process will still be 0. Errors in the initial daemonizing process still return proper exit codes, but errors after the fork won’t. Therefore, if you use this plugin to daemonize, don’t use the return code as an accurate indicator of whether the process fully started. In fact, that return code only indicates if the process successfully finished the first fork. The plugin takes optional arguments to redirect standard streams: stdin, stdout, and stderr. By default, these are all redirected to /dev/null, but you’re free to send them to log files or elsewhere. Warning You should be careful to not start any threads before this plugin runs. The plugin will warn if you do so, because “…the effects of calling functions that require certain resources between the call to fork() and the call to an exec function are undefined”. (ref). It is for this reason that the Server plugin runs at priority 75 (it starts worker threads), which is later than the default priority of 65 for the Daemonizer. Run as a different user¶ Use this engine plugin to start your CherryPy site as root (for example, to listen on a privileged port like 80) and then reduce privileges to something more restricted. This priority of this plugin’s “start” listener is slightly higher than the priority for server.start in order to facilitate the most common use: starting on a low port (which requires root) and then dropping to another user. DropPrivileges(cherrypy.engine, uid=1000, gid=1000).subscribe() PID files¶ The PIDFile engine plugin is pretty straightforward: it writes the process id to a file on start, and deletes the file on exit. You must provide a ‘pidfile’ argument, preferably an absolute path: PIDFile(cherrypy.engine, '/var/run/myapp.pid').subscribe() Systemd socket activation¶ Socket Activation is a systemd feature that allows to setup a system so that the systemd will sit on a port and start services ‘on demand’ (a little bit like inetd and xinetd used to do). CherryPy has built-in socket activation support, if run from a systemd service file it will detect the LISTEN_PID environment variable to know that it should consider fd 3 to be the passed socket. To read more about socket activation: Control via Supervisord¶ Supervisord is a powerful process control and management tool that can perform a lot of tasks around process monitoring. Below is a simple supervisor configuration for your CherryPy application. [unix_http_server] file=/tmp/supervisor.sock [supervisord] logfile=/tmp) [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock [program:myapp] command=python server.py environment=PYTHONPATH=. directory=. This could control your server via the server.py module as the application entry point. import cherrypy class Root(object): @cherrypy.expose def index(self): return "Hello World!" cherrypy.config.update({'server.socket_port': 8090, 'engine.autoreload.on': False, 'log.access_file': './access.log', 'log.error_file': './error.log'}) cherrypy.quickstart(Root()) To take the configuration (assuming it was saved in a file called supervisor.conf) into account: $ supervisord -c supervisord.conf $ supervisorctl update Now, you can point your browser at and it will display Hello World!. To stop supervisor, type: $ supervisorctl shutdown This will obviously shutdown your application. SSL support¶ Note You may want to test your server for SSL using the services from Qualys, Inc. CherryPy can encrypt connections using SSL to create an https connection. This keeps your web traffic secure. Here’s how. - Generate a private key. We’ll use openssl and follow the OpenSSL Keys HOWTO.: $ openssl genrsa -out privkey.pem 2048 You can create either a key that requires a password to use, or one without a password. Protecting your private key with a password is much more secure, but requires that you enter the password every time you use the key. For example, you may have to enter the password when you start or restart your CherryPy server. This may or may not be feasible, depending on your setup. If you want to require a password, add one of the -aes128, -aes192 or -aes256 switches to the command above. You should not use any of the DES, 3DES, or SEED algorithms to protect your password, as they are insecure. SSL Labs recommends using 2048-bit RSA keys for security (see references section at the end). - Generate a certificate. We’ll use openssl and follow the OpenSSL Certificates HOWTO. Let’s start off with a self-signed certificate for testing: $ openssl req -new -x509 -days 365 -key privkey.pem -out cert.pem openssl will then ask you a series of questions. You can enter whatever values are applicable, or leave most fields blank. The one field you must fill in is the ‘Common Name’: enter the hostname you will use to access your site. If you are just creating a certificate to test on your own machine and you access the server by typing ‘localhost’ into your browser, enter the Common Name ‘localhost’. Decide whether you want to use python’s built-in SSL library, or the pyOpenSSL library. CherryPy supports either. - Built-in. To use python’s built-in SSL, add the following line to your CherryPy config: cherrypy.server.ssl_module = 'builtin' - pyOpenSSL. Because python did not have a built-in SSL library when CherryPy was first created, the default setting is to use pyOpenSSL. To use it you’ll need to install it (we could recommend you install cython first): $ pip install cython, pyOpenSSL Add the following lines in your CherryPy config to point to your certificate files: cherrypy.server.ssl_certificate = "cert.pem" cherrypy.server.ssl_private_key = "privkey.pem" - If you have a certificate chain at hand, you can also specify it: cherrypy.server.ssl_certificate_chain = "certchain.perm" - Start your CherryPy server normally. Note that if you are debugging locally and/or using a self-signed certificate, your browser may show you security warnings. WSGI servers¶ Embedding into another WSGI framework¶ Though CherryPy comes with a very reliable and fast enough HTTP server, you may wish to integrate your CherryPy application within a different framework. To do so, we will benefit from the WSGI interface defined in PEP 333 and PEP 3333. Note that you should follow some basic rules when embedding CherryPy in a third-party WSGI server: If you rely on the “main” channel to be published on, as it would happen within the CherryPy’s mainloop, you should find a way to publish to it within the other framework’s mainloop. Start the CherryPy’s engine. This will publish to the “start” channel of the bus. cherrypy.engine.start() Stop the CherryPy’s engine when you terminate. This will publish to the “stop” channel of the bus. cherrypy.engine.stop() Do not call cherrypy.engine.block(). Disable the built-in HTTP server since it will not be used. cherrypy.server.unsubscribe() Disable autoreload. Usually other frameworks won’t react well to it, or sometimes, provide the same feature. cherrypy.config.update({'engine.autoreload.on': False}) Disable CherryPy signals handling. This may not be needed, it depends on how the other framework handles them. cherrypy.engine.signals.subscribe() Use the "embedded"environment configuration scheme. cherrypy.config.update({'environment': 'embedded'}) Essentially this will disable the following: - Stdout logging - Autoreloader - Configuration checker - Headers logging on error - Tracebacks in error - Mismatched params error during dispatching - Signals (SIGHUP, SIGTERM) Tornado¶ You can use tornado HTTP server as follow: import cherrypy class Root(object): @cherrypy.expose def index(self): return "Hello World!" if __name__ == '__main__': import tornado import tornado.httpserver import tornado.wsgi # our WSGI application wsgiapp = cherrypy.tree.mount(Root()) # Disable the autoreload which won't play well cherrypy.config.update({'engine.autoreload.on': False}) # let's not start the CherryPy HTTP server cherrypy.server.unsubscribe() # use CherryPy's signal handling cherrypy.engine.signals.subscribe() # Prevent CherryPy logs to be propagated # to the Tornado logger cherrypy.log.error_log.propagate = False # Run the engine but don't block on it cherrypy.engine.start() # Run thr tornado stack container = tornado.wsgi.WSGIContainer(wsgiapp) http_server = tornado.httpserver.HTTPServer(container) http_server.listen(8080) # Publish to the CherryPy engine as if # we were using its mainloop tornado.ioloop.PeriodicCallback(lambda: cherrypy.engine.publish('main'), 100).start() tornado.ioloop.IOLoop.instance().start() Twisted¶ You can use Twisted HTTP server as follow: import cherrypy from twisted.web.wsgi import WSGIResource from twisted.internet import reactor from twisted.internet import task # Our CherryPy application class Root(object): @cherrypy.expose def index(self): return "hello world" # Create our WSGI app from the CherryPy application wsgiapp = cherrypy.tree.mount(Root()) # Configure the CherryPy's app server # Disable the autoreload which won't play well cherrypy.config.update({'engine.autoreload.on': False}) # We will be using Twisted HTTP server so let's # disable the CherryPy's HTTP server entirely cherrypy.server.unsubscribe() # If you'd rather use CherryPy's signal handler # Uncomment the next line. I don't know how well this # will play with Twisted however #cherrypy.engine.signals.subscribe() # Publish periodically onto the 'main' channel as the bus mainloop would do task.LoopingCall(lambda: cherrypy.engine.publish('main')).start(0.1) # Tie our app to Twisted reactor.addSystemEventTrigger('after', 'startup', cherrypy.engine.start) reactor.addSystemEventTrigger('before', 'shutdown', cherrypy.engine.exit) resource = WSGIResource(reactor, reactor.getThreadPool(), wsgiapp) Notice how we attach the bus methods to the Twisted’s own lifecycle. Save that code into a module named cptw.py and run it as follows: $ twistd -n web --port 8080 --wsgi cptw.wsgiapp uwsgi¶ You can use uwsgi HTTP server as follow: import cherrypy # Our CherryPy application class Root(object): @cherrypy.expose def index(self): return "hello world" cherrypy.config.update({'engine.autoreload.on': False}) cherrypy.server.unsubscribe() cherrypy.engine.start() wsgiapp = cherrypy.tree.mount(Root()) Save this into a Python module called mymod.py and run it as follows: $ uwsgi --socket 127.0.0.1:8080 --protocol=http --wsgi-file mymod.py --callable wsgiapp Virtual Hosting¶ CherryPy has support for virtual-hosting. It does so through a dispatchers that locate the appropriate resource based on the requested domain. Below is a simple example for it: import cherrypy class Root(object): def __init__(self): self.app1 = App1() self.app2 = App2() class App1(object): @cherrypy.expose def index(self): return "Hello world from app1" class App2(object): @cherrypy.expose def index(self): return "Hello world from app2" if __name__ == '__main__': hostmap = { 'company.com:8080': '/app1', 'home.net:8080': '/app2', } config = { 'request.dispatch': cherrypy.dispatch.VirtualHost(**hostmap) } cherrypy.quickstart(Root(), '/', {'/': config}) In this example, we declare two domains and their ports: - company.com:8080 - home.net:8080 Thanks to the cherrypy.dispatch.VirtualHost dispatcher, we tell CherryPy which application to dispatch to when a request arrives. The dispatcher looks up the requested domain and call the according application. Note To test this example, simply add the following rules to your hosts file: 127.0.0.1 company.com 127.0.0.1 home.net Reverse-proxying¶ Nginx¶ nginx is a fast and modern HTTP server with a small footprint. It is a popular choice as a reverse proxy to application servers such as CherryPy. This section will not cover the whole range of features nginx provides. Instead, it will simply provide you with a basic configuration that can be a good starting point. Edit this configuration to match your own paths. Then, save this configuration into a file under /etc/nginx/conf.d/ (assuming Ubuntu). The filename is irrelevant. Then run the following commands: $ sudo service nginx stop $ sudo service nginx start Hopefully, this will be enough to forward requests hitting the nginx frontend to your CherryPy application. The upstream block defines the addresses of your CherryPy instances. It shows that you can load-balance between two application servers. Refer to the nginx documentation to understand how this achieved. upstream apps { server 127.0.0.1:8080; server 127.0.0.1:8081; } Later on, this block is used to define the reverse proxy section. Now, let’s see our application: import cherrypy class Root(object): @cherrypy.expose def index(self): return "hello world" if __name__ == '__main__': cherrypy.config.update({ 'server.socket_port': 8080, 'tools.proxy.on': True, 'tools.proxy.base': '' }) cherrypy.quickstart(Root()) If you run two instances of this code, one on each port defined in the nginx section, you will be able to reach both of them via the load-balancing done by nginx. Notice how we define the proxy tool. It is not mandatory and used only so that the CherryPy request knows about the true client’s address. Otherwise, it would know only about the nginx’s own address. This is most visible in the logs. The base attribute should match the server_name section of the nginx configuration.
http://cherrypy.readthedocs.io/en/latest/deploy.html
CC-MAIN-2018-05
refinedweb
2,264
50.53
A better way to manage and import dependencies. require.py A way to manage dependency conflicts. What Is require.py? The core of require.py is a hack of the Python import statement. By default, all Python modules are installed at the global, site-packages level. This makes it difficult, and sometimes impossible, to install libraries with conflicting dependency requirements. To a large extent, virtual environments have solved this problem by providing sandboxes in which Python modules can be installed without affecting other virtual environments. Even virtualenvs, however, do not allow a single Python process to load multiple, conflicting versions of a dependency as the same time. This project provides tools for managing dependencies at a Python package level. This means each Python package (a directory containing an __init__.py) can have a unique version of a dependency that is isolated from the other packages around it. Import Behaviour The import logic, and name for this project, are heavily inspired by the node.js module and import system. The relevant behaviour in node is documented here. This package exposes a callable named require that can be used to provide the alternate import logic. Alternatively, there are patch_import and unpatch_import available to affect an entire Python process. Here is a scenario to illustrate the import logic. Given the following project structure: /myproject/__init__.py /myproject/subpackage/__init__.py /myproject/subpackage/subsubpackage/__init__.py Where the __init__.py of subsubpackage has the following content: from require import require requests = require('requests') The custom import logic will first look for a ‘.pymodules’ directory in subsubpackage. If found, it will attempt to import requests from that directory. If not found, it will continue walking the file system upwards until it hits ‘/’. After hitting the root, if no ‘.pymodules’ directories are found the function falls back to the default Python import logic. Package Management Keep using pip. This project includes a helper command called requirepy that can be used to help install dependencies into the right subdirectories. It wraps pip. License Copyright 2014. 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/requirepy/
CC-MAIN-2017-51
refinedweb
359
52.15
Answered by: Creating an async method Question Answers All replies - A Class is automatically ASYNC as long as you don't have any blocking functions. Make sure the Class has Event(s) and they are registered in the class constructor. windows wil automatically execute the class code when the Event(s) occur. jdweng - Proposed as answer by Mike FengModerator Tuesday, May 21, 2013 8:06 AM Lets not worry about methods or blocking. Lets just talk about building a class library that runs asynchronously. The class needs two items 1) A constructor that initializes (register in windows) any Events 2) Event Handler(s) The reason it runs asynchronously in Windows (the timer tick service), the class is allowed to register new events and then when the event occurs the timer tick calls the function. When any event finishes processing it returns to the timer tick service which starts next process or handles another event. So as long as nothing is blocking the function runs asynchronously. In a blocking function the code sits and waits for an event to complete before proceeeding. Windows is a real time operating system and is swapping processes all the time so many functions can be blocking simultaneously while other processes continue to run. jdweng Below the Form class is an async class. When a load event occurs it processes the event and then returns. Nothing is blocking. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ConsoleApplication1 { class Program { [STAThread] static void Main(string[] args) { Form1 myClass = new Form1(); } } partial class Form1 : Form { public Form1() { this.Load +=new EventHandler(Form1_Load); } private void Form1_Load(object sender, EventArgs e) { } } } jdweng An event handle is an async method. What do you want to use as a trigger for the event? I often use a System.Threading.EventWaitHandle. The trigger can be a timer, a stream event, a port event, or a semiphore like the EventWaitHandle. The EventWaitHandle can wait for a signal from another async process before continueing. What make a process async is simply nothing blocks the code from running, and these is a mechanism for running the process. You can either call the process (class) from another process (class) or use an event to run the code. The theory is not complicated. You have to come up with a design concept for implimenting the async process. The first thing you have to consider is what/when the async process is going to run. jdweng - I am writing an WPF application and some times a classic winforms application. The operator clicks a button and the application starts a long running task. The button event should not block the application. If the long running task calls a .NET method that is asynchronous it is a very easy the mark the button event with the async modifier. If the long running task calls a .Net method that is synchronous I have to find a different method to make the long running task asynchronous. You suggest using an event handler. So far I have not been able to make the jump from theory to practical coding. Certified Geek The async event simply has to return after a running a certain amount of time. For example if you had a math function running one million times. You may want to break every thousand operations. Then set a timer to resume after 2 seconds. The 2 second times would be the trigger. If you were processing an input stream you would set an event indicating when the stream had data. Then after you hit a underflow (no data in the input stream) you can return. The next time the stream had data your code would resume because the event would be the trigger. jdweng I don't understand Joel in this thread either. If you want an asynchronous method, you have to run the method on a thread different from the calling thread. "If my method uses a class in .Net framework that does not have an async method, is there anything I can do to make my method async?" Call it from a thread. If you have a UI, simplest is to use the BackgroundWorker. The only thing I can report back from a Backgroundworker is an integer which can be used with a progress bar. With an async method I can pass in a delegate which can be used to report back any data I like. I understand how to create a thread, but I prefer to use an async method. Certified Geek See if the webpage below helps. The integer is really just the handle which is the process id number. Again the async is just creating a new process and you don't need the new process to process events. The only time you neeed a new process is you are trying to run more than one thread in parallel. If you PC has more than one core the parallel threads will run in parallel on seperate cores. If you just have a form that is waiting for a thread to complete then the async method doesn't do anything for you. jdweng "The only thing I can report back from a Backgroundworker is an integer which can be used with a progress bar." The BackgroundWorker wraps an AsyncOperation. It not only reports the results of the operation in the Completed event, but provides for intermediate return of progress and data in the ProgressChanged event. The use of the ProgressChanged event is not mandatory.
https://social.msdn.microsoft.com/Forums/en-US/7b0ba87a-94d7-436d-af04-57bd5a597ffb/creating-an-async-method?forum=netfxbcl
CC-MAIN-2020-50
refinedweb
924
74.08
Details - Type: Sub-task - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: 2.2.4 - - Component/s: jackrabbit-jcr-server, jackrabbit-spi2dav - Labels:None Activity - All - Work Log - History - Activity - Transitions Do we need this for 2.0 or can we postpone to a later release? +1 for postponing. adjusting summary as it only affects spi2dav(ex) - jcr-server This patch implements the missing feature. We would love to see this soon in a release (2.2.6 or 2.3). Then we no longer need to use a patched version. awesome, thanks uwe! would love to see this integrated. just tested it on the trunk branch for 2.3 and it works fine. one note for the record: this is only working to create node types or add properties. non-trivial operations (i.e. removing a property of a node type) lead to an exception in the cnd handling code, just as happens when you try to do such a change from the cli. hi uwe thanks a lot for the patch. looks good. i only have 1 minor issues: a) could you (for completeness) handle the JCR_NODETYPES_CND_LN property upon PROPFIND as well? b) the jcr tests related to node type registration are still commented in jcr2dav/pom.xml and spi2dav/pom.xml [1] could you uncomment those as part of the patch and make sure that they pass? that would be great. thanks in advance angela [1] the commented tests: <!-- JCR-2454 : node type registration --> org.apache.jackrabbit.test.api.nodetype.NodeTypeCreationTest#testRegisterNodeType org.apache.jackrabbit.test.api.nodetype.NodeTypeCreationTest#testRegisterNodeTypes hi angela, while b) is clear and seems to be ok with just uncommenting the tests if have actually no clue what I should do for a). Please give me a pointer where to start ... kind regards Uwe Hi, OK I found the place to start I assume a PROPFIND for JCR_NODETYPES_CND_LN on the workspace should return a CND representation of all registered node types (this is in analogy to the namespaces) - 404 else (what it already does). kind regards Uwe Hi, please find the slightly changed patch attached. One major change: PROPFIND for nodetypes-cnd was implemented. In order to use CompactNodeTypeDefWriter jackrabbit-jcr-server needs to depend on jackrabbit-spi and jackrabbit-spi-commons (not sure if that's a problem). Also the client now sends the allowUpdate-Flag (is not a problem for the JAVA client as this is already checked on the client side, but other clients have to set it now). If there any further comments, let me know. Kind regards Uwe applied slightly modified patch provided by uwe jaeger. - i didn't include the PROPFIND functionality but created a new issue JCR-2948 for this which depends on JCR-2946 - in addition i added a draft version for unregistration of node types (which then fails in jackrabbit-core). final note: i would like to review this in a calm moment... somehow i'm not yet convinced that this is the way to go... maybe i will find some time in the future to update my webdav-jcr mapping document... that would help me to think carefully about it. leaving it for the time being and resolving the issue. can't reopen the original [JSR 283 NodeType Management] subtask which was closed premature. the spi2dav still misses the implementation and so does the server-side part.
https://issues.apache.org/jira/browse/JCR-2454?focusedCommentId=12868589&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-35
refinedweb
565
66.94
6 May 16:47 2013 VariantAnnotation error with readVcf in Windows 7 ying chen <ying_chen@...> 2013-05-06 14:47:03 GMT 2013-05-06 14:47:03 GMT Hi guys, I tried a sample with Variant Annotation's eadVcf. I ran the code successfully in Linux (OK I had some warnings regarding " unpackVcf field '..': NAs introduced by coercion"). But when I tried the same code in R3.0.0 in windows 7, I got the error message: > for(i in 1:length(vcflist1)){ indexTabix(vcflist1[i], format="vcf") vcf <- readVcf(TabixFile(vcflist1[i]), "hg19", params) outputfile=paste(sub(".vcf.gz","",vcflist1[i]),"_test.vcf",sep="") writeVcf(vcf,outputfile) bgzip(outputfile, overwrite=TRUE) indexTabix(paste(outputfile,".gz",sep=""), format="vcf") rm(vcf) rm(outputfile) } Error in (function (classes, fdef, mtable) : unable to find an inherited method for function readVcf for signature "TabixFile", "character", "standardGeneric" What did I do wrong? Thanks a lot for the help! Ying > sessionInfo() R version 3.0.0 (2013-04-03)] VariantAnnotation_1.6.5 Rsamtools_1.12.2 Biostrings_2.28.0 GenomicRanges_1.12.2 [5] IRanges_1.18.0 org.Hs.eg.db_2.9.0 RSQLite_0.11.3 DBI_0.2-6 [9] AnnotationDbi_1.22.5 Biobase_2.20.0 BiocGenerics_0.6.0 BiocInstaller_1.10.1 loaded via a namespace (and not attached): [1] biomaRt_2.16.0 bitops_1.0-5 BSgenome_1.28.0 GenomicFeatures_1.12.1 RCurl_1.95-4.1 [6] rtracklayer_1.20.2 stats4_3.0.0 tools_3.0.0 XML_3.96-1.1 zlibbioc_1.6.0 > [[alternative HTML version deleted]] _______________________________________________ Bioconductor mailing list Bioconductor@... Search the archives:
http://permalink.gmane.org/gmane.science.biology.informatics.conductor/47938
CC-MAIN-2015-11
refinedweb
259
53.17
This is your resource to discuss support topics with your peers, and learn from each other. 01-15-2013 10:45 PM Since a lot of people are able to reproduce this behavior, I guess it is a bug. I think this bug is pretty serious because RIM is expecting BlackBerry 10 users to constantly go in an out of apps, if the user comes back to the app and find the animation broken, it will seriously take away the BlackBerry 10 flow experience. I have never logged a bug report, or even know how to. Can someone either do it or teach me? It would be fastest if someone from RIM see this thread. 01-15-2013 11:08 PM 01-15-2013 11:14 PM - edited 01-15-2013 11:15 PM Thanks. I'm going to try and build a test case to reproduce and escalate. 01-16-2013 12:04 AM Reproduced: on Dev Alpha A running 10.0.09.2320 import bb.cascades 1.0 Page { Container { layout: StackLayout { } Container { layout: AbsoluteLayout { } preferredHeight: 500 Label { id: fred text: "Fred" } } Button { text: "Dance Freddy DANCE!" onClicked: { fred.translationY = 400 - fred.translationY; } } } } 01-16-2013 09:25 AM We are also experiencing this bug in our app since the latest SDK update. The transition animations are broken after the app has been minimized once. Only a restart of the app fixes the problem. I discovered that the bug does NOT occur if "Application.cover" is set like e.g. in the QML Cookbook sample app. However we have not yet decided whether we prefer to display an app cover or just the default thumbnail view when our app is minimized, so it would be appreciated if this bug could be fixed before the final release of the OS. 01-16-2013 09:54 AM Good news, this appears fixed on newer (internal) builds. Tested on 2372. 01-16-2013 10:04 AM 01-16-2013 01:24 PM That is good news. For our current releases, should we wait for the upcoming SDK build or shall we do the workaround for now? 01-16-2013 01:45 PM Great!! now I can get back to coding in calm . Thanks for the info. 01-16-2013 06:16 PM
https://supportforums.blackberry.com/t5/Native-Development/Error-slogger2-buffer-handle-not-initialized/m-p/2100201
CC-MAIN-2016-40
refinedweb
381
75.71
From Documentation - Apache-Tomcat-5.5.X - ZK Freshly (zk-2.5.0-FL-2007-08-29 and later) - zrss-0.9.5.jar - Rome-0.9.jar - jdom.jar Introduction Last time in ZK RSS API Part III: Make Your RSS Publishing More Easily with ZK, I introduced how to use ZK RSS to publish your rss within a zul page. This time because ZK-2.5.0 begins to support ZK XML output and native namespace concept, I'll show how to refactor ZRSS to publish rss feed by using ZK XML output. Setup ZRSS Environment After downloading needed resources listed at the end of this article, please following the steps below: 1. Unpack rssxml.war as folder "/rssxml". 2. Unpack zk-bin-2.5.0-FL-2007-08-XX.zip, and put all JAR files into "/rssxml/WEB-INF/lib/". 3. Put "Rome-0.9.jar" and "jdom.jar" into "/rssxml/WEB-INF/lib/". 4. Modify web.xml: //Add this Servlet Mapping. Use zkLoader to handle zrss document. <servlet-mapping> <servlet-name>zkLoader</servlet-name> <url-pattern>*.zrss</url-pattern> </servlet-mapping> 5.Modify zk.xml: //Add this Language Mapping. Use XML output device to handle *.zrss file. <language-mapping> <language-name>xml</language-name> <extension>zrss</extension> </language-mapping> 6. Put or link folder "/rssxml" to Tomcat( or any other JavaEE Web Container) and startup the web server. Write a ZK RSS Publish Document(*.zrss file) To publish your RSS, here is an exemple of a zrss document: <r:rsspublisher <rssfeed> <attribute name="feedType">atom_1.0</attribute> <attribute name="title">ZK - #1 Ajax project in SourceForge.net</attribute> <attribute name="link"></attribute> <attribute name="copyright">POTIX Corp.</attribute> <attribute name="author">POTIX Engineer: Ian Tsai</attribute> <attribute name="description">A Simple Description.</attribute> <attribute name="publishedDate">2007/07/05</attribute> <rssentry> <attribute name="title">ZK 2.4 out now. Enrich your web application today. </attribute> <attribute name="author">Tom Yeh</attribute> <attribute name="link"></attribute> <attribute name="publishedDate">2007/06/08</attribute> <attribute name="updatedDate">2007/06/08</attribute> <attribute name="description"><![CDATA[<b>A Simple Description.</b> ]]></attribute> </rssentry> </rssfeed> ... <rssfeed aggregate="true" url="..."/> </r:rsspublisher> As we can see, this document is very like the previous version of ZRSS publisher. Although the concepts behind them are totally different, the only changed part between these two documents is that the current version of <r:rsspublisher> needs to declare it's namespace: xmlns:r="". If you want to know more detailed information about configuration in other part, please refer to ZK RSS API Part III: Make Your RSS Publishing More Easily with ZK. In downloaded demo package rssxml.war, you can use any RSS reader to browse the result in URL:. ZK Native Name Space & ZK XML Output Concept Before explaining the implementation of ZRSS over ZK XML output, I'll briefly explain these two new features from ZK 2.5.0: 1. ZK XML Output - While a ZUML page is requested, ZK parser will use the suffix of this request's URL(e.g. *.zul, *.mil, *.zhtml etc) to choose the right way to generate the response document. And in ZK-2.5.0 we add a new way for parser to handle the request from such client side application which requires a XML over HTTP response. In this demo, this client side application is an RSS reader. 2. ZK Native Name Space - With the Native namespace, an XML element in a ZUML page denotes that it should be sent to the client side application directly rather than becoming a ZK component. It provides better performance for static element declaration and plays an important part in ZK XML output. Actually if any ZUML page is denoted to response by XML output, all elements in this page will be regarded using ZK Native namespace by default. The Implementation of ZK RSS Publisher with ZK XML Component Based on the code clips I showed above, now we know what it means by the xmlns attribute with value: "" in <r:rsspublisher> tag. It means ZK must generate target component mapped by <r:rsspublisher> tag which is defined in "" Component set, and can't directly output as other plan text tags like <rssfeed>, <rssentry> and <attribute>. The picture below shows the component structure of zrss document. ZK processes this document by using XML output setting, and the first element <r:rsspublisher> will make ZK generate corresponding component whose Java class must extends org.zkoss.zml.XmlNativeComponent. You can find the definition of rsspublisher in zrss.jar->metainfo/zk/lang-addon.xml. The <rssfeed>, <rssentry> and <attribute> tags will be treated as native plan text document. While ZK invokes rsspublisher's redraw() method. rsspublisher will EAT this document and parse it to generate target rss content to page. Compared with the previous ZK RSS publishing Model, the current implementation is more straightforward. The comparison in pictures are shown below: Privious Version of ZRSS: Current Version of ZRSS: Download - rssxml.war(without jar files inside) - zrss-0.9.5.zip(from SourceForge.net - zkapp) - zk-2.5.0-FL-2007-08-29.zip( ZK-freshly or later)
http://books.zkoss.org/wiki/Small%20Talks/2007/September/ZK%20RSS%20Publish%20Revisit:%20Implemented%20with%20ZK%20XML%20Components
CC-MAIN-2015-35
refinedweb
856
59.3
#include <stdio.h> int main(int argc, char *argv[]) { printf("hello world\n"); return 0; }test2.cpp int printf;compiling with the command g++ -o test test1.cppand running gives: $ ./test hello world $thats what is expected. g++ -o test test1.cpp test2.cppand running gives: $ ./test Segmentation faultrunning it in gdb gives: $ gdb ./test GNU gdb 6.4 Copyright 2005 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public... welcome to change it and/or distribute copies of it under ... Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" ... This GDB was configured as "i686-pc-linux-gnu"...Using host ... (gdb) r Starting program: /home/sash/tmp/test Program received signal SIGSEGV, Segmentation fault. 0x080496a4 in printf () (gdb) bt #0 0x080496a4 in printf () #1 0x0804845c in main ()
http://paste.linuxhowtos.org/gcc.htm
crawl-002
refinedweb
141
72.63
I would like to be able to display in the Wine console all characters that the Win32 console can display. I've written a small test program to print out all 8-bit characters: #include <stdio.h> int main(int argc, char *argv[]) { int i, j; for (i = 0; i <= 0xF0; i+=0x10) { for (j = i; j <= i + 0x0F; ++j) printf("%2x:%c", j, (char)j); printf("\n"); } getchar(); return 0; } Under Wine, the best I can do so far is using Andale Mono: While this is what I see on Windows Server 2008: Is there anywhere I can legally download a font that will allow me to view all of those characters under Wine? edit I've found a set of DOS fonts that includes a CP437 font, which should cover the character set I'm interested in. However, even if I install this font, wineconsole doesn't seem to recognize it. Is there any way I can get wineconsole to use this font, or convert this font to a format that wineconsole can use? Or is there any way I can extract fonts from DOSEMU for use in Wine? wineconsole Oh, and I should probably mention that I'm on Mac OS X 10.6.2, installing Wine via MacPorts, using the wine-devel package. wine-devel more information I have tried installing some console fonts that should cover the full character set as Mac OS X fonts (such as the NewDOS font listed above, and a font I tried converting from the fonts supplied by DOSEMU). Wine does not seem to pick up on new fonts installed in Mac OS X. Is there a way to register new fonts I've installed with Wine? Would manually editing the system.reg file that seems to contain font mappings work, or is there something else I'd need to do? system.reg bump Bounty ends soon, I'm still looking for an answer for this. Does anyone use the Wine console for complex text user interfaces? Well, I tend to use unifont for a lot of things. I have a slightly-modified version of the TTF -- I basically flipped a bit in the metadata to get PuTTY to recognize it as a fixed-width font. I have no idea how to make Wine aware of it, though. From what I could find online, Wine doesn't support the FON bitmap font format. You should, however, be able to convert them to TTF, though that seems to be a bit of a tedious process. The Wine wiki refers to this page: which refers to an old version of some Wine documentation again. That link is broken, but it's the same as this page: This revolves around the fnt2bdf tool, which might be part of Wine, or otherwise you'll have to compile it yourself. You can find some more discussion about it here and here. To get from bdf to ttf again (if that's necessary, I'm not sure), you should be able to use FontForge. And incidentally, those DOSEMU fonts are in BDF format too and part of the DOSEMU source, so presumably you could convert those to TTF as well. wine C:\windows\fonts ~/.wine/drive_c/windows/fonts .wine/system.reg Z: C: ~/.wine/drive_c/windows/Fonts The Lucida Console font, which ships with Windows, is one of two fonts you can choose in the Windows Console, and supports the full character set demonstrated above (as well as many other accented Latin characters). It can be purchased from Ascender for $30. This would probably meet my need, but I would rather not spend $30 on a font, so I'm still looking to see if anyone can provide a free alternative. By posting your answer, you agree to the privacy policy and terms of service. asked 5 years ago viewed 2042 times active 3 years ago
http://superuser.com/questions/99732/font-for-wine-that-supports-the-entire-character-set-of-the-win32-console?answertab=active
CC-MAIN-2015-11
refinedweb
650
77.47
In this blog we will write native plugin for Phonegap on Android hwc container. Useful link Building Phonegap native plugin for HWC container – IOS The javascript class The javacript file will be the same as previos blog var SupuserinfoAccess = { devicename: function(types, success, fail) { return Cordova.exec(success, fail, “Supuserinfo”, “getUserinfo”, types); } }; The Native Class Get the source code of Android HWC container application on Eclipse for Android and create a new class name it as Supuserinfo. Open Supuserinfo class you just created and add the following code. As you can see it extends the Plugin superclass. package com.sybase.hwc; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import com.sybase.messaging.common.ClientConfig; import com.sybase.messaging.common.persist.Property; public class Supuserinfo extends Plugin{ public static final String FILEPATH = “getUserinfo”; @Override public PluginResult execute(String action, JSONArray data, String callbackId) { // TODO Auto-generated method stub if (FILEPATH.equals(action)) { String supUserName = “”; Property oProp = CustomizationHelper.getInstance().getDefaultConnectionAutoRegistration(); oProp = CustomizationHelper.getInstance().getDefaultConnectionUserName(); supUserName = oProp.Value.toString(); return new PluginResult(PluginResult.Status.OK, supUserName); } return null; } } Add your plugin to the Plugin.xml file On hwc container project go to “res->xml” and open the plugin.xml file Add following xml code to the bottom of the <plugins> tag. Make sure the package name is same as your project. <plugin name=”Supuserinfo” value=”com.sybase.hwc.Supuserinfo”/> Clean project and build again. Go to the your Hybrid app project and in custom.js file call our plugin to test. function customAfterWorkflowLoad() { document.addEventListener(“deviceready”, onDeviceReady, true); } function onDeviceReady() { SupuserinfoAccess.devicename([“x”],onSuccess,onFailure); } function onSuccess(name){ alert(name); } function onFailure(error){ } Deploy your project to the modified HWC container application and you will get registered username as below. nice one Tahir… 🙂 Great blog. Keep it up. – Midhun VP Thank you Tahir! You are amazing! 🙂 – Suraj Hi Tahir, I am very new to Android world. I followed your blog religiously, but I am sure that I have done mistakes and missed some pre-requisites. Therefore, please be kind enough to help me. (a) I don’t see plugins.xml in the xml folder. (b) Supuserinfo Javascript I hope I should create this Javascript in SUP HWC in html -> Js . Please provide a snapshot from your project ( if possible) Thanks for your help. – Suraj Hi Suraj, a- In SUP 2.2. plugin.xml moved into the config.xml. b- yes, you will add into the HWC project which in html->Js Regards Dear Tahir, Thank you very much. I encountered a small problem here. I am unable to build the application as I got an error for oprop.value. Did you encounter this error as well ? – Suraj Suraj, Change it with oProp.getValue().toString(); Regards. Tahir, I appreciate your prompt response. Unfortunately, I am unable to succeed yet. Here is what I have done. I will be glad if you can help me further. 1>New class created and config.xml updated 2> Javascript and workflow screen 3> custom.js But, when I open the application in HWC, I don’t see anything Any thoughts where I might have done wrong. Thank you. – Suraj Well it seems okay, have you cleaned and build your android project ?. Have you added the onFailure method in custom.js as well? You can also try hwc android project in debug mode see if it invokes the plugin. Tahir Hi Tahir, i am trying to implement above scenario. just want to understand first i create one mbo, deploy to server, create hybrid designer, generate js, html etc class and then add Supuserinfo js class with the mentioned code. after that you mentioned i didnt understand it? how to get the source code of android hwc container app? plz help. Rgrds, Jitendra Hi jitendra, You can get Android HWC application source code from the path of installation Sybase SDK as, C:\<sybasepath>\UnwiredPlatform\MobileSDK213\HybridWeb\Android Thanks Tahir for help. It worked. Rgrds, Jitendra
https://blogs.sap.com/2013/06/04/building-phonegap-native-plugin-for-hwc-container-anroid/
CC-MAIN-2021-04
refinedweb
664
53.07
This is the mail archive of the cygwin mailing list for the Cygwin project. Here's a small test program: #include <fcntl.h> #include <cstdlib> #include <iostream> using namespace std; int main() { int fd = ::open( "ESLF", O_RDONLY ); if ( fd == -1 ) { cerr << "could not open ESLF file" << endl; ::exit( 1 ); } char buf[ 64 ]; ssize_t bytesRead = ::read( fd, buf, sizeof( buf ) ); cout << "read " << bytesRead << " bytes" << endl; ::close( fd ); } Here's the contents of a small biinary file "ESLF" (printed in hex bytes): 54 39 CA 1A 44 When I compile the program as: g++ -o test test.cpp and run it, it prints "read 5 bytes" as one would expect. When I compile the program as: g++ -mno-cygwin -o test test.cpp and run it, it prints "read 3 bytes". Why? How do I teg it to read all 5 bytes? Ask the MinGW llist, since -mno-cygwin simply enables you to run their compiler "indirectly". As a result, questions about the MinGW compiler are off-topic for this list, since it's not Cygwin. See <>. -- Larry Hall RFK Partners, Inc. (508) 893-9779 - RFK Office 838 Washington Street (508) 893-9889 - FAX Holliston, MA 01746 -- Unsubscribe info: Problem reports: Documentation: FAQ:
http://cygwin.com/ml/cygwin/2006-03/msg00611.html
CC-MAIN-2019-47
refinedweb
201
79.3
Dave, I've implemented the inheritance as the tutorial say, it worked fine, but the factory method still need to get the initial artist class to know the type, then ask cayenne again to give the right class to instantiate. I think there may be another way to get the object without doing this double call to objectForPK. public static Artist getArtist(String id) { if (id == null || id.equals("")) return null; DataContext context = DataContext.getThreadDataContext(); Artist c = (Artist) DataObjectUtils.objectForPK(context, Artist.class, Integer.parseInt(id)); if (c.getTipoEnum() == EnumTipoArtist.EXPERT) return (Artist) DataObjectUtils.objectForPK(context, ExpertArtist.class, Integer.parseInt(id)); else return c; } Thanks Hans ----- "Dave Lamy" <davelamy@gmail.com> escribió: > Hey Hans-- > > While I'm certain that the inheritance structure isn't data based to > you, I > imagine that Cayenne is going to HAVE to have a data value to know > which > subclass to instantiate. It's effectively going to get back a row > from the > Artist table and be asked to transform that row into an Artist object. > How > can it determine which kind? Through some sort of data analysis. > Either a > particular attribute value (ARTIST_TYPE) or via a linked table > structure > (don't think Cayenne supports that yet?). That data attribute should > not be > of particular importance to your application, however. It's just an > ORM > crutch. > > Dave > > On Mon, Mar 2, 2009 at 8:41 AM, <hans@welinux.cl> wrote: > > > Michael, > > > > Thank you, i already saw it, but my intent was to make it entirely > outside > > cayenne mappings, the problem i need to solve is just behavioral, > not data > > based... by the way, it's not clear how to try the example using > the > > modeler: creating an empty class with no attributes or something. > > > > Hans > > > > ----- "Michael Gentry" <mgentry@masslight.net> escribió: > > > > > Is this what you are after? > > > > > > > > > > > > > > > On Sun, Mar 1, 2009 at 7:46 PM, <hans@welinux.cl> wrote: > > > > Hi, > > > > > > > > I'm trying to implement a factory method pattern based on a > cayenne > > > data object. > > > > > > > > Say for example i have a class (cayenne based) called Artist, i > want > > > to make a subclass of Artist, say ExpertArtist that implements > some > > > specific behavior. > > > > > > > > Actually i have a big static Factory class that give me the all > > > objects, i have a method like this: > > > > > > > > public static Artist getArtist(String id) { > > > > > > > > if (id == null || id.equals("")) > > > > return null; > > > > > > > > DataContext context = > > > DataContext.getThreadDataContext(); > > > > > > > > Artist object = (Artist) > > > DataObjectUtils.objectForPK( > > > > context, Artist.class, > > > Integer.parseInt(id)); > > > > return object; > > > > } > > > > > > > > Obviously i can declare ExpertArtist as an subclass of Artist. > > > > > > > > package xxx.xxx; > > > > > > > > public class EspertArtist extends Artist { > > > > public String getName() { > > > > return super.getName() + " i'am expert !!"; > > > > } > > > > } > > > > > > > > I've tried to instantiate an ExpertArtist, just modifying the > > > Factory method, with no results. I don't know how to bouild the > parent > > > class calling super or something... > > > > > > > > Obviously these are not the real classes, the actual classes > are > > > really big and this solution: just modifying the factory method is > the > > > best for me. > > > > > > > > > > > > Thanks > > > > Hans > > > > > > > > > > > > > > > > -- > > Hans Poo, WeLinux S.A. > > Oficina: 697.25.42, Celular: 09-319.93.05 > > Bombero Ossa # 1010, Santiago > > > > -- Hans Poo, WeLinux S.A. Oficina: 697.25.42, Celular: 09-319.93.05 Bombero Ossa # 1010, Santiago
http://mail-archives.apache.org/mod_mbox/cayenne-user/200903.mbox/%3C1314533533.4601236030009204.JavaMail.root@ronin%3E
CC-MAIN-2018-43
refinedweb
527
58.89
In this tutorial we will check how to get the UART OBLOQ firmware version, using the micro:bit board and uPython to send commands to the device. Introduction In this tutorial we will check how to get the UART OBLOQ firmware version, using the micro:bit board and uPython to send commands to the device. For an introductory tutorial that contains the wiring diagram between the micro:bit board and the UART OBLOQ, please consult this previous post. For a detailed explanation about the get firmware version command, please check here. Note that, for this tutorial, I’m using version 1.7.0 of uPython for the micro:bit board. So, like already covered in the previous tutorial where we sent a ping to the UART OBLOQ, the micro:bit will send a dummy byte with the value 0 when we initialize the serial interface. After receiving the dummy byte, the UART OBLOQ will start building a command that doesn’t exist, which means we have to first flush this wrong command, and only after that send the actual command to get the firmware version. Nonetheless, in more recent versions of uPython for the micro:bit, this issue is already solved. So, if you are using a version that already has the fix, you can skip the part of the code where we flush the command. The code The first thing we are going to do is importing the functionality we will need from the microbit module. We will import the uart object and the sleep function. from microbit import uart, sleep Then, we will call the init method on the uart object, in order to initialize the serial communication interface. We will use a baud rate of 9600, which is the one used by the UART OBLOQ. Additionally, we will set the serial Tx to pin 0 and the Rx to pin 1 of the micro:bit. uart.init(baudrate=9600, tx = pin0, rx = pin1) Then, since micro:bit sends a garbage character to the serial port after we call the init method, we will first send a “\r” character to the UART OBLOQ, so we flush any previous non-valid command it could be trying to build. After that, we will wait for 1 second and try to read 10 characters from the serial port. Note that these are more characters than the expected answer, which should be |1|-1|, but we do it as a safeguard. This should cause no problem because the number passed as input of the read method means that it should return at most that many characters [1], but the method call will return the number of bytes available so far after a timeout, even if they are less that the specified. We will store the result of the read method call on a variable, so we can later print it. Please take in consideration that we are using the delay approach to keep the code simple. In a real scenario application, we should use something more robust, such as implementing a “read until character” function that waits for the “\r” character, which is sent at the end of the UART OBLOQ responses. uart.write("\r") sleep(1000) output1 = uart.read(10) Now that we have flushed this garbage content, we can take care of sending the command to get the firmware version of the UART OBLOQ. The command to send is |1|2|, as covered here. As before, we will wait for 1 second and then try to read 10 bytes with the read method of the uart object, storing the result in a variable. uart.write("|1|2|\r") sleep(1000) output2 = uart.read(10) To finalize, we will re-initialize the micro:bit serial connection without passing the Tx and Rx pin values, in order to bring back the Python console [1]. As baud rate, we should use the value 115200. uart.init(baudrate=115200) After that, we can print the values of both output1 and output2 variables. The first one should contain the string |1|-1| because, as already said, it is only used to flush the byte that micro:bit writes to the serial port after we call the init method. The second variable should have the firmware version, in the following format: |1|2|version| The final source code can be seen below. from microbit import uart, sleep uart.init(baudrate=9600, tx = pin0, rx = pin1) uart.write("\r") sleep(1000) output1 = uart.read(10) uart.write("|1|2|\r") sleep(1000) output2 = uart.read(10) uart.init(baudrate=115200) print (output1) print (output2) Testing the code To test the code, save the file and upload it to your micro:bit board, assuming that all the connections between this board and the UART OBLOQ are already done. After the execution of the commands, you should get an output similar to figure 1. As can be seen, the first line corresponds to the |1|-1| expected response, since we are only flushing the byte sent by micro:bit, which corresponds to no command on the UART OBLOQ. Thus, the UART OBLOQ responds back with |1|-1|, simply indicating the command was not recognized. The second line corresponds to the UART OBLOQ firmware version command response. As can be seen, for my device, the firmware version is 3.0. Figure 1 – Output of the program, tested on the uPyCraft IDE. References [1] 3 Replies to “Micro:bit uPython: Getting firmware version of UART OBLOQ”
https://techtutorialsx.com/2018/11/20/microbit-upython-getting-firmware-version-of-uart-obloq/
CC-MAIN-2019-35
refinedweb
915
68.7
method chains. Method chains are an amazing programming pattern if you're building an API that needs to be expressive in how it changes data. In this series of video's we will make a pandas-like datacontainer for lists of dictionaries. Notes Next well define a new class called We'll load in the data via; import json import pathlib poke_dict = json.loads(pathlib.Path("pokemon.json").read_text()) Next well define a new class called Clumper. The idea is that this class will allow us to more flexibly analyse the list of json objects for us. class Clumper: def __init__(self, blob): self.blob = blob def keep(self, func): return [d for d in self.blob if func(d)] You can see how it works by running. Clumper(poke_dict).keep(lambda d: 'Grass' in d['type']) Can you see a downside with this current approach though? Feedback? See an issue? Something unclear? Feel free to mention it here. If you want to be kept up to date, consider getting the newsletter.
https://calmcode.io/method-chains/keep.html
CC-MAIN-2020-34
refinedweb
172
75.4
I reached the official website for SEO. To sum up the most important features: - Using Java 5 language features such as annotations, generics and varargs. - Providing the “Test”-Annotations for marking tests insted of reflecting by the method name prefix “test”. - Supporting easy definition of test suites via a list of classes instead of the need to build up a suite programmatically. - Only one textual test runner delivered. - Expected exceptions can now be tested by providing an optional parameter to the “Test”-Annotation - Skipped ExceptionTestCase whose usage could have been classified as antipattern. - Allowing to define parameterized tests (i.e. sort of data-driven tests) in a clean way with help of annotations. - Allowing to easily run old unit tests with help of an adapter class. - Now two package namespaces exist with JUnit: org.junit.* and the old junit.framework.*. The former one representing new implementations. The most significant change regarding developers is the usage of Java 5. Meaning that you cannot use JUnit with older Java versions. The currently (02/28/06) published release is release candidate 1. But candidate 2 has been available inofficially and shows some noticeable changes compared to its predecessor. The source code in the CVS has also evolved in the meantime. Soon, an article of mine describing JUnit 4 in more detail will be published in the German JavaMagazin Craig Btw Frank Westphal wrote an excellent article about 4.0. Get it here: (in german) regards Thomas
https://blogs.sap.com/2006/02/28/junit-4-released/
CC-MAIN-2020-34
refinedweb
243
50.53
mukund1776BAN USER def wildcard(wildcard_string): list_of_strings = [] for c in wildcard_string: if not list_of_strings: if c == '?': list_of_strings.append('0') list_of_strings.append('1') else: list_of_strings.append(c) else: new_list_of_strings = [] for string in list_of_strings: if c == '?': new_list_of_strings.append(string + '0') new_list_of_strings.append(string + '1') else: new_list_of_strings.append(string + c) list_of_strings = new_list_of_strings return list_of_strings print wildcard('01?0?') def checkPalindrome(string): startindex = 0 endindex = len(string) - 1 isPalindrome = True while True: if endindex <= startindex: break startchar = string[startindex] endchar = string[endindex] if not startchar.isalpha(): startindex += 1 continue if not endchar.isalpha(): endindex -= 1 continue if startchar.lower() != endchar.lower(): isPalindrome = False break else: startindex += 1 endindex -= 1 return isPalindrome print checkPalindrome('A man, a plan, a canal, Panama!') aalexlingram, AT&T Customer service email at ABC TECH SUPPORT I am Alex and I live in Colorado Springs . I am working as a International human resources manager and I ... chingdelisa, Accountant at ABC TECH SUPPORT I'm a Creative director in San Diego, USA.I map out future plans and make sure the result and ... giannanewhart, Cloud Support Associate at ABC TECH SUPPORT I am Clinical managers, a type of medical and health services manager, and work as managers in both administrative areas ... WilliamDGiles, Cloud Support Associate at ADP Spent 2001-2006 creating marketing channels for tar worldwide. Was quite successful at building tobacco for farmers. Won several awards for ... harryhamesh, Android Engineer at ADP I placement officers usually work in colleges and universities. One of My friends taught me about prayers that break curses ... sallieroliphant, Project Leader at Wissen Technology With years of experience I can guarantee you that our licensed company specializes in furnace maintenance scarborough, air conditioners and ... nyladsomerville, abc Want to purchase best quality silencer at affordable price manufactured by top most trusted brand Innovative Arms. Contact Stonefirearms now! limlocica, News reporter at Smitty's Marketplace Hello, I am a News reporter. Master's Degree in astrology and News reporter and 10 years of experience working ... delenestanf0, HR Executive at Agilent Technologies Hi, I am a Clinical social worker. methods of prevention and treatment in providing mental-health/healthcare services, I also have ... - mukund1776 May 09, 2015
https://careercup.com/user?id=5657404234530816
CC-MAIN-2022-40
refinedweb
357
51.24
Not every library needs a two-letter abbreviation. I think that hepunits loses usefulness if its usage involves weird u.MeV type things. I think there's an argument for from hepunits import MeV, GeV, mm, cm 0.510 * MeV # electron mass 125.2 * GeV # Higgs mass 0.456 * mm # B0 ctau 2.685 * cm # K0 ctau since these objects exist primarily for readability. By the way, Awkward's official two-letter abbreviation will be ak: import awkward1 as ak as in "ak! ak! this array is so awkward!". I've seen some import awkward as awk in the wild and I want to avoid mental overlap with Awk (which is a rather nice language for its domain, but still). ... as awkis not a good option ... These are about recommendations. I don't think I'd recommend import hepunits as u which is an extra step ( as u) for the sake of having a name around that's more likely to get clobbered than MeV or GeV. For instance, there could easily be a step in a calculation like u, v = math.cos(theta), math.sin(theta) that silently clobbers the u, but MeV = ... # ? would not be likely at all. It's about the names humans are likely to use and notice as being different. I wouldn't recommend from hepunits import * though. A given script is probably only going to use a couple of units, and pulling them into the namespace deliberately is not an abuse. active_imports()and get the list of imports you need to paste into your script. :) It has the from pylab import * touch, which is now, for good reasons, depreceated. For IPython, I have a startup script full of import package as pkg with suppressed ImporError warnings, because yeah, it's otherwise pain. It’s only for interactive work I see the use case, and it's nice. But I also see the abuse cases and prefer e.g. template python modules combined with an "optimize import" in my IDE that removes all unnecessary imports. No magic, just clean... (or better, what I actually do: an editor that imports modules like np, pd with a single shortcut when I use them) For IPython, I have a startup script full of import package as pkg This is exactly what it can and should be used for - and your start up script slows down your IPython startup time, even if you don’t use all the packages. If you copy your start up script to ~/.pyforest/user_imports.py, you will have instant startup times again, and things get imported when you use them. And you gain the ability to quickly see what you have used. I don’t use the from pyforst import * at all, it’s just an extention to IPython. I rather which that wasn’t there, for misusage issues. Hi all, the first release of scikit-stats, part of the scikit-hep toolset, has just been published. It contains 2 submodules: modeling: with the Bayesian Blocks algorithm that moved from scikit-hep to scikit-stats. hypotest: aims to provide tools do likelihood-based hypothesis tests such as discovery test, computations of upper limits or confidences intervals. Currently discovery test using asymptotic formulae is available. More functionalities will be added in the future. Quick documentation is available in the README and notebook examples in binder , a proper documentation will be added in future releases. Suggestions are welcome, and feel free to give it a try. Otherwise we will loose users. I would argue not many or maybe any. If we add a new package, regardless of the requirements, we can’t loose a user. If we add a new release of a package that is Python 3 only, existing users will still get the old Python 2 version, and again, won’t be lost. If experiments are using our code, they would fall into this category. The only ones I think we would risk loosing would be a new users, who are Python 2 only and want to start using our code - but a) I don’t think we have that many, b) they will still be able use older versions, and c) they already have to be using older versions of numpy, SciPy, matplotlib, and IPython, so our packages would just be one more thing. Keep in mind, the cost of keeping Python 2 compatibility is non-zero. It requires more complex code, limits use of time saving features, adds extra checks, increases binary build time, etc. It can also hamper the package API and user experience in Python 3. We could use the time we spend fiddling with Python 2 code or writing code in a way to be compatible with both instead developing new libraries and features. Obviously, the final decision for any package has done on a per-case basis by the core maintainers of that package. I still support Python 2.6 in Plumbum, for example. But..
https://gitter.im/HSF/PyHEP?at=5db307daa3f0b17849894b9f
CC-MAIN-2020-45
refinedweb
827
73.37
There are many ways that we can use when we want to share our applications with other people. For example, we can create a binary distribution that can be downloaded from our website. This blog post describes how we can create a runnable binary distribution by using the Maven Assembly Plugin. The requirements of our binary distribution are: - The jar file that contains the classes of our example application must be copied to the root directory of the binary distribution. - The manifest of the created jar file must configure the classpath and the main class of our application. - The dependencies of our application must be copied to the lib directory. - The startup scripts of our application must be copied to the root directory of the binary distribution. Let’s start by taking a quick look at our example application. The Example Application The example application of this blog post has only one class that writes the string 'Hello World!' to the log by using Log4j. The source code of the HelloWorldApp class looks as follows: import org.apache.log4j.Logger; public class HelloWorldApp { private static Logger LOGGER = Logger.getLogger(HelloWorldApp.class); public static void main( String[] args ) { LOGGER.info("Hello World!"); } } The properties file that configures Log4j is called log4j.properties, and it is found from the src/main/resources directory. Our log4j.properties file looks as follows: log4j.rootLogger=DEBUG, R log4j.appender.R=org.apache.log4j.ConsoleAppender log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n The startup scripts of our example application are found from the src/main/scripts directory. This directory contains the startup scripts for the Windows and *nix operating systems. Let's move on and find out how we can create a jar file that configures the classpath and the main class of our example application. Creating the Jar File We can package our application into a jar file by using the Maven Jar Plugin. We can configure the Maven Jar Plugin by following these steps: - Ensure that classpath of our example application is added to the created manifest file. - Specify that all dependencies of our application are found from the lib directory. - Configure the main class of our example application. The configuration of the Maven Jar Plugin looks as follows: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.5</version> <configuration> <!-- Configures the created archive --> <archive> <!-- Configures the content of the created manifest --> <manifest> <!-- Adds the classpath to the created manifest --> <addClasspath>true</addClasspath> <!-- Specifies that all dependencies of our application are found from the lib directory. --> <classpathPrefix>lib/</classpathPrefix> <!-- Configures the main class of the application --> <mainClass>net.petrikainulainen.mavenassemblyplugin.HelloWorldApp</mainClass> </manifest> </archive> </configuration> </plugin> Let’s move on and find out how we can assemble the binary distribution of our example application. Assembling the Binary Distribution We can assemble our binary distribution by using the Maven Assembly Plugin. If we want to create a binary distribution that fulfills our requirements, we have to follow these steps: - Create an assembly descriptor that dictates the execution of the Maven Assembly Plugin. - Configure the Maven Assembly Plugin to use the created assembly descriptor. First, we have create an assembly descriptor that dictates the execution of the Maven Assembly Plugin. We can create this assembly descriptor by following these steps: - Create an assembly.xml file to the src/assembly directory. - Configure the format of our binary distribution. Ensure that a zip file is created. - Copy the dependencies of our application to the lib directory. - Copy the startup scripts of our application from the src/main/scripts directory to the root directory of the binary distribution. - Copy the jar file of our example application from the target directory to the root directory of the binary distribution. Our assembly descriptor looks as follows: <assembly> <id>bin</id> <!-- Specifies that our binary distribution is a zip package --> <formats> <format>zip</format> </formats> <!-- Adds the dependencies of our application to the lib directory --> <dependencySets> <dependencySet> <!-- Project artifact is not copied under library directory since it is added to the root directory of the zip package. --> <useProjectArtifact>false</useProjectArtifact> <outputDirectory>lib</outputDirectory> <unpack>false</unpack> </dependencySet> </dependencySets> <fileSets> <!-- Adds startup scripts to the root directory of zip package. The startup scripts are copied from the src/main/scripts directory. --> <fileSet> <directory>${project.build.scriptSourceDirectory}</directory> <outputDirectory></outputDirectory> <includes> <include>startup.*</include> </includes> </fileSet> <!-- Adds the jar file of our example application to the root directory of the created zip package. --> <fileSet> <directory>${project.build.directory}</directory> <outputDirectory></outputDirectory> <includes> <include>*.jar</include> </includes> </fileSet> </fileSets> </assembly> Second, we have to configure the Maven Assembly Plugin to use the assembly descriptor that we created in step one. We can do this by adding the following plugin declaration to the plugins section of our POM file: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.5.1</version> <configuration> <!-- Configures the used assembly descriptor --> <descriptors> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> </configuration> </plugin> We have now configured the Maven Assembly Plugin to create our binary distribution. Let’s move on and find out what this really means. What Did We Just Do? We can create our binary distribution by running the command mvn clean package assembly:single at the command prompt. After we have done this, Maven creates the maven-assembly-plugin-bin.zip file to the target directory. This zip package is the binary distribution of our example application. In other words, the name of the created binary distribution is maven-assembly-plugin-bin.zip because: - The value of the finalName element, which is found from our pom.xml file, is maven-assembly-plugin. - The id of our assembly is bin. - We want to create a binary distribution that is packaged into a zip file. When we run the command unzip maven-assembly-plugin-bin.zip at the command prompt, the maven-assembly-plugin-bin directory is created to the target directory. The content of the created directory is described in the following: - The maven-assembly-plugin-bin directory contains the jar file of our example application and the startup scripts. - The maven-assembly-plugin-bin/lib directory contains the log4j-1.2.16.jar file. We can run our example application application by using the startup scripts found from the maven-assembly-plugin-bin directory. When we run our application, we see the following output: $ ./startup.sh 0 [main] INFO net.petrikainulainen.mavenassemblyplugin.HelloWorldApp - Hello World! Let’s move on and summarize what we learned from this blog post. Summary This blog has taught us two things: - We can customize the manifest of the created jar file by using the Maven Jar Plugin. - We can create a binary distribution, which doesn't use the so called "fat jar" approach, by using the Maven Assembly plugin. Thanks! That works for me. Great post!! This was exactly what I needed. Thanks for putting this together. Hi Petri, That was a great tutorial..thanks a ton for your efforts before i was struggling to put together my maven build as an app to invoke from batch script your example provided just what i needed to do that all in one click Thanks again Regards Prash Hi Prash, It is good to hear that you found this tutorial useful. At least I know that I have managed to actually help someone :) Hey Petri, thanks a lot for this wonderful tutorial, I'm new to Maven and I was having a hard time trying to pack the binaries of my project into an archive with external jars and all.. your ideas served me greatly :) Cheers! Radu Radu, it is good to hear that I could help you out. You helped me too. Tanks a lot. It can be useful to use 0755 so that the script file is executable. Also, it is safer to use ${project.build.directory} instead of target. And since the jar is added at the root of the archive, you should use false in to prevent including it twice. Laurent, Good to hear that I could help you out. Also, you gave some nice improvement ideas. I will update the code examples and the sample project as soon as possible. I moved the example application to GitHub and fixed the issues mentioned by Laurent. Hi. I may be extremely dense, and miss something obvious. But how do I get all the nice external jar files that I depend on in the maven build file included in the assembly generated jar file? It seems to me it only includes what is specifically present in my own project directories and not any dependencies. Do I combine it with "one-jar" plugin, or? Forget it... had a bad-brain-day or something and forgot mvn assembly:single :( Jakob, No worries. It happens to all of us =) Hi Jacob, Thanks for your comment. You can configure this in the assembly descriptor. The dependencySets element of my assembly descriptor example configures the Maven assembly plugin to copy the dependencies of your project under the lib directory. Hi Petri, I tried with your simple example app, but it gave me an exception at runtime Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger at net.petrikainulainen.mavenassemblyplugin.HelloWorldApp.(HelloWorldApp.java:11) Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger) I took a look inside the maven-assembly.jar and it didn´t have a log4j.jar inside not even a lib/ dir in the target directory. Have you any idea what could it be?. Would you mind try out with your example? Thanks in advance, great post. Hi Jose, What method were you using when you tried to run the example application (command line, IDE) and were you running it after you had assembled the binary distribution? I will describe two alternative ways of running this example: 1) From command line without using the Maven assembly plugin. Run the following command at the root directory of the project: mvn exec:java -Dexec.mainClass="net.petrikainulainen.mavenassemblyplugin.HelloWorldApp" 2) From command line after the binary distribution has been created. First, you have to create the binary distribution. You can do this by running the following command at command prompt (again, run this at the root directory of the project): mvn assembly:single Second, you have unzip the created zip package. You can find the zip package from the targetdirectory. Look for a file called maven-assembly-plugin-bin.zip. Third, you have to run the application. You can run the application by using the provided start up scripts (either startup.bat or startup.sh). Remember to run these scripts from the directory in which you unzipped the binary distribution. You can do this by running the following commands at command prompt: cd target cd maven-assembly-plugin startup.bat (or startup.sh) I will add this information the actual blog entry as well (Thanks for pointing this out). If this did not solve your problem, please let me know. Thanks for putting this tutorial together, wish I have found it before, it was helpful. Hi Nadia, It is great to hear that I could help you out. sweet Hello, I downloaded your example and tried it, but maven doesn't build a zip-File. I'm using maven 3.0.4 , eclipse Juno SR1 and m2eclipse 0.12.1. I'm not using the embedded version of maven within m2eclipse but the stand-alone one. Can you help me? Regards, Ulrich Hi Ulrich, I have got a few additional questions for you: mvn assembly:singleat the command prompt, what happens? This should create file called maven-assembly-plugin-bin.zipto the targetdirectory. Also, please note that my example application creates the binary distribution only when the correct goal of the Maven Assembly plugin is executed. In real life scenario it might be better to create the distribution during the packagelifecycle phase. Superb tutorial worked like a charm! David, Thank you! It is great to hear that this blog entry was useful to you. Great article; very helpful Thank you. It is good to hear that I could help you out. Great post :) Thank you! Thanks a lot man, you saved my life. Danilo - Brazil You are welcome! Thank you for leaving a comment. It is always nice to get feedback from my readers. Wow... THANK YOU! After days of searching and reading posts on StackOverflow, I was unable to come up with a suitable approach to a jar packaging requirement I have. This approach is exactly what I needed since I'm dealing with RSA jars that throw security exceptions if unpacked/repackaged into an uber-jar. As a newer person to maven, I found this article extremely helpful. Again, thank you! You are welcome! Great article! Very util, nice good! Thank you. I am happy to hear that you like it. Very useful. Thanks a lot. You are welcome! Thank you for this article. I had been searching for days. You are welcome. I am happy hear that I could help you out. :) Thanks for the article! It seems to be exactly what I'm looking for. I have one problem - when I package your "assembly-plugin" example, there is created only maven-assembly-plugin.jar file but not you mentioned directory structure. I am a beginner with Maven, what am I doing wrong? Do need these directories exist before I do a package command? Hi, You are not doing anything wrong. The package goal doesn't create the binary distribution. It simply packages the project and creates the jar file. You can create the binary distribution by running the following command at command prompt: mvn assembly:single I will add this information to the README of the example application. Thanks for pointing this out. Hi Petri, one more thing. When I call mvn assembly:single plugin ZIP file is created but doesn't contain jar file, please see this screenshot - Do I need to cal another command to create a jar file? I have tried mvn compile, mvn package but no jar has been created. Thanks again. Actually, If you use the command mvn assembly:single, the package phase is not invoked. I didn't expect this. I tested this myself now (I used Maven 3.1.1) and it seems that you have two options: Yes, "mvn assembly:assembly" works for me, thanks. You made my day! Petri, back to my last comment - I forgot to call "mvn package" command, now It works like a charm! You can delete my comment, thanks. If you don't mind, I will not delete it because I forgot that running the mvn assembly:single command doesn't invoke the package phase (see my answer to your previous comment). Maybe one suggestion to improve your code - is there some chance how to use artifactId or name for new jar file name? Your code works but generates "maven-assembly-plugin.jar" / "maven-assembly-plugin.zip". It's not a problem, it works, but... :) You can change the file names by using the finalNameelement. For example, if you change it to: <finalName>foo</finalName>, the names of the created files are: foo.jar and foo.zip. Your way of describing everything in this piece of writing is genuinely nice, all be capable of easily be aware of it, Thanks a lot. Hi Petri -- Thanks for the great blog. I have a question that is stumping me. I am using the assembly plugin with a bin distribution -- it works great. My script makes use of a flexible shell script in /bin, config files in /etc, logs in /log, jars in /lib. -- everything is great. However, I have to add some new functionality that requires shading. I've never worked with the shade plugin. I am also not super excited to completely revamp what I have now with the assembly plugin set up. My question is -- any tips on shading a handful of dependency jars, but keep the rest of the assembly configuration in tact (including some external jars, my /etc config files, etc). Any help much appreciated! -b Hi Bryan, I haven't used to Maven Shade plugin either but it seems that it is possible to include and exclude the artifacts which are added to the "Uber jar" created by the Shade plugin. It is also possible to include and exclude the artifacts added to the binary distribution. I would try to solve this problem by following these steps: I have no idea if this will work but based on the documentation of these two plugins, it should work. If you get it to work, it would be interesting to hear about it! Hi Petri, Greetings !! As always your blog is very helpful. Do you have any plans to make this work with multi-module project ? Keep up the good work. Adil. Thank you for your kind words. I really appreciate them. About your question: I can write a separate tutorial about using the Maven Assembly plugin in a multi-module projects. Do you have any special requirements which I should take into account? Hi Petri, Perfect !! I have been trying it without success. Regarding what i want is more of an open ended question. I am trying to architect a template where i have I tried to use the moduleset and tried to create a sample project. so far i have been unsuccessful. Partly due to my limited knowledge of advanced maven knowledge. Let me know if the above seems like a wrong approach to creating a template for rapid app development. Regards, Adil Fulara. PS: How do I subscribe to update from you on this page ? I didnt get any email regarding your follow up comment. Hi Adil, I got a pretty good idea about your requirements. I will try to create a similar project structure and write a blog post about it. At the moment it is not possible to get an email notification when someone answers to your comment. I will contact you by using your email address tomorrow. Awesome Petri..!! I have made it a routine to check your blog regularly. Your articles ate clear, precise and to the poi point. I always recommend my friends to check your tutorials too. Feel free to share your project on github and let me know if i can assist. After all its all a learning process and good to know where I made mistakes. Regards, Adil Fulara. This is very nice and clear. I want to go one step further though. I have the ProjectArtifact with a name like ${artifactid}-{version}.jar, but on the archive I want this to be just ${artifcatid}.jar. Any idea how to do this? I haven't personally tried this but you could try to use the outputFileNameMappingelement as suggested here. Hi Petri, how can i run the wicket programs with out using maven and eclipse like IDEs.Please help. Hi Kumar, If you have the war file of the application, you can deploy it to a servlet container. If you have to create the war file, you have to use a some kind of build tool (Ant, Gradle, or Maven). Many thanks!!! You are welcome! Thank you for you explain, but you didn't add in the begin of tuto what artifactID we should choose when we create new Maven Project There are no universal rules for selecting the artifactIdof a Maven project. Just pick something which describes the project in question or follow the guidelines of your employer (if it is a work project). very useful article and neat pom files. I hacked(?) it to generate zip file for multi module project. Wondering if you can extend this article to multi module setup (github code works for single module) Thank you for your comment. I added your blog post idea to my Trello board, and I will write the blog post in the future. Thank you for this nice tutorial. It was really helpful. One question: Why is it preferable to create a zip containing the libs and runnable scripts instead of creating a simple large jar-file with all dependencies included and which can be executed simply by double-clicking? Thank you Hi Julian, If you are creating a binary distribution for an application, I think that you can use the approach that makes sense to you (the single jar approach might be a better choice). On the other hand, if you are creating a binary distribution for a library or a framework, packaging its dependencies into a single jar doesn't make any sense because you must not decide how the users of your library (or framework) should manage their dependencies. Thank you very much for your answer. Now i get the point :) You are welcome! As others have already mentioned, awesome tutorial. Very thorough. Thank you for your kind words. I really appreciate them. Nice one, helped me !:) Thanks! I am happy to hear that this blog post was useful to you. This was immensely helpful. Precise and to-the-point tutorial! Thanks a lot! You are welcome! I am happy to hear that this tutorial was useful to you. Thank you. You've gave me at least few hours of sleep. You are welcome. I am happy to hear that this blog post helped you to get some sleep. In your example log4j.properties is packed in maven-assembly-plugin.jar. If I will want to change logging settings for binary distribution it requires unzipping log4j.properties, changing and zipping file back. Is it possible to place log4j.properties in 'maven-assembly-plugin/conf' directory and add additional entry to manifest 'Class-Path' attribute with maven? It should be possible. The Maven Jar plugin should support multiple classpath entries. I only needed to add this executions stuff to the assembly-plugins configuration in pom.xml to get exactly what I wanted with your help: org.apache.maven.plugins maven-assembly-plugin src/assembly/bin-assembly.xml make-assembly package single Unfortunately Wordpress strips XML elements from comments :( Anyway, It is good to hear that you were able to solve your problem! And... the question is ... how do I make me sure that my "classpath of my "example application" is added to the created manifest file." ? Can you explain that? Thank you. I am using Eclipse. Check out the section titled: 'Creating the Jar File'. If you look at the configuration of the Maven Jar plugin, you notice that you can do this by setting the value of the addClasspathelement to true. 2016 and this is still relevant. Chapeau and thanks for the info. :-) You are welcome! Petry You are awesome! The simple way of explaining complex things and actually make it working in real is a distinct property that not every blogger has in my opinion. Kudos!!! Thank you for your kind words. I really appreciate them. It is nice blog with good understanding. I am facing below issue. I have created jar called domain.jar (which contains only .class files) using assembley plugin and now I push this to nexus. I am trying to use this dependency jar in my other application with classifier and I am able to do that. Now the issue, while downloding domain.jar it comes with extra jars which is not required. I also mention false in descriptor file. Works, Thanks! I have 2 class main in my project, can i create 1 runnable binary distibution with 2 jars? Hi, If you want to create two jar files from one POM file, you have to add two executions to the configuration of the Maven Jar plugin (take a look at this post). After you have created these jar files, it should be fairly easy to add them to the binary distribution by using the Maven Assembly plugin.
https://www.petrikainulainen.net/programming/tips-and-tricks/creating-a-runnable-binary-distribution-with-maven-assembly-plugin/
CC-MAIN-2022-27
refinedweb
3,995
59.3
31 Days of Mango | Day #18: Using Sample Data 31 Days of Mango | Day #18: Using Sample Data Join the DZone community and get the full member experience.Join For Free This article is part of a series called 31 Days of Mango. Today, we are going to explore another great feature of Expression Blend by creating some sample data that our application can use. Many times, when you start building an application, you want to see what the data will look like in the user interface well before the database (or web service) is actually ready. To do this, we can use Expression Blend. Since I have covered Expression Blend and many of its features in the past, I’ll give you some recommended reading here: - 31 Days of Windows Phone | Day #4: System Theming - 31 Days of Windows Phone | Day #6: Application Bar - 31 Days of Windows Phone | Day #29: Animations - Expression Blend Training Kit For today’s article, we’re just going to dive right in. Creating Your Windows Phone Application As with most of my posts in this series, I have also created a video to demonstrate what I am trying to accomplish with this article. I will explain everything that is shown in the video, but if you’d prefer to watch it first, here it is: We will start by creating a new Windows Phone project. You’ve hopefully done this many times already in Visual Studio 2010, so I will walk you through doing this in Expression Blend this time. Once you have your new project, with your MainPage.xaml page open, we are going to add a ListBox to our page. To do this, click the arrow in the left-side menu bar, choose controls, and click the ListBox icon. Once you’ve selected the ListBox, you can click and drag one on to your design surface. I’ve expanded my ListBox to take up the entire space inside my ContentPanel Grid that was created by default when I created my project. (This is all of the space below the “page name” text on the screen. Creating Some Sample Data If you look in the top right corner of Expression Blend, you should see a tab with the word “Data” on it. Open that tab. By clicking the “New Sample Data” button on the top right of this panel, we will be able to get started creating our sample data. This will bring up the “New Sample Data” dialog box. Give your data a name (I named mine Furniture, to follow the example that I used in the video.) You’ll notice that you have the option to define this data in your project, or on the specific page. I recommend choosing “Project” because it will create a bunch of useful structures in your application that you can use in a more permanent fashion. Clicking OK will take you back to the Data tab, with a few new things added. We now have a structure that should look familiar to anyone that has worked with a database before. “Furniture” represents our database, and “Collection” is a table in that database. “Property1” and “Property2” are fields in the Collection table. I am going to add two new properties to the database, and rename the existing two, so that things are a little more descriptive. Collection will become “Chairs”, and we now have 4 properties: SKU, Price, Description, and Image. At the right end of each of the properties, there is an icon to indicate what type of data it is. For Description, I want it to be a long string of words. You can do this by choosing the “Lorem Ipsum” string type. This will give us random strings of 20 words, with no word being longer than 8 characters. We want the Image property to actually contain images, so you should choose the Image type. You can specify your own set of images if you’d like, and we’ll do that later in this article. I will quickly set the Price property to a String/Price type, and the SKU to be a Number value, with 6 character values. If you click on the “View Sample Data” button to the right of the “Chairs” title, you will be shown a grid of data that contains randomized data for each of the properties we have specified. By changing the value of the “Number of records” box at the bottom, you can determine how many data records you would like to use. So there you have it. We’ve created some sample data. At this point, you’re probably staring at the sample data above trying to figure out how it knew to use images of chairs. Regardless of what you name your data structures, if you use an Image type, and don’t specify a set of images, this set of chair images will always be used. No magic, just a tricky demo. To change the images to something more appropriate to your project, you can re-open the definition for the Image property that I created, and specify a folder on your computer. When you do this, you’ll end up with sample values that look more like this (assuming you used the same images I did.) Now it’s time to actually use this data. Using Sample Data in a Windows Phone App First, even though this is called “Sample Data"," if you have a small set of static data that you’re intending to use in your application, there’s absolutely nothing wrong with making this a permanent part of your application. That being said, in order to get this data into our ListBox that we created much earlier in this article, you can simply drag the “Chairs” node from the Data tab directly into your Listbox control, like this (the blue box is my mouse dragging the data to the ListBox…click to enlarge): The moment you let go of your data, it will immediately create two things for you: - An DataTemplate for laying out the individual elements in the ListBox. - A binding between the SampleData and your ListBox. In this example, the DataTemplate is stored directly in our MainPage.xaml page, and looks like this: <DataTemplate x: <StackPanel> <TextBlock Text="{Binding Description}"/> <Image Source="{Binding Image}" HorizontalAlignment="Left" Height="64" Width="64"/> <TextBlock Text="{Binding Price}"/> <TextBlock Text="{Binding SKU}"/> </StackPanel> </DataTemplate> You will see that our ListBox contains an ItemTemplate binding to this DataTemplate, and the ItemsSource is defined as our Chairs data: <ListBox Margin="8,8,0,8" ItemTemplate="{StaticResource ChairsItemTemplate}" ItemsSource="{Binding Chairs}"/> In order to edit how the DataTemplate appears, we can use Expression Blend to do this too. Right-click on your ListBox in Expression Blend, and choose Edit Additional Templates > Edit Generated Items (ItemTemplate) > Edit Current By doing this, you should notice that several things in our interface have changed. First, at the top of our design pane, it now indicates that we’re working on our ListBox’s ItemTemplate. Second, take a look at your Objects and Timeline panel. It is now specifically focused on the contents of the ItemTemplate, which contains 3 TextBlocks and an Image control. We can also now manipulate the elements of our ItemTemplate directly on the design surface. For example, I just made the first image larger. Since we are editing the template, you’ll notice that all of the images also got larger. In the next image, you’ll notice that I moved the Description TextBlock to the bottom of the template, and right aligned all of the TextBlocks. The Price has also had its font size increased, and the foreground color is now green. At this point, unless you have a need to make this prettier, you have a working application. Running it in the emulator will result in an application that has a scrolling ListBox. This is how it appears, based on the changes I have made: Where Is All Of This Data Stored? Since we can deploy this application to the emulator, and the data appears, and we can use and manipulate it, you might be wondering just how this is stored in our application, and how it works. If you take a look at your project structure, you should notice a new folder named SampleData. Inside this folder, you’ve got a Furniture.xaml file which contains your actual generated data. Its contents look like this: <!-- ********* DO NOT MODIFY THIS FILE ********* This file is regenerated by a design tool. Making changes to this file can cause errors. --> <SampleData:Furniture xmlns: <SampleData:Furniture.Chairs> :Furniture.Chairs> </SampleData:Furniture> The actual structure of the data in this file is defined by the Furniture.xaml.cs file, which contains the classes and properties that we defined when we first created our Sample Data. You can see that each of the properties are shown here, as well as references to the location of our sample images. // ********* DO NOT MODIFY THIS FILE ********* // This file is regenerated by a design tool. Making // changes to this file can cause errors. namespace Expression.Blend.SampleData.Furniture { using System; // To significantly reduce the sample data footprint in your production application, you can set // the DISABLE_SAMPLE_DATA conditional compilation constant and disable sample data at runtime. #if DISABLE_SAMPLE_DATA internal class Furniture { } #else public class Furniture : System.ComponentModel.INotifyPropertyChanged { public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } public Furniture() { try { System.Uri resourceUri = new System.Uri("/Day18_BlendSampleData;component/SampleData/Furniture/Furniture.xaml", System.UriKind.Relative); if (System.Windows.Application.GetResourceStream(resourceUri) != null) { System.Windows.Application.LoadComponent(this, resourceUri); } } catch (System.Exception) { } } private Chairs _Chairs = new Chairs(); public Chairs Chairs { get { return this._Chairs; } } } public class ChairsItem : System.ComponentModel.INotifyPropertyChanged { public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } private double _SKU = 0; public double SKU { get { return this._SKU; } set { if (this._SKU != value) { this._SKU = value; this.OnPropertyChanged("SKU"); } } } private string _Price = string.Empty; public string Price { get { return this._Price; } set { if (this._Price != value) { this._Price = value; this.OnPropertyChanged("Price"); } } } private System.Windows.Media.ImageSource _Image = null; public System.Windows.Media.ImageSource Image { get { return this._Image; } set { if (this._Image != value) { this._Image = value; this.OnPropertyChanged("Image"); } } } private string _Description = string.Empty; public string Description { get { return this._Description; } set { if (this._Description != value) { this._Description = value; this.OnPropertyChanged("Description"); } } } } public class Chairs : System.Collections.ObjectModel.ObservableCollection<ChairsItem> { } #endif } Finally, you have the Furniture_Files folder, which contains all of the actual sample images that we’re using. Because we used both the default chair images, as well as my own collection, you’ll find that each of the images is inside this folder for you. As the comments show, if you’re planning on editing this Sample Data from Expression Blend again, don’t do it. Your changes will be discarded. These are generated code files, and should be treated as such. Summary So, there you have it. You have an application that uses Sample Data that you created in Expression Blend to populate a ListBox, using a DataTemplate. There are many places where you might find this technique handy, so keep it in mind for static data sets rather than using something more complicated like a database or web service. If you would like to download this entire working Windows Phone application that uses this Sample Data, click the Download Code button below: Tomorrow, Doug Mair is back to discuss adding Tilt Effects to your XAML elements, giving some interaction to your user’s touch gestures. See you then! Source: Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/31-days-mango-day-18-using
CC-MAIN-2020-29
refinedweb
1,984
55.44
Graphics Assignment: MyPaint Wes Griffin & Sue Evans Press space bar for next slide MyPaint Description For this assignment you will be implementing a very simple paint program. The user should be able to draw circles in a window by clicking with the mouse. You should allow the user to specify a fill color for the circle. Your program should exit when the user double-clicks the mouse. Graphics Library Quick Reference Step 0 Make a lab8 directory in your 201/labs directory. Copy the graphics.py file from Mrs. Evans' directory into your lab8 directory. cp /afs/umbc.edu/users/b/o/bogar/pub/graphics.py . Use emacs to create a lab8.py in your lab8 directory. Important Note: You need to use a different version of Python for this lab. To run your program type: /usr/local/bin/python2.4 lab8.py If you run your program and see ImportError: No module named Tkinter you need to use the above command to run your program. MyPaint Tips Think about what you need to draw a circle: a center point and a radius The distance between two points P(x1, y1) and Q(x2, y2) is: sqrt( [ (x2 - x1) ** 2 ] + [ (y2 - y1) ** 2 ] ) where a ** b means a to the b'th power. You should plan on using an Entry object to allow the user to set the fill color. Caution: When the user types the color to use into the entry box, it is always either preceeded by or followed by a space. Since the color name won't be recognized with leading or trailing spaces, you'll need to strip them off. We'll make use of the string library's strip : circle.setFill(string.strip(fill)) To detect a double-click, check to see if the two points are the same. Step 1 Begin by opening a window and using two mouse clicks to draw a circle, where the first mouse click is to be used as the center of the circle and the second click is on the edge of the circle. Just use a default circle at first (black outline). Put this code in a loop that stops when the two mouse clicks are in the same position. Step 2 Next add the prompt and the Entry object to ask the user for a fill color. Don't forget to import string at the top of your program. Use the stripped string the user entered to set the fill color for the circle. Bonus Step Add another prompt and Entry object so that the user can also enter the outline color for the circle. Challenge Step Expand your program to look more like the original paint program with choices of what to draw along the left border. Allow the user to draw circles, rectangles and lines. The user should still be allowed to enter the outline and fill colors for the circle and rectangles.
http://www.csee.umbc.edu/courses/undergraduate/CMSC201/fall09/labs/lab_graphics2.html
crawl-003
refinedweb
489
72.36
I've looked everywhere online and can't find the answer i'm looking for. I don't know how to import the scanner and loop it properly to take the user's inputs and turn them into the polynomials and i have a lot of trouble with the syntax of doing so... I don't know much Java at all, but this is the assignment and what i have so far... god bless anyone willing to help! My assignment is: You are asked to write a Java program that helps the user add and print polynomials of any degree. If possible, students are encouraged to make the program help the user multiply two polynomials of any degree. 1. Polynomial Class This class stores polynomials as a linked list of terms. Each term contains a coefficient and a power of an unknown variable x. The implementations of linked lists in chapter 3 of the textbook or the LinkedList class in the Java collections package can be in this assignment. For example, the polynomial P(x) = 5x 10 + 9x 7 – x – 10 can be stored as list of terms (5, 10), (9, 7), (-1, 1) and (-10, 0) in the linked list. This class should have one or more constructors and methods to add, multiply, and print polynomials. For example, a polynomial P above can be constructed as: Polynomial p = new Polynomial(); p.addTerm(-10, 0); p.addTerm(-1, 1); p.addTerm(9, 7); p.addTerm(5, 10); For example, to multiply the polynomial P(x) by another polynomial Q(x), the following method can be used: Polynomial r = p.multiply(q); Of course, this multiply method can be after both polynomials were instantiated. To add the polynomial P(x) to another polynomial Q(x), the following method can be used: Polynomial r = p.add(q); To print the polynomial P(x) on the output console, the following method can be used: p.print(); In this assignment, the program should ask the user for the polynomial(s) and the operation to apply. You can parse the line input by the user or use a menu-driven input. Students are free to choose whichever is easier to implement. For simplicity, the main method must be implemented inside the Polynomial class to make the program consist of only a single file. What i have so far is: import java.util.ArrayList; import java.util.Scanner; public class PolynomialMath<E> { public static class Node <E> { private E element; private Node<E> next; public Node(E e, Node<E> n){ element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0; public PolynomialMath() { } public int size() { return size; } public boolean isEmpty() {return size == 0;} public E first() { if (isEmpty()) return null; return head.getElement(); } public E last() { if (isEmpty()) return null; return tail.getElement(); } public void addFirst(E e) { head = new Node<>(e, head); if (size == 0) tail = head; size++; } public void addLast(E e) { Node<E> newest = new Node<>(e, null); if (isEmpty()) head = newest; else tail.setNext(newest); tail = newest; size++; } public E removeFirst() { if (isEmpty()) return null; E answer = head.getElement(); head = head.getNext(); size--; if (size == 0) tail = null; return answer; } public static void main(String args[]){ ArrayList l = new ArrayList(); System.out.println("Enter the input"); Scanner input=new Scanner(System.in); String a =input.nextLine(); l.add(a); for (int i = 0; i < l.size(); i++) { System.out.println(l.get(i)); } System.out.println(l); } }
https://www.javaprogrammingforums.com/object-oriented-programming/40046-im-having-trouble-adding-polynomials-using-singly-linked-list.html
CC-MAIN-2020-34
refinedweb
603
56.05
0 Hello, I am still green to the C programming language. I am writing a multi-dimensional array program to store strings into an array. The program requires error checking to avoid overflow. I am using Visual Studio 2008. I am using a Windows O/S. The program runs fine on the first past through, but skips over the prompt on the next run. Here is the output: Please enter a word: word Are you finished: Please enter a word: Here is my code: #include "stdafx.h" #include <string.h> #define MAX 25 #define LENGTH 16 int _tmain(int argc, _TCHAR* argv[]) { char store[MAX][LENGTH]; char word[LENGTH]; int i=0; char exit='n'; while(exit!='y'||i==MAX) { printf("Please enter a word: "); scanf("%s",&word); printf("\n"); while(strlen(word)>15) { memset(word, NULL, LENGTH); printf("You have entered a word that is to large.\n"); printf("Please enter a word: "); scanf("%s",&word); } strcpy(store[i], word); printf("Are you finished: "); scanf("%c",&exit); i++; } return 0; } Thank you for your help. Edited by WaltP: Added CODE Tags
https://www.daniweb.com/programming/software-development/threads/273103/need-help-please
CC-MAIN-2018-30
refinedweb
182
75.71
Please add an option to import / export all editor settings (especially Tools / Options / Editor / Formatting; maybe other tabs in Editor options too?), preferably to a single .xml file. Rationale: 1) it would make working with multiple ide versions and/or multiple workstations much easier. 2) It would make frequent re-installing (especially important to people developing NB and / or simply testing nightlies) clean or semi-clean easier. 3) It would make working in a team with set code formatting conventions much easier, team leader could simply export his/her settings and mail them to other team members. Yes, there is Project / Properties / Formatting / Use project specific settings options, but it doesn't apply to all possible scenarios. On the other hand, it would probably be easy to reuse most of this functionality code for full import / export. Thanks for this RFE. Exporting/Importing formatting settings would certainly be very useful. Please see also issue #75875, issue #99494, issue #11848. Yes, and I would add to export/import formatting/style setting in checkstyle format, so (as it is my case) it is easier for a Netbeans user to share style settings with other team members that use Eclipse or InteliJ. *** Bug 193198 has been marked as a duplicate of this bug. *** alied: Is it really possible to import checkstyle config to eclipse or idea formatting? They haven't even got native checkstyle checking. I add Formatting/indentation and Formatting/java to export, import options. Integrated into 'main-golden', will be available in build *201208290001* on (upload may still be in progress) Changeset: User: Milutin Kristofic <mkristofic@netbeans.org> Log: #143494 - Import / export editor formatting settings Is this still not possible with CND? I'm trying build 20120926001 and found no options to export C/C++ and C/C++ Headers formatting settings. This is especially annoying when upgrading IDEs. I have to change the settings to my liking every time. Why is this marked as resolved / fixed when it has only been resolved for Java? What about other languages? I am still seeing incomplete exports as of 8.0.1 Steps to reproduce: 1. Configure your formatting preferences. 2. Export all preferences. (Also, observe that in the export dialog, All -> Formatting -> Indentation is the only option.) 3. Remove local NetBeans config, change formatting preferences, or otherwise destroy the current preferences. 4. Import previously exported settings. 5. Observe the formatting preferences have not been imported. This needs to be for C++ as well! This is a feature that is needed for sure - the ability to pass around a code formatting file between people on a team is a must have. Bump up the priority! Thanks!
https://netbeans.org/bugzilla/show_bug.cgi?id=143494
CC-MAIN-2015-11
refinedweb
442
58.48
Hello all, I have a few questions about C++ (I have programmed quite a bit in VBA and some in the past using C++, and have been working through relearning C++). Currently I am working through a bit on the "Char" variable type. regarding the following (from the FAQ): * Don't use system("pause") to pause your program if possible. Use getchar( ) if you are using C and cin.get( ) if you are using C++. I was using cin.get() to do this recently, but ran into a problem where it no longer worked? See the code below for where it was happening. I am not sure why cin.get() was working before, but as soon as I added a cin of my own, it stopped. I also am not entirely sure why this is not working as I thought it would, using the following program, I attempted to implement a couple things where it takes a user input char array (I am not sure I did this correctly) and then determines how many numbers/letters are in it. It also does not seem to like using a space as an input (for example if I put "this is a testing string 12345!" as the input, it seems to only get "this" from it). Now, I have found through some cout-ing that when I create the char array, it fills it with random stuff (so I get incorrect results). Am I completely missing something regarding the use of the Char here? #include <iostream> #include <string> #include <cctype> using namespace std; //define the functions used later int numbLetters(char inputChar[], int length); int numbNumbers(char inputChar[], int length); int main() { // There is a difference between single and double quotes // When declaring a character use single quotes // For strings use double quotes char userChar[50]; cout << "Input some text to be tested" << endl; cin >> userChar; cout << endl << "You gave: " << userChar << endl; cout << "Number letters: " << numbLetters(userChar, (int)sizeof(userChar)/sizeof(char)); cout << endl << "You gave: " << userChar << endl; cout << "Number of numbers: " << numbNumbers(userChar, (int)sizeof(userChar)/sizeof(char)) << endl; //pause (needs two for some reason?) actually I have no idea exactly how this works cin.get(); cin.get(); system("pause"); return 0; } int numbLetters(char inputChar[], int length) { int counter = 0; //loop through entire string to find number of characters for (int i=0; i<length; i++) { if (isalpha(inputChar[i])) counter++; } cout << endl << "str length: " << length << endl; return counter; } int numbNumbers(char inputChar[], int length) { int counter = 0; //loop through entire string to find number of numbers for (int i=0; i<length; i++) { if (isdigit(inputChar[i])) counter++; } return counter; } edit - ok while no forum searches helped, it turns out that someone else in the currnet last 5 posts or so was having a similar problem about the char input being cut off by a space and was referenced to here - - but I'm not sure how that relates to the Char array I have above Edited by enderland: further forum browsing
https://www.daniweb.com/programming/software-development/threads/269085/several-c-questions-related-to-char
CC-MAIN-2017-17
refinedweb
503
61.9
Chapter 3: Simulating GUI Events This time, let's assume you want to test the behavior of our QLineEdit class. As before, you will need a class that contains your test function: #include <QtWidgets> #include <QTest> class TestGui: public QObject { Q_OBJECT private slots: void testGui(); }; The only difference is that you need to include the Qt GUI class definitions in addition to the QTest namespace. void TestGui::testGui() { QLineEdit lineEdit; QTest::keyClicks(&lineEdit, "hello world"); QCOMPARE(lineEdit.text(), QString("hello world")); } In the implementation of the test function we first create a QLineEdit. Then we simulate writing "hello world" in the line edit using the QTest::keyClicks() function. Note: The widget must also be shown in order to correctly test keyboard shortcuts. QTest::keyClicks() simulates clicking a sequence of keys on a widget. Optionally, a keyboard modifier can be specified as well as a delay (in milliseconds) of the test after each key click. In a similar way, you can use the QTest::keyClick(), QTest::keyPress(), QTest::keyRelease(), QTest::mouseClick(), QTest::mouseDClick(), QTest::mouseMove(), QTest::mousePress() and QTest:) #include "testgui.moc".
https://doc.qt.io/qt-6/qttestlib-tutorial3-example.html
CC-MAIN-2021-31
refinedweb
181
53
Bookmark star icon in location bar should be blue (not black) when filled in VERIFIED FIXED in Firefox 56 Status () P1 normal People (Reporter: Virtual, Assigned: Gijs) Tracking (Blocks: 1 bug, {nightly-community, ux-consistency}) Firefox Tracking Flags (firefox-esr52 unaffected, firefox54 unaffected, firefox55 unaffected, firefox56 verified) Details (Whiteboard: [photon-structure]) Attachments (2 attachments) Created attachment 8882236 [details] Bookmark star icon.png Bookmark star icon in doorhanger/panelUI menu should be black to be consistent with other icons.Created attachment 8882236 [details] Bookmark star icon.png Bookmark star icon in doorhanger/panelUI menu should be black to be consistent with other icons. Has Regression Range: --- → irrelevant Has STR: --- → irrelevant Whiteboard: [photon][triage] → [photon] [triage] Are there specs of what the colour of the star should be when it's filled in, in the location bar? Maybe that shouldn't be black? I couldn't find any specs (nothing on )... Flags: needinfo?(shorlander) Whiteboard: [photon] [triage] → [photon-structure] [triage] at the table today shorlander said it should be filled in blue as it was before. Flags: qe-verify+ Priority: -- → P2 QA Contact: gwimberly Could able to track the bug in Firefox 56. Affected version : Firefox Nightly 56.0a1 [Build ID: 20170630030203] Affected OS: Windows 10.0 X 64 status-firefox56: --- → affected Assignee: nobody → gijskruitbosch+bugs Status: NEW → ASSIGNED Iteration: --- → 56.2 - Jul 10 Flags: needinfo?(shorlander) Priority: P2 → P1 Gah, I thought this was the bug that had discussion, but that was bug 1377227. Too many bugs. Anyway, from what I gathered there, and in bug 1377202 and here, I think this patch is correct... in theory. This uses 0.6 opacity because that's what the spec says, but IMO for dark themes (or at least the compact dark theme) this makes the icon too grey/light, because the current color isn't white but off-white already. I don't know that we should depend on that being the case for all dark themes, though... bug 1377227 comment 3 suggests it's not always the case that we'll use a dark location bar for dark themes (maybe non-compact dark lwthemes do something else)? I took the liberty of assuming the blue highlight colour for starred bookmarks shouldn't be opacity-d into greyness, so I'm forcing opacity: 1 there. Given the above, I'd like a UI review for this, especially as concerns behaviour on compact dark, other dark lwthemes, and (of course) the default theme. Trypush with builds (should be up 'soon' given they're artifact builds): (In reply to :Gijs from comment #1) > Are there specs of what the colour of the star should be when it's filled > in, in the location bar? Maybe that shouldn't be black? I couldn't find any > specs (nothing on > )... Yeah that has the specs for what the buttons / icons should look like. I can add the active state. Should be Blue 50: #0a84ff (In reply to :Gijs from comment #5) > I took the liberty of assuming the blue highlight colour for starred > bookmarks shouldn't be opacity-d into greyness, so I'm forcing opacity: 1 > there. Yeah, should be full opacity. Comment on attachment 8882605 [details] Bug 1377165 - use correct fill colours and opacity for in-urlbar icons, ::: browser/themes/shared/browser.inc.css:112 (Diff revision 1) > display: none; > } > > +%ifdef MOZ_PHOTON_THEME > +.urlbar-icon, > +#urlbar toolbarbutton { What's the point of this selector? The bookmark and page action buttons seem to have the urlbar-icon class, as they should. ::: browser/themes/shared/browser.inc.css:118 (Diff revision 1) > + -moz-context-properties: fill, fill-opacity; > + fill: currentColor; > + fill-opacity: 0.6; > + color: inherit; > +} > +%endif Please move this to urlbar-searchbar.inc.css. ::: browser/themes/shared/toolbarbutton-icons.inc.css:65 (Diff revision 1) > } > > +#star-button[starred] { > + fill-opacity: 1; > + fill: var(--toolbarbutton-icon-fill-attention); > +} #star-button should be in urlbar-searchbar.inc.css too. toolbarbutton-icons.inc.css is for full-fledged buttons on the toolbar, not other UI elements that happen to be <toolbarbutton>. Attachment #8882605 - Flags: review?(dao+bmo) → review- Comment on attachment 8882605 [details] Bug 1377165 - use correct fill colours and opacity for in-urlbar icons, ::: browser/themes/shared/urlbar-searchbar.inc.css:101 (Diff revision 3) > + fill: var(--toolbarbutton-icon-fill-attention); > +} > + > +/* Page action popup */ > +#page-action-bookmark-button { > + list-style-image: url("chrome://browser/skin/bookmark-hollow.svg"); This and related icons need to set a fill color. Can you file a new bug on this? Attachment #8882605 - Flags: review?(dao+bmo) → review+ (In reply to Dão Gottwald [::dao] from comment #11) > This and related icons need to set a fill color. Can you file a new bug on > this? Filed bug 1377535. Also filed bug 1377537 to move the zoom button CSS. status-firefox54: --- → unaffected status-firefox55: --- → unaffected status-firefox-esr52: --- → unaffected I've just realized that Stephen is out this week. Rather than keeping it in the current state (which has 3 separate issues filed against it - bug 1377227, bug 1377202 and this one) for another week, I think I'll just go ahead and get this landed (which I believe addresses all 3 bugs), and if we need follow-up changes we can do those in separate bugs. Pushed by gijskruitbosch@gmail.com: use correct fill colours and opacity for in-urlbar icons, r=dao Status: ASSIGNED → RESOLVED Last Resolved: 2 years ago status-firefox56: affected → fixed Resolution: --- → FIXED Target Milestone: --- → Firefox 56 I'm marking this bug as VERIFIED, as issue is fixed, starting from Mozilla Firefox Nightly 56.0a1 (2017-07-04). Thanks. Status: RESOLVED → VERIFIED status-firefox56: fixed → verified Flags: qe-verify+ Screenshots: Version: Trunk → 56 Branch QA Contact: gwimberly → Virtual
https://bugzilla.mozilla.org/show_bug.cgi?id=1377165
CC-MAIN-2019-04
refinedweb
949
55.54
docker runEstimated reading time: 29 minutes Edge only: This is the CLI reference for Docker CE Edge versions. Some of these options may not be available to Docker CE stable or Docker EE. You can view the stable version of this CLI reference or learn about Docker CE Edge. Description Run a command in a new container Usage docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Options Parent command Extended description The docker run command first creates a writeable container layer over the specified image, and then starts it using the specified command. That is, docker run is equivalent to the API /containers/create then /containers/(id)/start. A stopped container can be restarted with all its previous changes intact using docker start. See docker ps -a to view a list of all containers. The docker run command can be used in combination with docker commit to change the command that a container runs. There is additional detailed information about docker run in the Docker run reference. For information on connecting a container to a network, see the “Docker network overview”. Examples Assign name and allocate pseudo-TTY (–name, -it) $ docker run --name test -it debian root@d6c0fe130dba:/# exit 13 $ echo $? 13 $ docker ps -a | grep test d6c0fe130dba debian:7 "/bin/bash" 26 seconds ago Exited (13) 17 seconds ago test This example runs a container named test using the debian:latest image. The -it instructs Docker to allocate a pseudo-TTY connected to the container’s stdin; creating an interactive bash shell in the container. In the example, the bash shell is quit by entering exit 13. This exit code is passed on to the caller of docker run, and is recorded in the test container’s metadata. Capture container ID (–cidfile) $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test" This will create a container and print test to the console. The cidfile flag makes Docker attempt to create a new file and write the container ID to it. If the file exists already, Docker will return an error. Docker will close this file when docker run exits. Full container capabilities (–privileged) $ docker run -t -i --rm ubuntu bash root@bc338942ef20:/# mount -t tmpfs none /mnt mount: permission denied This will not work, because by default, most potentially dangerous kernel capabilities are dropped; including cap_sys_admin (which is required to mount filesystems). However, the --privileged flag will allow it to run: $ docker run -t -i --privileged ubuntu bash root@50e3f57e16e6:/# mount -t tmpfs none /mnt root@50e3f57e16e6:/# df -h Filesystem Size Used Avail Use% Mounted on none 1.9G 0 1.9G 0% /mnt The --privileged flag gives all capabilities to the container, and it also lifts all the limitations enforced by the device cgroup controller. In other words, the container can then do almost everything that the host can do. This flag exists to allow special use-cases, like running Docker within Docker. Set working directory (-w) $ docker run -w /path/to/dir/ -i -t ubuntu pwd The -w lets the command being executed inside directory given, here /path/to/dir/. If the path does not exist it is created inside the container. Set storage driver options per container $ docker run -it --storage-opt size=120G fedora /bin/bash This (size) will allow to set the container rootfs size to 120G at creation time. This option is only available for the devicemapper, btrfs, overlay2, windowsfilter and zfs graph drivers.. Mount tmpfs (–tmpfs) $ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image The --tmpfs flag mounts an empty tmpfs into the container with the rw, noexec, nosuid, size=65536k options. Mount volume (-v, –read-only) $ docker run -v `pwd`:`pwd` -w `pwd` -i -t ubuntu pwd The -v flag mounts the current working directory into the container. The -w lets the command being executed inside the current working directory, by changing into the directory to the value returned by pwd. So this combination executes the command using the container, but inside the current working directory. $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash When the host directory of a bind-mounted volume doesn’t exist, Docker will automatically create this directory on the host for you. In the example above, Docker will create the /doesnt/exist folder before starting your container. $ docker run --read-only -v /icanwrite busybox touch /icanwrite/here Volumes can be used in combination with --read-only to control where a container writes files. The --read-only flag mounts the container’s root filesystem as read only prohibiting writes to locations other than the specified volumes for the container. $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh By bind-mounting the docker unix socket and statically linked docker binary (refer to get the linux binary), you give the container the full access to create and manipulate the host’s Docker daemon. On Windows, the paths must be specified using Windows-style semantics. PS C:\> docker run -v c:\foo:c:\dest microsoft/nanoserver cmd /s /c type c:\dest\somefile.txt Contents of file PS C:\> docker run -v c:\foo:d: microsoft/nanoserver cmd /s /c type d:\somefile.txt Contents of file The following examples will fail when using Windows-based containers, as the destination of a volume or bind-mount inside the container must be one of: a non-existing or empty directory; or a drive other than C:. Further, the source of a bind mount must be a local directory, not a file. net use z: \\remotemachine\share docker run -v z:\foo:c:\dest ... docker run -v \\uncpath\to\directory:c:\dest ... docker run -v c:\foo\somefile.txt:c:\dest ... docker run -v c:\foo:c: ... docker run -v c:\foo:c:\existing-directory-with-contents ... For in-depth information about volumes, refer to manage data in containers Publish or expose port (-p, –expose) $ without publishing the port to the host system’s interfaces. Set environment variables (-e, –env, –env-file) $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash This sets simple (non-array) environmental variables in the container. For illustration all three flags are shown here. Where -e, --env take an environment variable and value, or if no = is provided, then that variable’s current value, set via export, _TEST_BAR=FOO TEST_APP_42=magic helloWorld=true 123qwe=bar org.spring.config=something # pass through this variable from the caller TEST_PASSTHROUGH $ TEST_PASSTHROUGH=howdy=howdy HOME=/root 123qwe=bar org.spring.config=something $= HOME=/root 123qwe=bar org.spring.config=something Set metadata on container (-l, –label, –label-file) A label is a key=value pair that applies metadata to a container. To label a container with two labels: $ docker run -l my-label --label com.example.foo=bar ubuntu bash The my-label key doesn’t specify a value so the label defaults to an empty string( ""). To add multiple labels, repeat the label flag ( -l or --label). The key=value must be unique to avoid overwriting the label value. If you specify labels with identical keys but different values, each subsequent value overwrites the previous. Docker uses the last key=value you supply. Use the --label-file flag to load multiple labels from a file. Delimit each label in the file with an EOL mark. The example below loads labels from a labels file in the current directory: $ docker run --label-file ./labels ubuntu bash The label-file format is similar to the format for loading environment variables. (Unlike environment variables, labels are not visible to processes running inside a container.) The following example illustrates a label-file format: com.example.label1="a label" # this is a comment com.example.label2=another\ label com.example.label3 You can load multiple label-files by supplying multiple --label-file flags. For additional information on working with labels, see Labels - custom metadata in Docker in the Docker User Guide. Connect a container to a network (–network) When you start a container use the --network flag to connect it to a network. This adds the busybox container to the my-net network. $ docker run -itd --network=my-net busybox You can also choose the IP addresses for the container with --ip and --ip6 flags when you start the container on a user-defined network. $ docker run -itd --network=my-net --ip=10.10.9.75 busybox If you want to add a running container to a network use the docker network connect subcommand. You can connect multiple containers to the same network. Once connected, the containers can communicate easily need only another container’s IP address or name. For overlay networks or custom plugins that support multi-host connectivity, containers connected to the same multi-host network but launched from different Engines can also communicate in this way. Note: Service discovery is unavailable on the default bridge network. Containers can communicate via their IP addresses by default. To communicate by name, they must be linked. You can disconnect a container from a network using the docker network disconnect command. Mount volumes from container (–volumes-from) $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd The --volumes-from flag mounts all the defined volumes from the referenced containers. Containers can be specified by repetitions of the --volumes-from argument. The container ID may be optionally suffixed with :ro or :rw to mount the volumes in read-only or read-write mode, respectively. By default, the volumes are mounted in the same mode (read write or read only) as the reference container. Labeling systems like SELinux require that proper labels are placed on volume content mounted into a container. Without a label, the security system might prevent the processes running inside the container from using the content. By default, Docker does not change the labels set by the OS. To change the label in the container context, you can add either of two suffixes :z or :Z to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The z option tells Docker that two containers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to read/write content. The Z option tells Docker to label the content with a private unshared label. Only the current container can use a private volume. Attach to STDIN/STDOUT/STDERR (-a) The -a flag tells docker run to bind to the container’s STDIN, STDOUT or STDERR. This makes it possible to manipulate the output and input as needed. $ echo "test" | docker run -i -a stdin ubuntu cat - This pipes data into a container and prints the container’s ID by attaching only to the container’s STDIN. $ docker run -a stderr ubuntu echo test This isn’t going to print anything unless there’s an error because we’ve only attached to the STDERR of the container. The container’s logs still store what’s been written to STDERR and STDOUT. $ cat somefile | docker run -i -a stdin mybuilder dobuild This is how piping a file into a container could be done for a build. The container’s ID will be printed after the build is done and the build logs could be retrieved using docker logs. This is useful if you need to pipe a file or something else into a container and retrieve the container’s ID once the container has finished running. Add host device to container (–device) $ docker run --device=/dev/sdc:/dev/xvdc \ --device=/dev/sdd --device=/dev/zero:/dev/nulo \ -i -t \ ubuntu ls -l /dev/{xvdc,sdd,nulo} brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/nulo It is often necessary to directly expose devices to a container. The --device option enables that. For example, a specific block storage device or loop device or audio device can be added to an otherwise unprivileged container (without the --privileged flag) and have the application directly access it. By default, the container will be able to read, write and mknod these devices. This can be overridden using a third :rwm set of options to each --device flag: $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc You will not be able to write the partition table. Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:rw -. Restart policies (–restart) Use Docker’s --restart to specify a container’s restart policy. A restart policy controls whether the Docker daemon restarts a container after exit. Docker supports the following restart policies: $ docker run --restart=always redis This will run the redis container with a restart policy of always so that if the container exits, Docker will restart it. More detailed information on restart policies can be found in the Restart Policies (–restart) section of the Docker run reference page. Add entries to container hosts file (–add-host) You can add other hosts into a container’s /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named docker: $ docker run --add-host=docker:10.180.0.1 --rm -it debian root@f38c87f2a42d:/# ping docker PING docker (10.180.0.1): 48 data bytes 56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms 56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms ^C--- docker ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms Sometimes you need to connect to the Docker host from within your container. To enable this, pass the Docker host’s IP address to the container using the --add-host flag. To find the host’s address, use the ip addr show command. The flags you pass to ip addr show depend on whether you are using IPv4 or IPv6 networking in your containers. Use the following flags for IPv4 address retrieval for a network device named eth0: $ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1` $ docker run --add-host=docker:${HOSTIP} --rm -it debian For IPv6 use the -6 flag instead of the -4 flag. For other network devices, replace eth0 with the correct device name (for example docker0 for the bridge device). Set ulimits in container (–ulimit) Since setting ulimit settings in a container requires extra privileges not available in the default container, you can set these using the --ulimit flag. --ulimit is specified with a soft and hard limit as such: <type>=<soft limit>[:<hard limit>], for example: $ docker run --ulimit nofile=1024:1024 --rm debian sh -c ` The values are sent to the appropriate syscall as they are set. Docker doesn’t perform any byte conversion. Take this into account when setting the values. For nproc usage Be careful setting nproc with the ulimit flag as nproc is designed by Linux to set the maximum number of processes available to a user, not to a container. For example, start four containers with daemon user: $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top The 4th container fails and reports “[8] System error: resource temporarily unavailable” error. This fails because the caller set nproc=3 resulting in the first three containers using up the three processes quota set for the daemon user. Stop container with signal (–stop-signal) The --stop-signal flag. Optional security options (–security-opt) On Windows, this flag can be used to specify the credentialspec option. The credentialspec must be in the format or registry://keyname. Stop container with timeout (–stop-timeout) The --stop-timeout flag sets the timeout (in seconds) that a pre-defined (see --stop-signal) system call signal that will be sent to the container to exit. After timeout elapses the container will be killed with SIGKILL. Specify isolation technology for container (–isolation) This option is useful in situations where you are running Docker containers on Windows. The --isolation <value> option sets a container’s isolation technology. On Linux, the only supported is the default option which uses Linux namespaces. These two commands are equivalent on Linux: $ docker run -d busybox top $ docker run -d --isolation default busybox top On Windows, --isolation can take one of these values: The default isolation on Windows server operating systems is process. The default (and only supported) isolation on Windows client operating systems is hyperv. An attempt to start a container on a client operating system with --isolation process will fail. On Windows server, assuming the default configuration, these commands are equivalent and result in process isolation: PS C:\> docker run -d microsoft/nanoserver powershell echo process PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo process PS C:\> docker run -d --isolation process microsoft/nanoserver powershell echo process If you have set the --exec-opt isolation=hyperv option on the Docker daemon, or are running against a Windows client-based daemon, these commands are equivalent and result in hyperv isolation: PS C:\> docker run -d microsoft/nanoserver powershell echo hyperv PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo hyperv PS C:\> docker run -d --isolation hyperv microsoft/nanoserver powershell echo hyperv Configure namespaced kernel parameters (sysctls) at runtime The --sysctl sets namespaced kernel parameters (sysctls) in the container. For example, to turn on IP forwarding in the containers network namespace, run this command: $ docker run --sysctl net.ipv4.ip_forward=1 someimage Note: Not all sysctls are namespaced. Docker does not support changing sysctls inside of a container that also modify the host system. As the kernel evolves we expect to see more sysctls become namespaced. Currently supported sysctls IPC Namespace: kernel.msgmax, kernel.msgmnb, kernel.msgmni, kernel.sem, kernel.shmall, kernel.shmmax, kernel.shmmni, kernel.shm_rmid_forced Sysctls beginning with fs.mqueue.* If you use the --ipc=hostoption these sysctls will not be allowed. Network Namespace: Sysctls beginning with net.* If you use the --network=hostoption using these sysctls will not be allowed.
https://docs.docker.com/edge/engine/reference/commandline/run/
CC-MAIN-2017-17
refinedweb
3,103
53.92
The problem with object oriented languages is that you often have to wrap up single functions in a class even when there’s no real reason for that class to exist. This is especially true for many ‘service’ classes. For example, for a long time I used to have something like this in most of my projects: public interface IDateProvider { DateTime Now(); } public class DateProvider : IDateProvider { public DateTime Now() { return DateTime.Now(); } } I would register my DateProvider with Windsor like this: container.Regisgter( Component.For<IDateProvider>().ImplementedBy<DateProvider>() ); Being able to set the current time in unit tests is essential if you’re doing any kind of logic that does date computations, and this served me well. But it’s a lot of boiler plate just to get the current date. It also means that I have to build a mock IDateProvider for my unit tests and set stubs on it – more irritating boiler plate. But C# is also quite a good functional language and Windsor deals with delegates just as easily as it deals with interfaces. These days I no longer have an IDateProvider, but just a simple delegate: public delegate DateTime Now(); Which I register like this: container.Register( Component.For<Now>().Instance(() => DateTime.Now), ); Now any component that needs to know the current DateTime value simply has a dependency on the Now delegate: public class MyComponent { private readonly Now now; public MyComponent(Now now) { this.now = now; } public void DoSomething() { var currentTime = now(); .... } } And it’s really easy to stub out for unit tests: var now = new DateTime(2010, 2, 15); var myComponent = new MyComponent(() => now); myComponent.DoSomething(); This is also a great way for providing infrastructure services when your infrastructure isn’t IoC container friendly. How about this: public delegate string CurrentUser(); ... container.Register( Component.For<CurrentUser>().Instance(() => HttpContext.Current.User.Identity.Name) ); In some ways delegates are more flexible than interfaces since you don’t have to declare that a particular lambda or method implements the delegate, so long as the signature matches you’re good. Indeed, if Windsor did currying we could probably remove most of our service classes and simply write our software as static methods. But that’s another blog post ;) 15 comments: Interesting idea, however it is best practise not to declare your own delegates- use Func and Action instead. Hi Richard, Sorry, I disagree. In this case it's definitely best to declare your own delegates. Of course you could use Func<DateTime> in my example, in fact that's how I started out implementing these things. But say you wanted some other service that provided say, next weekend. Then you'd have two Func<DateTime> and no way to for the container to differentiate between them, because you can only have one instance defined for a single service. It's also more intention revealing. Better to have a dependency on 'Now' than 'Func<DateTime>', there's no clue with the latter about what that DateTime represents. Mike, Didn't think about the container not working- good point. In which case I'd probably stick to using interfaces! Another option, would be to define a class as follows: public static class CurrentTime { public static Func Now = () => new DateTime(); } This can then be used as follows: DateTime now = CurrentTime.Now(); Console.WriteLine(CurrentTime.Now()); CurrentTime.Now = () => new DateTime(2010, 2, 15); Console.WriteLine(CurrentTime.Now()); Console.ReadLine(); Sorry about the code formatting! Yet another option would be to use TypeMock isolator or Moles. Mike, Sorry, just realised CurrentTime should be: public static class CurrentTime { public static Func Now = () => DateTime.Now; } Hi Richard, Well, the whole point of the post is that interfaces are too much ceremony in many cases. In any case, you can think of delegates as method interfaces, except that they're more flexible in some ways. Like the fact that you don't have to declare a method or lambda as implementing a particular delegate. I don't like the smell of your static field 'Now', but TBH, I can't see any benefit of using the container over it currently. Of course if I had my 'currying container' then the compositional possibilities would steer me back towards the container based delegate, but you've got me thinking, thanks :) After a few seconds' more thought... The reason I don't like the static Func<DateTime> field is because there's some vagueness about what its value might be. In my tests I'd have to set it to some stubbed value, but then set it back to it's original value afterwards, which I'd have to be aware of. The test would be expected to know far too much about the mechanics of CurrentTime.Now. By passing a delegate in as a dependency we're being explicit about it's implementation for that particular instance of the client component. Mike, Yes the downside to the static Func is the fact it returns the new value after assignment! I was going to add that! I'm sure that could lead to people writing unrepeatable tests if they were not careful! Yikes! TBH I'm not happy with any of the approaches 100%, but I still think the interface based approach is the most common and pragmatic, and that is the approach I always use in situations like this (until I'm convinced otherwise). The thing I don't like about this: container.Register( Component.For().Instance(() => DateTime.Now), Is it isn't obvious to call DateTime.Now either- this is even less obvious to me than having to add teardown behaviour to the static Func example I described earlier! Also how would it work if you are storing container configuration in a config file (I'm not familar with Windsor- but can't imagine this is possible/desirable?) I've always thought of delegates as being the equivalent to a single method interface (obviously it is not that simple, you can't do Interface.BeginInvoke!) but a useful comparision sometimes. I look forward to your posts on 'currying containers'. +1 on currying containers "I look forward to your posts on 'currying containers'." - Didn't you notice, the last sentence was a link to the post on currying containers :) Mike, You talked in a previous post about relying on the container, and making calls to the container as "a bit of an anti-pattern". Could you possibly elaborate on how that would, or wouldn't, apply in conjunction with this? Good to learn new tricks. Cheers mate. Thanks for the kind words Nick. Yes, scattering calls to container.Resolve() around your code is an anti-pattern. Here I'm simply pointing out that delegates can define service contracts in the same way as interfaces. Does this make no sense? Hi Mike, Once again a great post. The currying containers was me trying to be funny (obviously it failed! I'll try to be less humorous in the future! Richard, sorry, sense of humour bypass :p I'm so into my currying I forget how stupid it sounds. No, no it does seem a good way to do things and perfectly explained. I was just digging a bit deeper, wondering if it gets a bit easy to start relying on the container when maybe you shouldn't? Nick, "I was just digging a bit deeper, wondering if it gets a bit easy to start relying on the container when maybe you shouldn't?" Well of course the whole application structure relies on the container to wire it together. In this example we're registering functions with the container so that they can be passed by the container to components that depend on them. The magic is that we never see any direct reference to the container in our code (apart from the component registration and single call to resolve buried deep in our framework).
http://mikehadlow.blogspot.com/2011/02/delegates-make-great-container.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+CodeRant+%28Code+rant%29
crawl-003
refinedweb
1,314
62.27
Opened 23 months ago Last modified 23 months ago #20423 assigned Bug Template renderer does not parse numeric variables Description Currently a Variable is defined, according to the django template manual, as : Variable names consist of any combination of alphanumeric characters and the underscore ("_"). If a variable is composed of numbers only, it will not get its context data correctly, coming across as an int. This patch assigns the appropriate context data to the Variable class when it encounters an integer. Here's the current behavior: from django.template.base import Template from django.template.base import Context t = Template("{{ 123 }}") t.render(Context()) u'123' t = Template("{{ foo }}") t.render(Context({"foo":"bar"})) u'bar' Attachments (1) Change History (7) Changed 23 months ago by antonio@… comment:1 Changed 23 months ago by anonymous - Needs documentation unset - Needs tests unset - Patch needs improvement unset Definitely not full fix, it does cause regressions elsewhere - namely the view loading a changelist in the Admin. comment:2 Changed 23 months ago by charettes The issue is valid but IMHO the code should be fixed to disallow such uses of number variables and the documentation fixed accordingly (e.g Variable name can't start with an integer). I know this might be backward incompatible but I can't see any valid use case for this behavior, looks more like a side effect/oversight of the access by index feature. Am I missing something here? comment:3 Changed 23 months ago by charettes - Patch needs improvement set - Triage Stage changed from Unreviewed to Accepted comment:4 Changed 23 months ago by iapain - Owner changed from nobody to iapain - Status changed from new to assigned comment:5 Changed 23 months ago by iapain I totally agree with charettes that there may not be an use case for this. Hence, I'd propose to add warning first and then raise an exceptions if integer or float variable names are used. Does it makes sense? comment:6 Changed 23 months ago by anonymous Makes more sense as a doc ticket, agreed! Thanks for looking! Antonio Patch to assign context to numeric Variables in Django templating
https://code.djangoproject.com/ticket/20423
CC-MAIN-2015-14
refinedweb
359
61.06
This article is for the beginner level audience who has just started working on user controls. Sometimes while using user controls, you may need to access methods declared either on the parent user control and parent page from the child user control. Here is a simple solution for that. I came across the same issue where I needed to access the method declared on the parent user control from the child user control and ended up searching for options. I got a simple solution using abstract classes as it was not possible to access the user defined methods in the Parent object. Here is the little trick. I have created abstract class AbstractUserControl and AbstractPage, where AbstractUserControl is inherited from System.web.UI.UserControl and AbstractPage is inherited from System.Web.UI.Page. I placed these two classes inside the App_code folder so that it will be accessible anywhere in the site. Here is the abstract class with the declaration of abstract methods. These abstract methods will be overridden in the Page or UserControl where they need to be called from the child. namespace CodeProject.Sample { public abstract class AbstractPage : System.Web.UI.Page { public AbstractPage() { // // TODO: Add constructor logic here // } // implementation in the concrete class public abstract void callMefromChild(); } } I added a similar abstract class for a user control to inherit. Next, I use these abstract classes to achieve the functionality. Now it is pretty straight forward to access the parent page method from the child control. Here is the snippet: protected void btnClick_Onclick(Object sender, EventArgs e) { ((AbstractPage)Parent.Page).callMefromChild(); } Simple type casting of Parent.Page to the AbstractPage classes exposes the user defined method in the Page. We can use the same trick for accessing the method declared on the parent user control from the child user control. I am a long time user of The Code Project and never contributed to the community. Today I am starting with this simple article and expecting to come up with some interesting stuff later on. Hope this helps somebody. Please free to post a comment if you need any clarifications. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/user-controls/usecontrolsample.aspx
crawl-002
refinedweb
359
56.96
kgoldrunner #include <kgrgameio.h> Detailed Description The KGrGameIO class handles I/O for text-files containing KGoldrunner games and levels. The games and levels that are released with KGoldrunner are installed in a "System" directory (e.g. .../share/apps/kgoldrunner/system). Those that the user composes or edits are stored in a "User" directory (e.g. $HOME/.kde/share/apps/kgoldrunner/user). The class handles files in either KGoldrunner 2 format or KGoldrunner 3 format. In KGoldrunner 2 format, the data for games is in file "games.dat" and the data for levels is in multiple files "levels/<prefix><nnn>.grl". Each level-file has at least one line containing codes for the level's layout and can have optional extra lines containing a level name and a hint. In KGoldrunner 3 format, each game is in one file called "game_<prefix>.txt", containing the game-data and the data for all levels. The data formats are the same as for KGoldrunner 2, except that the first character of each line indicates what kind of data is in the rest of the line. "G" = game data, "L" = start of level data, with the level-number following the "L", and " " = level data, with line 1 being the layout codes, line 2 (optional) the level name and lines >2 (optional) the hint. This class is used by the game and its editor and is also used by a utility program that finds game names, level names and hints and rewrites them in a format suitable for extracting strings that KDE translators can use. KGoldrunner Game-File IO Definition at line 58 of file kgrgameio.h. Constructor & Destructor Documentation Default constructor. - Parameters - Definition at line 27 of file kgrgameio.cpp. Member Function Documentation Find and read data for games, into a list of KGrGameData structures. Definition at line 34 of file kgrgameio.cpp. Find and read data for a level of a game, into a KGrLevelData structure. Returns an OK or error status, but does not display error messages. Definition at line 182 of file kgrgameio.cpp. Find and read data for a level of a game. Can display error messages. Definition at line 151 of file kgrgameio.cpp. Definition at line 356 of file kgrgameio.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2019 The KDE developers. Generated on Mon Nov 11 2019 05:53:38 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/4.14-api/kdegames-apidocs/kgoldrunner/html/classKGrGameIO.html
CC-MAIN-2019-47
refinedweb
420
57.57
lp:wpf-math Created by Alexander Regueiro on 2009-10-11 and last modified on 2010-06-13 This branch represents active development. Rendering may not be considered stable in general. - Get this branch: - bzr branch lp:wpf-math Members of WPF-Math Developers can upload to this branch. Log in for directions. Branch merges Related bugs Related blueprints Branch information - Owner: - WPF-Math Developers - Status: - Development Recent revisions - 7. By Scott Weinstein on 2010-06-13 merge in chages - 6. By Scott Weinstein on 2010-06-13 removed ununsed 3.5 to 4.0 classes. Comment out not-ready ExpressionToTex code - 5. By Scott Weinstein on 2010-06-08 add backward compat support for 3.5 - 4. By Scott Weinstein on 2010-06-06 replace try/catch block with TryGetValue() - 3. By Scott Weinstein on 2010-06-06 Add support for non WPF entry points, such as Web and unit test to use the api - 2. By Alexander Regueiro on 2010-06-05 Put all classes in library in WpfMath namespace. Added RenderToBitmap method on TexRenderer. - 1. By Alexander Regueiro on 2010-06-05 Initial commit. Branch metadata - Branch format: - Branch format 7 - Repository format: - Bazaar repository format 2a (needs bzr 1.16 or later)
https://code.launchpad.net/~wpf-math-dev/wpf-math/devel
CC-MAIN-2016-07
refinedweb
206
60.92
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). Hi, I'm very new to C4D python and am having trouble doing the simplest thing. Eventually I want to create a script that controls quite a few things related to Takes. However, my first baby step is simply to create a new Take and add it to the list. My first attempt seems to work but when I right-click my new take I cannot delete it and certain behaviours crash C4D! Can someone tell me what I am doing wrong, as I've copied most of this script from a Cineversity script that seems to behave just fine. def main(): td = doc.GetTakeData() pt = td.GetMainTake() ct = td.SetCurrentTake(pt) nt = td.AddTake("",pt,pt) td.InsertTake(nt,pt,2) td.SetCurrentTake(nt) nt.SetName("My Take") c4d.EventAdd() Any help is much appreciated. welcome to the forum. Your major mistake is to try to clone the main take which apparently is meant to be unique. Cheers, zipit """ This will clone the first take after the main take and insert it as a new take. """ import c4d def main(): """ """ take_data = doc.GetTakeData() # This is the top most take node in the take window. It cannot be deleted # and basically is only there to "bind all the other takes together". main_take = take_data.GetMainTake() # Its first child which is the first "actual" take. child_take = main_take.GetDown() if child_take is None: msg = "Please insert at least one take to clone." raise RuntimeError(msg) # Not really needed. # current_take = take_data.SetCurrentTake(main_take) # Creates a new take and inserts it. The first argument is the name of # the node (which does not seem to work), the second the insertion point # and the third the cloning template. When you clone here from the main # take, you will get a "second main take", i.e. one that is not # deletable and you probably will confuse the heck out of Cinema. new_take = take_data.AddTake("", main_take, child_take) new_take.SetName("Bob is your uncle.") # We do not need to invoke TakeData.InsertTake(). # Set the new take as the active one and tell Cinema that we did # poke around in the scene graph. take_data.SetCurrentTake(new_take) c4d.EventAdd() if __name__ == "__main__": main() Hi @zipit . Thank you so much for your help. I don't think I would have ever figured this out for myself! Out of interest - How did you learn C4D Python? I can't find any ground up courses or tutes. They're either too advanced for beginners or so basic they just show you how to drag and drop commands from the script log. I've already taken a general python course. But I find the structure of C4D python baffling and need some help understand the basic structure of data in the program. Python was not my first programming language, so I sort of had a heads start. Learning a programming language is always a painful process to some degree, just like for a natural language. The only thing that helps is practice. I am also not too convinced about the quality or general helpfulness of programming language books or tutorials, they are usually a mess IMHO. But you are probably more after learning the Python standard libraries and the Cinema API, not the principal syntax of Python. There are for once a collection of sort of narrative scripts by Maxon which explain the basics of their classic API. And I know that @Cairyn has some Python stuff on Patreon. I have never seen the content, its probably also classic API only, but judging from his posts here, he seems to put quite some work into it. And then there is of course Cineversity, but that you already know. Getting to know APIs can only achieved by practice in the end. The first time doing it might be a bit daunting, but you will see its not so bad in the end. Just dive in and prepare for some bruises in the beginning Hi @davidtodman first of all welcome to the plugincafe community I would like to point you to few rules for your next topics (I've set up this one correctly, but don't worry this is your first topic) @zipit already provide you the answers, but I just wanted to point you to take_system Github repository where you can find several examples about the Take system, finally, I know it's C++ but you will see the code is very similar and you can find more verbal information about the Take system in Take System Overview. With that's said I guess we all agree that for the moment the best way to learn the Cinema 4D API is to simply practice and ask questions here whenever there is something you don't understand. Cheers, Maxime. @zipit Thank you for taking the time to reply. Much appreciated. @m_adam Thanks for your help. Apologies for not following the rules. I'm struggling with the rules of Python at the moment so it's not surprising! Will try to be a better poster in future.
https://plugincafe.maxon.net/topic/12947/create-new-take-using-python
CC-MAIN-2021-39
refinedweb
883
73.47