Assignment Chef icon Assignment Chef

Browse assignments

Assignment catalog

33,401 assignments available

[SOLVED] 5CCE2HMT Heat and Mass Transfer Coursework 1 Computing Distillation

Coursework 1: Computing Distillation 5CCE2HMT Heat and Mass Transfer 1    Overview—Ethanol Production using Distillation Distillation is a process that separates substances from liquid mixtures using boiling and condensation heat transfer. Early evidence of distillation was found on Akkadian tablets dated circa 1200 BCE. Distillation was used in many parts of the world by early centuries of the Common Era [1]. For instance, the Chinese were distilling a beverage from rice beer by 800 BCE, and arrack was distilled in the East Indies. The Arabs produced a distilled beverage from wine, and the Romans started distilling spirits before 100 CE. Production of distilled spirits was reported in Britain before the Roman conquest (43–84 BCE). As of 2022, the UK accommodates 820 spirit distilleries (Figure 1), and the number continues to grow. Besides beverages, distillation is a common process widely found in the chemical industry. Figure 1: Distillery. Ethanol (common alcohol) is produced by fermenting sugars dissolved in water with yeast. Under appropriate conditions, yeast converts the sugars into ethanol and carbon dioxide and dies when the ethanol concentration reaches about 15% by weight (wt%). After filtration, a water-ethanol mixture is obtained. Distillation is then used to produce concentrated ethanol. In this process, the water-ethanol mixture is heated and boiled. As ethanol has a lower boiling point than water, ethanol evaporates more readily. The ethanol-rich vapour is then collected and condensed in a separate container, resulting in a concentrated ethanol solution (Figure 2 (a)). As shown in the phase diagram (Figure 2 (b)), a 15wt% mixture of ethanol and water undergoes boiling at approximately 88 °C, generating a 60wt% mixture of vapour. The liquified 60wt% mixture boils at ca. 81 °C, producing a more ethanol-rich vapour with a concentration of 80wt%. The vapour is condensed again, and the mixture then boils at ca. 79 °C, yielding a mixture with a concentration reaching 96.5wt%. At this point, the aqueous solution of 96.5wt% ethanol is an azeotrope and cannot be further purified by distillation. Figure 2: (a) Schematic of distillation process of ethanol-water mixtures.  (b) Phase diagram repre- senting bubble point and dew point of ethanol-water mixtures [2]. In this coursework, you are asked to compute the distillation rate using a simplified heat transfer model.  To complete the task, you will need to be able to appropriately use heat transfer correlations and perform iterative calculations to reach a solution. 2 Problem Description A mixture of water and ethanol is boiling on a horizontal 304 stainless-steel plate (thickness:  1 mm, thermal conductivity:  16.7 W/(m · K)) at 0.1 MPa. To improve the energy efficiency of the entire plant, saturated water steam at 150 °C exhausted from a separate process is used to heat the plate. The water steam is fed to the plate and condenses on its underside. Complete the following tasks: 1.  Obtain the following quantities for various ethanol concentrations i.e.,  15wt%, 60wt%, 80wt% and 95.6wt%: (a)  Surface temperatures of each side  (hot and cold sides) of the plate in °C. (b)  Heat transfer coefficients of each side of the plate in kW/(m2·K). (c) Heat flux in kW/m2 . (d)  Hourly rate of steam generation of the mixture per unit area in kg/(m2·hr). (e)  Hourly rate of condensate of water per unit area in kg/(m2·hr) 2.  Repeat the above calculation for water steam temperatures of 180 。C and 200 °C + last 2 digits of your K-number e.g., if K21012345, then 200 + 45 = 245 °C. Assume that the process is steady state, and the concentration of the mixture is unchanged during each distillation stage.  Concentration gradients within the boiling liquid are negligible.  Use Tables 1 and 2 for the thermophysical properties necessary for the analysis. 3 Report and Mark Scheme Your report should be written on A4 paper with margins of at least 2 cm and a font size of 12pt in a suitable font.  It should be no longer than 8  pages in length, excluding the programme script.  Your report should contain at least the following information: (A) detailed calculation procedures [20 marks]; (B) your programming script used for calculation [20 marks]; (C) tables to summarise the calculated values of (a)–(e) (see the previous section).  The table should look like [50 marks]: The final [10 marks] are for the presentation of your report. 4 Correlations and Properties 4.1 Heat transfer correlation for condensation Heat transfer coefficient h for condensation at a subcooling of ∆Tsub on a wall with a length of L, inclined at θ is given by Gerstmann and Griffith [3] as where Nu and Ra are dimensionless Nusselt and Rayleigh numbers, respectively, and are given as where g is the acceleration due to gravity, k is the thermal conductivity, ρ is the density, µ is the viscosity, σ is the surface tension of the fluid, and hf g is the latent heat of vaporisation. The subscripts l and v represent liquid and vapour phases, respectively. For the present problem, L = 1 m and θ = 0°as we are interested in the distillation performance per unit area i.e., 1 m × 1 m of a horizontal surface. 4.2 Heat transfer correlation for boiling To calculate h for nucleate boiling at a system pressure of p, use Kutateladze’s correlation given below [4]. where is the Laplace constant, P r is the Prandtl number, q ′′ is the heat flux, and ν = µ/ρ is the kinematic viscosity. Keep in mind that we are making big assumptions to simplify the analysis here. One of them is the use of Equation 3 for boiling of mixtures although it was originally derived for pure liquids. Mixtures make boiling phenomena even more complex! There are additional effects due to the presence of secondary component, which have not yet been understood completely. Many experimental results of boiling of binary mixtures show lower heat transfer coefficients than those in their corresponding pure fluids. Therefore, this simple analysis you are doing in the coursework should be considered a rough estimation for the design of distillation process. In practice, you would need to collect actual data from separate experiments to improve accuracy of your analysis. Nevertheless, boiling of mixtures found in common distillation process is still an active research topic. If you are interested in this topic, please refer to a review article by Xu et al. [5]. 4.3 Fluid properties Thermophysical properties of saturated water and ethanol-water mixture are summarised in Tables 1 and 2. If you cannot find exact values for a specific temperature of interest (e.g., 245 °C if your K-number ends with 45), estimate those by linear interpolation between the two closest values (e.g., those at 240 °C and 250 °C). Table 1: Thermophysical properties of saturated water calculated using CoolProp [6]. Table 2: Thermophysical properties of saturated ethanol-water mixture at 0.1 MPa. The molar fraction of ethanol xethanol, bubble point temperature Tb, densities ρl and ρv, latent heat of vaporisation hlv, thermal conductivity kl , viscosity µl and Prandtl number P rl were calculated using CoolProp [6]. The surface tension σ was calculated using Phan’s model [7].

$25.00 View

[SOLVED] ECON0006/0010 Introduction to Mathematics for Economics Problem Set 3 2025

Department of Economics ECON0006/0010: Introduction to Mathematics for Economics Problem Set 3, 2025 General Instructions These are the instructions you will see on the final exam. They do not apply to this prob- lem set! But it is good to familiarize yourself with themanyway. Time allowance: You have THREE (3) hours to complete this examination. If you have been granted SoRA extra time and/or rest breaks, your individual examination duration will be extended pro-rata. Calculators (UCL approved models only) are permitted in this examination. Number of Questions Answered Policy: You are expected to attempt all questions. Recording of answers: Use the separate paper provided to do all the necessary rough work, calculations or drafting of answers. If you need more paper for rough work, alert the invigilators by raising your hand. Enter   your final answers, answer steps, and explanation/interpretation (as required) in the answer-boxes provided within this question-and-answer booklet. Only results, workings, diagrams, and writing   provided within the appropriate boxed answer-spaces will be marked. Comments, notes or any-thing else outside of the provided boxed answer-spaces will be ignored. Do not remove any pages from this answer booklet! If you inadvertently damage your answer booklet during the exam, alert the invigilators and request a new answer booklet. You will not get additional time! Submission of answers: Ensure that you have provided in the spaces above your correct student number (seeyour student card) and your correct name, in block capitals. Failure to provide this information may mean that  any marks awarded cannot be allocated to you correctly. Only submit your answer booklet! Submitting a damaged or incomplete answer booklet may result in a mark of 0. Instructions for this Exam . This exam consists of 5 questions, 1]-5], and each question has 4 sub-questions, a]-d]. All sub- questions have the same weight. . You are expected to attempt all questions, there is no selection of questions to be made. . Use the provided ‘scrap-paper’ to do your workings and solve the questions. . In each answer-box, complete the answer options at the top, and then complete the ‘workings’ or ‘comments’ or ‘sketch’ sections as appropriate. . You will likely need to select the important steps in your workings on the scrap paper and transcribe them into the answer boxes. Don’t use the boxes for initial, rough, workings and draft answers. 1] Using spectral methods in Matrix Algebra Consider the following 3 ×3 matrix . a] Compute the eigenvalues mj of M as well as the normalisedeigenvectors m(^)j. . b] Verify that we have . c] Find a matrix R = M1/2 for which R2 = M and which has only real-valued components. . d] Consider the system differential equations given by for some constant vectorf(-)0 = {1, -1, 1}. Find a solution withx(-)[0] = {0, 1, 0}? 2] Gradient-learning Consider a firm that produces a service or good for which it can charge an exogenous price per   unit q = 5, and its production technology gives it an output off[K, L] = Log[K] + 3 Log[L] units as a function of the inputs of labour L and capital K. In order to acquire these inputs the firm faces exogenous labor and capital market prices of w = 2 and r = 3/2 respectively. . a] Find the profit π[K, L] the company makes as a function of its labour and capital inputs. . b] Determine the optimal inputs {L*, K*} and the corresponding optimal output f* = f[K*, L*], and demonstrate that it is indeed a profit maximum π* . If we assume that the firm is ‘learning’ what their optimal inputs are via gradient-learning, then over time the firm’s will inputs will evolve according to . c] Assume that α = 1. Show that the optimum {L*, K*} is a stationary state and use small deviations {δL[t], δK[t]} from the optimum, to show this stationary state is stable under gradient- learning. . d] Determine the rate-of-change of profit dw/d π* and dr/d π* at the current prices w = 2 and r = 3/2. 3] Making a Matrix from Vectors Consider the vectors b(→)1 = {1, 1, 0} and b(→)2 = {1, -1, 1}. . a] Find a third vector b(→)3 such that it is orthogonal to both b(→)1 and b(→)2, and then normalize all three into an orthonormal basis b(^)jwith j = 1, 2, 3. . b] Consider the matrix verify that it is an orthogonal matrix and find a similar expression for BT. . c] Consider the matrix Calculate R[0] and M = dy/d R[y] y=0 and demonstrate this means that R[y] is a solution to the initial value problem . d] Consider quadratic functions of x ∈ [-1, 1] and the two linearly independent functions Find a third function β3 [x] that forms an orthonormal set with the other two, calculate the function and demonstrate that or an arbitrary quadratic function f[x] = a + bx + cx2 we get 4] Optimization problems Consider the quadratic function We want to find the local optimum, subject to the constraint . a] Write down the Lagrangian for this problem, and the first-order conditions. . b] Calculate the bordered Hessian HB. . c] Determine the constrained, local, optima ford = -1 and c = 2/1 , find its type, and sketch a few isoquants ofF[x(-)] and the constraint. Discuss whether there are restrictions on the value of d when we want to ensure that in generalx(-)* is not a saddle-point. d] What changes when the constraint becomes an inequality constraint g[x(=)] ≤ 0? 5] A Quadratic flow Consider the following vector-field and the difference equation . a] Determine all stationary states x(→)s . Consider small deviations from the stationary states . b] Find a linear approximation for the difference equation for δx[t] around each of the stationary states. . c] Find the eigenvalues of the corresponding Jacobians, determine whether or not the stationary states are also asymptotic states for pathsx(-)[t] starting sufficiently close to the stationary state, and sketch the ‘flow’ close to each of the stationary points. . d] Determine the eigenvectors of the Jacobians, sketch the overall ‘flow’ in a single sketch containing all stationary states.

$25.00 View

[SOLVED] 21-259 Calculus in Three Dimensions Lecture 2 Spring 2025SPSS

21-259: Calculus in Three Dimensions Lecture #2 Spring 2025 The Cross Product Definition: A 2×2 determinant of the matrix is the quantity For a 3×3 matrix, we can compute the determinant as follows: Example 1. Compute the determinants and Definition: Let u = 〈u1,u2,u3〉 and v = 〈v1, v2, v3〉 be vectors in R 3 . The cross product (or vector product) of u and v is the vector given by u × v = 〈u2v3 −u3v2,u3v1 −u1v3,u1v2 −u2v1〉. The cross product of u and v is really a determinant: Note: the cross product is defined only for vectors in R3 - there is an analogous quantity for vectors in R 2 (although it is interpreted as a scalar) and it can be generalized to higher dimensions, but in our context a cross product will only be computed for vectors in R3. u × v = u2v3ı +u3v1 ȷ +u1v2k −u2v1k −u3v2ı −u1v3 ȷ Example 2. Compute the following cross products: a) (ı + ȷ +k)×(ı −2ȷ +2k) b) 〈−1,−3,1〉 × 〈1,2,−2〉 Properties of the Cross Product: Let u, v, and w be vectors in R 3 and let a ∈ R. Then we have: 1. u × v = −v ×u                                  (anticommutativity of ×) 2. (au)× v = a(u × v) = u ×(av)             (associativity of scalar multiplication) 3. u ×(v +w) = u × v +u ×w                  (left distribution of × across + ) 4. (u + v)×w = u ×w + v ×w                 (right distribution of × across + ) Also, by using vectors of zeros and ones, it is easy to show the following: ı × ȷ = k                 ȷ ×k = ı                   k × ı = ȷ ȷ × ı = −k                k × ȷ = −ı               ı ×k = −ȷ ı × ı = 0                   ȷ × ȷ = 0                 k ×k = 0 Geometrically, the cross product of two vectors u and v results in a vector u × v that is orthogonal to both u and v. The direction of the vector is given by the right-hand rule - as the fingers of your right hand curl from u to v, your thumb points in the direction of u × v. The magnitude of the cross product vector is |u × v| = |u||v|sinθ where 0 ≤ θ ≤ π. If u and v are parallel, then u × v = 0. If u and v are orthogonal, then |u × v| = |u||v|. The cross product can then be used to compute a vector that is orthogonal to two given vectors. Example 3. Find a unit vector that is orthogonal to both u = 〈2,3,−5〉 and v = 〈−1,1,−1〉. Example 4. Find the magnitude of u × v if u = 〈1,−1,3〉 and v = 〈−2,0,−1〉. Example: What is the relationship between u · v and |u × v|? Example: If u · v = 0 and u and v are nonzero vectors, is it possible for u × v = 0? There are several geometric applications of the cross product. First, the magnitude of u × v gives the area of the parallelogram formed by u and v. Area = |v||u|sinθ Example 5. Find the area of the parallelogram formed by the vectors u = 〈1,0,1〉 and v = 〈2,4,2〉. Definition: The scalar triple product of the vectors u,v, and w is the scalar quantity u ·(v ×w). The absolute value of the scalar triple product gives the volume of a parallelepiped formed by the vectors u, v, and w. Note that it does not matter what order the three vectors are written when forming the parallelepiped: |u ·(v ×w)| = |v ·(u ×w)| = |w ·(u × v)| The tetrahedron formed by the vectors u, v, and w has volume 1/6 of the volume of the corresponding parallelepiped. Definition: The vector triple product of the vectors u, v, and w is the vector u ×(v ×w). Example 6. Let u, v, and w be vectors in R 3 . Which of the following expressions are meaningful? If not, explain why, and if so, state whether the result is a vector or scalar. a) (u · v)×w b) (u ×w)·(v ×w) c) u ·(v ·w) d) u ·(v ×w) Properties of the Vector Triple Product: Let u, v, and w be vectors in R3 and let a ∈ R. Then we have: 1. u ×(v ×w) = (u ·w)v −(u · v)w 2. (u × v)×w = −w ×(u × v) = −(w · v)u +(w ·u)v 3. u ×(v ×w)+ v ×(w ×u)+w ×(u × v) = 0 4. (u × v)×w = u ×(v ×w)− v ×(u ×w) Other useful identities: — (u × v)·(u × v) = |u × v|2 = |u|2 |v|2 −(u · v)2 — (t ×u)·(v ×w) = (t · v)(u ·w)−(t ·w)(u · v) Torque, or moment of force, is the tendency of a force to rotate an object about an axis. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Consider a rigid body situated at the origin of a coordinate system. If a force F acts on a rigid body at a point whose position is given by r , then the rotational force exerted on the body is the torque τ given by τ = r ×F. The torque vector has a magnitude of |τ| = |r ×F| = |r ||F|sinθ. Since |F| has units of Newtons (N), or kg-m/s2 , the magnitude of torque has units of Newton-meters (N-m). Lines in Space Lines in R2: We have known for some time that a line in R2 is determined by a point on the line and the slope of the line. Let a represent the change in x and b represent the corresponding change in y of the slope (if the line is vertical then a = 0). The slope m = b/a can be interpreted as a direction vector: v = 〈a,b〉. If a ≠ 0 and the line passes through the point (x0, y0), then we know its equation is given by which can also be written as (if b ≠ 0) Using vectors, we can also describe the line through (x0, y0) and slope m = b/a. Now any point on the line (x, y) lies somewhere in the direction of the slope vector v (we call v the direction vector of the line). In other words, there is some scalar multiple of v such that the position vector of the point (x, y) is the sum of the scaled v and the position vector r 0 of the known point (x0, y0). Thus there is some value of a parameter t (a scalar) such that the position vector for the point (x, y) is given by 〈x, y〉 = r (t) = r 0 + tv = 〈x0, y0〉 + t〈a,b〉 = 〈x0 + at, y0 +bt〉. In this case, the equation r (t) = r 0 + tv is known as the vector equation of the line L, and the two equations x = x0 + at, y = y0 +bt are the parametric equations of L. Note that if a = 0, then the line is vertical, so in this case the x-coordinate of any point on the line is x0. This yields the vector equation r (t) = 〈x0, y0〉 + t〈0,b〉, and thus the parametric equations are x = x0, y = y0 + bt. If b = 0, then y is always y0, and the vector equation is r (t) = 〈x0 + at, y0〉, and the parametric equations are x = x0 + at, y = y0. Definition: Let L represent the nonvertical line in R 2 passing through (x0, y0) with slope m = b/a. Then the following equations represent all points on L: Symmetric Equations: a/x − x0 = b/y − y0 Vector Equation: r (t) = r 0 + tv = 〈x0, y0〉 + t〈a,b〉 Parametric Equations: x = x0 + at, y = y0 +bt Example 7. Find the symmetric, vector, and parametric equations of the line passing through the points (−2,3) and (4,1). Then find an alternate parametrization of the line (i.e., another set of parametric equations that describe the same line). Example: How many different parametrizations does a line have? Two lines in R 2 are either parallel (i.e., have the same slope) or they intersect at a single point. The point of intersection (x, y) must lie on both lines, so the coordinates of the point of intersection must satisfy the equations of both lines. However, if using the parametric or vector equations of the lines, note that the values of t at the point of intersection may be different for each. Thus,if using parametric equations or vector equations to solve for a point of intersection, then you may want to use a different variable (e.g. s) for the parameter of one of the lines. Example 8. Find the coordinates of the point of intersection of the lines L1 and L2 given by L1 : r 1(t) = 〈3− t,2+ t〉, and   L2 : r 2(s) = 〈4+2s,−3s〉. Lines in R 3 : Lines in three spatial dimensions are described in the same way as they are in R2 . One major difference however is that the concept of slope does not readily extend to R 3 - the change in y with respect to x is no longer sufficient to describe the direction of the line. Thus in order to describe a line, we must have a point (x0, y0, z0) on the line and a vector v = 〈a,b,c〉 that gives the direction. The numbers a, b, and c are known as the direction numbers of the line. Symmetric Equations: a/x − x0 = b/y − y0 = c/z − z0 Vector Equation: r (t) = r 0 + tv = 〈x0, y0, z0〉 + t〈a,b,c〉 Parametric Equations: x = x0 + at, y = y0 +bt, z = z0 +c t Note that if one of the direction numbers is 0 the symmetric equations will be slightly different. For example, if a = 0, then L would be represented by the symmetric equations x = x0,    b/y − y0 = c/z − z0. Example 9. Find the symmetric, vector, and parametric equations of the line through the points (6,1,−3) and (2,4,5). While it is certainly the case that parallel lines do not intersect, in R 3 there are nonparallel lines that do not intersect. Definition: Two lines L1 and L2 in R 3 are skew if they are not parallel and do not intersect. Example 10. Determine whether the following lines are parallel, skew, or intersecting. If they intersect, find the point of intersection. a) L1 : x = −6t, y = 1+9t, z = −3t,         L2 : x = 1+2s, y = 4−3s, z = s b) L1 : 1/x = 2/y −1 = 3/z −2,               L2 : −4/x −3 = −3/y −2 = 2/z −1 c) L1 : r (t) = 〈1− t,2+ t,−2−4t〉,        L2 : r (s) = 〈−2s,2s +3,−8s −6〉 To parametrize a line segment between two points (x0, y0, z0) and (x1, y1, z1), one can simply take a convex combination of the position vectors r 0 and r 1 of the two points: r (t) = (1− t)r 0 + tr 1,    0 ≤ t ≤ 1. This just amounts to taking a weighted average of the two position vectors, with the extremes being r 0 when t = 0 and r 1 when t = 1.

$25.00 View

[SOLVED] COMM 3500 Winter 2025 Midterm

COMM 3500 – Winter 2025 Midterm (Excel Part) – 25 Marks The European Bakery in the Halifax area bakes 80 trays of its famous “borek”, a well-known savory pastry in the owner’s homeland, at the beginning of each day. Using the historical data, the owner believes that daily demand will follow the distribution shown in the following table: Each tray costs the European Bakery $25 and can be sold for $50. Any unsold trays can be salvaged/donated for $5 at the end of the day. The (daily) fixed cost has two components. The first component is known for certainty: the rent, insurance, and employee salaries add to $400 per day (daily conversion of $10,000 per month). The second component is uncertain and estimated using a continuous uniform. distribution with lower bound $a and upper bound $b. This includes maintenance (e.g., due to weather conditions), energy usage, shipping, etc., converted as daily expenses. You will determine a and busing the last 2 digits of your Banner ID. Set the smaller value times 100 as a and larger one times 100 as b. If they are equal, deduct 1 from adigit before multiplying it with 100. If there is a 0 in the last two digits or you get 0 after deducting 1, take a  =  100 and calculate b accordingly. If they are both 0 or a digit is 0 and the other is 1, use a  =  100 and b  = 200. Example: B01234567 yields a = 600 and b = 700. Example 2: B01234599 yields a  = 800 and b  = 900. Example 3: Both B01234500 and B01234501 yield a  =  100 and b = 200. A. Open a new Excel workbook. In cell A1, type your first and lastname. In cell A2, type your Banner ID and finally, in cell A3, type your Dalemail. Make them in bold font in size 16. If any of these items are missing or incorrect, you will receive a mark of zero for the Excel file! B. Change the name of the worksheet as ‘BE_analysis ’. Copy the worksheet or create another one and change its name to ‘Simulation ’. Both worksheets must contain the information in A. in the requested format. C. Please note that you will be marked based on the formatting in your spreadsheets too. Your values and plots must be neat and readable; and you must use frames and highlight cells with a formula, change decimals and/or format, etc. as in the Excel files we use in lectures/labs. D. Answer the questions below. Save your Excel file using filename: Last Name_First Name_Banner ID and place the file in the dropbox: Brightspace>Assessments>Assignments>Midterm (Excel Part). E. Important: It is recommended that the students first save the file to a safe place with the desired name and then, keep saving it frequently throughout the exam to avoid any unforeseen events that may result in crushing of the exam file. It is student's responsibility to upload a working Excel file. Perform. the following tasks: 1. Expected values and B-E analysis (3 Marks): a. Enter the necessary data into ‘BEanalysis ’ worksheet. Find the expected demand and expected fixed cost. (1.5 Marks) b. Find break-even point using the mean fixed cost. Is it attainable for the given information, why or why not? Comment using bold red font. (1.5 Marks) 2. Simulation (Part 1) (10 Marks): Simulate 1 month (25 workdays) of operation to calculate the bakery’s total monthly profit. Your worksheet must have the following four areas: I. The table of demand probability distribution (including the corresponding cumulative probability). II. Input data area that neatly displays the information provided in the question including the probability distribution of the fixed cost. III. Simulation area that neatly shows 25 replications to calculate daily profit for 25 days. IV. Analysis area that shows the total monthly profit. 3. Simulation (Part 2) (7 Marks): a. Replicate this calculation 1000 times and compute the average total monthly profit. (3 Marks) b. Create a summary statistics part and the histogram of the monthly profit. Comment using bold red font. (3 Marks) c. Calculate the probability of making more than $x profit per month. You determine $x according to the upper bound of the uncertain fixed cost (1 Mark): 4. Scenario Manager (3 Marks): The European Bakery would like to investigate the profitability of baking 60, 80, 100, or 120 trays at the start of the day. Create a table using Scenario Manager (don’t forget to replace cell addresses in the table with the labels). Which quantity would you recommend? Why? Comment using bold red font. Accurate data entry and general formatting (2 marks) Late Submission Penalties: This assignment should take around 30 mins and you are allocated 24 hours to complete it. My advice for you is to have at least a 10-15 mins buffer before the due date/time for submitting your Excel file as it is worth 25% of the Final. If you think you have a connectivity issue or some other problem that may cause a delay, I recommend submitting the file even earlier. For late submissions, we have apenalty policy: 30 mins but 1hr but 3hr Submissions not acceptable Files sent via e-mail will receive no marks and there will be no exceptions. Lastly, there is a 10% penalty in case the Excel file doesn’t include the necessary details (name, Banner ID, etc.).

$25.00 View

[SOLVED] BSBMKG434 - Promote products and services

Course Name:   BSB40820 Certificate IV in Marketing and Communication Unit / Subject Name:   BSBMKG434 - Promote products and services Assessment/evidence gathering conditions Each assessment component is recorded as either Satisfactory (S) or Not Yet Satisfactory (NYS). A student can only achieve competence when all assessment components listed under procedures and specifications of the assessment section are Satisfactory. Your trainer will give you feedback after the completion of each assessment. A student who is assessed as NYS is eligible for re-assessment. Should the student fail to submit the assessment, a result outcome of Did Not Submit (DNS) will be recorded. Student should be provided with an appropriate time frame. in which to resubmit their work, according to the RTO’s re-assessment policy and procedure. Plagiarism, cheating and collusion. Where a trainer/assessor believes there has been an incident of academic misconduct involving plagiarism, cheating, and/or collusion, they should report this along with reasons for the allegation. Assessors should refer to their RTO’s policy and procedures regarding training and assessment for further information.” When all unit’s assessment tasks have been submitted and assessed (including resubmissions), print out a copy of this unit’s Final Results Record, included as the last page of this document. Record the result for each task and the final result for the unit as C (Competent) or NYC (Not Yet Competent). There is also space to give the student some written feedback for the overall unit. Sign and date the middle section and give the sheet to the student. After discussing their results with them, the student must fill out and sign the final section of the Record, where they acknowledge the result that you have given them. When the student has filled out the final section of the Final Results Record, make a copy for them and retain the original with the student’s records. Reasonable Adjustment TM supports individual differences in the learning environment and provides ‘reasonable adjustment’ in training and assessment activities to support every learner. If you have any special needs that make it difficult for you to complete your learning or assessments, you should discuss this with your assessor beforehand and will be provided with reasonable alternatives to assist you to complete the required tasks such as completing tests verbally or using an interpreter. Resources required for this Assessment § All documents must be created using Microsoft Office suites i.e., MS Word, Excel, PowerPoint § Upon completion, submit the assessment printed copy to your trainer along with assessment coversheet. § Refer the notes on eLearning to answer the tasks § Any additional material will be provided by Trainer Assessment Information This Assessment is designed for you to complete the assessment for BSBMKG434 - Promote products and services. The assessment tasks include · Assessment 1: Short Questions where you need to demonstrate your knowledge and understanding of the unit, and the · Assessment 2: Simulated Environment, where you need to demonstrate your skills required in the unit. It is recommended that you complete all task in a simulated environment (Bounce Fitness). Before you commence your assessment, ensure that you have a good knowledge of the subject, have thoroughly read your Learner Resource, and clearly understand the assessment requirements and the expectations of the industry to which the assessment is related. You will be required to demonstrate knowledge and skills which must be observed directly by your assessor. Verification from trainer is required to confirm your demonstration of these practical knowledge and skills. Instructions are given for each task. If you have questions, or unclear how to proceed, consult with your assessor. Records of all aspects of the assessment must be kept in your Student Assessment Resources Required for Assessment To complete the Practical Assessment tasks, you will require access to: § Computer with internet and email access, and a working web browser § Installed software: Word, Adobe Acrobat Reader § A simulated workplace environment that will allow you access to: o Action plan template o Organisational documents or sources of information that contain: · Marketing plans of the organisation · Information on the organisation’s overall business objectives and goals, such as staff handbook, mission and vision, and business plans · Information qualifications of personnel for allocation of roles and responsibilities, such as job descriptions and work schedules · Information relevant to the scope of your responsibility such as your job description, staff handbook, and initial planning o Workplace policies and procedures relevant to: · Accessing and obtaining resources such as procedure for procurement of new equipment, and budgeting policy and procedure · Marketing products and services such as procedures for planning promotional activities, and marketing policies and procedures · Developing action plans, such as documentation policy and procedure, and style. guide · Communicating with stakeholders, such as communication policy and procedure and policies, and procedures for meetings · Allocating and communicating roles and responsibilities to personnel, such as communications processes, and digital communication policies and procedures · Implementation of action plans such as policies and procedures for plan implementation and performance, and implementation protocols · Progress monitoring such as policy and procedures for monitoring of workplace action plans, and marketing development procedures · Collecting and providing feedback, such as performance review policy, and communication policies and procedures · Reviewing promotional activities, such as promotional policies and procedures, and policies and procedures on workplace performance o People, including: · At least two relevant stakeholders with whom you will consult and collect feedback about planning promotional activities Relevant stakeholders refer to people in your organisation who are involved in coordinating promotional activities. This can include general marketing managers, public relations managers, or advertising managers. · At least two relevant personnel who are involved in implementation and delivery of promotional activities and will be provided feedback regarding the evaluation of implementation Relevant personnel refer to people who have the qualifications that match roles and responsibilities required for implementation of promotional activities. This can include promotion officers, brand managers, and social media experts. o Legislation, regulations, standards and codes for promoting products and services such as: · Competition and Consumer Act 2010 · Privacy Act 1988 · Spam Act 2003 · Competition and Consumer Regulations 2010 · Privacy Regulation 2013 · Spam Regulations 2004 o Opportunity to: · Consult with at least two relevant stakeholders about planning promotional activities · Provide feedback to at least two relevant personnel about the conduct of promotional activities Assessment 1-Short Questions Question 1 The table below includes parts of a typical action plan used for business promotional activities. Complete the table by indicating all information usually included in each indicated part. Part of Action Plan Information Included in Each Part a. Goal The main objective or purpose of the promotional activity, outlining what the business aims to achieve. b. Task steps Specific actions or steps that need to be taken to implement the promotional activity successfully. c. Costs Budget estimates, including expenses for advertising, materials, staff, and other resources. d. Timeframe The duration and key deadlines for each step of the promotional activity. e. Resources The materials, tools, personnel, and technology required to execute the plan. f. Responsibilities Assignments of duties and roles to team members or departments involved in carrying out the promotional activity. Question 2 Identify an example for each of the following who are involved in coordinating promotional activities: a. At least one internal stakeholder b. At least one external stakeholder For each identified stakeholder, briefly explain what they do as part of coordinating promotional activities. Type of Stakeholder Stakeholder Involved What Each Stakeholder Does When Coordinating Promotional Activities a. Internal Stakeholder Marketing Manager   Develops promotional strategies, oversees execution, and ensures alignment with business goals.   b. External Stakeholder Advertising Agency   Designs and executes advertising campaigns, manages media placements, and ensures brand visibility.   Question 3 Bounce Fitness is a health and fitness organisation that aims to be a premier provider of wellness in Australia. Assume that you are working for Bounce Fitness as one of their marketing officers. Marketing officers need to come up with promotional activities for the products and services offered by the organisation. Review Bounce Fitness’ Corporate Marketing Plan found in the link below: Bounce Fitness Corporate Marketing Plan https://bouncefitness.precisiongroup.com.au/category-infrastructure/current-projects/  Use the document to identify at least two promotional activities that can be conducted by Bounce Fitness. For each promotional activity: § Identify at least one planning process involved in organising the specific activity. § Briefly explain how the identified planning process is relevant to the corresponding promotional activity. Promotional Activity 1: Social Media Campaign   Planning Process Involved Explanation of How the Planning Process Relevant to the Promotional Activity Content Development   Ensures engaging, targeted content is created to attract and retain customers.   Promotional Activity 2: Free Trial Classes Planning Process Involved Explanation of How the Planning Process Relevant to the Promotional Activity Scheduling & Coordination   Ensures sessions are organized efficiently to accommodate prospective clients. Question 4 Bounce Fitness is a health and fitness organisation that aims to be a premier provider of wellness in Australia. Assume that you are working for Bounce Fitness as a General Manager for Marketing. One of the specific areas of your work is planning direct marketing activities. Review one of Bounce Fitness’ Marketing Plans found in the link below: Bounce Fitness Corporate Marketing Plan https://bouncefitness.precisiongroup.com.au/category-infrastructure/current-projects/ a. Using the document: i. Identify at least two overall business objectives of Bounce Fitness ii. Identify at least one marketing objective that supports each corresponding business objective  iii. Briefly explain how each marketing objective supports the corresponding business objective. b. As part of planning marketing activities: i. Write at least one promotional activity that can support each indicated marketing objective ii.  Briefly explain how each promotional activity can support the corresponding marketing objective Business Objective 1: Increase Memberships Supporting Marketing Objective Explanation of How the Marketing Objective Supports the Business Objective Improve Customer Outreach   Expanding reach ensures more potential customers are aware of services. Promotional Activity Explanation on How the Activity Supports the Marketing Objective Email Marketing Campaign   Sends personalized offers and updates to attract and retain customers. Business Objective 2: Enhance Brand Awareness Supporting Marketing Objective Explanation of How the Marketing Objective Supports the Business Objective Strengthen Online Presence   A strong digital presence increases brand recognition and engagement. Promotional Activity Explanation on How the Activity Supports the Marketing Objective Influencer Collaborations Partnering with fitness influencers to promote Bounce Fitness services through social media, blogs, and videos. This increases brand credibility and reaches a wider audience, supporting the goal of strengthening the online presence.                

$25.00 View

[SOLVED] DTS304TC Machine Learning Assessment Task 2

Module code and Title rningSchool ofAI and AdvancedComputingAssessment Task2 DTS304TC Machine Learning Coursework – Assessment Task 2 Submission deadline: TBD Percentage in final mark: 50% Learning outcomes assessed: C, D ●     Learning outcome C: apply ML algorithms for specific problems. ●     Learning outcome D: Demonstrate proficiency in identifying and customizing aspects on ML algorithms to meet particular needs. Individual/Group: Individual Length: This assessment comprises a guided coding and experimentation project, along with an associated research report. Late policy: 5% of the total marks available for the assessment shall be deducted from the assessment mark for each working day after the submission date, up to a maximum of five working days Risks: •  Please read the coursework instructions and requirements carefully. Not following these instructions and requirements may result in a loss of marks. •  The formal procedure for submitting coursework at XJTLU is strictly followed. Submission link on Learning Mall will be provided in due course. The submission timestamp on Learning Mall will be  used to check late submission. Guided Project: Street-view Semantic Segmentation with U-Net In this coursework, you will explore street-view  semantic segmentation using a U-Net model across multiple challenging scenarios. . Part A focuses on evaluating a pretrained daytime segmentation model. You will write your own evaluation script.  and compute metrics such as Dice and accuracy. Then, by examining both successful  and  failed  segmentations, you will highlight the difficulties of segmenting  diverse daytime scenes and discuss why semantic segmentation can be challenging. . Part B shifts attention to night-time images. You will evaluate the same pretrained model on night- time data, then implement  fine-tuning  using various loss functions (e.g., Dice, Cross-Entropy, combinations of both, or other losses of interest). In addition, you will experiment with one additional  training  technique of your choice—such as different data augmentations, different network learning-rate schedulers, optimizers (including momentum training), or layer-wise fine- tuning—and compare the results, explaining the outcomes. You will also discuss from a theoretical standpoint why combining Dice and Cross-Entropy losses can be advantageous and illustrate how fine-tuning improves performance on night-time images. . Part C involves retraining a U-Net from scratch on daytime images, with a focus on small or distant objects (e.g., people or cars far away in the scene). You are encouraged to propose and implement one or two strategies—such as incorporating object detection, targeted data augmentation, different loss  functions,  or multi-scale architectures—to enhance segmentation performance  for these  harder-to-segment classes. You will provide both quantitative metrics and qualitative analyses of your results. . Part  D offers an opportunity to reflect on the interesting and novel aspects of  the  work  you developed during the coursework, the principal challenges you faced, how you addressed them, and the lessons you  learned. Your coding quality will also be evaluated, so focus on clarity, organization, and efficiency. Completing this coursework will deepen your understanding of semantic segmentation  metrics,  fine-tuning  techniques,  network modifications for small object detection, and the practical challenges of deploying segmentation models under varied lighting and scene conditions. The assessment comprises two parts: 1. Coding and experimentation 2. Completing the assessment work sheet As you work on the coding and experimentation, it is crucial to record and document all relevant findings; these will be integrated into your assessment sheet. Before starting this project, please ensure you have downloaded the pretrained model, the assessment codebase, and the example Jupyter notebook. Notes: 1.    A sufficiently powerful GPU is required to complete this coursework. You may use the GPU machines available in our school labs (e.g., FYP labs). Please schedule and coordinate usage with your classmates well in advance to avoid conflicts. 2.    You are strongly encouraged to review the provided code and training notebook, as you will refer to and modify them throughout the project. Feel free to use code covered during our lab sessions or other online resources. However, please provide proper citations and links to any  external resources you use. Important: You may not use ChatGPT to directly generate answers for the coursework. It is important to think critically and develop your own solutions—by yourself or through reputable online resources—to strengthen your research and critical thinking skills. You may, however, use ChatGPT for code understanding or debugging, as well as for grammar and writing assistance. If you do so, use it responsibly, ensuring you fully understand and take ownership of all the content in your coursework. (A) Evaluate the Pretrained Model on Bright Sunny Test Images (10 marks) Complete the supplied notebook dts304_a2_part1.ipynb. The pretrained model and testing Dataloader code are provided, and you are required to implement both the testing loop and the evaluation metrics. (A1) Testing Loop .     Implement the testing loop to generate predictions for the test images using the pretrained model. .     Ensure the model is in evaluation mode (model.eval()) and use torch.no_grad() to optimize performance and accuracy. (A2) Accuracy Metrics 1.     Within the testing loop, calculate global image accuracy and per-class accuracy for each image, as well as for the overall dataset. .    Global Image Accuracy .     Defined as the percentage of correctly classified pixels per image. .     The overall dataset global image accuracy is the average of the global accuracies across all images. .    Per-Class Accuracy (IOU) .     Use Intersection-over-Union (IOU) for each of the  14 categories. .     Compute mean-IOU by averaging across the  14 categories. .     If a category does not appear in the ground truth or prediction, assign NaN and use np. nanmean for the mean-IOU calculation. .     The overall dataset per-class IOU is obtained by averaging the per-class IOU scores for each category across all images. 2.     Calculate the overall dataset global image accuracy and the overall dataset per-class IOU scores. Note any significant variations in the IOU scores across different classes and discuss potential reasons for these differences. (A3) Rank the images based on accuracy and IoU scores, then select a few examples where the model performs exceptionally well and others where it struggles. Use these selections to illustrate the strengths and limitations of your street-view segmentation approach. For example, the model might accurately segment large, well-lit vehicles but struggle with small or distant pedestrians, poorly illuminated regions, or overlapping objects. In each case, explain why these challenges arise (e.g., limited pixel information, lighting variations, or complex backgrounds), and use your chosen images to demonstrate these issues. B) Fine-Tune the Pretrained Model on the Cloudy Dataset (30 marks) Finish the supplied notebook dts304_a2_part2.ipynb. The pretrained model and testing data loader code  for the cloudy dataset are provided. You will evaluate the model’s current performance, implement fine- tuning using various loss functions, and then re-evaluate and analyse the results. (B1) Evaluate Cloudy Dataset Performance. Use the code from Part 1 (or a similar approach) to evaluate the model’s performance on the cloudy dataset by calculating Dice and accuracy (or other relevant metrics). Since cloudy conditions typically present additional challenges, you may observe a decrease in segmentation quality compared to the sunny scenes tested in Part  1. This lower performance highlights the need for further enhancements—such as model finetuning—to improve the model’s robustness under varying weather conditions. (B2) Fine-Tuning 1.    Adapt Training Notebook: Modify the notebook to fine-tune the model on the cloudy dataset. 2.    Loss Functions: Experiment with different loss functions (e.g., Dice, CE, Dice + CE) during the finetuning and analyse their impact on performance. 3.    Additional Training Technique: Implement at least one additional technique of your choice (e.g., data augmentations, alternative optimizers with momentum, learning-rate scheduling, or selective layer fine-tuning). 4.    Training Process Monitoring. Plot and compare training vs. validation loss to track improvements. Include at least one plot in your assessment worksheet to demonstrate how you selected the best fine-tuned model. (B3) Results and Analysis 1.    Loss Function Insights: Discuss the theoretical/algorithm properties of Dice and Cross- Entropy (CE) losses, including why their combination may offer unique advantages (e.g., gradient considerations). Compare these theoretical insights to your empirical findings by reporting accuracy and IOU scores for each loss configuration—Dice-only, CE-only, and Dice + CE. 2.    Enhancements & Experiments: Summarize the additional technique(s) you employed— such as new augmentations, different optimizers, or layer-wise training—by presenting both theoretical/algorithmic rationale and the observed experimental outcomes. 3.    Re-Evaluation: After selecting the most effective loss function and training enhancements, re-test your best fine-tuned model using the same procedure as the initial cloudy dataset evaluation. Present global image accuracy and per-class IOU results and  compare them against the baseline to highlight any performance gains. C) Retrain From Scratch on daytime images & Enhance Small-Object Segmentation (35 Marks) You are provided with the notebook dts304_a2_part3.ipynb, which you will use to train a segmentation model on daytime images. Your primary objective is to improve segmentation accuracy for small objects—specifically cars, pedestrians, and lane-markings—while maintaining or improving overall performance on other classes. (C1) Small-Object Challenge Evaluation (Cars, Pedestrians, Lane-Markings) 1.    Why small objects are difficult: Distant cars and pedestrians often occupy only a few pixels, leading to lower accuracy or missed detections. Lane markings can be thin and fragmented, causing false negatives and reduced IoU. 2.    You are given a function called compute_object_level_stats_percentile that: .    Splits objects into “small” or “large” based on a threshold (e.g., number of pixels) for each category. .    Computes precision, recall, and F1-score for each category (small vs. large objects). Use this function to analyse how well the model segments small vs. large cars, pedestrians, and lane markings. 3.   Tasks: .    Calculate Small/Large Object Metrics: Run compute_object_level_stats_percentile for car, lane-mark, and pedestrian classes. .    Compare Precision, Recall, F1: Compare small-object metrics with large-object metrics to validate that segmentation of small objects is indeed a challenge for the   car, lane-marker, and pedestrian classes. .    Provide Visual Examples: Show at least five images with ground-truth segmentations vs. model prediction results highlighting missed or partially segmented small objects. (C2) Strategies to Improve Small-Object Segmentation After identifying weaknesses in small-object segmentation, choose at least one of the following strategies (implementing two strategies may yield higher marks): 1.   Combine Semantic Segmentation with Object Detection .    Use an object detector to first locate small objects (cars/pedestrians), then apply a segmentation network to those regions. .     Or run a segmentation model and a detection model in parallel, fusing their outputs for improved small-object accuracy. .    You may use a pre-trained object detection model downloaded from the internet to detect cars and pedestrians. If you choose this method, it is acceptable to omit experiments for the 'lane-marker' class if no suitable object detection model is available for it. 2.   Custom Data Augmentation .    Example: Randomly zoom in on regions containing small objects, increasing their resolution during training. .    Alternatively, duplicate or scale small objects synthetically to increase their representation in the training set. 3.   Pixel Weighting Map .    Assign higher loss weights to pixels belonging to small objects .    Ensures the model pays more attention to the pixels of small objects but requires careful tuning to avoid overfitting. 4.   Multi-Scale / Pyramid Architectures .    Incorporate modules like ASPP (Atrous Spatial Pyramid Pooling) to capture features at multiple scales. .    Helps detect smaller objects without losing overall context. 5.   Other approaches .    You can select other approaches as you wish (for example, different loss function). .    However, if your approach is overly simplistic or only involves straightforward parameter tuning (e.g., adjusting image resolution, learning rate, or network parameters), it will not be awarded high marks. Modify or create a new training loop in dts304_a2_part3.ipynb to include your chosen technique(s).  Clearly mark or comment your changes. Provide all source code in your submission files and briefly mention modifications in your assessment worksheet. (C3) Results & Analysis 1.   Post-Training Evaluation .    Recompute overall metrics (global accuracy, mean IoU) as you did for the original model. .    Use compute_object_level_stats_percentile again to see how your improvements affect small-object metrics for cars, pedestrians, and lane-markings. .    Compare (precision_small, recall_small, F1_small) before and after your changes. 2.   Highlight Gains .    Discuss what strategies (1 or 2 strategies) have you made to improve small object segmentation and explain their algorithm principles. .    If you employed multiple improvements or strategies, clearly explain how each individual approach/strategy contributed to the enhancement of small-object segmentation based on experimental evaluation results (for example, the small-object metrics, mean IOU or global accuracy) and/or your analysis. .    Note any trade-offs, such as slightly lower performance on large objects or other classes. 3.   Qualitative Examples .     Show side-by-side images (ground truth vs. predicted segmentation) demonstrating improvements in small-object detection. .    Point out any remaining challenges (extremely tiny objects, occlusions, etc.). D) Coursework Reflections (15 Marks) .     Write a brief reflection highlighting unique or interesting algorithms or strategies you implemented in the coursework. .     Reflect on the challenges you personally faced during the coursework, describing the efforts you made to overcome them and the key lessons you learned. .     Based on your reflections, discuss potential future work that could further enhance semantic segmentation in street-view applications. E) Coding Quality, Worksheet Quality and Adherence to Submission Guidelines (10 Marks) .     Ensure your code is clear, easy to understand, and includes well-written comments to explain its functionality. .     Follow the worksheet template, formatting guidelines, and all prescribed requirements for the submission. .     Write in clear and proper English, keeping your answers concise and within the specified word limit. Pay close attention to maintaining excellent formatting throughout.

$25.00 View

[SOLVED] INU1110 Assessment 2R

INU1110 – Assessment 2 Brief for Students                   February 2025 “Evidence and evaluate the main reasons for the low economic growth experienced in the UK economy between January 2020 and January 2025”. This second assessment for the module INU1110 – Introduction to Economics is a creative digital project – A VLOG or Video blog based on the work of a group of 4 or 5 students. It is worth 60% of each student’s final mark. Crucially, 30% of the total marks are peer-marked  2. The final deadline for A2 assessment - Completed Video Blog using MS SWAY By 9.00 on Monday 28th April ((week 12). Each group will submit a VLOG presented in MS SWAY using an interactive visual design that includes 1000 words of relevant text, plus graphics, diagrams, TV and social media footage, sound files and student video with academic references /citations.  3.  Deadline for draft version for teacher feedback The draft will be submitted on Sunday 24.00 on 10th March (week 7). The draft VLOG with include two examples of potential theory, one detailed example of effect on economic actor, one piece of edited footage and a video recording for each student, each speaking for a minimum of 1 minute on a relevant topic. It will include a minimum of 5 references including academic ones.  4. VLOG marking scheme                                                    Marks     4.1.Develop points to level of detail expected of an academic study (reference,        10 cite, state, evidence, illustrate and apply concepts from macroeconomics        relevant to context.                                                              4.2. Use relevant macroeconomic theory to analyse performance trends, causes      15 and effects on economic growth over the period (indicators incl.UK Interest Rates,  Inflation, Balance of Payments, Business Cycle events, Investment, Employment, Skills, GDP, Productivity, the SR & LR, Aggregate Demand and Aggregate Supply. 4.3. Use relevant policy analysis to evaluate Government interventions to stimulate   15 UK Economic growth including specific fiscal and/or monetary policies, supply-side and/or demand-side policies. Use AD&AS analysis in your answer.                            4.4 Provide relevant examples, (one for each of the four economic actors: firms,          15 households, governments, and overseas trading partners).                                                         Demonstrate the     impacts of levels of economic growth rates. Use indicators such                              as the standard of living, per capita incomes, debt, borrowing, Saving, Consumption, Wages, investment Assets.         4. 5. Delivery of Blog Posts (Presentation & Technical Production Performance).                                                                                                                                                    15   4.6.  Student participation (peer assigned mark subject to teacher endorsement).         30 5. Media Platform The project is structured to make full creative and innovative use of MS SWAY. This digital media platform. can be used to present all audio-visual, social, sound and TV video media. Organise your work and sources using Teams, or WhatsApp or . Students should collaborate intensively over 10 weeks to design and execute the work.  6. Narrative The VLOG project will tell an audio-visual multimedia story answering the question “Evidence and evaluate the main reasons for the low economic growth experienced in the UK economy between January 2020 and January 2025”. 7. Relevant Topics & Concepts for Analysis The list of topics above is not exclusive as there may be many others not indicated. Choose a minimum of 4 Key Topics from Macro and 3 from Micro in your narrative. 8. Structure of VLOG Content Present your work under the following headings   i)   Executive Summary (list of 10 key findings/ incl. thesis statement - main answer). ii) Introduction – Economic Growth Definition. UK context, comparative GDP growth. iii) Relevant Macro. Theory (Relevant concepts, sources of growth, relevant policy).  iv) Relevant Microeconomic Theory (incl. Key growth industries and drivers of growth)  v) Analysis of UK GDP Trends /Policy Responses (Identify success /failure of Policies).   vi) Relevant Examples - Impact of growth rates on Key Economic Actors in the UK.  vii) Conclusion  viii) Academic References & Media Index. 

$25.00 View

[SOLVED] Csci 4210 — operating systems homework 4

In this fourth and final assignment, you will use C library to implement a single-threaded single process server to run a simple multiplayer ”Guess the Word” game supporting up to 5 players at once. We will focus on only writing the server, since netcat can be used to act as a client.The server should support up to 5 clients, and cannot use fork() or threads. Since you will potentially have multiple clients, you will need to make use of the select() call. You should handle a client quitting at any point during the game, as well as any other error cases you think of.The program will take four arguments: ./word_guess.out [seed] [port] [dictionary_file] [longest_word_length] It should use TCP and listen on the port given as the second arguemnt [port]. When the server starts, and whenever a game finishes, it should select a word randomly from a dictionary, which will be referred to as the secret word. The filename of the dictionary, which just has one word per line, is passed in as the third argument to the program ([dictionary_file]), and the length of the longest word (number of letters) is passed in as the fourth argument ([longest_word_length]). Word lengths will not exceed 1024 bytes, and will not exceed [longest_word_length]. The example dictionary does use ISO-8859-1 encoding instead of UTF8, so don’t be surprised if you see strange characters in your terminal when using this dictionary.The autograder input will only use A-Z and a-z, you do not need to write code in your solution to handle any character encoding issues. Usernames, guess words, and secret words are not case sensitive, ”Bob”, ”bOB”, and ”bob” should all be treated as the same thing.To make the grading deterministic, you should read in the entire dictionary once, preserving the ordering, and then immediately after the initial read, use srand() with the [seed] provided as the first argument to the program. Do NOT sort the dictionary. Secret words should then be selected by using rand() % dictionary_size.Usernames When a client joins, the server should send a message asking the client to select a username, which will be used to uniquely identify the player among all currently connected players: Welcome to Guess the Word, please enter your username. If a client disconnects, its username is no longer reserved. For example client 1 could be the first to connect and claim the username bob: Let’s start playing, bobIf client 2 then connected and requested bob, the server would reject the username by asking for the username a second time: Username bob is already taken, please enter a different username If client 1 then disconnected and client 3 connected and claimed the username bob, the game would continue with client 3 being bob: Let’s start playing, bobGameplay Once a username is selected, the server should then notify that user about how many players are currently playing (including the new user), and what the length of the secret word is: There are 3 player(s) playing. The secret word is 5 letter(s).Any user can send as many guesses as they want, there is not a concept of “taking turns” in this game. However, each message should contain one word of the same length as the secret word, followed by a newline. Whenever the server receives a word from a user (called a guess word), it should send a message to all connected users in the format: Z guessed G: X letter(s) were correct and Y letter(s) were correctly placed. X counts duplicate letters as a separate letters, so if the secret word is GUESS and bob sent a guess word of SNIPE, the message would be: bob guessed SNIPE: 2 letter(s) were correct and 0 letter(s) were correctly placed. (Once for one S and once for the E.) Similarly, if the sceret word is GUESS and the guess word is CROSS, the response would be: bob guessed CROSS: 2 letter(s) were correct and 2 letter(s) were correctly placed. (Once for each S in the secret word.)Finally, if the secret word is GRUEL and bob guesses spill, the response would be: bob guessed spill: 1 letter(s) were correct and 1 letter(s) were correctly placed. (Only one L counts since there is only one L in the secret word.) Note that game is not casesensitive. If a user correctly guesses the secret word, all connected users should receive the message Z has correctly guessed the word S, and then all users should be disconnected from the server. The server should continue to run and should select a new word. Z is the username of the user who correctly guessed the word, and S is the secret word. If a user sends a guess word that is not the correct length, the server should send an error message to only the user with the invalid guess, but should not disconnect that client: Invalid guess length. The secret word is 5 letter(s).Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform.That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, make use of the DEBUG_MODE technique to make sure that Submitty does not execute any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -g -D DEBUG_MODE *.c -pthread Second, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use.

$25.00 View

[SOLVED] Csci 4210 — operating systems homework 3

In this third assignment, you will use C and the POSIX thread (Pthread) library to implement a single-process multi-threaded program that attempts to solve the knight’s tour problem, i.e., can a knight make valid moves to cover all squares exactly once on a given board? Sonny plays the knight in our assignment.Goal The fundamental goal of this homework is to use pthread_create() and pthread_join() to achieve a fully synchronized parallel multi-threaded solution to the knight’s tour problem. In brief, your program must determine whether a valid solution is possible for the knight’s tour problem on an m×n board, and if so, how many solutions exist. To accomplish this, your program uses a brute force approach and simulates all valid moves. For each board configuration, when multiple moves are detected, each possible move is allocated to a new child thread, thereby forming a tree of possible moves. Note that a new child thread is created only if multiple moves are possible at that given point of the simulation.Remember that all threads will run within one process. Valid moves and child threads A valid move constitutes relocating Sonny the knight two squares in direction D and then one square 90◦ from D (in either direction), where D is up, down, right, or left. Key to this problem is the further restriction that Sonny may not land on a square more than once in his tour.Also note that Sonny can start and finish on different squares; we are not looking for a cycle. When a dead end is encountered (i.e., no more moves can be made), the leaf node thread knows the number of squares it was able to cover, which might be a full knight’s tour. The leaf node thread compares the number of squares covered to a global maximum (max_squares), updating this global maximum as necessary.And if a full knight’s tour is achieved (i.e., the last move of a knight’s tour has been made), the child thread also increments a global count (total_tours). For consistency, row 0 and column 0 identify the upper-left corner of the board. Sonny starts at the square identified by row r and column c, which are given as command-line arguments. When the top-level main thread joins all of its child threads, it displays the final maximum result, which is equal to product m × n if a full knight’s tour is possible. Further, if a full knight’s tour is possible, the number of tours found is also reported.The given hw3-main.c source file contains a short main() function that initializes three global variables (as described below), then calls the simulate() function, which you must write in your own hw3.c source file. Submitty will compile your hw3.c code as follows: bash$ gcc -Wall -Werror hw3-main.c hw3.c -pthread You are required to make use of the three global variables in the given hw3-main.c source file.To do so, declare them as external variables in your hw3.c code as follows: extern int next_thread_id; extern int max_squares; extern int total_tours; The three global variables are described below. Feel free to use additional global variables. Since multiple threads will be accessing and changing these global variables, synchronization is required. 1. Given that Pthread IDs can vary, use the global next_thread_id variable to assign each thread its own unique ID. This variable is initialized to 1. Using this global variable, each child thread that is created must be assigned the next available thread ID in sequence (i.e., the first child thread created is assigned ID 1, the second child thread created is assigned ID 2, etc.); this requires synchronization.2. Initialized to zero, the global max_squares variable tracks the maximum number of squares covered by Sonny so far. When a dead end is encountered in a child thread, that thread checks the max_squares variable, updating it if a new maximum has been found. 3. Also initialized to zero, the global total_tours variable tracks the number of full tours that are found. When a full knight’s tour is encountered in a child thread, that thread increments the total_tours variable.There are four required command-line arguments. First, integers m and n together specify the size of the board to be m × n, where m is the number of rows and n is the number of columns. Rows are numbered 0 . . .(m − 1) and columns are numbered 0 . . .(n − 1). The next pair of command-line arguments, r and c, indicate the starting square on which Sonny starts his attempted tour. Validate inputs m and n to be sure both are integers greater than 2, then validate inputs r and c accordingly. If invalid, display the following to stderr and return EXIT_FAILURE: ERROR: Invalid argument(s) USAGE: a.outDynamic memory allocation As with Homework 2, your program must use calloc() to dynamically allocate memory for the m×n board. Use calloc() here to allocate an array of m pointers, then for each of these pointers, use calloc() to allocate an array of size n. You must also use free() and have no memory leaks when your program terminates. Do not use malloc() or realloc(). Be sure your program has no memory leaks. Given that your solution is multi-threaded, you will need to be careful in how you manage your child threads and the boards, i.e., you will need to allocate (and free) memory for each child thread that you create. 4 Program execution To illustrate using an example, you could execute your program and have it work on a 3 × 3 board with Sonny starting at row 0 and column 0 as follows: bash$ ./a.out 3 3 0 0 This will generate the thread tree shown below, with indicating the current position of Sonny and indicating multiple possible moves from that cause child threads to be created. The numbers in this diagram show the order in which Sonny visits each square. +—+—+—+ main: || | | +—+—+—+ | | || +—+—+—+ | || | +—+—+—+ / pthread_create() / pthread_create() / +—+—+—+ +—+—+—+ T1: | 1 | 6 | 3 | T2: | 1 | 4 | 7 | +—+—+—+ +—+—+—+ | 4 | || | 6 | | 2 | +—+—+—+ +—+—+—+ | 7 | 2 | 5 | | 3 || 5 | +—+—+—+ +—+—+—+ Note that the center square is not visited at all in this example. Also note that both of these child threads will simultaneously try to set the global max_squares to 8 before terminating. To ensure a deterministic order of thread creation, if Sonny is in row a and column b, start looking for moves at row (a-2) and column (b-1), checking for moves counter-clockwise from there. As with Homework 2, try writing out the tree by hand using the 3×4 board below. Remember that child threads are created only when multiple moves are possible from a given board configuration. +—+—+—+—+ main: || | | | +—+—+—+—+ | | | | | +—+—+—+—+ | | | | | +—+—+—+—+ / pthread_create() / pthread_create() / etc. etc. 5 Required output When you execute your program, you must display a line of output each time you detect multiple possible moves, each time you reach a dead end or full knight’s tour, each time you update the global max_squares or total_tours variables, and each time a child thread is joined back in to its parent thread. Below is example output that shows the required output format. bash$ ./a.out 3 3 0 0 MAIN: Solving Sonny’s knight’s tour problem for a 3×3 board MAIN: Sonny starts at row 0 and column 0 (move #1) MAIN: 2 possible moves after move #1; creating 2 child threads… T1: Dead end at move #8; updated max_squares T2: Dead end at move #8 MAIN: T1 joined MAIN: T2 joined MAIN: Search complete; best solution(s) visited 8 squares out of 9 If a full knight’s tour is found, use the output format below. bash$ ./a.out 3 4 0 0 MAIN: Solving Sonny’s knight’s tour problem for a 3×4 board MAIN: Sonny starts at row 0 and column 0 (move #1) … T5: Sonny found a full knight’s tour; incremented total_tours … MAIN: Search complete; found 2 possible paths to achieving a full knight’s tour Match the above output format exactly as shown above, though note that the assigned thread IDs will vary. Further, interleaving of the output lines is expected, though the first few lines and the last line must be first and last, respectively. Running in “no parallel” mode To simplify the problem and help you test, you are also required to add support for an optional NO_PARALLEL flag that may be defined at compile time (see below). If defined, your program should join each child thread immediately after calling pthread_create(); this will ensure that you do not run child threads in parallel, which will therefore provide deterministic output that can more easily be matched on Submitty. To compile your code in NO_PARALLEL mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D NO_PARALLEL hw3-main.c hw3.c -pthread NOTE: This problem grows extremely quickly, so be careful in your attempts to run your program on boards larger than 4 × 4. 6 Error handling In general, if an error is encountered in any thread, display a meaningful error message on stderr by using either perror() or fprintf(), then abort further thread execution by calling pthread_exit(). Only use perror() if the given library function or system call sets the global errno variable. Error messages must be one line only and use the following format: ERROR: Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform. That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, make use of the DEBUG_MODE technique to make sure that Submitty does not execute any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -g -D DEBUG_MODE hw3-main.c hw3.c -pthread Second, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use. 7

$25.00 View

[SOLVED] Csci 4210 — operating systems homework 2

In this second homework, you will use C to implement a multi-process file parser that extracts valid words and sends them to a separate process via a pipe. More specifically, for each command-line argument, create a child process (via fork()) to open and read from each file. And for each file, extract valid words and write them to a pipe, which you will connect to a separate executable that is running on Submitty. (This executable is hidden.)All child processes will be running in parallel, i.e., given n input files, you will have n child processes running in parallel, each child process opening and reading its assigned input file. The parent process must call waitpid() for each child process—and the separate executable—before it also terminates. No square brackets allowed!To continue to master the use of pointers and pointer arithmetic, you are not allowed to use square brackets anywhere in your code! If a ‘[‘ or ‘]’ character is detected, including within comments, that line of code will be removed before running gcc. (Ouch!) To detect square brackets, remember you can use the command-line grep tool as shown below. bash$ grep ‘[‘ hw2.c … bash$ grep ‘]’ hw2.c …Each command-line argument specifies an input file. There is no defined limit to the number of input files given. For each input file, create a child process that opens the file, then parses and extracts all words (if any) from the given file. As with Homework 1, a word is any string of two or more alphanumeric characters, as defined by isalnum(). And you can again assume that each word is no more than 127 bytes long. All other characters serve as delimiters. Words are case sensitive (e.g., Lion is different than lion).Before creating any child processes, the parent process should create one pipe via the pipe() system call. This results in a “read” descriptor and a “write” descriptor for the pipe. Remember that when you call fork(), these descriptors are copied to the child process, i.e., the file descriptor table is inherited by the child process.The pipe “write” descriptor is used by each child process as follows. When a valid word is detected, the word is written to the pipe with a ‘.’ character to mark its end. For example, if valid words “lion” and “mouse” are extracted, they are sent as shown below in two separate write() calls of five bytes and six bytes, respectively. lion.mouse. The pipe “read” descriptor must first be passed as a command-line argument to the hw2-cache.out executable. Call fork() and execl() to execute this hidden executable program as a child process on Submitty. This hidden executable essentially collects words from the pipe descriptor and performs logic similar to that of Homework 1, storing words into a cache structure. Output from this separate executable will be captured in hw2-cache.txt and will be part of the auto-grading in Submitty. When no more data is written to the pipe, the hw2-cache.out executable will terminate, which must be acknowledged by your parent process via waitpid().Required output and exit status values When you execute your program, you must display a line of output in the parent for each input file, as well as a line of output describing the status of the child process when it terminates. Further, each child process must display the number of valid words encountered.When each child process terminates, it must return one of the following three values: • 3 if no valid words were found in the input file; • 2 if the given input file was not found; • EXIT_FAILURE (1) if some other error occurred; • EXIT_SUCCESS (0) if everything worked as expected. Given the lion.txt example file, you could run your code as follows: bash$ ./a.out lion.txtBelow is sample output from the above program execution that shows the format you must follow ((v1.1) corrected the output to show number of words in lion.txt): PARENT: Created pipe successfully PARENT: Calling fork() to create child process to execute hw2-cache.out… PARENT: Calling fork() to create child process for “lion.txt” file… CHILD: Successfully wrote 174 words on the pipe PARENT: Child process terminated with exit status 0 PARENT: Child running hw2-cache.out terminated with exit status 0 If any child process has an abnormal termination, display one of the following two lines of output: PARENT: Child process terminated abnormally PARENT: Child running hw2-cache.out terminated abnormally Note that the hw2-cache.out executable only outputs to an output file unless an error occurs. Errors are output to stderr.Error handling If improper command-line arguments are given, report an error message to stderr and abort further program execution. In general, if an error is encountered, display a meaningful error message on stderr by using either perror() or fprintf(), then aborting further program execution. Only use perror() if the given library or system call sets the global errno variable. Error messages must be one line only and use the following format: ERROR: Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform. That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below.First, make use of the DEBUG_MODE technique to make sure that Submitty does not execute any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw2.c Second, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use.

$25.00 View

[SOLVED] Csci 4210 — operating systems homework 1

In this first homework, you will use C to implement a rudimentary cache of words, which will be populated with strings read from an input file. Your cache must be a dynamically allocated hash table of a given fixed size that handles collisions by replacing the existing word.This hash table is really just a one-dimensional array of char * pointers. These pointers should all initially be set to NULL, then set to point to dynamically allocated strings for each cached word. No square brackets allowed!To emphasize and master the use of pointers and pointer arithmetic, you are not allowed to use square brackets anywhere in your code! As with our first lecture exercise, if a ‘[‘ or ‘]’ character is detected, including within comments, that line of code will be removed before running gcc. (Ouch!) To detect square brackets, consider using the command-line grep tool as shown below. bash$ grep ‘[‘ hw1.c … bash$ grep ‘]’ hw1.c … Can you combine this into one grep call? As a hint, check out the man page for grep. Review the posted code examples to better understand pointer arithmetic. In brief, square bracket expressions can generally be rewritten using pointer arithmetic by removing the square brackets, enclosing the sum of the array variable and the index in parentheses, then dereferencing the resulting pointer. A few equivalent examples follow: str[32] = ‘A’; *(str+32) = ‘A’; values[i] += 20; *(values+i) += 20; results[j] = j * 3.14; *(result+j) = j * 3.14; if ( strcmp( a, &b[10] ) == 0 ) { … } if ( strcmp( a, &(*(b+10)) ) == 0 ) { … } if ( strcmp( a, b+10 ) == 0 ) { … } Note that in this last example, we do not need to dereference the pointer since we are then using the address-of & operator; combined, these two operations negate one another.The first command-line argument specifies the size of the cache, which therefore indicates the size of the dynamically allocated char * array that you must create. Use calloc() to create this array of “placeholder” pointers. And use atoi() (or strtol()) to convert from a string to an integer on the command line. Next, your program must open and read the regular file specified by the second command-line argument. Your program must parse and extract all words (if any) from the given file. Here, a word is any string of two or more alphanumeric characters (see below). If a collision occurs, replace the pre-existing entry.To read in words from the input file, consider using a dynamically allocated character array of a fixed buffer size, e.g., 128. Read in 128-byte “chunks” from the file, parsing out words in this buffer. You can assume that each word is no more than 127 bytes long (since you want to save one byte to store the end-of-string ‘’ character).Initially, your cache is empty, meaning it is an array of NULL pointers. Storing each valid word therefore also requires dynamic memory allocation. For this, use calloc() if the cache array slot is empty; otherwise, to replace an existing value, use realloc() if the size of the required memory differs from what is already allocated.For words (e.g., “arch”), be sure to calculate the number of bytes to allocate as the length of the given word plus one, since strings in C are implemented as char arrays that end with a ‘’ character. Note that you are not allowed to use malloc() anywhere in your code! Is it a word or an integer—and how do you “hash” it? For this assignment, words are defined as containing only alphanumeric characters (see isalnum()) and consisting of at least two characters in length. All other characters serve as delimiters. And note that words are case sensitive (e.g., Lion is different than lion).To determine the cache array index for a given word, i.e., to properly “hash” the word, write a separate function called hash() that calculates the sum of each ASCII character in the given word as an int variable, then applies the “mod” operator to determine the remainder after dividing by the cache array size. As an example, the valid word Meme consists of four ASCII characters, which sum to 77 + 101 + 109 + 101 = 388. If the cache array size was 17, for example, then the array index for Meme would be the remainder of 388/17 or 14.Required Output When you execute your program, you must display a line of output for each valid word that you encounter in the given file. For each word, display the cache array index and whether you called calloc() or realloc()—or did not need to change the already existing memory allocation. Given the lion.txt example file, you could run your code as follows: bash$ ./a.out 17 lion.txtBelow is sample output from the above program execution that shows the format you must follow: Word “Once” ==> 15 (calloc) Word “when” ==> 9 (calloc) Word “Lion” ==> 11 (calloc) Word “was” ==> 8 (calloc) Word “asleep” ==> 5 (calloc) Word “little” ==> 8 (realloc) Word “Mouse” ==> 11 (realloc) Word “began” ==> 16 (calloc) Word “running” ==> 4 (calloc) Word “up” ==> 8 (realloc) Word “and” ==> 1 (calloc) Word “down” ==> 15 (nop) Word “upon” ==> 8 (realloc) Word “him” ==> 12 (calloc) … Further, when you have finished processing the input file, show the contents of the cache by displaying a line of output for each non-empty entry in the cache. Use the following format: Cache index 0 ==> “on” Cache index 1 ==> “gnawed” Cache index 2 ==> “King” Cache index 3 ==> “LITTLE” Cache index 4 ==> “went” Cache index 5 ==> “PROVE” Cache index 6 ==> “to” Cache index 7 ==> “tree” Cache index 8 ==> “little” Cache index 9 ==> “said” Cache index 10 ==> “MAY” Cache index 11 ==> “Mouse” Cache index 12 ==> “him” Cache index 13 ==> “FRIENDS” Cache index 14 ==> “GREAT” Cache index 15 ==> “the” Cache index 16 ==> “began”Error handling If improper command-line arguments are given, report an error message to stderr and abort further program execution. In general, if an error is encountered, display a meaningful error message on stderr by using either perror() or fprintf(), then aborting further program execution. Only use perror() if the given library or system call sets the global errno variable. Error messages must be one line only and use the following format: ERROR: Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform.That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, make use of the DEBUG_MODE technique to make sure that Submitty does not execute any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw1.c Second, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use.

$25.00 View

[SOLVED] Csci 4210 homework 4 network programming and multi-threaded programming using c

In this fourth and final homework assignment, you will use C to write server code to implement a multi-threaded chat server using sockets. Clients will be able to send and receive short text messages from one another. Note that all communication between clients must be handled and sent via your server.Clients communicate with your server via TCP or UDP via the port number specified as the first command-line argument. For TCP, clients connect to this port number (i.e., the TCP listener port). For UDP, clients send datagram(s) to this port number. To support both TCP and UDP at the same time, you must use the select() system call in the main thread to poll for incoming TCP connection requests and UDP datagrams.Your server must not be a single-threaded iterative server. Instead, your server must allocate a child thread for each TCP connection. Further, your server must be parallelized to the extent possible. As such, be sure you handle all potential synchronization issues. Note that your server must support clients implemented in any language (e.g., Java, C, Python, MIPS, etc.); therefore, only handle streams of bytes as opposed to any language-specific structures. And though you will only submit your server code for this assignment, plan to create one or more test clients. Test clients will not be provided, but feel free to share test clients with others via Submitty.Do not share server code. Also note that you can use netcat to test your server; but do not use telnet. Also remember the -u flag for UDP in netcat. Simultaneously supporting TCP and UDP To provide flexibility to clients, clients can either establish a connection via TCP or simply send/receive datagrams via UDP. As noted above, to support both TCP and UDP at the same time, you must use the select() system call in the main thread to poll for incoming TCP connection requests and UDP datagrams. Your server must support at least 32 concurrently connected clients (i.e., TCP connections, with each connection corresponding to a child thread).For TCP, use a dedicated child thread to handle each TCP connection. In other words, after the accept() call, immediately create a child thread to handle that connection, thereby enabling the main thread to loop back around and call select() again. For TCP, you are only guaranteed to receive data up to and including the first newline character in the first packet received; therefore, expect to implement multiple read() calls. Since UDP is connectionless, for UDP, use an iterative approach (i.e., handle incoming UDP datagrams in the main thread, then immediately loop back to the select() system call). Application-layer protocol The application-layer protocol between client and server is a line-based protocol. Streams of bytes (i.e., characters) are transmitted between clients and your server. Note that all commands are specified in upper-case and end with a newline (‘ ’) character, as shown below. In general, when the server receives a request, it responds with either a four-byte “OK! ” response or an error. When an error occurs, the server must respond with: ERROR For any error message not specified below, use a short human-readable description matching the simple one-line format shown above. Expect clients to display these error messages to users.The following subsections define the application-layer protocol commands. LOGIN If a client uses TCP, the user must first log in (though authentication is not required). A user identifies itself as follows: LOGIN Note that a valid is a string of alphanumeric characters with a length in the range [4,16]. Upon receiving a LOGIN request, if successful, the server sends the four-byte “OK! ” string. If the given is already connected via TCP, the server responds with an of “Already connected”; if is invalid, the server responds with an of “Invalid userid” (and in both cases keeps the TCP connection open).2 WHO A user may send a WHO request to obtain a list of all users currently active within the chat server. When your server receives this request, in addition to sending “OK! ” to the client, the response should consist of an ASCII-based sorted list of all users, with users delimited by newline (‘ ’) characters. As an example, the server may respond with the following: OK! Morty Rick Shirley Summer meme qwerty Note that the WHO command must be supported for both TCP and UDP. LOGOUT A user connected via TCP may send a LOGOUT request to ensure the server marks the user as being completely logged out and inactive.Note that this is recommended but not required for TCP, since the client can simply close its connection to indicate it is logging out. When a LOGOUT command is sent, the server is required to send an “OK! ” response. And the connection should stay open (until the remote side closes the connection). SEND A user connected via TCP may attempt to send a private message to another user via the SEND command.The required format of the SEND command is as follows: SEND To be a valid SEND request, the must be a currently active user and the (i.e., length of the portion) must be an integer in the range [1,990]. Note that the can contain any bytes whatsoever. You may assume that the number of bytes will always match the given value. If the request is valid, the server responds by sending an “OK! ” response. Further, the server attempts to send the message to the by sending a TCP packet using the following format: FROM If the request is invalid, send the appropriate error message from among the following: ˆ “Unknown userid” ˆ “Invalid msglen” ˆ “Invalid SEND format” ˆ “SEND not supported over UDP” 3 BROADCAST If a user wishes to send a message to all active users, the BROADCAST command can be used.This command can also be used via UDP, i.e., without the need to first log in. The format of this command is as follows: BROADCAST The and parameters match that of the SEND command above. For UDP, use a hard-coded “UDP-client” string for the that all UDP clients use. Handling system call errors In general, if a system call fails, use perror() to display the appropriate error message on stderr, then exit the program and return EXIT_FAILURE. If a system or library call does not set the global errno, use fprintf() instead of perror() to write an error message to stderr. Error messages must be one line only and use one of the appropriate formats shown below: MAIN: ERROR Or: CHILD : ERROR 4 Required Output Your server is required to output one or more lines describing each request that it receives.Required output is illustrated in the example below. As per usual, output lines may be interleaved as multiple clients interact with the server simultaneously. bash$ ./a.out 9876 MAIN: Started server MAIN: Listening for TCP connections on port: 9876 MAIN: Listening for UDP datagrams on port: 9876 … MAIN: Rcvd incoming TCP connection from: CHILD : Rcvd LOGIN request for userid Rick … MAIN: Rcvd incoming TCP connection from: CHILD : Rcvd LOGIN request for userid Morty CHILD : Rcvd WHO request CHILD : Rcvd SEND request to userid Rick CHILD : Rcvd SEND request to userid Summer CHILD : Sent ERROR (Unknown userid) CHILD : Rcvd WHO request MAIN: Rcvd incoming UDP datagram from: MAIN: Rcvd BROADCAST request CHILD : Client disconnected CHILD : Rcvd LOGOUT request CHILD : Client disconnected … MAIN: Rcvd incoming TCP connection from: CHILD : Rcvd LOGIN request for userid Rick CHILD : Rcvd WHO request CHILD : Rcvd SEND request to userid Rick CHILD : Rcvd SEND request to userid Rick CHILD : Rcvd SEND request to userid Morty MAIN: Rcvd incoming UDP datagram from: MAIN: Rcvd WHO request CHILD : Rcvd SEND request to userid Morty CHILD : Rcvd BROADCAST request CHILD : Client disconnected … Note that the required output above is certainly different than the specific data sent and received via the application-layer protocol. On Submitty, test clients will connect to your server and test whether you have correctly implemented all aspects of the application-layer protocol.Submission instructions To submit your assignment (and also perform final testing of your code), please use Submitty, the homework submission server. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should perform adequate testing on your own Ubuntu platform. That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, as discussed in class, use the DEBUG_MODE technique to make sure you do not submit any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of x is %d ”, x ); printf( “the value of q is %d ”, q ); printf( “why is my program crashing here?!” ); fflush( stdout ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw4.c -pthread Second, as also discussed in class, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure correctness on Submitty, this is a good technique to use. 6

$25.00 View

[SOLVED] Csci 4210 homework 3 multi-threading in c using pthreads

In this third assignment, you will use C and the POSIX thread (Pthread) library to implement a single-process multi-threaded system that solves the knight’s tour problem, i.e., can a knight move over all squares exactly once on a given board? Sonny plays the knight in our assignment.In brief, your program must determine whether a valid solution is possible for the knight’s tour problem on an m × n board. To accomplish this, your program simulates valid moves. And for each board configuration you encounter, when multiple moves are detected, each possible move is allocated to a new child thread, thereby forming a tree of possible moves.You must keep track of a global variable called max_squares that maintains the maximum number of squares covered by Sonny; when a dead end is encountered in a thread, that thread checks the max_squares variable, updating it if a new maximum is found. Further, a global shared array called dead_end_boards is used to maintain a list of “dead end” board configurations.Child threads add their detected “dead end” boards to the end of this array, which therefore requires proper synchronization. Note that a “dead end” does not include a fully covered board, i.e., a full knight’s tour. A valid move constitutes relocating Sonny the knight two squares in direction D and then one square 90° from D, where D is up, down, right, or left. Key to this problem is the restriction that Sonny may not land on a square more than once in its tour. Also note that Sonny starts in the upper-left corner of the board. When a dead end is encountered (i.e., no more moves can be made) or a fully covered board is achieved, the leaf node thread compares the number of squares covered to the global maximum, updating the global maximum, if necessary.Once all child threads have terminated for a given parent thread, the parent thread reports (i.e., returns to its own parent thread) the number of squares covered. When the top-level main thread joins all of its child threads, it displays the final maximum result, which is equal to product m × n if a full knight’s tour is possible. The top-level main thread also displays either all of the “dead end” boards or all “dead end” boards with at least x squares covered, where x is an optional (third) command-line argument.Command-line arguments and error handling There are two required command-line arguments; both are integers n and m, which together specify that the size of the board is m × n, where m is the number of rows and n is the number of columns in the board. As noted above, a third optional command-line argument, x, indicates that the main thread should display all “dead end” boards with at least x squares covered. Validate the inputs m and n to be sure both are integers greater than 2. Further, if present, validate input x to be sure it is a positive integer no greater than m × n. If invalid, display the following error message to stderr: ERROR: Invalid argument(s) USAGE: a.out [] In general, if a system call fails, use perror() to display the appropriate error message on stderr, then exit the program and return EXIT_FAILURE.If a system or library call does not set the global errno, use fprintf() instead of perror() to write an error message to stderr. See the various examples on the course website and corresponding man pages. Note that error messages must be one line only and use the following format: ERROR: 2 Dynamic memory allocation As with the previous two homework assignments, your program must use calloc() to dynamically allocate memory for the m × n board.More specifically, use calloc() to allocate an array of m pointers, then for each of these pointers, use malloc() or calloc() to allocate an array of size n. Of course, your program must also use free() and have no memory leaks. Note that you do not need to use realloc() for the individual m × n boards, but you definitely need to use realloc() to expand the global dead_end_boards array, as necessary. Given that your solution is multi-threaded, you will need to be careful in how you manage your child threads and the board; i.e., you will need to allocate (and free) memory for each child thread that you create.Program Execution To illustrate using an example, you could execute your program and have it work on a 3 × 3 board as follows: bash$ ./a.out 3 3 This will generate the thread tree shown below, with indicating the current position of Sonny. There are two dead end boards (i.e., the leaf nodes). For clarity on the order of moves, this diagram also shows the order in which Sonny visits each square. +—+—+—+ || | | +—+—+—+ | | | | +—+—+—+ | | | | +—+—+—+ / / / +—+—+—+ +—+—+—+ | 1 | 4 | 7 | | 1 | 6 | 3 | +—+—+—+ +—+—+—+ | 6 | | 2 | | 4 | || +—+—+—+ +—+—+—+ | 3 || 5 | | 7 | 2 | 5 | +—+—+—+ +—+—+—+ Note that the center square is not visited at all in this example. Also note that each of the two “dead end” boards would be added to the global shared array and displayed by the main thread once all child threads have completed. And note that child threads are only created if a given board configuration has multiple possible moves for Sonny the knight. To ensure a deterministic order of thread creation, if Sonny the knight is in row r and column c, start looking for moves at (c-2) and (r-1), then check for possible moves going clockwise from there. And note that row 0 and column 0 identify the upper-left corner of the board. 3 Required Output When you execute your program, you must display a line of output each time you detect multiple possible moves and each time you encounter a dead end. Note that you only display the dead end boards in the main thread once all child threads have ended (and been joined back in). Below is example output to illustrate the required output format. In this example, thread ID (tid) 1000 is the top-level main thread, with threads 1001 and 1002 being child threads to thread 1000. bash$ ./a.out 3 3 THREAD 1000: Solving Sonny’s knight’s tour problem for a 3×3 board THREAD 1000: 2 moves possible after move #1; creating threads… THREAD 1001: Dead end after move #8 THREAD 1002: Dead end after move #8 THREAD 1000: Thread [1001] joined (returned 8) THREAD 1000: Thread [1002] joined (returned 8) THREAD 1000: Best solution(s) found visit 8 squares (out of 9) THREAD 1000: Dead end boards: THREAD 1000: > SSS THREAD 1000: S.S THREAD 1000: SSS THREAD 1000: > SSS THREAD 1000: S.S THREAD 1000: SSS If a full knight’s tour is found, display the following line of output: THREAD 2010: Sonny found a full knight’s tour! Match the above output format exactly as shown above, though note that the tid values will vary. Further, interleaving of the output lines of the child threads may occur. To simplify the problem and help you test, you are also required to add support for an optional NO_PARALLEL flag that could be defined at compile time (i.e., via -D NO_PARALLEL). If defined, your program should join each child thread immediately after calling pthread_create() to be sure that you do not run child threads in parallel. This will also provide fully deterministic output that can more easily be matched on Submitty. To compile this code in NO_PARALLEL mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D NO_PARALLEL hw3.c -pthread 4 Submission instructions To submit your assignment (and also perform final testing of your code), please use Submitty, the homework submission server. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should perform adequate testing on your own Ubuntu platform. That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, as discussed in class, use the DEBUG_MODE technique to make sure you do not submit any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of x is %d ”, x ); printf( “the value of q is %d ”, q ); printf( “why is my program crashing here?!” ); fflush( stdout ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw3.c -pthread Second, as also discussed in class, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure correctness on Submitty, this is a good technique to use. 5

$25.00 View

[SOLVED] Csci 4210 homework 2 process creation and process management in c

In this second homework, you will use C to implement a rudimentary interactive shell similar to that of bash. The focus of this assignment is on process creation, process management, and inter-process communication (IPC) via fork(), wait(), waitpid(), pipe(), etc.As with Homework 1, continue to use calloc(), realloc(), and free() to properly and efficiently manage your memory usage. Consider using valgrind to verify that there are no memory leaks. We will continue to test for this on Submitty.To properly implement your shell, create an infinite loop that repeatedly prompts the user to enter a command, parses the given command, locates the command executable, then executes the command (if found).To execute the given command, a child process is created via fork(), with the child process then calling execv() to execute the command. In the meanwhile, the parent process calls waitpid() to suspend its execution and wait for the child process to terminate. This is called foreground processing. (And note that you must use these specific system calls.)If instead the command is to be run with the parent process not waiting for the child process to complete its execution, then your shell will instead use background processing, which is achieved by using the & symbol (and explained in more detail on page 4).Before executing a command entered by the user, the command executable must be found using the list of possible paths specified by an assignment-specific environment variable called $MYPATH. Do not use $PATH for this assignment (since $PATH is used for bash).Similar to $PATH, this new $MYPATH environment variable consists of a series of paths delimited by the : character. And if $MYPATH is not set, use /bin:. as the default, meaning commands will be searched for first in the /bin directory, then the . (i.e., current) directory. By default, the $MYPATH variable is not set, so for testing, set and unset this variable manually in the bash shell before running your shell.Here’s how: bash$ export MYPATH=/usr/local/bin:/usr/bin:/bin:. bash$ echo $MYPATH MYPATH=/usr/local/bin:/usr/bin:/bin:. bash$ unset MYPATH To obtain $MYPATH (or any environment variable, e.g., $HOME) from within your program, use the getenv() function. Do not use setenv().Searching left-to-right in $MYPATH, if the requested command is found in one of the specified directories, your program runs the executable in a child process via the fork() and execv() system calls. Note that you must use execv().Further, in the parent process, you must use lstat() to determine whether the requested command exists (e.g., does /bin/ls exist?) and whether it is executable. See the man page and the directories.c example.Commands are line-based, as in bash. Therefore, each command may optionally have any number of arguments (i.e., argv[1], argv[2], etc.). You can assume that each command read from the user will not exceed 1024 characters. Further, you can assume that each argument will not exceed 64 characters, but all memory must be dynamically allocated. You may also assume that command-line arguments do not contain spaces. In other words, do not worry about parsing out quoted strings in your argument list, as in: bash$ cat a.txt b.txt “some weird file.txt” d.txtNot all commands entered into the shell actually result in a call to fork(). For the cd command, if your shell did execute the command via fork(), your shell’s current working directory would not change! Therefore, you must use the chdir() system call in the parent to handle this special case. Further, if the cd command has no arguments, then you should use the $HOME environment variable as the target directory.As for wildcards and special characters, you do not need to support *, ?, and [] in your shell, though note that these are typically expanded by the shell before calling fork() and execv(). Finally, to exit your shell, the user enters exit. When this occurs, your shell must output bye and terminate.Required output The command prompt in the shell must show the current working directory followed by the ‘$’ prompt character and one space. To obtain the current working directory for the running process, use the getcwd() function. And use fgets() to read in a command from the user. Required output is shown below, with sample input also shown. As per usual, you must match the given output format exactly as shown. /cs/goldsd/s19/os/assignments/hw2$ cocoapuffs ERROR: command “cocoapuffs” not found /cs/goldsd/s19/os/assignments/hw2$ ls annoying.c a.out code hw2.aux hw2.log hw2.out hw2.pdf hw2.tex /cs/goldsd/s19/os/assignments/hw2$ ls -l total 156 drwxrwx–x 3 goldsd goldsd 4096 May 27 15:08 . drwxrwx–x 5 goldsd goldsd 51 May 27 11:59 .. -rw-rw—-+ 1 goldsd goldsd 197 May 27 15:08 annoying.c -rwxrwx–x 1 goldsd goldsd 8344 May 27 15:08 a.out drwxrwx–x 2 goldsd goldsd 6 May 27 15:04 code -rw-rw—- 1 goldsd goldsd 662 May 27 15:04 hw2.aux -rw-rw—- 1 goldsd goldsd 20507 May 27 15:04 hw2.log -rw-rw—- 1 goldsd goldsd 0 May 27 15:04 hw2.out -rw-rw—- 1 goldsd goldsd 97289 May 27 15:04 hw2.pdf -rw-rw—-+ 1 goldsd goldsd 9886 May 27 15:07 hw2.tex /cs/goldsd/s19/os/assignments/hw2$ cat annoying.c /* annoying.c */ #include #include #include int main() { while ( 1 ) { printf( “Hey, get back to work! ” ); sleep( 3 ); } return EXIT_SUCCESS; } /cs/goldsd/s19/os/assignments/hw2$ exit byeNormally, a shell will execute the given command via a child process, with the parent calling either wait() or waitpid() to wait for the child process to complete its command and terminate. The child process essentially calls execv() to execute the given command with the arguments allocated dynamically.Your shell must be able to execute a process in the background if the user includes an ampersand (i.e., ‘&’) at the end of a command. In this case, when the child process is created, the parent does not wait for the child to terminate before prompting the user for the next command.For a background process, the parent must report that the child process has been created. The parent must also report when the child process does terminate (if it does). When you detect that the background process has terminated (i.e., before you display the prompt), display the child process ID and its exit status, as in: [process 9335 terminated with exit status 0]This should be the normal reporting for all children that terminate whether they return EXIT SUCCESS or an error code. For background child processes that terminate due to a kill signal or other abnormal termination, display the following: [process 9335 terminated abnormally]Note that the & symbol can only be included at the end of the command line; otherwise, this is a user error. Also note that the output may be interleaved with background processes, so do not expect to always match the example output exactly line for line. /cs/goldsd/s19/os/assignments/hw2$ ls annoying.c a.out code hw2.aux hw2.log hw2.out hw2.pdf hw2.tex /cs/goldsd/s19/os/assignments/hw2$ a.out & [running background process “a.out”] Hey, get back to work! /cs/goldsd/s19/os/assignments/hw2$ Hey, get back to work! Hey, get back to work! Hey, get back to work! /cs/goldsd/s19/os/assignments/hw2$ ls annoying.c a.out code hw2.aux hw2.log hw2.out hw2.pdf hw2.tex /cs/goldsd/s19/os/assignments/hw2$ Hey, get back to work! Hey, get back to work! Hey, get back to work! /cs/goldsd/s19/os/assignments/hw2$ exit bye Hey, get back to work! Hey, get back to work! For the above example, you will need to use kill in the bash shell to terminate the background process since it will continue to execute after your shell terminates. And note that for this assignment, you are required to use waitpid() for both foreground and background processes.Do not do anything extra to kill any child processes, in particular when the user exits your shell. And to properly “catch” background processes when they terminate, mimic the behavior of bash by checking for terminated background processes immediately before you display the prompt to the user. Do not use a signal handler for this.IPC via pipes Finally, add support for a pipe between two processes; you need only support one pipe per command line. Two processes (i.e., A and B) may be connected via a pipe such that the output on stdout from process A is the input on stdin to process B. A pipe is indicated via the | symbol. To create a pipe, use the pipe() system call. Further, the two processes A and B must have your shell process as their parent process. /cs/goldsd/s19/os/assignments/hw2$ ps -ef | grep goldsd root 23553 1414 0 15:00 ? 00:00:00 sshd: goldsd [priv] goldsd 23556 1 0 15:00 ? 00:00:00 /lib/systemd/systemd –user goldsd 23558 23556 0 15:00 ? 00:00:00 (sd-pam) goldsd 23714 23553 0 15:00 ? 00:00:00 sshd: goldsd@pts/0 goldsd 23715 23714 0 15:00 pts/0 00:00:00 -bash goldsd 23716 23715 0 15:00 pts/0 00:00:00 myshell root 23729 1414 0 15:01 ? 00:00:00 sshd: goldsd [priv] goldsd 23813 23729 0 15:01 ? 00:00:00 sshd: goldsd@notty goldsd 23814 23813 0 15:01 ? 00:00:00 /usr/lib/openssh/sftp-server goldsd 24615 23716 0 15:15 pts/0 00:00:00 ps -ef goldsd 24616 23716 0 15:15 pts/0 00:00:00 grep goldsd /cs/goldsd/s19/os/assignments/hw2$ ls -1 annoying.c a.out code hw2.aux hw2.log hw2.out hw2.pdf hw2.tex /cs/goldsd/s19/os/assignments/hw2$ ls -1 | wc -l 8 /cs/goldsd/s19/os/assignments/hw2$ exit byeNote that a pair of piped processes can be run in the background if the user specifies an ampersand at the end of the line. When run in the background, both processes are background processes. And when these processes terminate, show both processes.Here is an example with 12117 and 12118 as the process IDs of the two background processes: /cs/goldsd/s19/os/assignments/hw2$ ls -1 | wc -l 8 /cs/goldsd/s19/os/assignments/hw2$ ls -1 | wc -l & [running background process “ls”] [running background process “wc”] /cs/goldsd/s19/os/assignments/hw2$ 8 [process 12117 terminated with exit status 0] [process 12118 terminated with exit status 0] /cs/goldsd/s19/os/assignments/hw2$ exit bye As noted previously, output may be interleaved with background processes, so do not expect to always match the example output exactly line for line. Relinquishing allocated resources Be sure that all processes (i.e., the parent shell process and all child processes) properly deallocate memory via free(), close all opened file descriptors, etc.Error handling If improper command-line arguments are given, report an error message to stderr and abort further program execution. In general, if an error is encountered, display a meaningful error message on stderr by using either perror() or fprintf(), then abort further program execution. Error messages must be one line only and use the following format: ERROR: Note that you should not abort your shell program if the user enters an invalid command (e.g., command not found) or if the child process reports an error.Submission instructions To submit your assignment (and also perform final testing of your code), please use Submitty, the homework submission server. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform.That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, as discussed in class, use the DEBUG_MODE technique to make sure you do not submit any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of x is %d ”, x ); printf( “the value of q is %d ”, q ); printf( “why is my program crashing here?!” ); printf( “aaaaaaaaaaaaagggggggghhhh!” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw2.c Second, as discussed in class, output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use.

$25.00 View

[SOLVED] Csci 4210 homework 1 files, strings, and memory allocation in c

In this first homework, you will use C to implement a rudimentary cache of words found in a given text file. For this assignment, the cache will simply be a hash table. And this hash table will handle collisions by replacing the existing word with the new word.The goal of this assignment is to become more comfortable programming in C on Linux, in particular handling strings, working with pointers, and dynamically allocating memory. To emphasize and master the use of pointers, you are not allowed to use square brackets in your code! If a ‘[‘ or ‘]’ character is anywhere in your code, including within comments, you will receive a zero for this assignment. (Ouch!)The first command-line argument specifies the size of the cache, which therefore indicates the size of the dynamically allocated array that you must create. To create the array, use calloc() (not malloc()) to create an array of character pointers. Use atoi() for the conversion here.Your program must then open and read the regular file specified as the second command-line argument. Your program must parse all words from the given file (if any), determine the cache array index for each word (in the order encountered), then store the word in the cache, replacing any existing word if a collision occurs.To read in each word from the given file, you should use a dynamically allocated character array of size 128. In other words, you can assume that each word is no more than 127 characters long. Initially, your cache is empty, meaning it is an array of NULL pointers, since calloc() will zero out the allocated memory. Storing each word therefore also requires dynamic memory allocation.For this, use calloc() if the cache array slot is empty; otherwise, to replace an existing word, use realloc(). Be sure to calculate the number of bytes to allocate as the length of the given word plus one, since strings in C are implemented as char arrays that end with a ‘’ character. Finally, be sure to use free() to ensure all dynamically allocated memory is properly deallocated. Consider using valgrind to verify that there are no memory leaks.What is a word and how do you “hash” it? For this assignment, words are defined as containing only alphanumeric characters and being at least three characters in length. Further, words are case sensitive (e.g., Lion is different than lion). To determine the cache array index for a given word (i.e., to properly “hash” the word), write a function to add up the sum of each ASCII character in the given word as an int variable, then use the “mod” operator to determine the remainder after dividing by the cache array size. As an example, the valid word Meme consists of four ASCII characters, which sum 77 + 101 + 109 + 101 = 388. If the cache array size was 17, then the array index for Meme would be the remainder of 388/17 or 14.Error handling If improper command-line arguments are given, report an error message to stderr and abort further program execution. In general, if an error is encountered, display a meaningful error message on stderr by using either perror() or fprintf(), then aborting further program execution. Error messages must be one line only and use the following format: ERROR: Required Output When you execute your program, you must display a line of output for each word that you encounter. And for each word, display the cache array index and whether you called calloc() or realloc(). As an example, below is sample output, showing the format you must follow: Word “Once” ==> 15 (calloc) Word “when” ==> 9 (calloc) Word “Lion” ==> 11 (calloc) Word “was” ==> 8 (calloc) Word “asleep” ==> 5 (calloc) Word “little” ==> 8 (realloc) Word “Mouse” ==> 11 (realloc) Word “began” ==> 16 (calloc) … Further, when you have processed the entire file, show the contents of the cache by displaying a line of output for each non-empty entry in the cache, using the following format: Cache index 5 ==> “asleep” Cache index 8 ==> “little” Cache index 9 ==> “when” Cache index 11 ==> “Mouse” Cache index 15 ==> “Once” Cache index 16 ==> “began”Hints Consider using fopen(), fgets(), fgetc(), isalnum(), strlen(), strcpy(), strncpy(), and other such string and character functions for this assignment. Be sure to check out the details of each function by reviewing the corresponding man pages from the terminal.Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty, the homework submission server. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask on the Discussion Forum when Submitty will be available, as you should perform adequate testing on your own Ubuntu platform.That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, as discussed in class (on 1/17), use the DEBUG_MODE technique to make sure you do not submit any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of x is %d ”, x ); printf( “the value of q is %d ”, q ); printf( “why is my program crashing here?!” ); fflush( stdout ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw1.c Second, as discussed in class (on 1/17), output to standard output (stdout) is buffered. To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure correctness on Submitty, this is a good technique to use.

$25.00 View

[SOLVED] Csci 4210 homework 3 multi-threaded network programming and wordle

In this third and final assignment, you will use C to implement a single-process multi-threaded TCP server for the Wordle word game. You will use POSIX threads to implement a TCP server that handles multiple client connections in parallel.Specifically, your top-level main thread blocks on the accept() system call, listening on the port number specified as a command-line argument. For each connection request received by your server, create a child thread via pthread_create() to handle that specific connection. Each child thread manages game play for one client and only for one hidden word. Both during and after game play ends, child threads update a set of global variables.Note that child threads are not joined back in to the main thread. And remember that all threads run within one process. Wordle game play To learn how to play this one-player game, visit https://www.nytimes.com/games/wordle. In brief, a five-letter word is selected at random, then a player has up to six guesses to guess the hidden word. For each guess, the player sees which guessed letters are in the correct position (if any), which guessed letters are in the word in an incorrect position (if any), and which guessed letters are not in the word at all.Note that only valid five-letter words are allowed as guesses! Therefore, if a guess is not in the given dictionary file, it does not count as a guess. In general, expect your server to receive anything, including erroneous data. Game play stops when the player guesses the word correctly or runs out of guesses. In either case, the server thread closes the TCP connection, then that corresponding thread terminates. Global variables and compilation The given hw3-main.c source file contains a short main() function that initializes four global variables, then calls the wordle_server() function, which you must write in your own hw3.c source file.Submitty will compile your hw3.c code as follows: bash$ gcc -Wall -Werror hw3-main.c hw3.c -pthread You are required to make use of the four global variables in the given hw3-main.c source file. To do so, declare them as external variables in your hw3.c code as follows: extern int total_guesses; extern int total_wins; extern int total_losses; extern char ** words; The first three global variables shown above count the total number of valid guesses, the total number of games won, and the total number of games lost, respectively. These totals are accumulated across all active players during game play for the entire lifetime of the server. The words array is a dynamically allocated array of character strings representing all of the hidden words actually used in game play.This array is initially empty—specifically, it is set (in hw3-main.c) to be an array of size 1, with *words initialized to NULL. Similar to argv, the last entry in this array must always be NULL so that the list of hidden words can be displayed using a loop, as shown below. (Refer to command-line-args.c for an example using this technique.) for ( char ** ptr = words ; *ptr ; ptr++ ) { printf( “HIDDEN WORD: %s ”, *ptr ); } Submitty test cases will check these global variables when your wordle_server() function returns. Be sure your server returns either EXIT_SUCCESS or EXIT_FAILURE. Feel free to use additional global variables in your own code. And since multiple threads will be accessing and changing these global variables, synchronization is required.The specifications below focus on the application-layer protocol that your server must implement to successfully communicate with multiple clients simultaneously. Once a connection is accepted, the client sends a five-byte packet containing a guess, e.g., “ready”; the guessed word can be a mix of uppercase and lowercase letters, as case does not matter. The server replies with an eight-byte packet that is formatted as follows: +—–+—–+—–+—–+—–+—–+—–+—–+ SERVER REPLY: |valid| guesses | result | |guess| remaining | | +—–+—–+—–+—–+—–+—–+—–+—–+ The valid guess field is a one-byte char value that is either ‘Y’ (yes) or ‘N’ (no).The guesses remaining field is a two-byte short value that indicates how many guesses the client has left. Since a client starts with six guesses, this counts down from five to zero for each valid guess made. The result field is a five-byte character string that corresponds to the client’s guess. If a guess is not valid, simply send “?????”; for a valid guess, encode the results as follows. Use an uppercase letter to indicate a matching letter in the correct position. Use a lowercase letter to indicate a letter that is in the word but not in the correct position. And use a ‘-‘ character to indicate an incorrect letter not in the word at all. As an example, if the hidden word is “wears,” and a client guesses “ready,” the server replies with “rEA–“; note that both guesses and words may contain duplicate letters. In such cases, there are additional rules to follow.As an example, assume the hidden word is “radar.” If a client guesses a word with duplicate letters, the response indicates how many such duplicates appear in the hidden word. For example, guessing “whirr,” the response is “—rR”. If instead the hidden word is “sewer,” the response is “w—R” for guess “whirr.” As a trickier example, if the guess is “error” (for hidden word “radar”), the response is “-r–R” since the matching letter is shown, then duplicates are evaluated left-to-right. As another example, if a client guesses a word with a duplicate letter that only appears once in the hidden word (e.g., guessing “muddy” when the hidden word is “radar”), only one duplicate letter guessed will be in the response (e.g., “–D–“).Finally, if a client guesses a word with a duplicate letter that appears at least twice in the hidden word (e.g., guessing “muddy” when the hidden word is “udder”), both duplicate letters guessed will be in the response (e.g., “-uDd-“). The game ends when the client sends the correct word or the number of guesses remaining reaches zero. When the game is over, the server closes the TCP connection. 3 Command-line arguments There are four required command-line arguments. The first command-line argument specifies the TCP listener port number.The second command-line argument specifies the seed value for the pseudo-random number generator— this is used to “randomly” select words in a predictable and repeatable manner via rand(). The third command-line argument specifies the name (or path) of the input file containing valid words (i.e., the dictionary file), and the fourth command-line argument specifies the number of words in this input file. Validate the inputs as necessary. If invalid, display the following to stderr and return EXIT_FAILURE: ERROR: Invalid argument(s) USAGE: hw3.out The input file should contain words delimited by newline characters. Case does not matter. Here is an example file: “ready heavy UPPER VaguE ” Signals and server termination Since servers are typically designed to run forever without interruption, ignore signals SIGINT, SIGTERM, and SIGUSR2.Still, we need a mechanism to shut down the server. Set up a signal handler for SIGUSR1 that gracefully shuts down your server by terminating any running child threads, freeing up dynamically allocated memory, and returning from the wordle_server() function with EXIT_SUCCESS. Dynamic memory allocation As with previous homeworks, you must use calloc() to dynamically allocate memory. For the global words array, you must also use realloc() to extend the size of the array. Do not use malloc(). And of course, be sure your program has no memory leaks. No square brackets allowed! As per usual, you are not allowed to use square brackets anywhere in your code! If a ‘[‘ or ‘]’ character is detected, including within comments, that line of code will be removed before running gcc.4 Program execution and required output To illustrate via an example, you could execute your program as shown below, which has your server process listening on port 8192 for incoming TCP connection requests. bash$ ./hw3.out 8192 111 wordle-words.txt 5757 MAIN: opened wordle-words.txt (5757 words) MAIN: seeded pseudo-random number generator with 111 MAIN: Wordle server listening on port {8192} MAIN: rcvd incoming connection request THREAD 139711842105088: waiting for guess THREAD 139711842105088: rcvd guess: stare THREAD 139711842105088: sending reply: –ArE (5 guesses left) THREAD 139711842105088: waiting for guess THREAD 139711842105088: rcvd guess: brade THREAD 139711842105088: invalid guess; sending reply: ????? (5 guesses left) THREAD 139711842105088: waiting for guess MAIN: rcvd incoming connection request THREAD 139711833601792: waiting for guess THREAD 139711842105088: rcvd guess: brake THREAD 139711842105088: sending reply: BRA-E (4 guesses left) THREAD 139711842105088: waiting for guess THREAD 139711842105088: rcvd guess: brace THREAD 139711842105088: sending reply: BRACE (3 guesses left) THREAD 139711842105088: game over; word was BRACE! … MAIN: SIGUSR1 rcvd; Wordle server shutting down… To display thread IDs, use “%lu” and pthread_self() in your printf() calls.Note that you might see duplicate thread IDs for threads not running in parallel. If a client closes the TCP connection, your server must detect that and display the following, counting the game as a loss: THREAD 139711833601792: client gave up; closing TCP connection… Match the above output format exactly as shown above, though note that thread IDs will certainly vary. Also, interleaving output across multiple child threads is expected, though the first four lines and the last line must be first and last, respectively. 5 Error handling In general, if an error is encountered in any thread, display a meaningful error message on stderr by using either perror() or fprintf(), then aborting further program execution by calling pthread_exit(). Only use perror() if the given library function or system call sets the global errno variable. Error messages must be one line only and use the following format: ERROR:Submission Instructions To submit your assignment (and also perform final testing of your code), please use Submitty. Note that this assignment will be available on Submitty a minimum of three days before the due date. Please do not ask when Submitty will be available, as you should first perform adequate testing on your own Ubuntu platform. That said, to make sure that your program does execute properly everywhere, including Submitty, use the techniques below. First, make use of the DEBUG_MODE technique to make sure that Submitty does not execute any debugging code. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh square brackets! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw3.c Second, output to standard output (stdout) is buffered.To disable buffered output for grading on Submitty, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice, as this can substantially slow down your program, but to ensure good results on Submitty, this is a good technique to use. 6

$25.00 View

[SOLVED] Csci 4210 homework 1 processes, pipes, and an abridged (m, n)-queens problem

In this second homework, you will use C to implement a multi-process solution to a variation of the n-Queens problem. In the classic n-Queens problem, the goal is to place n Queens on an n × n chessboard such that no Queens attack any other Queens. For our homework, we generalize the problem to an m × n chessboard and will attempt to answer the following questions: • What is the maximum number of non-attacking Queens that we can place on an m×n board? Note that if a solution exists, this maximum will be the minimum of m and n.• If a solution exists, how many distinct solutions exist? • (v1.1) Using the abridged algorithm described below, how many dead ends do we encounter? (v1.1) Call our problem the Abridged (m, n)-Queens problem. The fundamental goal of this homework is to use fork(), waitpid(), and pipe() to achieve a fully synchronized parallel solution.To accomplish this, your program uses a brute force approach to explore (v1.1) a subset of all possible valid boards. Here, each subsequent placement of a Queen occurs via fork() to generate a (potentially very large) process tree. For consistency, row 0 and column 0 identify the upper-left corner of the m × n board. If m and n are equal or m < n, the algorithm that you must implement attempts to place a Queen in each row, starting at row 0.For each square within that row in which a Queen can be placed, call fork() to assign a child process the task of exploring that “move”; here, a valid move is the placement of a Queen such that no Queen attacks any other Queen currently on the board. Continue to row 1, row 2, etc., until an end-state is reached. An end-state is either (1) a valid solution or (2) a dead-end in which a Queen cannot be placed in the given row. In both of these cases, the child process is a leaf node in the generated process tree.Specifically, a new child process is created only if a move is possible with the given board configuration. As a hint to implementing this, when you call fork(), the state of the parent process is copied to the child, i.e., all variables within scope are copied. If n < m, then m − n rows are empty; therefore, to simplify the problem and use the above algorithm, just swap m and n before your first line of output.To communicate between processes, the top-level parent process creates exactly one pipe that all child processes will use to report their results. Each child process will share this unidirectional communication channel back to the top-level parent process. Do not create more than one pipe! The pipe is written to for each end-state encountered, i.e., when a final Queen is placed and therefore either a solution is found or a dead-end is reached. When this occurs (in a leaf node of the process tree), the child process writes to the pipe to notify the top-level parent process how many Queens were successfully placed. Use whatever protocol you would like to accomplish this, noting that the values written to the pipe will range from 1 to m. And you may assume that m will be no larger than 256. Each intermediate node of the tree must wait until all of its child processes have terminated. At that point, the intermediate node terminates. (v1.1) The exit status of each process should be EXIT_SUCCESS or, if an error occurs, use abort() to stop the process.Once all child processes in the process tree have terminated, the top-level process outputs a summary of the results. If an error occurs (e.g., fork() fails), use abort() to stop the running process. In the parent process, if a child process terminates abnormally, have the parent process also call abort(). The goal is to have an error cascade back to the top-level process. Dynamic Memory Allocation You must use calloc() to dynamically allocate memory for the m × n board. Use the two-layer structure approach from Homework 1, i.e., use calloc() to allocate an array of m pointers, then for each of these pointers, use calloc() to allocate an array of n characters.Of course, you must also use free() and have no memory leaks or invalid reads/writes through all running and terminating processes. Do not use malloc(), realloc(), or memset(). Command-line arguments There are two required command-line arguments. Integers m and n together specify the size of the board as m × n, where m is the number of rows and n is the number of columns. Rows are numbered 0 . . .(m − 1) and columns are numbered 0 . . .(n − 1). Validate m and n to be sure that both are integers greater than zero. If invalid, display the following error message to stderr and return EXIT_FAILURE; (v1.1) do not use abort() in this case. ERROR: Invalid argument(s) USAGE: hw2.out As a reminder, if n < m, swap m and n before your first line of output.3 Program Execution As an example, you could execute your program and have it work on a 3 × 3 board as follows: bash$ ./hw2.out 3 3 This will generate the process tree shown below starting with process P100. +—+—+—+ P100:| | | | +—+—+—+ | | | | +—+—+—+ | | | | +—+—+—+ / | / | / | fork() / | fork() / | / fork() | / | / | +—+—+—+ +—+—+—+ +—+—+—+ P101:| Q | | | P102:| | Q | | P103:| | | Q | +—+—+—+ +—+—+—+ +—+—+—+ | | | | | | | | | | | | +—+—+—+ +—+—+—+ +—+—+—+ | | | | | | | | | | | | +—+—+—+ +—+—+—+ +—+—+—+ | | fork() | fork() | | | +—+—+—+ +—+—+—+ P104:| Q | | | P105:| | | Q | +—+—+—+ +—+—+—+ | | | Q | | Q | | | +—+—+—+ +—+—+—+ | | | | | | | | +—+—+—+ +—+—+—+ To ensure a deterministic order of process creation at each row, iterate through the given row from column 0 to column (n − 1).In the above example, P100 creates processes P101, P102, and P103 in that order. Leaf nodes P104 and P105 both write 2 to the pipe, whereas P102 writes 1. 4 Required output Display a line of output when you determine the number of moves for a given row and when you reach an end-state. (v1.1) Note that sample output below and on the next page has been updated by adding “Abridged” to the output. Corresponding to the example on the previous page, below is sample parallelized output that shows the required output format. Use getpid() to display actual process IDs. bash$ ./hw2.out 3 3 P100: solving the Abridged (m,n)-Queens problem for 3×3 board P100: 3 possible moves at row #0; creating 3 child processes… P101: 1 possible move at row #1; creating 1 child process… P102: dead end at row #1; notifying top-level parent P103: 1 possible move at row #1; creating 1 child process… P104: dead end at row #2; notifying top-level parent P105: dead end at row #2; notifying top-level parent P100: search complete P100: number of 1-Queen end-states: 1 P100: number of 2-Queen end-states: 2 P100: number of 3-Queen end-states: 0 If a solution is found, use the output format below. bash$ ./hw2.out 4 4 P200: solving the Abridged (m,n)-Queens problem for 4×4 board P200: 4 possible moves at row #0; creating 4 child processes… P201: 2 possible moves at row #1; creating 2 child processes… … P208: found a solution; notifying top-level parent … P200: search complete P200: number of 1-Queen end-states: 0 P200: number of 2-Queen end-states: 2 P200: number of 3-Queen end-states: 2 P200: number of 4-Queen end-states: 2Match the above output format exactly as shown, though note that the process IDs will vary. Further, interleaving of the output lines is expected, though the first two lines and the last m+1 lines must always be first and last, respectively.5 Running in “quiet” mode To help scale your solution up to larger boards, you are required to support an optional QUIET flag that may be defined at compile time (see below). If defined, your program displays only the first two lines and the final m+1 lines of output in the top-level parent process. To compile your code in QUIET mode, use the -D flag as follows: bash$ gcc -Wall -Werror -o hw2.out -D QUIET hw2.c bash$ ./hw2.out 8 8 P200: solving the Abridged (m,n)-Queens problem for 8×8 board P200: 8 possible moves at row #0; creating 8 child processes… P200: search complete P200: number of 1-Queen end-states: 0 P200: number of 2-Queen end-states: 0 P200: number of 3-Queen end-states: 0 P200: number of 4-Queen end-states: 18 P200: number of 5-Queen end-states: 150 P200: number of 6-Queen end-states: 256 P200: number of 7-Queen end-states: 220 P200: number of 8-Queen end-states: 92 In your code, use the #ifdef and #ifndef (i.e., if not defined) preprocessor directives as follows: #ifndef QUIET printf( “P%d: dead end at row #%d; notifying top-level parent ”, … ); #endif Running in “no parallel” modeTo simplify the problem and help you test, you are also required to add support for an optional NO_PARALLEL flag that may be defined at compile time (see below). If defined, your program uses a blocking waitpid() call immediately after calling fork(); this will ensure that you do not run child processes in parallel, which will therefore provide deterministic output that can more easily be matched on Submitty. To compile this code in NO_PARALLEL mode, use the -D flag as follows: bash$ gcc -Wall -Werror -o hw2.out -D NO_PARALLEL hw2.c NOTE: This problem grows extremely quickly, so be careful in your attempts to run your program on boards larger than 4 × 4.6 Submission instructions To submit your assignment (and perform final testing of your code), we will use Submitty. To help make sure that your program executes properly, use the techniques below. First, make use of the DEBUG_MODE preprocessor technique that helps avoid accidentally displaying extraneous output in Submitty. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh square brackets! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw2.c Second, output to standard output (stdout) is buffered. To disable buffered output, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice since this can slow down your program, but to ensure you see as much output as possible in Submitty, this is a good technique to use. 7

$25.00 View

[SOLVED] Csci 4210 homework 1 dynamic memory allocation, pointer arithmetic, and files

In this first homework, you will use C to implement a rudimentary cache of words, which will be populated with strings read from one or more input files. Your cache must be a dynamically allocated hash table of a given fixed size that handles collisions by simply replacing the existing word.This hash table is really just a one-dimensional array of char * pointers. These pointers should all initially be set to NULL, then set to point to dynamically allocated strings for each cached word.No square brackets allowed! To emphasize and master the use of pointers and pointer arithmetic, you are not allowed to use square brackets anywhere in your code! As with our first lecture exercise, if a ‘[‘ or ‘]’ character is detected, including within comments, Submitty will remove that line of code before running gcc.To detect square brackets, consider using the command-line grep tool as shown below. bash$ grep ‘[‘ hw1.c … bash$ grep ‘]’ hw1.c …Can you combine this into one grep call? As a hint, check out the man page for grep. As shown below, square bracket expressions can generally be rewritten using pointer arithmetic by removing the square brackets, enclosing the sum of the array variable and the index in parentheses, then dereferencing the resulting pointer. A few equivalent examples follow: str[32] = ‘A’; *(str+32) = ‘A’; values[i] += 20; *(values+i) += 20; results[j] = j * 3.14; *(result+j) = j * 3.14; if ( strcmp( a, &b[10] ) == 0 ) { … } if ( strcmp( a, &(*(b+10)) ) == 0 ) { … } if ( strcmp( a, b+10 ) == 0 ) { … }Note that in this last example, we do not need to dereference the pointer since we are then using the address-of & operator; combined, the dereference * and address-of & operators negate one another.The first command-line argument specifies the size of the cache, which therefore indicates the size of the dynamically allocated char * array that you must create. Use calloc() to create this array of “placeholder” pointers. And use atoi() (or strtol()) to convert from a string to an integer on the command line. The cache size must be a positive integer.Next, your program must open and read the regular file(s) specified by the remaining command-line arguments. Your program must parse and extract all words, if any, from each given file, in the given order the files are listed on the command line.Here, a word is any string of three or more alphanumeric characters; see below for how to “hash” a word. And if a collision occurs in your cache, simply replace the existing entry. (v1.1) To read each input file, you must use open(), read(), and close(); you may also consider using lseek(). Any calls to library functions that make use of FILE* will be deactivated in Submitty; this includes fopen(), fscanf(), fgets(), etc.Initially, your cache is empty, meaning it is an array of NULL pointers. Storing each valid word therefore also requires dynamic memory allocation. For this, use calloc() if the cache array slot is empty; otherwise, to replace an existing value, use realloc() if the size of the required memory differs from what is already allocated.For words (e.g., “arch2024”), be sure to calculate the number of bytes to allocate as the length of the given word plus one, since strings in C are implemented as char arrays that end with a ‘’ character. Do not use malloc() or memset() in your code. Is it a valid word—and how do you “hash” it?For this assignment, words are defined as containing only alphanumeric characters (see isalnum()) and consisting of at least three characters. All other characters therefore serve as delimiters. And note that words are case sensitive (e.g., Lion is different than lion). (v1.2) Note that input files can be of any size and may have valid words at the beginning and/or end of the file, i.e., the file may begin and/or end in an alphanumeric character.To simplify your code, you can assume that the maximum valid word length is 128 bytes. To determine the cache array index for a given word, i.e., to properly “hash” the word, write a separate function called hash() that calculates the sum of each ASCII character in the given word as an int variable, then applies the “mod” operator to determine the remainder after dividing by the cache array size.As an example, the valid word Meme consists of four ASCII characters, which sum to 77 + 101 + 109 + 101 = 388. If the cache array size was 17, for example, then the array index for Meme would be the remainder of 388/17 or 14.Required output When you execute your program, you must display a line of output for each valid word that you encounter in the given file. For each word, display the cache array index and whether you called calloc() or realloc()—or did not need to change the already existing memory allocation. Given the lion.txt example file, you could run your code as follows: bash$ ./a.out 17 lion.txtBelow is sample output from the above program execution that shows the format you must follow: Word “Once” ==> 15 (calloc) Word “when” ==> 9 (calloc) Word “Lion” ==> 11 (calloc) Word “was” ==> 8 (calloc) Word “asleep” ==> 5 (calloc) Word “little” ==> 8 (realloc) Word “Mouse” ==> 11 (realloc) Word “began” ==> 16 (calloc) Word “running” ==> 4 (calloc) Word “and” ==> 1 (calloc) Word “down” ==> 15 (nop) Word “upon” ==> 8 (realloc) Word “him” ==> 12 (calloc) …Further, when you have finished processing the input file(s), show the contents of the cache by displaying a line of output for each non-empty entry in the cache. Use the following format: Cache: [0] ==> “they” [1] ==> “gnawed” [2] ==> “King” [3] ==> “LITTLE” [4] ==> “went” [5] ==> “PROVE” [6] ==> “sad” [7] ==> “tree” [8] ==> “little” [9] ==> “said” [10] ==> “MAY” [11] ==> “Mouse” [12] ==> “him” [13] ==> “FRIENDS” [14] ==> “GREAT” [15] ==> “the” [16] ==> “began”If improper command-line arguments are given, report an error message to stderr and abort further program execution. In general, if an error is encountered, display a meaningful error message on stderr by using either perror() or fprintf(), then aborting further program execution. Only use perror() if the given library or system call sets the global errno variable. Error messages must be one line only and use the following format: ERROR: Submission instructions To submit your assignment (and perform final testing of your code), we will use Submitty. To help make sure that your program executes properly, use the techniques below. First, make use of the DEBUG_MODE preprocessor technique that helps avoid accidentally displaying extraneous output in Submitty. Here is an example: #ifdef DEBUG_MODE printf( “the value of q is %d ”, q ); printf( “here12 ” ); printf( “why is my program crashing here?! ” ); printf( “aaaaaaaaaaaaagggggggghhhh square brackets! ” ); #endif And to compile this code in “debug” mode, use the -D flag as follows: bash$ gcc -Wall -Werror -D DEBUG_MODE hw1.c Second, output to standard output (stdout) is buffered. To disable buffered output, use setvbuf() as follows: setvbuf( stdout, NULL, _IONBF, 0 ); You would not generally do this in practice since this can slow down your program, but to ensure you see as much output as possible in Submitty, this is a good technique to use.

$25.00 View