text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
In this article, You will learn how to use the Python json module to write Python serialized objects as JSON formatted data into file and string. The json module provides the following two methods to encode Python objects into JSON format. - The json.dump()method (without “s” in “dump”) used to write Python serialized object as JSON formatted data into a file. - The json.dumps()method encodes any Python object into JSON formatted String. Further reading - Solve Python JSON Exercise to practice Python JSON skills - Also, read the Complete guide on Python JSON The json.dump() and json.dump() is used for following operations - Encode Python serialized objects as JSON formatted data. - Encode and write Python objects into a JSON file - PrettyPrinted JSON data - Skip nonbasic types while JSON encoding - Perform compact encoding to save file space - Handle non-ASCII data while encoding JSON Syntax of json.dump() and json.dumps() You can do many things using json.dump() and json.dumps() method. Let’s understand the different parameters of json.dump() to achieve different results. Syntax of json.dump() json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Use: It is used to write a Python object into a file as a JSON formatted data. Syntax of json.dumps() json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Use: It is used to write a Python object into a JSON String. Parameters used: objis nothing but a Python serializable object which you want to convert into a JSON format. - A fpis a file pointer used to write JSON formatted data into file. Python json module always produces string objects, not bytes objects, therefore, fp.write()must support string input. - If skipkeysis true (default: False), then dict keys that are not of a basic type, (str, int, float, bool, None) will be skipped instead of raising a TypeError. For example, if one of your dictionary keys is a custom Python object, that key will be omitted while converting the dictionary into JSON. - If ensure_asciiis true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_asciiis false, these characters will be output as-is. allow_nanis True by default so their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. If False it will be a ValueError to serialize out of range float values (nan, inf, -inf). - An indentargument is used to pretty-print JSON to make it more readable. The default is (', ', ': '). To get the most compact JSON representation, you should use (',', ':')to eliminate whitespace. - If sort_keysis true (default: False), then the output of dictionaries will be sorted by key json.dumps() to convert Python primitive types into JSON equivalent There are multiple scenarios where you need to use serialized JSON data in your program. If you need this serialized JSON data in your application of further processing then you can convert it to a native Python str object instead of writing it in a file. For example, you receive an HTTP request to send developer detail. you fetched developer data from the database table and store it in a Python dictionary or any Python object, Now you need to send that data back to the requested application so you need to convert the Python dictionary object into a JSON formatted string to send as a response in JSON string. To do this you need to use json.dumps(). The json.dumps() returns the JSON string representation of the Python dict. Let see the example now. Example: Convert Python dictionary into a JSON formatted String import json def SendJsonResponse(resultDict): print("Convert Python dictionary into JSON formatted String") developer_str = json.dumps(resultDict) print(developer_str) # sample developer dict developer_Dict = { "name": "Jane Doe", "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com" } SendJsonResponse(developer_Dict) Output: Writing JSON data into a Python String {"name": "Jane Doe", "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com"} Mapping between JSON and Python entities while Encoding To encode Python objects into JSON equivalent json module uses the following conversion table. The json.dump() and json.dumps() the method performs the translations when encoding. Now let’s see how to convert all Python primitive types such as a dict, list, set, tuple, str, numbers into JSON formatted data. Please refer to the following table to know the mapping between JSON and Python data types. Let see the example now. import json sampleDict = { "colorList": ["Red", "Green", "Blue"], "carTuple": ("BMW", "Audi", "range rover"), "sampleString": "pynative.com", "sampleInteger": 457, "sampleFloat": 225.48, "booleantrue": True, "booleanfalse": False, "nonevalue": None } print("Converting Python primitive types into JSON") resultJSON = json.dumps(sampleDict) print("Done converting Python primitive types into JSON") print(resultJSON) Output: Converting Python primitive types into JSON Done converting Python primitive types into JSON {"colorList": ["Red", "Green", "Blue"], "carTuple": ["BMW", "Audi", "range rover"], "sampleString": "pynative.com", "sampleInteger": 457, "sampleFloat": 225.48, "booleantrue": true, "booleanfalse": false, "nonevalue": null} json.dump() to encode and write JSON data to a file We can use it in the following cases. - To write the JSON response in a file: Most of the time, when you execute a GET request, you receive a response in JSON format, and you can store JSON response in a file for future use or for an underlying system to use. - For example, you have data in a list or dictionary or any Python object, and you want to encode and store it in a file in the form of JSON. In this example, we are going to convert the Python dictionary into a JSON format and write it into a file. import json # assume you have the following dictionary developer = { "name": "jane doe", "salary": 9000, "email": "JaneDoe@pynative.com" } print("Started writing JSON data into a file") with open("developer.json", "w") as write_file: json.dump(developer, write_file) # encode dict into JSON print("Done writing JSON data into .json file") Output: Started writing JSON data into a file Done writing JSON data into developerDetail.json file Write Indented and pretty printed JSON data into a file If the user wants to read a JSON file so it must be readable and well organized, so whoever consumes this will have a better understanding of a structure of a data. The dump() method provides the following arguments to pretty-print JSON data. - The indent parameter specifies the spaces that are used at the beginning of a line. - The separator argument of a json.dump method you can specify any separator between key and value. - The sort_keysto sort JSON data by keys. Let’s see how to write pretty-printed JSON data into a file. import json developer = { "name": "jane doe", "salary": 9000, "skills": ["Raspberry pi", "Machine Learning", "Web Development"], "email": "JaneDoe@pynative.com" } with open("developerPrettyPrint.json", "w") as write_file: json.dump(developer, write_file, indent=4, separators=(", ", ": "), sort_keys=True) print("Done writing pretty printed JSON data into a file") Output: Done writing pretty printed JSON data into a file Compact encoding to save file space by changing JSON key-value separator If you are not reading a file, but you only need to write JSON data into a file to use by the underlying system or application, then you can write JSON data into a file by doing compact encoding. We can write JSON data into a file by changing the JSON key-value separator. You can change JSON representation as per your needs. Using the separator argument of a json.dump() method you can specify any separator between key and value. To limit the JSON file size we can remove extra spacing between JSON key-value. I have decided to do the compact encoding ( separators=(',', ':')). Using this separator we can remove the whitespaces from JSON to make the JSON more compact and save bytes from being sent via HTTP. Now, Let see the example. import json developer_dict = { "name": "jane doe", "salary": 9000, "skills": ["Raspberry pi", "Machine Learning", "Web Development"], "companies": ["Google", "Facebook", "IBM"], "email": "JaneDoe@pynative.com" } print("Started writing compact JSON data into a file") with open("developerDetailCompact.json", "w") as write_file: json.dump(developer_dict, write_file, separators=(',', ':')) print("Done writing compact JSON data into json file") Output: Started writing compact JSON data into a file Done writing compact JSON data into .json file File content: {"name":"jane doe","salary":9000,"skills":["Raspberry pi","Machine Learning","Web Development"],"companies":["Google","Facebook","IBM"],"email":"JaneDoe@pynative.com"} Skip nonbasic types while writing JSON into a file using skipkeys parameter The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent (e.g., dictionary, lists, strings, ints, None, etc.). If the Python dictionary contains a custom Python object as one of the keys and if we try to convert it into a JSON format, you will get a TypeError i.e., Object of type "Your Class" is not JSON serializable. If this custom object isn’t required in JSON data, you can skip it using a skipkeys=true argument of the json.dump() method. If skipkeys=true is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError. If it is necessary to convert it into JSON, then you can refer to our article on how to Make Python class JSON Serializable. Now, Let’s see the example. import json class PersonalInfo: def __init__(self, name, age): self.name = name self.age = age def showInfo(self): print("Developer name is " + self.name, "Age is ", self.age) dev = PersonalInfo("John", 36) developer_Dict = { PersonalInfo: dev, "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com" } print("Writing JSON data into file by skipping non-basic types") with open("developer.json", "w") as write_file: json.dump(developer_Dict, write_file, skipkeys=True) print("Done") Output: Writing JSON data into file by skipping non-basic types Done As you can see in the JSON output the PersonalInfo object is skipped. Handle non-ASCII characters from JSON data while writing it into a file The json.dump() method has ensure_ascii parameter. The ensure_ascii is by-default true. The output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is. If you want to store non-ASCII characters, as-is use the following code. import json unicode_string = u"\u00f8" print("unicode String is ", unicode_string) # set ensure_ascii=False print("JSON character encoding by setting ensure_ascii=False") print(json.dumps(unicode_string, ensure_ascii=False)) Output: unicode String is ø JSON character encoding by setting ensure_ascii=False "ø" Also, read the Complete Guide on Encode and Decode Unicode data into JSON using Python. So What Do You Think? I want to hear from you. What do you think of this article? Or maybe I missed one of the uses of json.dump() and json.dumps(). Either way, let me know by leaving a comment below. Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.
https://pynative.com/python-json-dumps-and-dump-for-json-encoding/
CC-MAIN-2021-10
refinedweb
1,864
56.76
A Windows Phone 7 application I was working on kept sitting on the shelf because I was too overwhelmed with a couple of contracts to finish it. Then several weeks ago I won a free Samsung Focus in a Microsoft-sponsored contest, and the application (currently called Lifting Calculator) went from a hobby to a valuable tool. It also seemed like the perfect opportunity for me to try out IronRuby in the Windows Phone 7 environment. Download IronRuby I had IronRuby 1.1.1 installed, but I learned that IronRuby 1.1.2 was released in early February, and it includes Windows Phone 7 support. You need to download the binaries package (the MSI version is not fine — I learned that the hard way). Also, while you are in the directory, look at each DLL’s properties and click the Unblock button. Write a Windows Phone 7 app in IronRuby I read Shay Friedman’s MSDN article about writing Windows Phone 7 apps in IronRuby, and then I tweaked his directions to fit my needs. One reason for the tweaks is that I already completed quite a bit of work on my application, and I wanted to see how to use IronRuby for one piece of my app first. Another issue was that the article’s instructions were not entirely correct; I’m sure that this was primarily due to IronRuby changing since the article was written. Here are the steps that I took: - I added a reference to the IronRuby binaries. I added all of the Windows Phone 7 binaries from the package. - I prepped my XAML and attached code behind for the functionality I wanted. (No, I haven’t moved to MVVM yet.) - In the C# code that I wanted to call Ruby from, I added the following using statements: using System.Reflection; using System.IO; using Microsoft.Scripting.Hosting; using IronRuby; - I created my Ruby file that contained the functionality I wanted. The Ruby script should manipulate global variables that will be passed into it by the Silverlight host, and return an output value. - I set the Build Action and Copy to Output Directory of the new Ruby file as Content and Copy if newer, respectively. - I added the code needed to call the IronRuby script, and received its output into a variable. I had to cast it to make sure I could use it nicely after I got it back. For the full details, see Code sample A (the C# code calling the IronRuby script) and Code sample B (the IronRuby script). To get an idea of what this app does, this functionality is to determine how many weight plates of what size to put onto each side of a barbell to load it to the desired weight. This is a big help in the gym once you get past a certain point, and you end up taking forever to do the math and end up improperly loading the barbell. (This is part of a bigger project that I am working on, and I hope to release it in the near future.) In Shay’s article, he passes in the entire application to the script; for my discrete functionality, that is overkill. Instead, I pass in an object that represents my input parameters and an object that will hold my output. After I run the script, I use the output information to put the results on the screen. If I really wanted to be picky, I could bind the controls to this object. Code sample A: The C# code to call the IronRuby script and consume its output. private void ShowBarbellLoadout(int barbellWeight, int desiredLoad) { var resourceStream = Application.GetResourceStream(new Uri("BarbellLoader.rb", UriKind.Relative)); var dataFile = new StreamReader(resourceStream.Stream); var code = dataFile.ReadToEnd(); var engine = Ruby.CreateEngine(); engine.Runtime.Globals.SetVariable("BarbellWeight", barbellWeight); engine.Runtime.Globals.SetVariable("DesiredLoad", desiredLoad); var loadoutResults = (IronRuby.Builtins.Hash)engine.Execute(code); var results = new List<BarbellLoadout> { {new BarbellLoadout{ PlateSize = 45, PlateCount = int.Parse(loadoutResults["45"].ToString()) }}, {new BarbellLoadout{ PlateSize = 25, PlateCount = int.Parse(loadoutResults["25"].ToString()) }}, {new BarbellLoadout{ PlateSize = 10, PlateCount = int.Parse(loadoutResults["10"].ToString()) }}, {new BarbellLoadout{ PlateSize = 5, PlateCount = int.Parse(loadoutResults["5"].ToString()) }}, {new BarbellLoadout{ PlateSize = 2.5M, PlateCount = int.Parse(loadoutResults["2.5"].ToString()) }} }; Code sample B: The IronRuby script. currentTotal = DesiredLoad.to_i - BarbellWeight.to_i output = {} output["45"] = (currentTotal / 90).truncate currentTotal -= output["45"] * 90 output["25"] = (currentTotal / 50).truncate currentTotal -= output["25"] * 50 output["10"] = (currentTotal / 20).truncate currentTotal -= output["10"] * 20 output["5"] = (currentTotal / 10).truncate currentTotal -= output["5"] * 10 output["2.5"] = (currentTotal / 5).truncate currentTotal -= output["2.5"] * 5 return output I learned a very important lesson: All global variables set from the outside must have a capitalized variable name; otherwise, the variables will not work. Even more frustrating, in my script I prefaced the global variables with a dollar sign, and they didn’t balk — the variables auto initialized to the defaults, giving me no output. It took me a couple of hours to really get things working. One alternative to my technique is to use the dynamic functions of C# 4. For example, a Ruby script could create classes, and you could use dynamic to instantiate them and run their methods from C#. I didn’t try this directly, but dynamic worked when I gave it a dry run in plain C#, and I have no reason to believe that it wouldn’t work to call IronRuby code. Conclusion This novel approach is not terribly practical, unless you prefer Ruby or have a deep investment in it. The big issue is that the already lean debugging options are nonexistent in the hosted DLR scenario. You can’t step into the Ruby code; for me to debug it, I copied it into another IronRuby project and set up global variables to replicate what my C# code was setting so I could step into the code. This might be enough for a Ruby pro, but as a Ruby novice, it’s not what I need. All the same, using IronRuby in Windows Phone 7 apps is of interest. If you want more Ruby on Windows Phone 7, check out iron7, a Ruby interpreter for WP7. J.Ja
http://www.techrepublic.com/blog/smartphones/use-ironruby-to-develop-a-windows-phone-7-app/2257
crawl-003
refinedweb
1,037
56.35
Back to index Interface of a Parallel_Salome_file This interface is used by parallel components and containers. More... import "SALOME_PACOExtension.idl"; Interface of a Parallel_Salome_file This interface is used by parallel components and containers. It adds methods to enable to choose on which node of the parallel component the file has to be received. Definition at line 77 of file SALOME_PACOExtension.idl. Close the file transfer. when the file transfer is finished, close method releases structures created by open method, identified by fileId. Connect a Salome_file with another Salome_file. It works only if the Salome_file managed only one file Connect the managed file file_name to a Salome_file. Obsolete, left for compatibility reasons only. Use UnRegister() instead. Get a file data block. Get successive blocks of octets from the original file. The last block is empty, and identifies the end of file. Get a file managed by the Salome_file. Get the number of the node that actually managed the file. Get the list of the files managed by the Salome_file. The list can be empty. Return the state of the Salome_file. Load a Salome_file from a hdf5 file. Open the file transfer. open method returns a key (fileId) that identifies the structure (ex: C FILE), associated to the original file on the server. The structure is created by a container for transfer of files availables on the computer which runs the container. Each open gives a unique fileId, to allow concurrent reads of the same File. Open the file transfer in write mode for file fileName. Put a file data block. Get all the distributed files managed by the Salome_file and check all the local files. This method is used by the parallel implementation of recvFiles. Increase the reference count (mark as used by another object). Remove a file of the Salome_file. Remove all the files of the Salome_file. Save a Salome_file into a hdf5_file. Save a Salome_file into a hdf5_file. All files that are managed are saved into the hdf5_file Set the container where files are. Add a Distributed file to the Salome_file. Connect the file_name with a Distributed file_name. Set a number of node for the file. Default is the node 0. \param file_name name of the file. \param node_nbr node number where the file is. \exception raised if the file doesn't exist. Add a Local file to the Salome_file. Decrease the reference count (release by another object). This method update the state of file for the Parallel_Salome_file.
https://sourcecodebrowser.com/salome-kernel/6.5.0/interface_engines_1_1_parallel___salome__file.html
CC-MAIN-2016-44
refinedweb
409
70.39
2D Robot Arm Inverse Kinematics using Mixed Integer Programming in Cvxpy Mixed Integer programming is crazy powerful. You can with ingenuity encode many problems into it. The following is a simplification of the ideas appearing in . They do 3d robot arms, I do 2d. I also stick to completely linear approximations. The surface of a circle is not a convex shape. If you include the interior of a circle it is. You can build a good approximation to the circle as polygons. A polygon is the union of it’s sides, each of which is a line segment. Line sgements are convex set. Unions of convex sets are encodable using mixed integer programming. What I do is sample N regular positions on the surface of a circle. These are the vertices of my polygon. Then I build boolean indicator variables for which segment we are on. Only one of them is be nonzero $ \sum s_i == 1$. If we are on a segment, we are allowed to make positions $ x$ that interpolate between the endpoints $ x_i$ of that segment $ x = \lambda_1 x_1 + \lambda_2 x_2$, where $ \lambda_i >= 0$ and $ \sum \lambda=1$. These $ \lambda$ are only allowed to be nonzero if we are on the segment, so we suppress them with the indicator variables $ \lambda_i <= s_i + s_{i+1}$. That’s the gist of it. Given a point on the circle (basically sines and cosines of an angle) we can build a 2d rotation matrix $ R$ from it. Then we can write down the equations connecting subsequent links on the arm. $ p_{i+1}=p_{i} +Rl$. By using global rotations with respect to the world frame, these equations stay linear. That is a subtle point. $ p$ and $ R$ are variables, whereas $ l$ is a constant describing the geometry of the robot arm. If we instead used rotation matrices connecting frame i to i+1 these R matrices would compound nonlinearly. All in all, pretty cool! import cvxpy as cvx import numpy as np import matplotlib.pyplot as plt # builds a N sided polygon approximation of a circle for MIP. It is the union of the segments making up the polygon # might also be useful to directly encode arcs. for joint constraint limits. def circle(N): x = cvx.Variable() y = cvx.Variable() l = cvx.Variable(N) #interpolation variables segment = cvx.Variable(N,boolean=True) #segment indicator variables, relaxing the boolean constraint gives the convex hull of the polygon angles = np.linspace(0, 2*np.pi, N, endpoint=False) xs = np.cos(angles) #we're using a VRep ys = np.sin(angles) constraints = [] constraints += [x == l*xs, y == l*ys] # x and y are convex sum of the corner points constraints += [cvx.sum(l) == 1, l <= 1, 0 <= l] #interpolations variables. Between 0 and 1 and sum up to 1 constraints += [cvx.sum(segment) == 1] # only one indicator variable can be nonzero constraints += [l[N-1] <= segment[N-1] + segment[0]] #special wrap around case for i in range(N-1): constraints += [l[i] <= segment[i] + segment[i+1]] # interpolation variables suppressed return x, y, constraints x, y, constraints = circle(8) objective = cvx.Maximize(x-0.8*y) prob = cvx.Problem(objective, constraints) res = prob.solve(solver=cvx.GLPK_MI, verbose=True) # build a 2d rotation matrix using circle def R(N): constraints = [] c, s, constraint = circle(N) # get cosines and sines from a circle constraints += constraint r = cvx.Variable((2,2)) # build rotation matrix constraints += [r[0,0] == c, r[0,1] == s] constraints += [r[1,0] == -s, r[1,1] == c] return r, constraints # np.array([[c , s], [-s, c]]) #robot linkage of differing arm length link_lengths = [0.5,0.2,0.3,0.4] pivots = [] Rs = [] N = 8 constraints = [] origin = np.zeros(2) p1 = origin for l in link_lengths: R1, c = R(8) constraints += c p2 = cvx.Variable(2) constraints += [p2 == p1 + R1*np.array([l,0])] # R1 is global rotation with respect to world frame. This is important. It is what makes the encoding linear. p1 = p2 pivots.append(p2) Rs.append(R1) end_position = np.array([-0.5, .7]) constraints += [p2 == end_position] objective = cvx.Maximize(1) prob = cvx.Problem(objective, constraints) res = prob.solve(solver=cvx.GLPK_MI, verbose=True) print(res) #print(R(x,y)) print(p2.value) print(list(map(lambda r: r.value, Rs))) #print(y.value) p1 = origin for l, r in zip(link_lengths, Rs): p2 = p1 + r.value@np.array([l,0]) plt.plot([p1[0],p2[0]], [p1[1],p2[1]],>IMAGE_0<<
https://www.philipzucker.com/2d-robot-arm-inverse-kinematics-using-mixed-integer-programming-in-cvxpy/
CC-MAIN-2021-43
refinedweb
747
61.12
installing this toolbox? felix-tracxpoint opened this issue · comments felix-tracxpoint commented How does one install this toolbox, actually? - I wanted to install via pip but pip install pyImgSegm produces an error Searching the PyPi website also did not bring up anything. - So I cloned the repository and ran the setup.py file, per the readme instructions. But from gco import <something> still fails. What am I doing wrong? Jirka Borovec commented GCO is not part of this package, the GCO you can find here - Also, the GCO can be installed as pip install gco-wrapper Jirka Borovec commented this package is not in PyPi storage, but you can install it locally python setup.py install or throw PyPi pip install git+
https://giters.com/Borda/pyImSegm/issues/13
CC-MAIN-2022-27
refinedweb
122
66.74
Components and supplies Apps and online services About this.Ports.SerialPort and how you can build the source code on Windows and run the binary on linux-arm (Raspbian).Note - By the time I write this article, .NET Core and System.IO.Ports are on preview, when you read this article, do check if there are any new releases. Run your code with the latest stable release. - I build and test the codes of this article on Windows 10 and run them in Raspberry Pi Raspbian. If you are using Mac/Linux as development machine, SerialPort library should also work. 1. Download and install.NET Core 3.0 SDK (Not Runtime) on you development machine. After installation, open terminal and type dotnet --version. You should see a dotnet version like 3.0.x. 2. Install Visual Studio Code as C# code editor. Then install C# extension. 3. Install.NET Core on Raspberry pi. If you want to build C# code on development machine and run the binary on PI, you just need to install .NET Runtime. If you want to build and run the source code on PI, you need to install .NET SDK which also includes.Net Runtime. Do note you should use the linux arm32 build for your PI. For simplicity, I will show you how to install.NET Core SDK on PI: # in raspberry pi terminal sudo apt-get update # install .net core dependencies sudo apt-get install curl libunwind8 gettext cd ~ # download .net core 3.0 wget mkdir -p $HOME/dotnet && tar vzxf dotnet-sdk-3.0.100-preview-010184-linux-arm.tar.gz -C $HOME/dotnet echo "export PATH=$PATH:$HOME/dotnet" >> ~/.bashrc echo "export DOTNET_ROOT=$HOME/dotnet" >> ~/.bashrc export PATH=$PATH:$HOME/dotnet export DOTNET_ROOT=$HOME/dotnet After installation, verify with dotnet --info. You should see installation info like this: 4. Prepare any serial enabled device to receive and send serial messages. For me it is an Arduino Uno.Hello SerialPort After setting up development tools, let's start our journey with a simple C# project which will print all the serial ports available. On your dev machine, start a dotnet project with following commands: mkdir hello-serialport && cd hello-serialport dotnet new console dotnet add package System.IO.Ports --version 4.6.0-preview.19073.11 Open program.cs file, replace content with following code: using System; using System.IO.Ports; namespace hello_serialport { class Program { static void Main(string[] args) { // Get a list of serial port names. string[] ports = SerialPort.GetPortNames(); Console.WriteLine("The following serial ports were found:"); // Display each port name to the console. foreach(string port in ports) { Console.WriteLine(port); } Console.ReadLine(); } }} Type dotnet run to run the code on dev machine. To build your project for RPi, run: dotnet publish -r linux-arm --self-contained false then go to {your_project_root}\bin\Debug\netcoreapp3.0\linux-arm, copy folder publish to your PI. On Pi, go to the publish folder, run: chmod +x hello-serialport ./hello-serialport Your hello-serialport is running on Rapsberry Pi!.NET Core Application Deployment In the hello serialport project, we did the development on windows, build the linux-arm binary then run the binary on raspberry pi. According to Microsoft's documentation, we just made an Framework-dependent executable(FDE) which means the executable can only run on raspberry pi with proper version.NET Core Runtime installed. You can play with different kind of deployment by referring following documents:Serial Read Open Arduino IDE, go to File-->Examples-->03.Analog-->AnalogInOutSerial and upload it to Arduino. Paste the code here: /* Analog input, analog output, serial output Reads an analog input pin, maps the result to a range from 0 to 255 and uses the result to set the pulse width); } This program keep sending out the reading of analog pin. Let's write a C# program to read the message: using System; using System.IO.Ports; namespace serial_read { class Program { static SerialPort _serialPort; static void Main(string[] args) { Console.Write("Port no: "); string port = Console.ReadLine(); Console.Write("baudrate: "); string baudrate = Console.ReadLine(); // Create a new SerialPort on port COM7 _serialPort = new SerialPort(port, int.Parse(baudrate)); // Set the read/write timeouts _serialPort.ReadTimeout = 1500; _serialPort.WriteTimeout = 1500; _serialPort.Open(); while (true) { Read(); } _serialPort.Close(); } public static void Read() { try { string message = _serialPort.ReadLine(); Console.WriteLine(message); } catch (TimeoutException) { } } } } Build and run on Raspberry Pi: One thing to mention is that SerialPort.ReadLine() is a blocking method. If you don't want main thread be blocked, please use multithreading. please refer to the example provided by Microsoft to learn how to do serial write and multithreading. Serial Events are also good things to explore.Further Work - ASP.NET Core is available since v1 of.NET Core. By combining SerialPort API and ASP.NET, we can build a web UI to control some devices like a mobile robot. - Microsoft open sourced WPF and WinForms which would all be available since.NET Core 3.0. One day we may safely port our old windows desktop serial applications to all platforms or even write a winForm serial communication application on Raspberry Pi! [1] Installing the.NET Core 2.x SDK on a Raspberry Pi and Blinking an LED with System.Device.Gpio. URL: Code dotnet-serialport-demos Schematics Author Published onMarch 3, 2019 Members who respect this project you might like
https://create.arduino.cc/projecthub/sxwei123/serial-communication-with-net-core-3-0-on-rpi-linux-0f2ed4
CC-MAIN-2021-49
refinedweb
894
52.76
Download Games often need to get the current state of various keys in order to respond to user input. This is not the same as responding to key down and key up events, but is rather a case of discovering if a particular key is currently pressed. In Actionscript 2 this was a simple matter of calling Key.isDown() with the appropriate key code. But in Actionscript 3 Key.isDown no longer exists and the only intrinsic way to react to the keyboard is via the keyUp and keyDown events. To rectify this I have created the KeyPoll class, which has isDown and isUp methods, each taking a key code as a parameter and returning a Boolean. Using the class looks like this. package { import flash.display.Sprite; import flash.events.Event; import flash.ui.Keyboard; import bigroom.input.KeyPoll; public class Test extends Sprite { var key:KeyPoll; public function Test() { key = new KeyPoll( this.stage ); addEventListener( Event.ENTER_FRAME, enterFrame ); } public function enterFrame( ev:Event ):void { if( key.isDown( Keyboard.LEFT ) ) { trace( "left down" ); } if( key.isDown( Keyboard.RIGHT ) ) { trace( "right down" ); } } } } The constructor for the KeyPoll class takes a single parameter which is a DisplayObject on which the object should listen to keyboard events. To listen globally to all keyboard input this should be the stage (as in the example). The class uses a ByteArray to hold the current keyboard state, which is updated in response to Keyboard events and queried by the public methods, isDown and isUp. Using a ByteArray is more compact than using an Array of Booleans, and in tests it also turned out to be marginally faster, although the difference in speed was not significant enough to matter. In addition, the class clears the key state array when the deactivate event occurs, so key state is not retained if the Flash Player loses focus and stops receiving keyboard input. great class! thanks for this! Just what I needed, great stuff! is there a way to determine if a key is just pressed? great class! thanks for this! Just what I needed, great stuff! is there a way to determine if a key is just pressed?
http://code.google.com/p/bigroom/wiki/KeyPoll
crawl-002
refinedweb
360
67.04
There are times when you check Facebook to just fill a free minute or post something and then you find you’ve been pulled into the vortex of links worth clicking. You can unfollow everyone and everything until your timeline slows down, but then they give you trending topics, suggested pages, ads etc. Well, today you can switch your Facebook from looking like this: To this: You can still see that there’s more than your timeline if you look for it, but it’s not in your face and it will still become opaque when you hover your mouse cursor. How do I get there? - Install Tampermonkey plugin into your browser. I tested in Chrome, but there’s a version for some other browsers and the original Greasemonkey might work if you’re on Firefox. It seems like the Internet Explorer flavor is called Trixie. - Add the following script to your monkey, go to Facebook and you’re done! // ==UserScript== // @name Hide FB distractionpane // @namespace // @version 0.1 // @description Hide distraction panel on Facebook // @author Filip Skakun // @match *.facebook.com/* // @grant none // ==/UserScript== (function() { 'use strict'; var timeout; var styleElement = document.createElement('style'); var declarations = document.createTextNode( `#leftCol, #rightCol, #pagelet_ticker, #pagelet_canvas_nav_content { opacity: 0.1; transition: opacity 0.5s; } #leftCol:hover, #rightCol:hover, #pagelet_ticker:hover, #pagelet_canvas_nav_content:hover { opacity: 1; -webkit-transition-timing-function: ease-out; transition: opacity 0.1s; }` ); styleElement.type = 'text/css'; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = declarations.nodeValue; } else { styleElement.appendChild(declarations); } var headElement = document.getElementsByTagName('head')[0]; headElement.appendChild(styleElement); })(); The script adds a little bit of CSS to Facebook to hide the left and right panels that have ads, news and infrequently used parts, leaving only the timeline and Messenger contacts visible. These panels reappear once you move your mouse cursor over them, which still keeps them readily available, but stops your gaze from wandering around the screen, so you can quickly scan the timeline and get back to what you were doing before.
https://blog.onedevjob.com/2016/06/08/how-to-stop-facebook-from-stealing-your-attention/
CC-MAIN-2019-47
refinedweb
329
56.55
We can convert python dict to csv using CSV module and pandas module. CSV module use DictWriter and pandas firstly covert dict to dataFrame. Once we have the dataFrame, We can export the dataFrame to CSV using to_csv() function. How to convert python dict to csv – We will see the conversion using pandas and CSV in different methods. Method 1: Using CSV module- Suppose we have a list of dictionaries that we need to export into a CSV file. We will follow the below implementation. Step 1: Import the csv module. The first step is to import python module for CSV and it is csv. import csv Step 2: Create a dummy list of dict. For converting dict to csv lets create a sample list of dict. You can use your own dict. sample_dict = [ {'key1': 1, 'key2': 2, 'key3': 3}, {'key1': 4, 'key2': 5, 'key3': 6}, {'key1': 7, 'key2': 8, 'key3': 9}, ] Step 3: Use DictWriter for writing the dicts into the list. Here we need to define the column name explicitly. col_name=["key1","key2","key3"] with open("export.csv", 'w') as csvFile: wr = csv.DictWriter(csvFile, fieldnames=col_name) wr.writeheader() for ele in sample_dict: wr.writerow(ele) Here we define the column name for the CSV. Suppose we have five keys in the dict. But we need to export only three, Then we will only define those three only. The above code will export the dict into export.csv Method 2: Using the Pandas module- Firstly, We will create a dummy dict and convert it to dataFrame. After it, We will export it to a CSV file using the to_csv() function. Step 1: Here is the list of dicts with some sample data. It will be used for converting the dict to dataframe here. import pandas as pd sample_dict = [ {'key1': 1, 'key2': 2, 'key3': 3}, {'key1': 4, 'key2': 5, 'key3': 6}, {'key1': 7, 'key2': 8, 'key3': 9}, ] df = pd.DataFrame.from_dict(sample_dict) Step 2: Let’s create the CSV out of the dataFrame. df.to_csv (r'gen.csv', index = False, header=True) Here index and header parameters are optional. In our scenario, We have used index as False and Header as True in the generated CSV file. When we run the code together. It will generate a gen.csv file. Conclusion – Well, These two are the most popular way to write a dictionary to CSV python. Personally, I found pandas way easier than CSV module. Please tell me which you found most convenient for this conversion. You may comment below at the comment box. Thanks Data Science Learner Team Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://www.datasciencelearner.com/convert-python-dict-to-csv-implementation/
CC-MAIN-2021-39
refinedweb
448
76.32
JXTextField background weirdness Hi, I'm using the code (below) to generate a JXTextField with a prompt, setting the background colour to white. I then create a JTextField for comparison. Note that the rendered background colour is not white (OS X Lion). When I then insert a value into the JXTextField, note that the background is now white but it is rendered outside of the text field area. (see images) I see this with swingx 1.6.1 and 1.6.3. I believe it is a bug. import java.awt.Color; import java.awt.Dimension; import javax.swing.*; import org.jdesktop.swingx.JXTextField; public class Scratch { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); JXTextField jxText = new JXTextField("Prompt"); jxText.setMaximumSize(new Dimension(300, 20)); jxText.setPromptBackround(Color.WHITE); JTextField text = new JTextField("Prompt"); text.setMaximumSize(new Dimension(300, 20)); panel.add(jxText); panel.add(new JLabel(" ")); panel.add(text); frame.add(panel); frame.setSize(300, 300); frame.setVisible(true); } } I would guess that the AquaLookAndFeel is using some painting tricks on their border. We have the paint the prompt on the textfield giving it the same insets as the original, but with an empty border. I am going to guess that there is some Aqua custom code in their to draw that border that is not working 100% with our solution. I don't have a Mac to test on, so I'll need help solving this issue. Please file one in the issue tracker () and we'll see what we can do. Karl
https://www.java.net/node/887297/atom/feed
CC-MAIN-2015-14
refinedweb
273
61.53
Products and Services Downloads Store Support Education Partners About Oracle Technology Network Consider this small test program: import java.io.*; public class test { /* * Make sure 0xFEFF is encoded as this byte sequence: EF BB BF, when * UTF-8 is being used, and parsed back into 0xFEFF. */ public static void main(String[] args) throws Exception { /* * Write */ FileOutputStream fos = new FileOutputStream("bom.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); osw.write(0xFEFF); osw.close(); /* * Parse */ FileInputStream fis = new FileInputStream("bom.txt"); InputStreamReader isr = new InputStreamReader(fis, "UTF8"); char bomChar = (char) isr.read(); System.out.println("Parsed: " + Integer.toHexString(bomChar).toUpperCase()); if (bomChar != 0xFEFF) { throw new Exception("Invalid BOM: " + Integer.toHexString(bomChar).toUpperCase()); } isr.close(); } } On Linux JDK1.6 Beta b59d, the char is parsed correctly. However, on Linux JDK1.6 rc b69, the program throws this exception: Exception in thread "main" java.lang.Exception: Invalid BOM: FFFF at test.main(test.java:28) See 6378267 for more details. EVALUATION The update we made to recognized the BOM in UTF-8 (4508058) is correct according to the Unicode Standard. Our assumption was that our change should rarely break any real-world applications because that would imply that they were not following the Unicode Standard. Unfortunately, we have found a common application where our assumption was incorrect. We will back out the changes associated with 4508058, thus reverting to our previous behaviour of ignoring the BOM for UTF-8. No changes were ever made to BOM handling for UTF-16 or UTF-32 as these double-byte encodings require its processing. EVALUATION UTF8 charset has been updated to recognize sequence EF BB BF as a "BOM" as specified at, so this utf8 signature is being skipped out during decoding if it appears at the beginning of the input stream. See#4508058. So the assumption of "parsed back into 0xFEFF" no longer stands, suggest the test case get. updated accordingly EVALUATION *** (#1 of 1): [ UNSAVED ] ###@###.### EVALUATION I am reopening this bug because it is breaking backwards-compatibility. The JSP container in the Java EE 5 RI and SJSAS 9.0 has been relying on detecting a BOM, setting the appropriate encoding, and discarding the BOM bytes before reading the input. The purpose of the test program I provided with the bug report was to demonstrate the issue. It is not just a matter of changing the test program to make things work. This has worked up until JDK 1.6, and I expect it to continue to work with that JDK release. If you want to support the new functionality of automatically detecting and discarding a BOM, this should be enabled with a flag, but not by default. We cannot have our container implement one behaviour when running on JDK 1.5, and a different behaviour when running on JDK 1.6. Just curious, have the following encodings been updated as well: UTF-32 BE UTF-32 LE UTF-16 BE UTF-16 LE EVALUATION It sounds like the customer code is doing "encoding detection". But specifying UTF-8 is already choosing an encoding... If you really want to examine the input to auto-detect encodings (in general, an impossible task), then read the first few bytes from the input stream directly *as bytes*, and compare to the various encodings of BOM. If a BOM is detected, deduce the encoding, discard the BOM, and read the rest of the input using the detected encoding. If you don't find something that looks like a BOM, guess and pray. Auto-detecting encodings are never reliable; only heuristics. The change to UTF-8 is incompatible, but a strong case can be made that UTF-8 is specified by a standard, and so the change was simply a bug fix. What do other implementations of UTF-8 do? EVALUATION The "encoding autodetection" approach mentioned above is exactly what we have been doing. However, after having deduced an encoding from the BOM bytes (if present), we need to reset the input stream so we can later pass it to the javax.xml.parsers.SAXParser (for JSP pages in XML syntax) or our "hand-written" parser (for JSP pages in classic syntax). This means that in the classic syntax case, we must discard the BOM manually (in the XML syntax case, the javax.xml.parsers.SAXParser is taking care of this) when running against a JRE with a version < 1.6, but must rely on the decoder to do this for us as of JRE 1.6. The problem is that we cannot implement different behaviour depending on the JRE version we're running against. Also, do these encodings also discard a BOM as of JDK 1.6: UTF-32 BE UTF-32 LE UTF-16 BE UTF-16 LE or was the change made to UTF-8 only? EVALUATION I don't understand why the technique that works with 1.6, namely "discarding the BOM manually", doesn't also work with 1.5. If you consistently pass a BOM-free stream to the decoder, the behavior will be unchanged. EVALUATION Sorry if I wasn't clear: We currently detect the encoding of a JSP file from its BOM, reset the input stream, and pass the input stream to the appropriate parser, based on the JSP file's syntax. Notice that the SAXParser (invoked for XML syntax) would choke on a BOM-free stream. If the JSP page is in classic syntax, we remember if a BOM was present by setting a flag, set the stream's encoding to that derived from the BOM, and have our parser read and parse the JSP page from the stream. If the BOM flag is set, the parser knows to discard the first char. With JDK 1.6, this approach no longer works, because the decoder will already have discarded the BOM, so our parser will look at the wrong char. Also, I never got an answer if the automatic BOM-stripping is now also done in the case of UTF-32 and UTF-16, or just UTF-8.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6378911
CC-MAIN-2013-20
refinedweb
1,006
55.64
New York Times Plugs OpenOffice Suite 411 MrNovember writes "The New York Times (registration blah blah) describes a new choice for office suites. The writer seems a bit slanted toward OpenOffice but it's a fair discussion of its pros and cons. The article has identified some interesting compatibility issues to those who aren't using OpenOffice but might. Again we see major media discussing open source as an actual alternative to a longstanding standard. The article concludes amusingly with 'Every now and then, you get what you don't pay for;' just tack on 'Open Source' to the beginning for the perfect sig." We've gotten numerous submissions recently from people whose [company/school/whatever] is switching to OpenOffice. perfect sig? (Score:4, Interesting) ;-P Re:perfect sig? addendum! (Score:5, Funny) Pr0n: every now and then, you get what you don't pay for Warez:every now and then, you get what you don't pay for... Re:perfect sig? The coin Flips.. (Score:2) Re:perfect sig? The coin Flips.. (Score:3, Funny) economics of software (Score:2) Re:economics of software (Score:2, Insightful) While you have a point (Score:4, Insightful) When you are buying a game, you are buying entertainment, and that content will likely still be proprietary (plots, etc). A compelling game is like a compelling movie, and it is not just the rendering, etc, but it is also the plot, the innovation, and the rest of the content. Think of games as being part programming and part litterature Re:economics of software (Score:3, Insightful) Re:economics of software (Score:3, Insightful) How many geeks are going to write software they're not going to use themselves? Re:economics of software (Score:2) Proprietary situation: Company X pays Company M $10,000 to write a program for them. What Company X actually get is a licence to use the program Company M wrote, which still belongs to company M. If it goes wrong, or they want it updated, then they have to pay whatever Company A want for it. Free situation: Company Y pays Company G $10,000 to write a program for them. They get the source code for the program, and the right to do whatever they want with it (after all, they paid for it). If they want an upgrade, then they can ask company G, H, J, K or L to do it, or they can do it themselves, whichever is cheapest. I know what I'd prefer if I were a manager. Re:economics of software (Score:2) Brings a smile to my face. (Score:2, Funny) Sometimes I derive great pleasure thinking of Microsoft lawyers running around saying, "Hey wait, who can we sue!?" and MS lackies running around going, "Hey wait, how can we run those Open Source people outta business!?" Must be hard to compete with a good, free product minus draconian licensing. It's just beautiful man. Re:Brings a smile to my face. (Score:3, Insightful) Re:Brings a smile to my face. (Score:3, Interesting) Until now, the customer has had little way of knowing there is competition. Now, with Linux/Open-source, Microsoft is in a position where they have to compete directly. This means their marketing material will probably have to mention Linux. And with each mention, Linux will gain more and more headway, because it is big enough to be in Microsoft's marketing material. It's pretty sweet for those of us in open-source. Re:Brings a smile to my face. (Score:2, Interesting) OpenOffice XML file (Score:4, Interesting) Append to the beginning (Score:3, Insightful) Sorry if I'm being pedantic. OpenOffice.org Compatibility (Score:4, Informative) Since my resume contains bullets, I have not been able to uninstall Word. OpenOffice.org is my default application for all Office filetypes. Regards, javajeff Re:OpenOffice.org Compatibility (Score:2, Interesting) If you're looking for a number in OO, and one of the cells in your range contains text, the LOOKUP command will return an error. But, Excel just ignores it. Since my company has a number of older Excel documents that use that feature, we'd have to change them all in order for OO to work for us. Until then, we have to stick with MS. I am working on changing those processes and spreadsheets, but it'll take a while before we're able to switch. I really do like OO, but until they either change the implementation (I submitted a bug, but the closed it as "RESOLVED"), or I change the files, we can't use it company-wide. Re:OpenOffice.org Compatibility (Score:2, Insightful) If you don't know how then I'm sure an OOo hacker would do it for a cash donation. Re:OpenOffice.org Compatibility (Score:2, Informative) Resumes (Score:3, Informative) Re:Resumes (Score:3, Funny) >Microsoft doesn't take Word format resumes on their website .. they insist on ASCII only. Now isn't that interesting? They're probably worried about getting macro viruses. Re:OpenOffice.org Compatibility (Score:2) Good Way to Promote OSS (Score:2, Insightful) NYT Random Login Generator (Score:4, Interesting) Reg Free Link (Score:2, Informative) You Get What You Don't Pay For? (Score:2) This is close, but it's not quite right. The correct principle is: you get what the people you patronize want to provide. We often forget this in a world that's interested in repeating the "customer is king" mantra. installed last night.. (Score:4, Informative) So far it starts up quicker than staroffice and there is no so desktop which is nice. It failed to recognize my jvm during the install, but I'm not that bothered by that just yet. I am using it on Linux and installed it as root, and ran into a problem with permissions it seems. I had to change ownership to (chown -R : ) to then run it as myself. It would start up and then crash right away until I did this. Or I could run it as root. Not sure why though, and now I dont care as it works. It does use lots of disk space but then so does MS office and SO 5.x. So far I am pleased with it, as it gives me yet another option to deaeling with MS docs and excel spread sheets... I give it a thumbs up ;-) Re:installed last night.. (Score:2) setup Then go through the setup program, get it where you want it, and then log in as yourself and run setup again, this time without the MicroSoft's cash cow and achille heel (Score:2) Remember, MS changes stripes each decade. 75-85 it was a languages company, then became an OS company, then became a business software company. Lotus, Word Perfect, and Harvard Graphics "owned" the business app sector before MS did. Now MS is trying to become a personal entertainment company- games, digital TV, ISP Linux + OpenOffice IS ready for the desktop (Score:5, Insightful) How many times does your mom install a new printer? even when she had Windows and she got a new LaserJet she called me!. We all know all the people and institutions that are migrating towards Linux and OO, its just a matter of time to see it as a mainstream. On the other hand, it would come handy if the WalMart Mandrake PCs come with StarOffice preinstalled and with a HUGE icon in the middle of the desktop for all users. Re:Linux + OpenOffice IS ready for the desktop (Score:3, Informative) I'm on Debian Woody, and I've been fiddling with both KDE 2.2.2 and 3. Configuring the HP OfficeJet T65 is a major pain. I have an ad hoc-solution now that works OK on PS files. But those PS files created by KWord look nothing like they did on screen, and often, some of the words are lost at the end of lines. I haven't got OpenOffice to import anything but it's native format. Is there some kind of subprocess that is supposed to do the filtering, that just dies? It's a hell to debug this stuff. The really bad thing is though that this box is not on the net right now, so it is too hard to get to the docs and to the updates. Last night, I burnt OO debs on a CD, and when I got home, it turned out that the CD was corrupted.... Arrrrgh! Well, I'm going to quite a lot of pain, some of it is definately not Linux' fault, but I think that if I hadn't been into it for freedom, I wouldn't have bothered. Freedom is still Linux major selling point. Re:Linux + OpenOffice IS ready for the desktop (Score:2) Intuitive Windows? All I can sys is that I love the stability of Linux, FreeBSD and MAC OS X. As far as intuitive goes its a question of what you are used to. What I love about X on Linux and FreeBSD is the desktops. If you need to work on more than one app at a time and to cut and paste between apps nothing beats X. As far as stability goes, I only reboot when I install new hardware or upgrade the system to a new version about once or twice a year. Reluctance to Open Office (Score:4, Interesting) Long and short, articles like this help my case that Open Office is becoming more mainstream. I love it! Sleeping giant? (Score:2, Interesting) I think OpenOffice shows a lot of promise in the windows world, but I wonder how long it'll take for Microsoft Word to obfuscate its file format (it's pretty obfuscated as is, but I get the feeling they have not yet begun to fight). Far too often, it's convenience that rules the day; despite the fact that RTF is still a darn good format, people save in Microsoft Word 2008.324 Re:Sleeping giant? (Score:2) Re:Sleeping giant? (Score:2) hmmm, that's interesting. You mean files that could only be opened with MS Office? I can certainly envision a cat and mouse game of office documents between MS and open source, much like the RIAA / Valenti vs. practically everyone wars going on now. Wonder who would win? Re:Sleeping giant? (Score:2) Certainly not the users, and someday they may realize this. Re:Sleeping giant? (Score:2) Even more interesting will be the litigation that would ensue if a large corp. decided to migrate from, say, MSOffice to OpenOffice.org and MS refused to assist them in decrypting their documents Open Office Pre-installed from OEM (Score:5, Interesting) We're a small tier OEM, and myself and another tech have convinced 'those that be' within our company to include Open Office on our low end systems instead of MS Worksuite 2002 OEM. Unfortunately the systems still come with MS Windows XP Home on them, but at least it's a step in the right direction. All of us techs now have Open Office installed on our computers and use it for pretty much all of our office app needs except for a few Excel quote sheets that have embedded macros that don't seem to function properly. So far we've had no complaints from any customers that have purchased these systems, but then again we've gotten no rave reviews either. I would definately say that it is an option though, at least for people who aren't tied directly into the MS specifics of the different file formats. Anyone who just wants to use a word processor, spreadsheet, presentation software and do thier work from scratch should be more than happy with this software. Re:Open Office Pre-installed from OEM (Score:2) Re:Open Office Pre-installed from OEM (Score:2) It's not about "Microsoft wins" or "OpenSource wins" it's about doing your work in the most effective and cost effective way possible. Hopefully the OP's company will be able to convert their spreadsheets over to OOo -- but if they have too many spreadsheets that are heavily macro'd it may not be cost effective to do so -- regardless of the price structure of the suites themselves. People need to get their head out of their ass when it comes to things like this. The computer is a tool, not a political statement. And people simply want to get their job done, not fight with the computer over how they should do it. OOo is great (I use it at home), but if it doesn't do what you need then get something that does. There's only 2 major gripes for the linux version (Score:5, Insightful) 2. Can't read ALL the Word documents 3. Still a bit sluggish Three! I mean three major gripes! Seriously, font ugliness is a big problem under linux and it's all X's fault. You've seen the hundreds of people gawking at anti-aliased desktops, it just looks cooler. I believe there are many articles on exactly why fonts are ugly in linux... I also believe that the lack of cool, MS-compatible fonts (let's face it guys, Truetype was one thing MS carried from Win 3.1 to Win XP for a reason) are because of licensing issues. The next time a big company wants to donate money to open source, get them to design or fund fonts! That'll get Linux on the desktop. That'll cause secretaries to use OpenOffice and that'll make me happy. 'nuff said. Re:There's only 2 major gripes for the linux versi (Score:3, Insightful) How often have we heard this phrase. Re:There's only 2 major gripes for the linux versi (Score:2) Yes, but it's happening. A couple of years ago, the idea of Walmart selling linux boxes as desktop machines was laughable. Not now. OSS evangelists saying this is like kids on car journeys repeatedly asking "are we there yet?" Just because they're annoying - and we're not there yet, dammit - doesn't mean we're not going to get there. Re:There's only 2 major gripes for the linux versi (Score:2, Interesting) Also, have you checked out nautilus? if you don't mind the occasional crash (it's improving) those fonts look nifty! Re:There's only 2 major gripes for the linux versi (Score:2, Interesting) Re:There's only 2 major gripes for the linux versi (Score:3, Insightful) Last I looked, the Linux version of Microsoft Office didn't exist. When given the choice between "cake or death", most everyone will choose the cake. Re:There's only 2 major gripes for the linux versi (Score:2) Except for Hitler. Remember, he took the vegitarian (that Nazi shithead). Re:There's only 2 major gripes for the linux versi (Score:3, Informative) Whatever, the basic idea is so good that its worth is obvious. And I beleive that progress is underway. Don't both KDE3 and Gnome2 support "anti-aliased" fonts? That's a partial answer. Now what is needed are some decent tools for building those fonts. If I recall correctly, the idea of a font is a collection of objects that know how to draw themselves are various sizes and resolutions and which can be mapped to a keyboard. One way to specify this is with Bezier curves (+ hinting), but I don't see any reason that it shouldn't be possible to specify programs that would do the same thing: draw(char#, rect=(top, left, height, width), weight, color=false, solid=true, underline=false, FontMaker used to show one a rectangle and allow one to specify which dots were black for which letter (rather like an icon designer). Fontographer, it's sequel, changed this to specifying the same thing in terms of what appeared to be Bezier curves, with hints for things like how lines ended, how you specified holes inside of letters, etc. These programs allowed the Mac to have MANY custom fonts that did just what was needed. The pixelated fonts looked ugly at every size but the design size, and appropriate reductions, but the bezier fonts looked good at many sizes. (There were scaling problems with things like serifs, size of dots, etc. which created esthetic problems if you deviated too far from the design sizes, so even scalable fonts look better at appropriate sizes.) I haven't gone searching for projects like these, but they would certainly be a "good thing(tm)". Re:There's only 2 major gripes for the linux versi (Score:2) OTOH, when do those patents run out? 1989 + 20? = 2009 (right guess?) and how long would it take to build a new engine? and all the fonts to use it, too, of course... But if the 1992 patent is the blocker, then that's 3 extra years. Might make all the difference which one is the blocker. Re:There's only 2 major gripes for the linux versi (Score:2) (I'm not saying that GTK's AA is perfect. Diagonal lines tend to disappear.) I'm reminded of when Mac users show examples of anti-aliased paragraphs of text rendered "before Quartz" and "after Quartz", raving over how perfect the "after Quartz" picture looks. The "before Quartz" one always looks MUCH better to read, as Quartz makes each character absolutely true to the letter form but, as a trade-off, really fuzzy. I assume that the good antialiasing also takes hinting into consideration. So, are there any comparisons between properly-hinted AA and non-AA text? Nice to think about what's happening in Microsoft (Score:3, Funny) Defeating Linux and open source apps - strategy Re:Nice to think about what's happening in Microso (Score:2) 1) collect underpants 2) ??? 3) profit! At least the Underpants Gnomes would end up with a pile of underpants - which could be useful - even if they didn't make any profit. Comparison of how MS & OO handle the same docu (Score:4, Informative) OpenOffice.org, not OpenOffice (Score:3, Informative) From the faq: 8. Why should we say "OpenOffice.org" instead of simply "OpenOffice"? [openoffice.org] Besides, OOO is less confusing... (Score:2) Most of us think "object oriented" when we see OO. When we see OOO, we think "exclamation of extreme satisfaction." Hope they help... (Score:2) Hopefully some of those companies that are now saving many thousands of dollars by running OpenOffice (Especially the largeer firms/localities.) will consider hiring a developer to kick in some work on OpenOffice. Even if only a dozen companies worldwide did it, OpenOffice would suddenly get a huge boost of forward momentum. great trick (Score:5, Informative) Travis What is the percentage of "power" users? (Score:2, Interesting) I don't use Word much and I personally probably approach 5% of the potential functionality. I just recently was sharing a Word doc that I had added comments with (using their functionality for, not just writing them in). None of the recipients knew how to find my comments and they wanted to know why I had hilited some words (mousing over the hilite brings up my comment). Well... (Score:2) Re:Well... (Score:3, Informative) I couldn't find MS's volume licensing, but even if they gave a huge discount from retail (say 75%off the retail price of $450 for Office XP Standard), the 1,000 user company would still wind up paying $112,500. In other words, Star Office would save the 1,000 user company $72,500. (Companies might shy away from the free Open Office because there's no official support channels whereas you can call up Sun with tech support inquiries.) Re:Well... (Score:2) I consulted for an organization with a 1200-station PC based network. Licensing changes and the threat of an audit got them sheepishly admit to me that they had *no* licenses for any Microsoft products, despite the products being installed on like 99% of the workstations. Every machine had: Win2k, Office2k, a few addons, Adobe Photoshop, Visual Interdev, and a bunch of other stuff. The bottom line is that out of 1200 users, they all used e-mail, all needed to be able to look at (though not necessarily edit) Word documents, and also use a proprietary app. About 100 needed a full copy of Word. About 200 more needed just Word. The good thing about licensing is that you can evaluate what you need as opposed to what you would install. All the machines got re-installed, but this time with legal software. The base machines got a copy of Word Viewer, Outlook, and a whole bunch of free/site license tools (plus the vertical makret apps that are really important). The "power users" (basica;ly managers who needed things for spreadsheets, presentations, etc). The developers (about 3 or 4) got development tools. The bosses were thinking "ohh crap, its 1200 x ($cost_of_Win2k + $cost_of_Office + $cost_of_AdobeStuff + $cost_of_DevelopmentStuff) = 7 figures (I think the number was about $4 million). After we really got it all figured out, the cost was a minor fraction of that - like $300k or something tiny like that. Re:Well... (Score:2) Not surprised... (Score:4, Interesting) PPA, the girl next door. GNOME OOo users: That stupid exit-on-startup bug (Score:5, Informative) There are a couple ways around the purge. The easiest one is to add "unset SESSION_MANAGER" to the soffice startup script. One file, all GNOME users happy. A somewhat more intrusive and wide-ranging solution is to add "exec $PATH_TO_GNOME-SESSION/gnome-session --purge-delay=0" to ~/.gnomerc. Supposedly, this will solve a similar problem with Opera, according to the bug comments. Re:GNOME OOo users: That stupid exit-on-startup bu (Score:2) too lazy to try to figure out what was causing it. Stellar Product (Score:3, Informative) Economics 101 (Score:4, Interesting) Econ 101 - consumers purchase things because they perceive value > total cost. If the VALUE of MS Office lies in its perceived ubiquity (since the software functions of the two products are practially the same), the moment that this "value" the opportunity or real costs of BSA Audits, harrassment, and the fear of that 'disgruntled employee' narc'ing sometime in the future, well DUH people are going to move away from these 'excessive costs' whenever they can. It's my conviction that the widespread piracy of Win95 (and thus its widespread adoption) KILLED an arguably better competitor, OS/2. If every single copy of Win95 had to be paid for (the theoretical goal) it would not be the dominant OS. The tighter they squeeze, the more systems will slip through their fingers, indeed. Sure piracy costs Microsoft; if IBM had recognized this at the time, and been handing out FREE OS/2 versions MS probably wouldn't have to spend the $$ to buy the Justice Dept today. Ch ch ch changes... (Score:2, Insightful) I remember back when Microsoft were backslapping saying they had 'turned-on-a-dime' with regard to the Internet, and 'won' the browser wars by giving away IE. I remember thinking - this is the beginning of the end for you, mate. The day MS gave away IE was the start of a new epoch in the software industry which will result in the death of MS. Ironic. Re:Ch ch ch changes... (Score:2) Who do you call for tech support? (Score:5, Interesting) That's the big bugaboo question with corporations: Who do we blame if something goes wrong? That's the question that MS wants to stick in your craw, to give the perception that open source software is unreliable. However, if you're using Microsoft products, when is the last time you got tech support from Microsoft? I've been supporting Microsoft products in a Helpdesk environment for over six years now. I have never even thought of support from Microsoft as much of an option. Am I missing something? I do know that every time I have submitted bug reports to Microsoft (which I've done on multiple occasions) the report seems to disappear into a black hole. I've never got even so much as an automatic confirmation or anything. And always, the suggestion to correct the bug has gone unanswered, with no bug fix. Yes, I rather resent the poor service back to me, when I was trying to help them. Every open source project I've submitted bug fixes for have almost always sent feedback back to me. Usually in the form of a personal email from the author. Now how's that for service? --Yekrats Seriously. (Score:2) So I say this is a total red herring, and one that will bite the commercial vendors in the ass real soon now. As soon as OpenOffice hits Mac I'll definitely try it (and I'm using Mozilla now). Re:Who do you call for tech support? (Score:2, Insightful) If you are a personal user and the kind to go to the MS website to get your support then searching openoffice.org or google to get help isn't much of a stretch. The only stretching will be from the money left in your wallet. Re:Who do you call for tech support? (Score:2) This isn't accurate. Quoting from MS's Product SUpport page, for Office XP: If you purchased this product at a retail store, you are eligible for unlimited no-charge Installation Support and two no-charge Personal Support incidents. Personal Support is designed to provide support for everyday product usage to help U.S. consumers, home users, home office customers who use Microsoft consumer products. After that, its $35 an incident, again quoting: In addition to no-charge support: If you purchased this product at a retail store, you are eligible for Paid Personal Support available at $35 U.S. per incident and billable to your VISA, MasterCard, or American Express credit card. Does that seem so unreasonable? Unlimited help installing the package, 2 normal support incidents, and after that its $35/incident. Sounds extremely reasonable to me. Re:Who do you call for tech support? (Score:2) Re:Who do you call for tech support? (Score:2) Amen to that. I recall trying to report a bug in MSVC 5.2, and drawing a complete blank. It wasn't a new version with a beta program, there was (at that time) no links on their site that we could find to report bugs, and whoever we got through to on the 'phone eventually ended up putting us through to tech support, who wanted to charge us $75 to ask two question. Think about that. You are talking to someone in Microsoft. You say to them "I have a bug to report. A bug. Not a technical support issue. I know how to use it, and it doesn't work. It hangs the machine if you try and compile an MFC collection class inside a double nested namespace. The product doesn't work, and I'm trying to provide feedback to help you fix it. Don't put me through to tech support. Do not put me through to tech support." "Transferring you now... Hi, welcome to tech support. My name is Mindy, and I'll talk to you for ten whole minutes for only $75 dollars. Mmm, you sound like a real stud. What's your credit card number, you hot stallion?" OK, I'm perhaps paraphrasing slightly at the end, but they really seemed to go out of their way to make it hard to help them. Re:Who do you call for tech support? (Score:2) I've used this numerous times, and have found the support and help to be great (and free). Re:Who do you call for tech support? (Score:2) As if ANY software licence (GPL included) allows you to sue the maker. MS, Oracle, Lotus/IBM, Sun, etc all license their software such that they are absolved if anything goes wrong. Honest question here, when was the last time anyone's been sued for COTS software defects? I can't recall any. Re:Who do you call for tech support? (Score:2) I think it really depends on what amount of risk you associate with time lost trying to figure it out yourself. For example, I have been working in a proprietary development environment (high-end CAD), where the total cost of my software is probably $40,000 (just one seat!). The API documentation is sketchy at times, and our contract is definitely time-constrained. So, is it best for me to burn $100/hour of the contract to figure stuff out, or should I call up our support line and get an expert's answer quickly? In my case, the our software vendor is pretty good, and the support is well worth it. The same is true for some super-high-end server installations. I believe Sun sells a support option, where Sun actively monitors your servers. If something goes wrong, they know before you do, and begin figuring out a resolution! Is it possible to beat this? Again, a lot is at stake, here. I don't have experience with M$ support, so I'll stop talking, now. Re:Who do you call for tech support? (Score:2) The "There's no tech support for Open Source Software" is a glass-half-empty way of looking at it. The upside is that a situation could arise where several companies are providing support, each with their own competitive advantages. They could charge for individual cases, as well as selling service contracts to corporations. Another idea: start a database of issues/resolutions. Any support company can use it, provided they feed back new solutions to it. It would not only lower the cost of providing service and eliminate redundancies, but it would provide the OO.o hackers with valuable data about their product. I'm starting to like this idea, and if anyone has a few million to spare, I'll gladly implement it. Or change my name and make for the Bahamas. Who you gonna call? Madame Cleo, that's who! (Score:2) This would be funnier if it weren't so accurate: Microsoft Technical Support vs. The Psychic Friends Network [bmug.org] And I'm not just MS bashing. I've had experiences with MS tech that closely resemble these. Every time I hear a PHB say "We have to use MS, becase we need the support" I just laugh and laugh and laugh. Then I go back to my office and cry. Pimping the benefits of OSS to the masses? (Score:3, Interesting) OpenOffice can't run macros written in Microsoft's programming language, either. (On the bright side, you're therefore safe from Word and Excel macro viruses.) I don't know if macro viruses are still floating around in the wild, but in a computer-illiterate, yet paranoid user culture, this may prove to be an important selling point. Time will tell if StarBasic can be used for similar abuses. The article notes a few things that, if I understand correctly, OOo does better than MSO: It's nice to have a proper Font menu (showing font names in their actual typefaces) at the top of the window, instead of on a toolbar that may not be open. It's also a pleasure to be able to open any kind of OpenOffice document (text, spreadsheet, presentation, drawing) from the File menu of any of its programs. [...] Both Word and OpenOffice Writer let you set up abbreviations that when typed expand into longer words or phrases. But only OpenOffice offers to complete frequently used long words automatically, which quickly becomes a huge timesaver. If you listen to Bill's Legions, MSO is the all-singing, all-dancing crap of the world that can do everything you can think of and more. I would appreciate being corrected here if MSO does the above, and I'd be surprised if it didn't. Fortunately, the open-source nature of OpenOffice.org holds tantalizing promise for improved versions. Anyone is permitted, even encouraged, to submit bug reports, wish lists of features and other feedback via the Web site. As a new droplet in the tidal wave of the open-source movement, you may even experience the thrill of watching your tiny input have an effect on the next version. *jumps up and down like a moron on speed* This is what keeps me coming back to OSS efforts. I may not be able to program worth a lick, but I can still directly contribute to the improvement of a program I use and interact with the programmers as if they're human beings, instead of distant gods on top of a mountain of C code somewhere. I think this aspect of the Mozilla project should have been screamed to the heavens even more than it was to the users, the idea that Joe User could make a solid, tangible contribution to making their computers easier and better, rather than waiting for God Gates to bestow His latest Blessings upon the unwashed masses. Maybe it's due to my anarchist leanings, but I think we're better when we work together and listen to the people affected by our decisions and our work, instead of assuming I, and I alone, know what's best for everyone else. Give a person a taste of the power, freedom, and agency s/he can have as an individual among many, and that person will never want to give it up. It's a liberating feeling. For most users it should replace MS-Office (Score:2, Interesting) Admittedly this is just my own experiences, but all of the users I've had to support in an office environment, as well as my own use of office suites says that the functionality in OpenOffice and StarOffice should completely replace MS-Office with about zero user impact. It's good to see that OpenOffice is getting the kind of press coverage needed to make it a real challenger to Microsoft's dominance. The NY Times article is exactly the type of thing any product (not just open source) needs to become accepted as mainstream. Bravo! I have one issue with open office (Score:4, Informative) Since I write scientific articles and need to be able to do all of the above, I can't use OOo (I use framemaker right now). I checked with issuezilla and this is something they are aware of, even though there doesn't seem to be much activity on the issue. I really hope they fix this soon. Honest question about OSS (Score:2) Re:Honest question about OSS (Score:2) I love Open Office, even if it's not perfect (Score:2, Informative) I've always found Word to be one of the least-intuitive, poorly-supported applications that I've ever had the displeasure of working with. To say that I hate Word with a passion would not be an understatement. To make matters worse, with each new release, the number of Word's "features" seems to expand nearly geometrically, while my ability to use nearly ANY feature decreases by some sort of evil inverse proportion. Microsoft needs to hire Jacob Nielsen [useit.com] to conduct some usability studies on the app, seriously. So for me, ANYTHING that can help me to escape from the grasp of Word sounds good. I've got the 1.0 release of OpenOffice and I love it. Sure, it's got bugs vis-a-vis opening and saving Word files perfectly, and the bulleted list thing is really annoying (although some Windows people think they look really cool! LOL), but since most of my documents need to be created for hardcopy printing only, I'm learning to love OpenOffice. It would be nice if... (Score:2) Write Congress and pressure them to switch (Score:3, Insightful) Openoffice.org -- real life use (Score:2, Informative) So far I'm pretty happy. The UI is okay, and things are pretty nice. However, I've had a lot of problems. (all in OO writer) Given all of these complaints I still expect I'll finish this using OOo. It seems to work well enough and I'd like to move away from MS tools if possible. databases and OO (Score:4, Interesting) However, it has some darn nice database features. If you have existing odbc sources defined in windows, you can access them. However, unlike word, which let's you access them via the mail merge function only, OO goes one better: you can see and edit the tables as tables. You can create new queries, that are then available to all the OO components. Let me say that again another way. You get everything MS Access gives you except for the ability to create custom forms. And they say that OO doesn't have a database. You can also use jdbc or just link to an existing excel file. That's right, you can access an excel file as if it were a set of records and columns. I just linked to an excel spreadsheet with 17,000 rows and 30 columns, viewed it as if it were a table in a database, wrote a custom query that will now be available to all the OO components. And they call this not having a database. I've got users using OO to edit mysql tables that hold data for our website because MS Access couldn't work correctly with the myodbc drivers. I really wish people would cover that aspect more in their reviews. It's a very important feature to us here. Our hidebound faculty will never move to it of course, but for some tasks like basic mysql database entry, that's what I'm going to have them use. Re:databases and OO (Score:3, Interesting) or with unixODBC in Linux. I had never touched unixODBC before, but there's a HOWTO PDF (I don't remember the URL, but it was in LinuxToday last week) that explained the process. I had OpenOffice.org talking to my Postgres database in minutes! (And the Howto was for mysql!) > You get everything MS Access gives you except for the ability to create custom forms. BZZT. File | AutoPilot | Form... ok, it might not be quite as complete as Access (maybe it is, I don't know how they compare), but it's there! I know you can write events for DB updates from StarBasic, and they can supposedly access form widgets, so it probably has all the functionality of Access. No reports though, that I'm aware of -- Access may lead there. > I really wish people would cover that aspect more in their reviews. Agree 100%. Really, OpenOffice.org is SOOO close to being The MS Office Killer it's not even funny. It just needs 1) more end user documentation, especially for the macro language (which is quite powerful), 2) maybe a reports system like Access has, 3) fixes for a few little bugs that have been mentioned here and elsewhere. All this should be done in a few months. Combine OOo for most uses and LaTeX for books and technical writings, and there will be absolutely no reason whatsoever to pay for MS Office. Re:Batch-mode Converters? (Score:5, Informative) Sure. (Score:2) Re:OpenOffice dash problem (Score:2) Its part of the autoreplace stuff - similar to the "smart quotes" options et al that have been adding bloat to word-processors for years. The question mark appears when you're displaying in a font or charset that doesnt have the character its looking for as a replacement (I think) Whatever the reason its easy to turn off. Disable the "Turn minus signs into dashes" autoreplace option. Re:OpenOffice dash problem (Score:2, Insightful) The problem is that using a hyphen, the "-" character, within a sentence is incorrect usage. What should be used is the em dash. The em dash is twice as wide as the hyphen, and is most frequently used to punctuate an abrupt change in thought for emphasis. In no circumstances are there spaces on either side of the mark. So OpenOffice doesn't really have a "dash" problem; it is flagging incorrect usage. If the author were to use two hyphens--like this--without spaces OpenOffice would change them to em dashes, which would be correct usage. By the way, journalists aren't know for their command of grammar or spalling. MS Grammar Checking, phhhft! (Score:2) Not I, says this grammar wonk. I've got a better grasp on grammar than Word does (not hard, if you actually understand things like gerunds and subjunctives), and I'm tired of having to argue with it constantly. Why not switch? Because my project boss won't switch, so my hands are tied. In fact, Word has very silly grammar checking, and its spell-checker blows diseased goats, too...especialy from the point of view of someone who professionally must keep a dictionary or two AND a thesaurus underhand constantly, and who may have to consult numerous specialized glossaries [state.pa.us] on any given day besides. Nasty partisan shot: I like Word Perfect because it's the perfectionist's tool: It shuts up and leaves you alone. (If I have to fix those "you must really want..." MS 'regenerating' defaults one...more...time...) I Go To Bed Angry and Wake Up Angrier the Next Morning, just like Harlan Ellison, and here're the reasons! Re:Open Office feature (Score:2) I also find that it can work best if you create an envelope, then save it, and just use that one as a template for the future.
http://news.slashdot.org/story/02/06/20/1433230/new-york-times-plugs-openoffice-suite
CC-MAIN-2016-07
refinedweb
7,028
71.75
In a previous part of this series, you updated the demo application to organize links into lists in your database. The main application view now shows a menu with all lists that are currently registered within the database, but the menu has no active links yet. In this section, you’ll create a new route within the application to show links by list. You’ll also learn how to use the where() method in Eloquent to better filter results in a database query. To get started, open the routes/web.php file in your code editor: routes/web.php The file currently has the following content: <() ]); }); The Route::get call defines an HTTP GET route for the application entry page. When a request to / is made to the application, this callback function will be triggered to return the index view. You’ll now create a second route to show lists of links based on a list slug. A slug is a short string that is typically used to build user-friendly URLs. The new route must query the database’s link_lists table for a list that has the provided URL parameter as its slug field. If a list with that slug cannot be found, the application should inform the user with an HTTP 404 or not found error. The following code creates a GET route using a dynamic parameter (defined by {slug}), named link-list. This will: LinkListEloquent model to query the database with the where()method, using slug as search criteria. The first()method will make sure only one object is returned. abortmethod. The $lists parameter is provided to build the list menu, and the $links parameter is provided for compatibility with the current version of the index view, since it loops through a variable with that name. Include the following code at the bottom of your routes/web.php file: Route::get('/{slug}', function ($slug) { $list = LinkList::where('slug', $slug)->first(); if (!$list) { abort(404); } return view('index', [ 'list' => $list, 'links' => $list->links, 'lists' => LinkList::all() ]); })->name('link-list'); Save the file when you’re done. Although there are shortcuts to implement routes that reference Eloquent models, in this tutorial we focus on using the where() method for learning purposes. To test that your new route works as expected, you can go to your browser and access the link for the default list page. If you’ve followed all steps in this series so far and your database is not empty, the default list page should be available at the following local address: You’ll see the same page as before, but links are now limited to those from the default list. If you have additional lists, you can access their page by replacing the highlighted default slug in the URL with the slug of your list. With your new route configured, you can now use the route Blade method to dynamically generate URLs for your link lists, from your template view. You can also customize the page header to show information about a list in case one is available. Open the resources/views/index.blade.php file in your code editor: resources/views/index.blade.php This file has 2 lines that need updating. First, locate the subtitle paragraph containing the menu you created in another part of this series. This is how it looks like now: <p class="subtitle"> @foreach ($lists as $list)<a href="#" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach </p> You’ll update the href hyperlink to include the current URL for the list page, using the route blade method. This method expects the name of the route as the first argument, with URL parameters provided as additional arguments to the method call. Replace the # character with the following highlighted content: <p class="subtitle"> @foreach ($lists as $list)<a href="{{ route('link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach </p> Next, locate the links section and the foreach loop within. You’ll need to include another call to the route() method where the list name is printed for each link. This will be similar to the previous example, however, the list object is accessed differently, through the $link variable: <p>{{$link->url}}</p> <p class="mt-2"><a href="{{ route('link-list', $link->link_list->slug) }}" title="{{ $link->link_list->title }}" class="tag is-info">{{ $link->link_list->title }}</a></p> Next, you may want to include information about a list, when additional information is provided. You can check for the existence of a $list variable, and print the list title only when that variable is available. Replace your title section with the following highlighted code: <h1 class="title"> @if (isset($list)) {{ $list->title }} @else Check out my awesome links @endif </h1> This is how the index.blade.php file will look once you’re finished. The changes are highlighted for your convenience: <"> @if (isset($list)) {{ $list->title }} @else Check out my awesome links @endif </h1> <p class="subtitle"> @foreach ($lists as $list)<a href="{{ route('link-list', $list->slug) }}"="{{ route('link-list', $link->link_list->slug) }}" title="{{ $link->link_list->title }}" class="tag is-info">{{ $link->link_list->title }}</a></p> </div> @endforeach </section> </div> </section> </body> </html> Save the file when you’re done updating its contents. You can now access the application main page through your browser. If you are using the included Docker Compose setup, the application should be available through the following local address: You’ll get a page similar to the following screenshot: In the next part of this series, you’ll learn how to order query results in Laravel Eloquent.! Great tutorial. Thank you for sharing… A one liner: Same as the code above.
https://www.digitalocean.com/community/tutorials/how-to-refine-database-queries-in-laravel-with-eloquent-where
CC-MAIN-2022-33
refinedweb
957
58.72
04 January 2007 22:57 [Source: ICIS news] HOUSTON (ICIS news)--Chemical railcar traffic for 2006 reached 1,519,261 carloads, 1.1% lower than in 2005, according to data released on Thursday by the Association of American Railroads (AAR). For the final week of the year, there were 27,094 chemical carloads originated, 1.1% higher than the same week last year. Analysts consider the weekly statistics to be a good indicator of current chemical industry activity, as railroads transport 22% of chemicals produced in the ?xml:namespace> Among all commodities that report to the Freight volume for the week ended 30 December was estimated at 27.6bn ton-miles. In Total carload volume on the Kansas City Southern de Mexico was down 2.5% for the year to 592,025 units. Washington
http://www.icis.com/Articles/2007/01/04/1117930/us-chem-railcar-traffic-ends-year-behind-2005.html
CC-MAIN-2015-06
refinedweb
134
55.95
Extended Events Server2010-06-24T01:11:00ZExtended Events demos on Microsoft Virtual Academy<p>I had an opportunity recently to contribute a presentation to the Microsoft Virtual Academy as part of the <a href="" target="_blank">Mission Critical Confidence using SQL Server 2012</a> course offering. The MVA offers you a myriad of free training opportunities, so I encourage anyone who is interested in expanding your knowledge to take advantage of this offering.</p> <p>For those of you who don’t want to invest the time to go through the whole course, you can access my presentation <a href="" target="_blank">here</a>. I cover the following topics:</p> <ul> <li>Integration of Extended Events into AlwaysOn troubleshooting.</li> <li>Troubleshooting Login failures using client/server correlation.</li> <li>Troubleshooting query performance issues using client/server correlation.</li> </ul> <p>I’m not sure how long content is made available on MVA, I got the impression that it would be removed as some point in the future, but should be there for at lease several months.</p> <p>- Mike</p><img src="" width="1" height="1">extended_events with the system_health session in SQL Server 2012<p>The ever alert Jonathan Kehayias (<a href="" target="_blank">Blog</a> | <a href="" target="_blank">Twitter</a>) sent me a question recently asking about the <a href="" target="_blank">Extended Event UI</a> used for showing predicates. In particular, he was wondering about the predicate for the wait_info event that is defined in the system_health session and was wondering what was going on.</p> <p><a href=""><img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="wait_info_pred" border="0" alt="wait_info_pred" src="" width="347" height="343" /></a></p> .</p> <h6>Bug or Artifact – You make the call</h6> <p…</p> <p:</p> <blockquote> <p><em>wait_type = 120</em></p> </blockquote> <p>A quick check of dm_xe_map_values shows us that 120 is equivalent to the SOS_SCHEDULER_YIELD wait type, so the UI would display:</p> <blockquote> <p>wait_type | equal_uint64 | SOS_SCHEDULER_YIELD</p> </blockquote> <p:</p> <blockquote> <pre class="csharpcode"><span class="kwrd">SELECT</span> <span class="kwrd">TOP</span> 50 * <span class="kwrd">FROM</span> sys.dm_xe_map_value</pre> </block>What you’ll see is the following:</p> <table cellspacing="0" cellpadding="2"> <tr> <td> <p align="center"><strong>map_keys</strong></p> </td> <td> <p align="center"><strong>values</strong></p> </td> </tr> <tr> <td>0</td> <td>UNKNOWN</td> </tr> <tr> <td>1-21</td> <td>Lock waits</td> </tr> <tr> <td>22-31</td> <td>Not used</td> </tr> <tr> <td>32-37</td> <td>Latch waits</td> </tr> <tr> <td>38-47</td> <td>Not used</td> </tr> <tr> <td>48-50</td> <td>Pagelatch waits</td> </tr> </table> <p>In the system_health session we specify a filter that selects for the waits that we want to collect, but but instead of specifying each wait independently we specify ranges. So for example, to collect all the PAGELATCH* waits, we’d use this predicate:</p> <pre class="csharpcode">(wait_type > 47 <span class="kwrd">and</span> wait_type < 54)<.</p> <h6>You said there was an “issue”</h6> <p>Yes I did, and thank you for reminding me.</p> .</p> <p>This script will do the following:</p> <ul> <li>If the system_health session exists, it will remove the wait_info & wait_info_external events and replace them with the corrected filter. Any modifications you’ve made to these events in your system_health session will be lost. </li> <li>If the system_health session does not exist, it will created it. </li> <li>If the system_health session is not running, it will be started. </li> </ul> <div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:aeaaaaa2-81a3-4425-9b6d-22b527f5273f" class="wlWriterEditableSmartContent"><p>Download the fix for the <a href="" target="_blank">system health session</a></p></div><img src="" width="1" height="1">extended_events Tracking event session template is broken<p.</p> <p>MVP Jonathan Kehayias has posted the <a href="">steps to fix</a> this problem along with a corrected copy of the Activity Tracking template – check it out.</p> <p> <p>We are hoping to fix this in the first service pack of SQL Server 2012.</p> <p>- Mike</p></p><img src="" width="1" height="1">extended_events the Extended Events Reader<p>Check out <a href="" target="_blank">What's new for Extended Events in SQL Server Codenamed "Denali" CTP3</a>: <a href="" target="_blank">Introducing the Extended Events Object Model</a>.</p> <h4><a title="_Toc286048385" name="_Toc286048385"></a>Event stream defined</h4> <p:</p> <ul> <li>The event stream is asynchronous, not live, but to make the experience seem “more live” the event stream modifies the latency behavior of the source event session. When the event stream is hooked to an event session, the latency period specified by MAX_DISPATCH_LATENCY is changed to 3 seconds. When the event stream is disconnected, the latency is changed back to it’s original value. You may notice some odd behavior if you connect more than one XeReader to the same event session; the latency modification assumes only one connection so the <span style="text-decoration:underline;">first disconnect</span> from the event session will revert the latency back to the original value (eg. no ref-counting). </li> <li>The event stream aggressively follows the <a href="" target="_blank">prime directive</a> – if the application utilizing the event stream API gets far enough behind in processing events that it risks blocking the server, the application will be disconnected. This is to prevent a “client tracing” application from bringing down a server; a problem often documented with SQL Profiler. If the event rate from your event session is so high that it causes a disconnection, then the event file is a more appropriate target for you. </li> </ul> <h4><a title="_Toc286048386" name="_Toc286048386"></a>Exploring the API</h4> <p.</p> <h5>Using the XeReader API</h5> <p>In order to code against the API you’ll need to add a reference to the following assembly:</p> <p><em>Microsoft.SqlServer.XEvent.Linq.dll</em></p> <p>You’ll also need to add the following namespaces to your classes.</p> <p><em>using Microsoft.SqlServer.XEvent.Linq;</em></p> <p>Note: By the time we release “Denali” you will also need to add a second namespace, <em>Microsoft.SqlServer.Xevent</em>, to your code. Just letting you know so it’s not a surprise.</p> <h5>Reading an event file (XEL)</h5> <p:</p> <ul> <li>A single string with a valid path. </li> <li>A single string array containing a set of paths to XEL files. </li> <li>Two string arrays containing sets of paths to XEL and XEM files respectively. </li> </ul> <p>The paths can be fully qualified files or any valid representation of a path using wildcards. Here are a couple examples:</p> <p><span style="text-decoration:underline;">Read all XEL files from a specific location</span><span style="text-decoration:underline;"></span></p> <pre class="csharpcode">QueryableXEventData events = <span class="kwrd">new</span> QueryableXEventData(<span class="str">@"C:\Temp\myFile*.xel"</span>);</pre> <p><span style="text-decoration:underline;">Read a specified multiple of XEL files</span></p> <pre class="csharpcode"><span class="kwrd">string</span>[] fileList = <span class="kwrd">new</span> <span class="kwrd">string</span>[2]; fileList[0] = <span class="str">@"C:\Temp\demo_trace_0_129418467298110000.xel"</span>; fileList[1] = <span class="str">@"C:\Temp\demo_trace_0_129391767647570000.xel"</span>; QueryableXEventData events = <span class="kwrd">new</span> QueryableXEventData(fileList);</pre> <p><span style="text-decoration:underline;">Provide both XEL and XEM files</span></p> <pre class="csharpcode"><span class="kwrd">string</span>[] xelFiles = <span class="kwrd">new</span> <span class="kwrd">string</span>[1]; xelFiles[0] = <span class="str">@"C:\Temp\demo_trace_0_129418467298110000.xel"</span>; <span class="kwrd">string</span>[] xemFiles = <span class="kwrd">new</span> <span class="kwrd">string</span>[1]; xemFiles[1] = <span class="str">@"C:\Temp\demo_trace_0_129418467298110000.xem"</span>; QueryableXEventData events = <span class="kwrd">new</span> QueryableXEventData(xelFiles, xemFiles);</pre> <p>You get the idea.</p> <h5>Reading an event stream</h5> <p>You can read a stream from a running session by providing a connection string and event session name to the constructor along with a couple extra options.</p> <pre class="csharpcode">QueryableXEventData stream = <span class="kwrd">new</span> QueryableXEventData( <span class="str">@"Data Source = (local); Initial Catalog = master; Integrated Security = SSPI"</span>, <br> <span class="str">"alert_me"</span>, EventStreamSourceOptions.EventStream, EventStreamCacheOptions.DoNotCache);</pre> <ul> <li>EventStreamSourceOptions – EventStream is the only option that exists at this point. We’ll be adding one more option before we release but I’ll leave that for a later blog post when it’s relevant. </li> <li>EventStreamCacheOptions – You can either choose to not cache any data (DoNotCache) or to cache the data (CacheToDisk). This option determines whether you can enumerate across the history of events that have come from the stream. The DoNotCache option will pull events from the server as fast as possible and keep them in memory as long as possible. It is possible for events to be ejected from memory before they are processed by the enumerator. The CacheToDisk option will store events to the disk until the disk is full. </li> </ul> <h5>Working with the Events</h5> <p>The constructors all return an enumerable collection of type PublishedEvent, so the code to work with the events is identical regardless of source. I’ll cover the basics here to get you started.</p> <p>You can loop through the collection of events just like you would expect for an enumerable object so you can imagine using a <i>foreach</i>:</p> <pre class="csharpcode"><span class="kwrd">foreach</span> (PublishedEvent evt <span class="kwrd">in</span> events) { Console.WriteLine(evt.Name); <span class="kwrd">foreach</span> (PublishedEventField fld <span class="kwrd">in</span> evt.Fields) { Console.WriteLine(<span class="str">"\tField: {0} = {1}"</span>, fld.Name, fld.Value); } <span class="kwrd">foreach</span> (PublishedAction act <span class="kwrd">in</span> evt.Actions) { Console.WriteLine(<span class="str">"\tAction: {0} = {1}"</span>, act.Name, act.Value); } }</pre> <p>You can perform conditional expressions as you would expect, say if you wanted to perform an action based on a specific value being returned from a field:</p> <pre class="csharpcode"><span class="kwrd">if</span> (evt.Fields[<span class="str">"field_name"</span>].Value == <span class="str">"foo"</span>)</pre> <blockquote> <p>or</p> </blockquote> <pre class="csharpcode"><span class="kwrd">if</span> (fld.Value == <span class="str">"foo"</span>)</pre> <p>It is worth pointing out some “weirdness” associated with map fields if you want to evaluate using the friendly text that you would find in dm_xe_map_values rather than the integer map_key. You have to explicitly cast the field to a MapValue:</p> <pre class="csharpcode"><span class="kwrd">if</span> (((MapValue)evt.Fields[<span class="str">"field_name"</span>].Value).Value == <span class="str">"foo"</span> )</pre> <p.</p> <div style="margin:0px;padding:0px;float:none;display:inline;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:c66c510c-fc4f-4482-a0ce-5d8857acd3d7" class="wlWriterEditableSmartContent"><p>Download the Extended Event Reader <a href="" target="_blank">sample code</a></p></div> <p>Happy Eventing</p> <p>- Mike</p><img src="" width="1" height="1">extended_events the Extended Events User Interface<p>Check out <a href="" target="_blank">What's new for Extended Events in SQL Server Codenamed "Denali" CTP3</a> for an overview of all of the new functionality released in CTP3. This post details the new user interface. In my overview post I mentioned that the user interface is built directly into management studio (SSMS) and that there are four parts:</p> <ol> <li>The session list in Object Explorer.</li> <li>A Create Session wizard.</li> <li>A Create Session dialog.</li> <li>A display grid.</li> </ol> <p>This post focuses on the mechanisms for creating event sessions and displaying event session data.</p> <h4><a title="_Toc286048381" name="_Toc286048381"></a>Creating and modifying event sessions</h4> <p.</p> <h5>General page</h5> <p><img style="width:624px;height:482px;" src="" width="624" height="482"> </p><p>The <b>General</b> page collects the basic information about the session:</p> <p>· Name – You can figure this one out.</p> <p>· Template – We’ve carried over the idea of templates similar to SQL Profiler. You can export any session you’ve created to a template (Expand the context menu of your event session and click <b>Export Session…</b>). If you save the template to the default location, it will show up in this dropdown under the <i>User Templates</i> category.</p> <p>· Schedule – You can choose to make this an Autostart event session, start the session immediately after you complete the dialog and even choose to start up the event stream viewer. (More on that later.)</p> <p>· Causality Tracking – Turn on the correlation ids in your trace.</p> <p><strong>Wizard differences: </strong>These options are spread across three different wizard steps.</p> <h5>Event page - Library</h5><h5><img style="width:624px;height:520px;" src="" width="624" height="520"></h5><h5>The Event page has a couple parts. The Event Library allows you to select which events you want to add to your event session. The library supports Excel-like filtering using dropdown lists for Category and Channel. You can also search for specific events by just typing in the search text box. You choose an event by double-clicking or by selecting it and clicking the right arrow to move it to the Selected events list. We support Shift+Click and Ctrl+Click for choosing multiple events at once.</h5> <h5>Event page – Configure</h5> <p>In Extended Events, each event can be extended to include additional data or cause a specific action, only fire under defined conditions and to enable optional fields. Clicking on the <b>Configure</b> button takes you to the advanced event configuration options. You configure an event by selecting it in the <b>Selected events</b> list and then setting the configuration options on one of the tabs. When you select multiple events, the configuration options will apply to all selected events.</p> <p><img style="width:624px;height:523px;" src="" width="624" height="523"></p><p>The <b>Global Fields (Actions)</b> tab allows you select the list of Actions that you want to append to the event(s).</p> <p><a href=""><img style="border-width:0px;width:434px;height:105px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="434" height="105"></a></p> <p>The <b>Filter (Predicate)</b> tab is used to define the conditions under which the event will be collected.</p> <p><a href=""><img style="border-width:0px;width:434px;height:282px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="434" height="282"></a></p> <p>The <b>Event Fields</b> table allows you to enable or disable the collection of optional fields. (Fields without a checkbox are always collected.) You can also see the description and data type of each field on this tab.</p> <p><strong>Wizard differences:</strong> Global Fields and Predicates apply to all selected events. You cannot configure the events individually.</p> <h5>Data Storage page</h5> <p><a href=""><img style="border-width:0px;width:554px;height:465px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="554" height="465"></a></p> <p.</p> <p><strong>Wizard differences:</strong> The wizard supports only the event file and ring buffer targets.</p> <h5>Advanced page</h5> <p><a href=""><img style="border-width:0px;width:554px;height:327px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="554" height="327"></a></p> <p>Configure the options for the entire event session here. We use the same defaults you would get with the DDL syntax.</p> <p><strong>Wizard differences: </strong>You cannot configure the event session options in the wizard, the defaults are used.</p> <h5>Other stuff</h5> <p.</p> <p>You can change the configuration of an event session by right-clicking the session name in Object Explorer and clicking <b>Properties</b>. The same user interface will be presented showing all your configured settings. Most settings can be changed on a running session, but you’ll need to stop the session to change the Advanced options. You cannot change the target configuration (<b>Data Storage </b>page) on an existing target, you’ll need to delete the target and re-add it to change that. You will also find that the <b>Script </b>button is not enabled in the Properties dialog, you can still script your event session to DDL, but you’ll need to do it from Object Explorer by right-clicking the session name and choosing one of the <b>Script Session as…</b> commands.</p> <p><strong>Wizard differences: </strong>The wizard is not re-entrant. Sessions created in the wizard can be modified using the Property dialog just like any other session.</p> <h4><a title="_Toc286048382" name="_Toc286048382"></a>Viewing event session data</h4> <p>SSMS includes an event session data viewer for all of the supported targets with the exception of the ETW file target. (There are many other tools for working with ETL files.) There are basically two different types of event session data display.</p> <h5>In-memory targets</h5> <p>The in-memory targets include: ring buffer, event counter, histogram and event pairing. The data from these targets is displayed in a simple grid format.</p> <p><a href=""><img style="border-width:0px;width:504px;height:135px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="504" height="135"></a></p> <p.</p> <h5>Event stream and event file</h5> <p>You can open a “live view” of a running session by right-clicking on the session name and choosing the <b>Watch Live Data</b> <a href="" target="_blank">prime directive</a> – this is one of those tradeoffs.) If you have a very busy server (eg. lots of events) the file target will be a more appropriate target.</p> <p:</p> <p><b>File | Open | File</b> – Pick an XEL file and click <b>Open</b></p> <p><b>File | Open | Merge Extended Event files</b> – Use the dialog to collect multiple files to be merged</p> <p>Both the event steam and event files are displayed in the same user interface:</p> <p><a href=""><img style="border-width:0px;width:704px;height:535px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="704" height="535"></a></p> <p>The picture is a bit small, but you get the idea. Open up an XEL file in SSMS to get the full experience.</p> <p <b>Details</b> pane when you select a specific row in the grid. There is a bunch of functionality in this UI, almost too much to fit into a summary such as this, so I’ll hit the high points and let you explore.</p> <p>· You can add additional columns to the grid by either right-clicking the in the <b>Details</b> pane and choosing <b>Show Column in Table</b> or by clicking the <b>Choose Columns</b> button to open the Choose Columns dialog.</p> <p>· You can <b>Find</b> event records using the typical SSMS find behavior.</p> <p>· You can <b>Bookmark</b> records of interest and move between bookmarked records.</p> <p>· You can apply a filter to the results using a flexible criteria builder. (This is worth a picture; so much better than SQL Profiler!)</p> <p><a href=""><img style="border-width:0px;width:504px;height:312px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="504" height="312"></a></p> <p>· You can use the <b>Grouping</b> and <b>Aggregation </b>commands to do some basic analysis of your data directly in the display UI.</p> <p><a href=""><img style="border-width:0px;width:454px;height:304px;padding-top:0px;padding-right:0px;padding-left:0px;display:inline;background-image:none;" border="0" src="" width="454" height="304"></a></p> <p>· You can save the configuration of the display table (columns, filter, sorting and group/aggregation) using the <b>View Settings </b>button. (Note: This button name may change before RTM.)</p> <p>· You can export the list of events to a SQL Server table, CSV or XEL using the <b>Export to</b> menu item. (Note: This is only on the menu, not the command bar.)</p> <p>· You can Start and Stop the collection of the data and control the scrolling of the data in the window for the event stream.</p> <p <a href="">SQL Server Database Engine</a> forum.</p> <p>Happy Eventing!</p> <p>- Mike</p><img src="" width="1" height="1">extended_events’s New for Extended Events in SQL Server Codenamed “Denali” CTP3<p><a href="">CTP3</a> is finally here and the crowd goes wild! Since I’m sure everyone has been anticipating the CTP3 updates to Extended Events (because, let’s face it, Extended Events is the most important part of the product, right?) let’s get to it.</p> <h1>Introduction</h1> .</p> <p>Foremost is our prime directive (not that I’m a Star Trek™ fan):</p> <p><b>The most important workload on the server is the customer workload; diagnostic systems should not prevent the customer workload from running.</b></p> <p.”</p> <p>The goal for “Denali” has been twofold:</p> <ol> <li>Provide a diagnostic tracing facility, built on Extended Events, that will not just replace the existing SQL Trace/SQL Profiler based system, but exceed it.</li> <li>Drastically improve the usability of Extended Events.</li> </ol> <p>A significant part of meeting our first goal was accomplished in CTP1 by providing data parity with SQL Trace event classes. I’ve already discussed <a href="" target="_blank">migration from SQL Trace to Extended Events</a> in the blog, so I won’t go into details about that work here. With that preamble, let’s take a look and how we accomplished the second goal.</p> <h1>Extended Events User Interface</h1> <p><em><span style="font-size:small;">Get more details: <a href="" target="_blank">Introducing the Extended Events User Interface</a></span></em></p> <p:</p> <ul> <li>Session list – You will find a list of sessions within the Object Explorer under the node <b>Management | Extended Events | Sessions</b>.</li> <li>New Session Wizard – A wizard (duh) that provides a simplified experience for creating an event session. Only the most common options and functionality is exposed with everything else being configured automatically. Expand the context menu of the <b>Sessions</b> node and click <b>New Session Wizard</b>.</li> <li>New Session dialog – The complete set of Extended Events configuration in handy dialog format. Expand the context menu of the <b>Sessions </b>node and click <b>New Session…</b>. The same dialog is used for creating new sessions and for modifying existing sessions (click <b>Properties</b> on the context menu).</li> <li>Extended Events display – A collection of SSMS pages (tabs like the Query window) that display Extended Events trace data.</li> </ul> <h3>The user interface you designed…really</h3> <p.)</p> <h3>You might want to sit down for this next section</h3> <p>It’s an unpopular word, but I have to say it … Deprecation.</p> <p>Yeah, I said it; we are announcing deprecation of SQL Trace in Denali. Before everyone goes off the deep end, remember, this is only the <span style="text-decoration:underline;">announce</span>.)</p> <h1>Programming Extended Events</h1> <p><em><span style="font-size:small;">Get more details: <a href="" target="_blank">Introducing the Extended Events Reader</a></span></em></p> <p>Another important aspect of creating a usable diagnostic system is a programmatic interface. (Not everyone loves DDL as much as we do apparently.) We’ve covered this in two pieces:</p> <ul> <li>A “management” API that lets you create and modify event sessions as well as explore the Extended Events metadata on a server. This API was release in CTP1 and I’ve already provided examples in my post <a href="" target="_blank">Introducing the Extended Events Object Model</a>.</li> <li>A “reader” API that provides functionality for reading event files (XEL) and event streams coming from a running event session.</li> </ul> <p>The UI is built on top of these APIs so you have all the capabilities you need to write your own customized tools for working with Extended Events.</p> <h1></h1> <h1>The “other” stuff</h1> <p.</p> <h3>Some (target) names have been changed to protect the innocent</h3> <p>We’ve changed the names of some of the targets to be friendlier:</p> <table cellSpacing="0" cellPadding="0"> <tr> <td> <p><b>Old Target Name</b></p> </td> <td> <p><b>New Target Name</b></p> </td> </tr> <tr> <td> <p>asynchronous_file_target</p> </td> <td> <p>event_file</p> </td> </tr> <tr> <td> <p>synchronous_event_counter</p> </td> <td> <p>event_counter</p> </td> </tr> <tr> <td> <p>asynchronous_bucketizer</p> </td> <td> <p>histogram</p> </td> </tr> <tr> <td> <p>synchronous_bucketizer</p> </td> <td> <p>histogram (I’ll explain below)</p> </td> </tr> </table> <p>To make this change easier we’ve done some work under the covers:</p> <ul> <li>ADD TARGET with the old target names will <span style="text-decoration:underline;">still work</span>. We do name fixup inside SQL Server when we execute the DDL.</li> <li>DROP TARGET with the old target names <span style="text-decoration:underline;">will not work</span>. We fixed up the names so there are no records in the catalog with the old names.</li> <li>The target_name field of dm_xe_session_targets will be fixed up to have the new target names for any running sessions during Upgrade.</li> <li>The name field of server_event_session_targets will be fixed up to have the new target names for any configured session during Upgrade.</li> </ul> <p.</p> <h3>There can be only one – file that is</h3> <p.</p> <p><strong>Note:</strong> We do not support the XEL/XEM files created in SQL Server Codenamed “Denali” CTP1.</p> <p>The single file model has some downstream implications for event_file target and the fn_xe_file_target_read_file function.</p> <p><b>event_file</b> – You no longer need to set the <i>metadatafile</i> attribute but it is still available (but optional) so as not to break your DDL scripts. If you do provide a value for <i>metadatafile</i> it will be ignored for valid paths and it will throw an error for invalid paths.</p> <p><b>fn_xe_file_target_read_file</b> – The <i>mdpath</i> attribute is optional and ignored (but will throw if you provide an invalid path) when the <i>filename</i> path represents “Denali” XEL version files. You should just pass ‘NULL’ for <i>mdpath</i> as you would for all other optional attributes.</p> <h3></h3> <h3>New options available for some targets</h3> <p>We’ve added a few new options to make some of the targets a bit more flexible.</p> <p><b>pair_matching</b> – In order to help prevent the pair_matching target from running amok in cases where you have an excessive number of orphaned records we’ve added the <i>max_orphans</i> option to the target with a default of 10000. As you might surmise, this option controls the number of orphaned records that will be maintained in the pair_matching target.</p> <p><b>ring_buffer</b> – We’ve introduce the <i>max_events_limit</i> for the ring_buffer to provide a deterministic way to control the number of events in the target. The default value is 1000 and we’ve changed the default for <i>max_memory</i> to be unlimited, meaning that the ring_buffer will use as much memory as required to store 1000 events by default. You can set one or both of these. When both are set we’ll honor the one that is hit first.</p> <h1>Wrapping up</h1> <p <a href="">SQL Server Database Engine</a> forum.</p> <p>Happy Eventing!</p> <p>- Mike</p><img src="" width="1" height="1">extended_events SQL server batch activity<p class="MsoNormal"><span style="font-size:small;"><span style="font-family:Calibri;">Recently I was troubleshooting a performance issue on an internal tracking workload and needed to collect some very low level events over a period of 3-4 hours.<span style="mso-spacerun:yes;"> </span>During analysis of the data I found that a common pattern I was using was to find a batch with a duration that was longer than average and follow all the events it produced.<span style="mso-spacerun:yes;"> </span></span></span></p> <p class="MsoNormal"> <p><span style="font-family:Calibri;"> <p><span style="mso-spacerun:yes;"> <p class="MsoNormal"><span style="font-size:small;">This pattern got me thinking that I was discarding a substantial amount of event data that had been collected, and that it would be great to be able to reduce the collection overhead on the server if I could still get all activity from some batches.</span></p> <p class="MsoNormal"><span style="font-size:small;">In the past I’ve used a sampling technique based on the counter predicate to build a baseline of overall activity (see Mikes post </span><a href=""><span style="color:#0000ff;font-size:small;">here</span></a><span style="font-size:small;">).<span style="mso-spacerun:yes;"> </span>This isn’t exactly what I want though as there would certainly be events from a particular batch that wouldn’t pass the predicate.<span style="mso-spacerun:yes;"> </span>What I need is a way to identify streams of work and select say one in ten of them to watch, and sql server provides just such a mechanism: session_id.<span style="mso-spacerun:yes;"> </span>Session_id is a server assigned integer that is bound to a connection at login and lasts until logout.<span style="mso-spacerun:yes;"> </span>So by combining the session_id predicate source and the divides_by_uint64 predicate comparator we can limit collection, and still get all the events in batches for investigation.</span></p> </span></p> <span style="font-size:small;"> <p class="MsoNormal" style="line-height:normal;margin:0in 0in 0pt;mso-layout-grid-align:none;"><span style="font-family:Consolas;color:blue;font-size:9.5pt;">CREATE</span><span style="font-family:Consolas;font-size:9.5pt;"> <span style="color:blue;">EVENT</span> <span style="color:blue;">SESSION</span> <span style="color:teal;">session_10_percent</span> <span style="color:blue;">ON</span> <span style="color:blue;">SERVER<_starting<_external<_completed<;">TARGET</span> <span style="color:teal;">ring_buffer</span><o:p></o:p></span></p> <p class="MsoNormal" style="line-height:normal;margin:0in 0in 0pt;mso-layout-grid-align:none;"><span style="font-family:Consolas;color:blue;font-size:9.5pt;">WITH </span><span style="font-family:Consolas;color:gray;font-size:9.5pt;">(</span><span style="font-family:Consolas;color:teal;font-size:9.5pt;">MAX_DISPATCH_LATENCY</span><span style="font-family:Consolas;color:gray;font-size:9.5pt;">=</span><span style="font-family:Consolas;font-size:9.5pt;">30 <span style="color:teal;">SECONDS</span><span style="color:gray;">,</span><span style="color:teal;">TRACK_CAUSALITY</span><span style="color:gray;">=</span><span style="color:blue;">ON</span><span style="color:gray;">)</span><o:p></o:p></span></p> <p class="MsoNormal" style="line-height:normal;margin:0in 0in 0pt;mso-layout-grid-align:none;"><span style="font-family:Consolas;color:blue;font-size:9.5pt;">GO</span><span style="font-family:Consolas;font-size:9.5pt;"><o:p></o:p></span></p> <p class="MsoNormal"> </p> </span></span><o:p><span style="font-family:Consolas;font-size:9.5pt;"><o:p><span style="font-size:small;"><span style="font-family:Calibri;">There we go; event collection is reduced while still providing enough information to find the root of the problem.<span style="mso-spacerun:yes;"> </span><o:p></o:p></span></span></o:p></span></o:p></p> </p> <p> <p class="MsoNormal"><o:p><span style="font-family:Calibri;font-size:small;"></span></o:p></p> <p class="MsoNormal"><span style="font-size:small;"><span style="font-family:Calibri;">By the way the performance issue turned out to be an IO issue, and the session definition above was more than enough to show long waits on PAGEIOLATCH*.<span style="font-family:Consolas;font-size:9.5pt;"><o:p></o:p></span></span></span></p> <p class="MsoNormal"> </p> <p> </p> <p> </p> <p> </p> </p><img src="" width="1" height="1">extended_events the Extended Events Object Model<p.</p> <p>In the graphic below you can see that there are two “sides” of the object model:</p> <p><strong>Metadata</strong>: Describes the set of events, actions, targets, etc. that are available on the system. All access to the metadata objects has to go through the <strong>Package</strong> object.</p> <p><strong>Runtime</strong>: Describes the event sessions that are configured and various aspects of their runtime state. All access to the runtime objects has to go through the <strong>Session</strong> object.</p> <p><a href=""><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="" width="514" height="608" /></a> </p> <p>The top level object is named <strong>XEStore;</strong>.</p> <pre class="code"><span style="color:blue;">private static </span><span style="color:#2b91af;">XEStore </span>ConnectToXEStore() { Microsoft.SqlServer.Management.Sdk.Sfc.<span style="color:#2b91af;">SqlStoreConnection </span>server; <span style="color:#2b91af;">SqlConnectionStringBuilder </span>conBuild = <span style="color:blue;">new </span><span style="color:#2b91af;">SqlConnectionStringBuilder</span>(); conBuild.DataSource = <span style="color:#a31515;">"(local)"</span>; conBuild.InitialCatalog = <span style="color:#a31515;">"master"</span>; conBuild.IntegratedSecurity = <span style="color:blue;">true</span>; <span style="color:green;">// Create the actual SqlStoreConnection... </span>server = <span style="color:blue;">new </span>Microsoft.SqlServer.Management.Sdk.Sfc.<span style="color:#2b91af;">SqlStoreConnection<br /> </span>(<span style="color:blue;">new </span><span style="color:#2b91af;">SqlConnection</span>(conBuild.ConnectionString.ToString())); <span style="color:green;">// ...and then create the XEStore to return to the calling function. </span><span style="color:blue;">return new </span><span style="color:#2b91af;">XEStore</span>(server); }</pre> <p.</p> <p.</p> <p>- Mike</p> :1165aae7-7e2d-4660-afb4-b69bee1f2d6c" class="wlWriterEditableSmartContent"><p><div>Download sample code: <a href="" target="_blank">XeObjectModel.cs</a></div></p></div><img src="" width="1" height="1">extended_events from SQL Trace to Extended Events<p.</p> <p>In my <a href="" target="_blank">initial post</a>.</p> <h1></h1> <h1>Can you relate?</h1> <p…</p> <p.</p> <p.</p> <p.</p> <h1>Let me draw you a map.</h1> <h2></h2> <h2>Event Mapping</h2> <p>The table dbo.trace_xe_event_map exists in the master database with the following structure:</p> <table cellspacing="0" cellpadding="0"> <tr> <td> <p><b>Column_name</b></p> </td> <td> <p><b>Type</b></p> </td> </tr> <tr> <td> <p>trace_event_id</p> </td> <td> <p>smallint</p> </td> </tr> <tr> <td> <p>package_name</p> </td> <td> <p>nvarchar</p> </td> </tr> <tr> <td> <p>xe_event_name</p> </td> <td> <p>nvarchar</p> </td> </tr> </table> <p.</p> <blockquote> <p><font color="#c0c0c0">SELECT <br />    t.trace_event_id, <br />    t.name [event_class], <br />    e.package_name, <br />    e.xe_event_name <br />FROM sys.trace_events t INNER JOIN dbo.trace_xe_event_map e <br />    ON t.trace_event_id = e.trace_event_id</font></p> </blockquote> <p>There are a couple things you’ll notice as you peruse the output of this query:</p> <ul> <li>For the most part, the names of Events are fairly close to the original Event Class; eg. SP:CacheMiss == sp_cache_miss, and so on. </li> <li>We’ve mostly stuck to a one to one mapping between Event Classes and Events, but there are a few cases where we have combined when it made sense. For example, Data File Auto Grow, Log File Auto Grow, Data File Auto Shrink & Log File Auto Shrink are now all covered by a single event named database_file_size_change. This just seemed like a “smarter” implementation for this type of event, you can get all the same information from this single event (grow/shrink, Data/Log, Auto/Manual growth) without having multiple different events. You can use Predicates if you want to limit the output to just one of the original Event Class measures. </li> <li>There are some Event Classes that did not make the cut and were not migrated. These fall into two categories; there were a few Event Classes that had been deprecated, or that just did not make sense, so we didn’t migrate them. (You won’t find an Event related to mounting a tape – sorry.) The second class is bigger; with rare exception, we did not migrate any of the Event Classes that were related to Security Auditing using SQL Trace. We introduced the SQL Audit feature in SQL Server 2008 and that will be the compliance and auditing feature going forward. Doing this is a very deliberate decision to support separation of duties for DBAs. There are separate permissions required for SQL Audit and Extended Events tracing so you can assign these tasks to different people if you choose. (If you’re wondering, the permission for Extended Events is ALTER ANY EVENT SESSION, which is covered by CONTROL SERVER.) </li> </ul> <h2>Action Mapping</h2> <p>The table dbo.trace_xe_action_map exists in the master database with the following structure:</p> <table cellspacing="0" cellpadding="0"> <tr> <td> <p><strong>Column_name</strong></p> </td> <td> <p><strong>Type</strong></p> </td> </tr> <tr> <td> <p>trace_column_id</p> </td> <td> <p>smallint</p> </td> </tr> <tr> <td> <p>package_name</p> </td> <td> <p>nvarchar</p> </td> </tr> <tr> <td> <p>xe_action_name</p> </td> <td> <p>nvarchar</p> </td> </tr> </table> <p>You can find more details by joining this to sys.trace_columns on the trace_column_id field.</p> <blockquote> <p><font color="#c0c0c0">SELECT <br />    c.trace_column_id, <br />    c.name [column_name], <br />    a.package_name, <br />    a.xe_action_name <br />FROM sys.trace_columns c INNER JOIN    dbo.trace_xe_action_map a <br />    ON c.trace_column_id = a.trace_column_id</font></p> </blockquote> <p.</p> <h3></h3> <h2>Putting it all together</h2> <p <a href="" target="_blank">How To: View the Extended Events Equivalents to SQL Trace Event Classes</a>.</p> <blockquote> <p><font color="#c0c0c0">USE MASTER; <br />GO <br />SELECT DISTINCT <br />   tb.trace_event_id, <br />   te.name AS 'Event Class', <br />   em.package_name AS 'Package', <br />   em.xe_event_name AS 'XEvent Name', <br />   tb.trace_column_id, <br />   tc.name AS 'SQL Trace Column', <br />   am.xe_action_name as 'Extended Events action' <br />FROM (sys.trace_events te LEFT OUTER JOIN dbo.trace_xe_event_map em <br />   ON te.trace_event_id = em.trace_event_id) LEFT OUTER JOIN sys.trace_event_bindings tb <br />   ON em.trace_event_id = tb.trace_event_id LEFT OUTER JOIN sys.trace_columns tc <br />   ON tb.trace_column_id = tc.trace_column_id LEFT OUTER JOIN dbo.trace_xe_action_map am <br />   ON tc.trace_column_id = am.trace_column_id <br />ORDER BY te.name, tc.name</font></p> </blockquote> <p <a href="" target="_blank">How to: Convert an Existing SQL Trace Script to an Extended Events Session</a>.</p> <blockquote> <p><font color="#c0c0c0">USE MASTER; <br />GO <br />DECLARE @trace_id int <br />SET @trace_id = 1 <br />SELECT DISTINCT el.eventid, em.package_name, em.xe_event_name AS 'event' <br />   , el.columnid, ec.xe_action_name AS 'action' <br />FROM (sys.fn_trace_geteventinfo(@trace_id) AS el <br />   LEFT OUTER JOIN dbo.trace_xe_event_map AS em <br />      ON el.eventid = em.trace_event_id) <br />LEFT OUTER JOIN dbo.trace_xe_action_map AS ec <br />   ON el.columnid = ec.trace_column_id <br />WHERE em.xe_event_name IS NOT NULL AND ec.xe_action_name IS NOT NULL</font></p> </blockquote> <p>You’ll notice in the output that the list doesn’t include any of the security audit Event Classes, as I wrote earlier, those were not migrated.</p> <h1>But wait…there’s more!</h1> <p.</p> <p.</p> :3953a850-8ce5-40d5-bfb6-e219df34966d" class="wlWriterEditableSmartContent"><p>Sample code: <a href="" target="_blank">TraceToExtendedEventDDL</a></p></div> <h2></h2> <h2> </h2> <h2>Installing the procedure</h2> <p>Just in case you’re not familiar with installing CLR procedures…once you’ve compile the assembly you can load it using a script like this:</p> <blockquote> <p><font color="#c0c0c0">-- Context to master <br />USE master <br />GO </font></p> <p><font color="#c0c0c0">-- Create the assembly from a shared location. <br />CREATE ASSEMBLY TraceToXESessionConverter <br />FROM 'C:\Temp\TraceToXEventSessionConverter.dll' <br />WITH PERMISSION_SET = SAFE <br />GO </font></p> <p><font color="#c0c0c0">-- Create a stored procedure from the assembly. <br />CREATE PROCEDURE CreateEventSessionFromTrace <br />@trace_id int, <br />@session_name nvarchar(max) <br />AS <br />EXTERNAL NAME TraceToXESessionConverter.StoredProcedures.ConvertTraceToExtendedEvent <br />GO</font></p> </blockquote> <h1></h1> <p></p> <p>Enjoy!</p> <p>-Mike</p><img src="" width="1" height="1">extended_events memory – who’s this guy named Max and what’s he doing with my memory?<p>SQL Server MVP Jonathan Kehayias (<a href="" target="_blank">blog</a>).</p> <p>In a previous post (<a href="" target="_blank">Option Trading: Getting the most out of the event session options</a>):</p> <blockquote> <p>max memory / # of buffers = buffer size</p> </blockquote> <p>If it was that simple I wouldn’t be writing this post.</p> <h3>I’ll take “boundary” for 64K Alex</h3> <p:</p> <p>Note: This test was run on a 2 core machine using per_cpu partitioning which results in 5 buffers. (Seem my previous post referenced above for the math behind buffer count.)</p> <table style="width:468px;" cellspacing="0" cellpadding="0"> <tr> <td> <p><strong>input_memory_kb</strong></p> </td> <td> <p><strong>total_regular_buffers</strong></p> </td> <td> <p><strong>regular_buffer_size</strong></p> </td> <td> <p><strong>total_buffer_size</strong></p> </td> </tr> <tr> <td> <p>637</p> </td> <td> <p>5</p> </td> <td> <p>130867</p> </td> <td> <p>654335</p> </td> </tr> <tr> <td> <p>638</p> </td> <td> <p>5</p> </td> <td> <p>130867</p> </td> <td> <p>654335</p> </td> </tr> <tr> <td> <p><span style="color:#008000;">639</span></p> </td> <td> <p><span style="color:#008000;">5</span></p> </td> <td> <p><span style="color:#008000;">130867</span></p> </td> <td> <p><span style="color:#008000;">654335</span></p> </td> </tr> <tr> <td> <p><span style="color:#800080;">640</span></p> </td> <td> <p><span style="color:#800080;">5</span></p> </td> <td> <p><span style="color:#800080;">196403</span></p> </td> <td> <p><span style="color:#800080;">982015</span></p> </td> </tr> <tr> <td> <p>641</p> </td> <td> <p>5</p> </td> <td> <p>196403</p> </td> <td> <p>982015</p> </td> </tr> <tr> <td> <p>642</p> </td> <td> <p>5</p> </td> <td> <p>196403</p> </td> <td> <p>982015</p> </td> </tr> </table> <p>This is just a segment of the results that shows one of the “jumps” between the buffer boundary at 639 KB and 640 KB. You can verify the size boundary by doing the math on the regular_buffer_size field, which is returned in bytes:</p> <blockquote> <p>196403 – 130867 = 65536 bytes</p> <p>65536 / 1024 = 64 KB</p> </blockquote> <p.</p> <table style="width:597px;" cellspacing="0" cellpadding="0"> <tr> <td> <p><strong>start_memory_range_kb</strong></p> </td> <td> <p><strong>end_memory_range_kb</strong></p> </td> <td> <p><strong>total_regular_buffers</strong></p> </td> <td> <p><strong>regular_buffer_size</strong></p> </td> <td> <p><strong>total_buffer_size</strong></p> </td> </tr> <tr> <td> <p>1</p> </td> <td> <p>191</p> </td> <td> <p>NULL</p> </td> <td> <p>NULL</p> </td> <td> <p>NULL</p> </td> </tr> <tr> <td> <p>192</p> </td> <td> <p>383</p> </td> <td> <p>3</p> </td> <td> <p>130867</p> </td> <td> <p>392601</p> </td> </tr> <tr> <td> <p>384</p> </td> <td> <p>575</p> </td> <td> <p>3</p> </td> <td> <p>196403</p> </td> <td> <p>589209</p> </td> </tr> <tr> <td> <p><span style="color:#008000;">576</span></p> </td> <td> <p><span style="color:#008000;">767</span></p> </td> <td> <p><span style="color:#008000;">3</span></p> </td> <td> <p><span style="color:#008000;">261939</span></p> </td> <td> <p><span style="color:#008000;">785817</span></p> </td> </tr> <tr> <td> <p>768</p> </td> <td> <p>959</p> </td> <td> <p>3</p> </td> <td> <p>327475</p> </td> <td> <p>982425</p> </td> </tr> <tr> <td> <p>960</p> </td> <td> <p>1151</p> </td> <td> <p>3</p> </td> <td> <p>393011</p> </td> <td> <p>1179033</p> </td> </tr> <tr> <td> <p>1152</p> </td> <td> <p>1343</p> </td> <td> <p>3</p> </td> <td> <p>458547</p> </td> <td> <p>1375641</p> </td> </tr> <tr> <td> <p>1344</p> </td> <td> <p>1535</p> </td> <td> <p>3</p> </td> <td> <p>524083</p> </td> <td> <p>1572249</p> </td> </tr> <tr> <td> <p>1536</p> </td> <td> <p>1727</p> </td> <td> <p>3</p> </td> <td> <p>589619</p> </td> <td> <p>1768857</p> </td> </tr> <tr> <td> <p>1728</p> </td> <td> <p>1919</p> </td> <td> <p>3</p> </td> <td> <p>655155</p> </td> <td> <p>1965465</p> </td> </tr> <tr> <td> <p>1920</p> </td> <td> <p>2111</p> </td> <td> <p>3</p> </td> <td> <p>720691</p> </td> <td> <p>2162073</p> </td> </tr> <tr> <td> <p>2112</p> </td> <td> <p>2303</p> </td> <td> <p>3</p> </td> <td> <p>786227</p> </td> <td> <p>2358681</p> </td> </tr> <tr> <td> <p>2304</p> </td> <td> <p>2495</p> </td> <td> <p>3</p> </td> <td> <p>851763</p> </td> <td> <p>2555289</p> </td> </tr> <tr> <td> <p>2496</p> </td> <td> <p>2687</p> </td> <td> <p>3</p> </td> <td> <p>917299</p> </td> <td> <p>2751897</p> </td> </tr> <tr> <td> <p>2688</p> </td> <td> <p>2879</p> </td> <td> <p>3</p> </td> <td> <p>982835</p> </td> <td> <p>2948505</p> </td> </tr> <tr> <td> <p>2880</p> </td> <td> <p>3071</p> </td> <td> <p>3</p> </td> <td> <p>1048371</p> </td> <td> <p>3145113</p> </td> </tr> <tr> <td> <p>3072</p> </td> <td> <p>3263</p> </td> <td> <p>3</p> </td> <td> <p>1113907</p> </td> <td> <p>3341721</p> </td> </tr> <tr> <td> <p>3264</p> </td> <td> <p>3455</p> </td> <td> <p>3</p> </td> <td> <p>1179443</p> </td> <td> <p>3538329</p> </td> </tr> <tr> <td> <p>3456</p> </td> <td> <p>3647</p> </td> <td> <p>3</p> </td> <td> <p>1244979</p> </td> <td> <p>3734937</p> </td> </tr> <tr> <td> <p>3648</p> </td> <td> <p>3839</p> </td> <td> <p>3</p> </td> <td> <p>1310515</p> </td> <td> <p>3931545</p> </td> </tr> <tr> <td> <p>3840</p> </td> <td> <p>4031</p> </td> <td> <p>3</p> </td> <td> <p>1376051</p> </td> <td> <p>4128153</p> </td> </tr> <tr> <td> <p>4032</p> </td> <td> <p>4096</p> </td> <td> <p>3</p> </td> <td> <p>1441587</p> </td> <td> <p>4324761</p> </td> </tr> </table> <p>As you can see, there are 21 “steps” within this range and max_memory values below 192 KB fall below the 64K per buffer limit so they generate an error when you attempt to specify them.</p> <p><strong>Clarification: </strong.</p> <p.</p> <h3>Max approximates True as memory approaches 64K</h3> <p>The upshot of this is that the max_memory option does not imply a contract for the maximum memory that will be used for the session buffers (Those of you who read <a href="" target="_blank">Take it to the Max (and beyond)</a>.</p> <p.</p> <p.</p> <p><span style="color:#c0c0c0;">DECLARE @buf_size_output table (input_memory_kb bigint, total_regular_buffers bigint, regular_buffer_size bigint, total_buffer_size bigint) <br />DECLARE @buf_size int, @part_mode varchar(8) <br />SET @buf_size = 1 -- Set to the begining of your max_memory range (KB) <br />SET @part_mode = 'per_cpu' -- Set to the partition mode for the table you want to generate </span></p> <p><span style="color:#c0c0c0;">WHILE @buf_size <= 4096 -- Set to the end of your max_memory range (KB) <br />BEGIN <br /> BEGIN TRY </span></p> <p><span style="color:#c0c0c0;"> IF EXISTS (SELECT * from sys.server_event_sessions WHERE name = 'buffer_size_test') <br /> DROP EVENT SESSION buffer_size_test ON SERVER <br /> DECLARE @session nvarchar(max) <br /> SET @session = 'create event session buffer_size_test on server <br /> add event sql_statement_completed <br /> add target ring_buffer <br /> with (max_memory = ' + CAST(@buf_size as nvarchar(4)) + ' KB, memory_partition_mode = ' + @part_mode + ')' </span></p> <p><span style="color:#c0c0c0;"> EXEC sp_executesql @session </span></p> <p><span style="color:#c0c0c0;"> SET @session = 'alter event session buffer_size_test on server <br /> state = start' </span></p> <p><span style="color:#c0c0c0;"> EXEC sp_executesql @session </span></p> <p><span style="color:#c0c0c0;"> INSERT @buf_size_output (input_memory_kb, total_regular_buffers, regular_buffer_size, total_buffer_size) <br /> SELECT @buf_size, total_regular_buffers, regular_buffer_size, total_buffer_size FROM sys.dm_xe_sessions WHERE name = 'buffer_size_test' <br /> END TRY <br /> BEGIN CATCH <br /> INSERT @buf_size_output (input_memory_kb) <br /> SELECT @buf_size <br /> END CATCH <br /> SET @buf_size = @buf_size + 1 <br />END </span></p> <p><span style="color:#c0c0c0;">DROP EVENT SESSION buffer_size_test ON SERVER </span></p> <p><span style="color:#c0c0c0;">SELECT MIN(input_memory_kb) start_memory_range_kb, MAX(input_memory_kb) end_memory_range_kb, total_regular_buffers, regular_buffer_size, total_buffer_size from @buf_size_output group by total_regular_buffers, regular_buffer_size, total_buffer_size</span></p> <p>Thanks to Jonathan for an interesting question and a chance to explore some of the details of Extended Event internals.</p> <p>- Mike</p><img src="" width="1" height="1">extended_events sure to read Jonathan Kehayias’ 31 day series on extended events<p>If you have not seen it already, Jonathan Kehayias is writing a 31 day series on extended events in celebration of the public release of Denali CTP1. You can start at the <a href="" target="_blank">master post</a> to find links to each days efforts. As of this writing he is on day 3 and this is well worth the read.</p> <p>Enjoy!</p> <p>-Mike</p><img src="" width="1" height="1">extended_events’s new for Extended Events in SQL Server code-named “Denali” CTP1<p.</p> <p>(For those of you who haven’t seen yet, we announced SQL Server code-named “Denali” as the 2010 PASS Summit. You can get information about it, and download it, at <a title="" href=""></a>.)</p> .</p> <p><strong>From SQL Trace to Tracing with Extended Events</strong></p> <p>We’ve ported the complete set of <u>diagnostic</u>.</p> <p>.]</p> <p:</p> <p><a href="" target="_blank">How To: View the Extended Events Equivalents to SQL Trace Event Classes</a> <br /><a href="" target="_blank">How to: Convert an Existing SQL Trace Script to an Extended Events Session</a></p> <p>These should get you started examining how to create equivalent event sessions for SQL Trace sessions you’re already using. In a future post I’ll discuss this in more detail and describe how event fields and action are related to SQL Trace columns.</p> <p><a href=""><img style="border-bottom:0px;border-left:0px;margin:0px 0px 15px 15px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" align="right" src="" width="228" height="244" /></a> <strong>Exposing ourselves to Object Explorer</strong></p> <p!</p> <p:</p> <ul> <li>Sessions | Import Session – Allows you to import an XML based definition of an event session.</li> <li><Event session name> |</li> <ul> <li>Start / Stop Session – Does what it sounds like.</li> <li>Import Session – Allows you to import an XML based definition of an event session.</li> <li>Export Session – Allows you to export the selected session to an XML based defintion.</li> <li>Script Session – The standard T-SQL script options that produce Extended Events DDL.</li> </ul> </ul> <p>The other menu options are self-explanatory or standard SSMS menu commands.</p> <p><strong>Beyond the DDL</strong></p> <p <a href="" target="_blank">Microsoft.sqlserver.management.xevent</a> namespace on MSDN. I’ll be posting some code samples to this blog in the future.</p> <p>We’ve also exposed this API through PowerShell, so if you’re one of the new elite scripting, we’ve got you covered. You can find some details of the PS provider in the BOL topic <a href="" target="_blank">Using the PowerShell Provider for Extended Events</a>.</p> <p><a href=""><img style="border-bottom:0px;border-left:0px;display:block;float:none;margin-left:auto;border-top:0px;margin-right:auto;border-right:0px;" title="image" border="0" alt="image" src="" width="450" height="237" /></a> </p> <p>So that’s the run down of Extended Events in CTP1. I’ll follow-up with some posts that go into specifics for these areas and there is more to come in the next CTP so stay tuned.</p> <p>- Mike</p><img src="" width="1" height="1">extended_events your Data Collector to Extended Events<P>One of the things I haven’t gotten around to blogging about yet is how to utilize Data Collector to capture data from event sessions. Raoul Illyes (<A href="" target=_blank>blog</A>) has relieved me of that duty by posting an article demonstrating how to use Data Collector to pull data out of the <A href="" target=_blank>system_health</A> event session.</P> <P>You can find Raoul’s post <A href="" target=_blank>here</A>. Thanks Raoul!</P><img src="" width="1" height="1">extended_events it to the MAX (and beyond)<p>I got an interesting question from our Support team today and thought I’d blog the answer since it identified an area that can easily cause some confusion. In the BOL documentation for <a href="" target="_blank">CREATE EVENT SESSION</a> the description for the MAX_MEMORY session option states the following:</p> <blockquote> <p>“Specifies the maximum amount of memory to allocate to the session for <u>event buffering</u>. The default is 4 MB. <em>size</em> is a whole number and can be a kilobyte (kb) or a megabyte (MB) value.” [Underline is mine.]</p> </blockquote> <p>An observant Extended Events user noticed that their event session appeared to be using more than the specified value of for MAX_MEMORY and and that the amount over MAX_MEMORY could be quite large. So what’s up with that?</p> <p><strong>Buffer memory versus session memory</strong></p> <p>You’ve probably already guessed that I underscored the words “event buffering” in the BOL description because it was important. To better understand the importance, you need a crash course in how the asynchronous targets in Extended Events work. This is the real short version…</p> <blockquote> <p <a href="" target="_blank">post</a>.</p> </blockquote> <p>So the MAX_MEMORY option of the session is really only specifying the amount of memory to allocate for the event buffer, <u>not<.</p> <p><strong>So what’s the catch?</strong></p> <p>The most interesting in-memory target in terms of giving you “unexpected” behavior (but I’m telling you about it now, so it won’t be unexpected anymore) is the pairing target. The pairing target handles memory like this:</p> <ol> <li>The event buffer is processed to the pairing target. </li> <li>The target finds all the “pairs” and throws them out. </li> <li>The target allocates memory for the “orphans” and stores them. </li> <li>The event buffer is free to collect more event data. </li> <li>Lather, Rinse, Repeat. </li> <li>The next time around the target will attempt to match any orphans that it has stored with the new data from the event buffer (and throw out the pairs) and then allocate memory to store the new orphans along with any remaining orphans. </li> </ol> .</p> <table cellspacing="0" cellpadding="2"> <tr> <td><strong>What not to do <br /> <br /></strong>The canonical example of events that people would like to pair but that “don’t pair well” is the lock_acquired / lock_released events. These events are just begging to be paired, but it’s common for the SQL engine to release multiple, related locks as a single event. This results in a situation where multiple lock_acquired events are fired, but only a single lock_released event is fired and you end up with an increasing number of lock_acquired events being tracked in the pairing target that don’t represent legitimate lock orphans. <br /> <br />The typical reason for wanting to do this type of pairing is to identify blocking but it is better to use the dm_tran_locks DMV to track blocking in this case.</td> </tr> </table> <p>Hopefully this clarifies the MAX_MEMORY option and what it is actually controlling.</p> <p>-Mike</p><img src="" width="1" height="1">extended_events’s Subject: Predicates<P>Don’t worry, I haven’t suddenly switched the topic of this blog to English grammar, but if you want to learn more about Predicates as they apply to sentence constriction you can start with <A href="" target=_blank>this article on WikipediA</A>. Rather, today’s topic is about predicates in Extended Events. You can find a brief description of predicates in <A href="" target=_blank>Using SQL Server 2008 Extended Events (by Jonathan Kehayias)</A> so I’ll try to <EM>extend</EM> your knowledge a bit beyond what that says.</P> <P><STRONG>Pre versus Post processing</STRONG></P> <P>There is usually more than one way to accomplish almost everything so it’s worth taking a moment to consider two different ways to process and event log. <SPAN style="TEXT-DECORATION:underline;">Post-processing</SPAN>. <SPAN style="TEXT-DECORATION:underline;">Pre-processing</SPAN> is when the filtering of events happens as part of the event generation code and therefore can “short-circuit” the event from firing. Extended Events support this type of pre-processing and that is what a Predicate if for.</P> <P>Pre-processing has some cost associated with evaluating the predicate which is why some diagnostic systems choose not to offer this functionality, ETW is an example of a diagnostic system that does not support pre-processing of events.</P> <TABLE style="WIDTH:600px;" cellSpacing=0 cellPadding=2> <TR> <TD><STRONG>Aside:</STRONG> Some ETW gurus (I don’t claim to be one) may argue that ETW does support pre-processing because you have the ability to define which events are collected based on Channel, Keyword and Level. For our purposes I’m defining pre-processing as requiring a finer level of control than that; you can decide if this is a semantic point or not.</TD></TR></TABLE> <P:</P> <UL> <LI>Only collect events that occur within a specific database or session_id. </LI> <LI>Only collect a sampling of events from your system. (I’ve described sampling in <A href="" target=_blank>this</A> post.) </LI></UL> <P><STRONG>So, how much do I save?</STRONG></P> <P.</P> <P> <IMG style="BORDER-RIGHT-WIDTH:0px;DISPLAY:inline;BORDER-TOP-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-LEFT-WIDTH:0px;" title="1. Check if Enabled, 2. Collect EventData, 3. Analyze Predicate, 4. Collect Action Data, 5. Publish to Targets" border=0extended_events
http://sqlblog.com/blogs/extended_events/atom.aspx
CC-MAIN-2014-35
refinedweb
10,020
52.09
On Thu, 17 Nov 2005 02:19:30 +0100, in gmane.linux.vdr you wrote: > Thiemo Gehrke wrote: >> But on the other hand I do not see the need of having different namespaces >> (domains) for every plugin. > > To avoid collisions. A string may be differently translated in different > contexts. Within one plugin, this can be avoided. But with different > plugins, its surely fun to watch two plugin writers arguing about the > 'right' translation. ;) > You could still get collisions within a single plugin, unless you use unique string IDs (assuming this is how gettext works?). If the plugin i18n rules specify that the string ID has to contain the name of the plugin (e.g. FEMON_MENU_SETUP_BGROUND_TRANSP = "Background transparency") then inter-plugin string ID collisions can be avoided completely. Sharing strings even within a plugin is /a bad idea/ - you never know where the string might be reused next time, and the translator may need to inflect, conjugate or decline the term differently in each context. If you're worried translators having to translate the same term twice, how about persuading translators to use translation memory (such as OmegaT, see - doesn't handle PO natively, but can AIUI a filter is available). This gives the translator the freedom to decide whether to translate the string in the same way twice or whether to change his translation on the basis of the context. When it comes to preloading language support and that delaying VDR's start-up times, how about allowing the user to select which languages he wants to compile in? A compile flag UILANGS=/path/to/list_of_ui_langs would mean that each user could, if they wanted to, define their own list of languages to compile in. For example, I only speak English, German and French, so my list_of_ui_langs would contain: en de fr Given most reseller versions are for specific markets (with tailored channels.conf, etc.) this would allow resellers to tailor their packages too. Iwan -- Translutions Ltd. French & German > English Translation Solutions
https://www.linuxtv.org/pipermail/vdr/2005-November/006189.html
CC-MAIN-2016-36
refinedweb
332
61.97
Join devRant Search - "no time" - - - - - You have done a great job!! Thanks for delivering the project on time. It is exactly what I asked for. I will ask for no changes and I will pay you right away. Said no client ever.3 - work remotely. This means that sometimes I work with no pants on. ...ok I work with no pants on all the time.7 - Breaking developer stereotypes one step at a time: ✅ No beard and has job ✅ Girlfriend (as of Thursday evening, 2017/06/29) Now to work on getting some more money and free time 😀11 - I AM FREE!!!! I no longer work for that unappreciative, condescending, dolt driven company! Time for bigger and better things!13 - That time when you search for a bug and find same question at StackOverflow, GitHub and Quora... All from the same person, and all with no answer.. 😓🐜7 - - Every time I hear "if it's stupid but it works..." NO Fucking No!!! If you know that it's stupid you should fucking correct it!!!21 - Lecturer: Unfortunately, you will have to manually write these 16 combinations in the program. Me: *writes a script to generate the combinations*12 - I love how "minimal" devRant is. No username, no time... just the number of likes and number of comments .. *it's a feature not a bug* ✌(◕‿-)✌3 - - - I made this a couple of years ago for a joke but no one really got it. It's a printable smartwatch that always tells the right time, no need for charging...20 - - How malloc works? It's easy. Just follow this simple flowchart and you will understand in no time.9 - No, I don't want desktop notifications Yes, I understand you use cookies No, I don't want free books We see you use AdBlock ... [closing the tab] And this happens every time I desperately search for smth7 - I had a scrolling addiction on Facebook, then I installed devRant... I can say that I no longer have a scrolling addiction on Facebook... *No time for Facebook, must read all rants!*4 - - - Hey it's lunch time! - Yeah let me push these changes... - No! You'll do it later. - But, it will take 2 minutes! - NO! WE'RE HAVING LUNCH NOW. Windows crashes ._.3 - All Terms of Services agreement changes, etc. need to be in GitHub. I don't want to reread the whole thing, where's the diff?4 - Everytime I have to execute several commands to do something, I tell myself: I will write a script for that. But now I have no time. I will do it the next time. I will never write these scripts.4 - - !rant My ISP just sent me an email: I have double the bandwidth for the next 6 month while still paying the same as before. No fishy things, no special conditions... What a time to be alive.14 - - - - Requirements gathering is fun said no developer!! P.S. Friday implies more time implies more devranting!!1 - - - My Friends say i´m no dev... Why???? :( I love do Sports, I have free time, I´m eating healthy, I don't like coffee....10 - No Rant, just wanted to say devRant is something I have been looking for in a long time, Love it !3 -...4 - That moment you realise why you enjoy the dev life again. It's been a long time since I've had a solid day of coding, just coding..., no meetings, no wild requests, no crazy issues, no data fixing because someone can't type a number correctly, just me, myself and that keyboard going on a field trip of quality coding time again. Ah, it's a good day to end the week on - - - Did someone tested it on our test machines? - No there was no time to do this. *preparing for nuclear fallout from customer in 3..2..1..*3 - A client sent me a message this morning asking for a change to the software I'm developing. It's Sunday, right?6 - - Overhearing first year software dev students argue that object oriented programming is pointless and makes no sense... You're gonna have a bad time.. - Mobile plan with fairly decent call time and 2gigs of internet: $20 Mobile plan with no calls and unlimited internet: $5 Yep its time to put telegram on my family's phones17 - Dear Developers at Microsoft, Why the FUCK does windows try to update EVERY TIME I boot my VM even though it fails EVERY FUCKING TIME? Can't it fucking learn that it's fucking broken and doesn't work? No? OK...7 - When your team has no time to address technical debt/infrastructure improvements but we need to make that square checkbox round immediately.1 - - Everyone given the iPhone a hard time over no headphone jack, while Samsungs are exploding. Decision time: - living with an adapter - living with chargrilled testicles Choose15 - - Doctor: "How do you feel?" Me: "Stressed." Doctor: "And something other than that?" Me: "More stress." Doctor: "Depression maybe?" Me: "No, I don't have time for that!" Doctor: "You will have time for iron infusion next week though." FML.6 - - No Wi-Fi = No Food.. Great motivation to pay your internet bill on time... This 'smart' shit is going way too far lol..15 - - Another package from NY? More stickers? - No. It's a ball this time! People are starting to look weird at me over here...1 - - no matter how big shot programmer you are, you 90% time you will only code if(condition) { // do something } else { // do something else }8 - [DevArt No. 7] Title: "Saturday Night Fever" 💤 Come on! 💤 🍹 It's the weekend! 🍹 🍻 It's time to party! 🍻23 - tfw you compile another time cause even though the code doesn't run, you're sure you made no mistakes3 - "No time for implementing a new alert with buttons, so the radio buttons' one should do for now..."3 - - - Pings google, no losses in 1 hour! And just as I run that JavaScript code on Node.js, the internet stops! Every fricking time! -_-' >_<3 - Opens pycharm import time; print(time. *hits Ctrl+space* >Auto complete not working >Searches SO no answer >Realized file saved as time.py > Proceeds to contemplate career choice3 - Boss: I have a demo NOW, but there os an error message on that page. Me: okay, give me sometime to elaborate the problem.. Boss: No No please, this is urgent Me: Okay.. My code:5 - - That fucking ironic time when all you need to make money is Internet connection but you have no money at all to pay for it.6 - - - Real-time physics calculation of +250000 blocks on AMD Athlon. No worries boys, I had fire extinguisher.4 - Who in their right mind though it would be a good idea to move the web development team to a new office without checking that the internet is connected. What a waste of three working days. And of course the project needs to be delivered by Sunday...3 - - - 3 weeks off work - complete. 1st day back - in progress Shit storm flurry awaiting my arrival - bring it on!1 - - - - - As lead developer I was not allowed to implement automated testing as "we don't have time for that" - you have no idea how much time it would save!6 - - your week has been so busy and exhausting you remember at 1PM Friday you have a deadline for Monday morning and force yourself to do a weeks worth of work in 4 hours and deploy it on a Friday without QA testing! To future me - I apologise for Monday’s headaches. - - was working on a passion project, looking at the clock periodically. was surprised a couple of times that it's still before 12 but kept on working. it wasn't. its 3 am. windows' clock was stuck. i have to get up in 4 hours. fml - We spent 80% of development time implementing a feature requested by a client. Client for no reason says "the feature is no longer needed take it out ". Am so fucking furious now. Such a waist of time6 - Programming with a best friend. Knocked out a project in no time. Just a friendly race between friends. - - For the first time I have enough seniority to say no to a request from another team...and it felt so good.3 - - Open Source 101 Teacher : Ubuntu only supports GUI on terminal no 7, that's because more GUI's would slow the system. Me : *startx (enter)* Ladies...one at a time!!3 - I look after servers, softwares,vendors and write code too. I am also learning datascience in spare time. Suddenly I found that I am giving no time to family and friends.6 - - Haven’t eaten any proper breakfast nor lunch, My body has subsisted only on snacks (carbs, sugar, msg) throughout the day, What are the “flat-food”(s) you guys usually ate in substitute of proper meal?24 - - - - - Literally no work to do. Learning Ruby to fill the time. Forgot how fun it is to learn new things!4 - - Director: hey, we need this new functionality that I saw somewhere else... Easy right? Just copy & paste!!! Copy & paste... It works every time... Right? No!2 - - - HELL WEEK is coming!! they are going to make us code IN PAPER again.... no compilers, no way to check for errors, time to die again4 - Does anyone know of any good audio book sites besides audible? Free ones are good too, of course, but I don't mind paying for them. Likewise for a good player, since books aren't music.14 - - - Procrastinate 1 work day - Try to crunch 2 work days into one - Feel frustrated because there is not enough time - Repeat2 - - Why ? Why is there no time left for the cool stuff? Spending too much time at work - beeing tired- bought a new rasp-pi - it's already 1 year old - untouched @ home ... just why? had holidays ... spent 4 days of 7 to recover - just slept.2 - - 60 hour work week deserves down time....no code, just immersion...feel like I'm being watched though7 - - No one tests in production like I do.. Just gave the wife a Brazilian wax for the first time. I guess I could have tried on the dog first but ... No.4 - - It's really sad how companies in UAE misusses the internship term, and make the poor interns do full time job with minimum or no salary.4 - Wasting my time when I was 18-22 not building something great while I had little to no responsibility1 - - When you spend 10x time coding just because you can't, just can't resist writing good code, even when you no it's gng to make no difference whatsoever🙁 Why brain, oh why?4 - - So a typo brought down large swaths of S3. Programming is a merciless profession. No wonder I am stressed all the time.1 - - Had Weekend free for my own...No Kid No wife...just plenty time...what did?...I brew beer 🍺😎👌...of course I didnt used any ready-to-go mixtures...all done from the basics. Feels so good11 - - BAT0 (Charging - 100% remaining time 00:00:00), health 100.0%: 8.318V 0.592A 4.92426W Fuck yeah!! No more "Charging - 186%", no more "health 54%". I feel alive again!!!!2 - - A tutorial app that convinces everyone to adopt UTC (so I no longer have to account for time zones and/or DST in code.)3 - today I spent an hour and a half (30 mins past my paid hours) explaining go my boss that I'm not just being rebellious; that the time I'm taking to do the job right is appropriate and the only way to end up with a piece of software that they'll be able to request features for without adding on to the absolute shit pile frankenkrakken that is their mutated 13 year old OSCOMMERCE dumpsterfire. I convinced him. - - When I post a collab and someone asks me how the project is going and how much the progress.. Inside me: oh boy, I just post ideas here.. not time for implementation - - - - Coolest project? No project is cool anymore after clients changed their mind for the 9000th time which happens like... always.2 - - - - Our QA team love writing really awkward bug tickets No reproductions steps and every time i see one appear all i can think of is this1 - Sometime we forget who we really are. We aren't dumb guys with no future and it's time to remember this to yourself. We're losing time in our lives, let's just use it as we think is better to.4 - when you get to Friday and realized you've had almost no time to code this entire week. There is always next week.1 - - - why the fucking fuck no one, no one explains their problem It's just the same every fucking time, 'It is not working' How the fuck'd I know why it's not working.5 - Firewall is down. That means no access to developer environments. That means more time for DevRant.1 - For half a year, I couldn't find a job. Now I can't find any to hire. WTF, that doesn't make sense.3 - - - I may have convinced my boss to start using Gitea to manage our git repos! 😆 Right now we have a NAS with bare repos, so we have no access rights, no overviews, no forks, no issues, no pull requests, nothing! 🤐 Now it's time to pray to the gods for his decision. 🤞 - Phone always on silent. And disable notifications on most apps. Have been using a Pebble Time for a while and can't even remember the last time my phone has been ringing or beeping. Sadly Pebble is no more 😧3 - When, for the 100th time, you see the git commit comment: "All work and no play makes Jack a dull boy" - - Quiet working environment (aside from hearing a joke from time to time) Fast computer, lots of screens, keyboard and mouse of my choice Good product owner that doesn't accept bullshit request into the sprint No legacy crap5 - The sinking feeling you get when you have looked forward to working on your project for a week and your gf tells you that the inlaws will wisit on your only free days in 2 weeks.. Please aliens take me awayyyy. - I just wrote my final and last exam. First graduate in my family. No more semester. Am so excited. At least I can concentrate on coding now full time time2 - Is there an easy way to make your website not look like complete garbage, if you have no idea and no time for some web front-end?11 - - - - - - - - Some minutes ago our firewall in office overheated, no internet, no network, no real way to work some time for coffee and nerd talk - not bad at all2 - Interviewer: Here's a marker, diagram how you would implement a time management system to track user work. Me: [draws out complex system to track user work via heartbeat] Interviewer: God, no.. something more simple like a time clock. [sigh] - I just fucked myself big time with iptable rules and blocked all incoming connections to my WiFi-AP. No SSH, can't go back, time for a factory-reset... - I visit these tech meetups and most of the time I have no clue what they are talking about. It's good that they give free food. - I just setup a new VPS I made all configuration required I reboot the server I forgot which port I set for ssh 😭 Luckily I have console to access from 😅14 - The day I understand how CSS works will be a lifetime achievement...!!! Having hard time when you have to design and develop a website at a time... I just hate designing... (No offense.. personal opinion)7 - I want to learn so much programming languages, go with so many personal projects. But I have no time ! Sad Me. who is else have this situation3 - Oh boi, that weird feeling when the code is alright, no errors, the first time you save or compile it14 - Finally code start working fine no bugs, no warning just working. Moments later! start to compile again but this time either with warning or with bugs. Anyone? - 9 pm - let me just quickly setup up a media center/NAS in my RPI, then it's off to bed! 3 am - shit, i have to get up in 3 hours >< - Spent an hour and a half debugging why binders are not working on my Asp.Net project to end up finding out that my controller was missing: [Route("[controller]")] attribute at the beginning Life is wonderful :)2 - - "You can Download Sublime Merge, and try it for yourself - there's no time limit, no accounts, no metrics, and no tracking. The evaluation version is fully functional, but is restricted to the ***light theme only.***" In your butt light theme haters ;)4 - - So I was doing some hackerrank challenges when I completed a challenge that kept me thinking for a lot. In the moment I finished, no electricity in my home for a brief time. No internet. No submission. This was destiny.1 - - First time today trying a sensory deprivation chamber. All I could think was "error no input signal"5 - - Worst practice -- our application isn't built to properly handle threads and I just added a Sleep statement to wait for the backend process to replicate its data. I feel so guilty and dirty. - I'm working on 3 projects, alone, and no chance to finish any of them in time. Woosh goes the deadlines....2 - - Those working as freelancer, how many times has a potential client told you that if you do this job for cheap he would refer you in his business circle and you would for sure get atleast X projects in next quarter ?4 - After 8 hours of carefully installing Gentoo in my laptop I ended up with a... Completely unusable OS. Guess I'll try again tomorrow, apparently I didn't set up the kernel with the appropriate drivers.2 - - - - - Webpacker works on branch master. Webpacker doesn't work on the "back-end" branch. I didn't touch anything javascript related between the branch's creation and now. Why. Why why why why why.4 - How does the created time work in Devrant's API? I get 'created_time': 1563478239 It makes literally no sense14 - "I'm nearly done. Just one last bug to fix." Time passes, coding happens ... "No, not quite done. Just three more bugs to fix."1 - I'm currently working nights, away from home, and have no time for programming. God I miss programming... So much.2 - I've done it! No more secondary projects this time. Whole Christmas spent with family and casual stuff. Have you also succeed?5 - I have some ex colleagues and friends now devs in Facebook, Amazon, or other major companies. No life, monothematic arguments, no hobbies, no time. I surely prefer my simpler life.1 - What's more better than diving in for a REST after an entire day of SOAPing? I'm happy I'm getting no REACTions after all that time being NODE.1 - Was looking forward to a nice day of programming, finally had some free time to spend No power today, fml :( My laptop is now out of power - - - finally no more lecture, no more class, holiday is here. time for side project :D no, most of the time i hate vacation. - - After office time. That time really works. Learn from online courses. And apply it. No one will be there. Silence!1 - - Log 1: Day 10 of crunch time. I have entered a sleepless zen state. Lord willing, I will be able to get 7 hours of sleep Saturday night. The building is terrifying at night, as there are a lot of noises. Security guards are nice, but curious to see me all alone. Must not show weakness in case they think numbers will give them an advantage over me. Supplies are low. Only one type of energy drink left in the machine, and coffee gone for the night. My phone is out of fast data so Pandora is spotty at best. I have battery to get me through the night at least. Tomorrow and Saturday decide the fate of the project. My team lead has not slept in at least 2 days. I feel guilty napping when I do, but she is driven like Ahab so I will let her obsession carry her. If I am alive tomorrow I will report in.1 - I would rant about my life right now i i know people wouldnt understand the problem that Im facing right know. "Nah. Post it we wanna help, it cant be that bad" - nope i just say nope1 - - - - - - - - Ain't no sunshine when it stops.. Ain't no sunshine when it bug's, And it always crashes too hard, Any time my coffee's away..1 - I want to switch to arch and zsh, but I don't have time 😟. I don't even have time to code. Damn uni😡4 - When you propose a project and your friend programms the funny parts that you seek forward to do, while you had no time to spare. 😭😭😭 - Fixing a bug under Drupal 8 has a bright and an other bad side The bad sight is that you slowly get insane trying to fix a bug. The bright side is that you get to see the lead the lead dev, who assigned you this bug, to get insane too 😁 - the current power outage is an additional reminder why i will always decide for a notebook. no internet though, so that is the ending for my spare programming time :( - -.4 - Did you ever think time estimations are hard? If so, did you ever try adding your actual taken time months after working on a ticket?8 - - The first time I tried "sudo apt install caffeine" and realized there was a repo I got excited. And then promptly disappointed that no coffee mug showed up...1 - Idk about you but when I get half a dozen opvotes from a single account and it seems to be a female, I fall in love a little bit. Now, if I could just spare time for an actual relationship...7 - - Nothing makes me want to work on my own projects more than spending 40 hours a week trying to solve problems in the boring behemoth of legacy code that is my company's app. Doing everything myself seems downright peaceful in comparison. - Working on a project that's due "yesterday" but girlfriend wants to go out. Two bullets. Client. Her. Which one do you choose?6 - I keep putting off coding because "there is never enough time" and "there are too many distractions." Next thing you notice I don't get any coding done for the longest time... 😥 - Bruce Lee, "If you love life, don't waste your time, life is made of time" "Si amas la vida, no pierdas el tiempo, de tiempo está hecha la vida" - There should be a garbage collector for IRC channels. If there's no activity for a given period of time, then just cancel it from above...2 - - While debugging a service on a linux server... Log-level info: no really useful information and no hint about the bug Log-level debug: OMFG TAKE THAT 2GB LOG FILE Why all the time 😧 - - When you wake up late, then have an event you're going to this evening. Means I get less than 3 hrs to code. - Time to bare your souls!! Name your 5 most recently used apps, no cheating :) devRant, Facebook, Dungeon Boss, Play Store, BabyCenter10 - Friend hands me a computer with a fried motherboard and asks if I can fix it in my free time. Mind you, this computer is no longer used.. 😑2 - Today I was forced to code in 4 hours what I had planned for 2 days. I have a feeling that any change to that code will take a day to implement. - Presumably the name you give it when the deadline is hours away, you're tight as a knot from stress and feel like you're seven leagues under the bastard sea from pressure is this "Crunch" period I've heard so much about. Eesh, this is rough. - Shit... watched too many videos about AI. Now I'm convinced human coding will be obsolete in the near future... Hello code block, long time no see...1 - - After a long time of not using devRant, I’m back. Is Linuxxx still huge? Is that wonky raven thing still going on? Does everybody have a Tiger now?7 - .3 - - No Problem Android Studio, just get completly fucked up. It's not like if i would need to finish this course before thursday, no i definitly have time for this shit.2 - - - Stop fucking argue with awwwards you shithead. I have no time argue back to your tiny designer brain.10 - When you have no time to learn by code snippet, you'd have to copy and paste it rather than writing it line by line. - Since I have a part time dev job I have no time for gaming . My gaming friends must think that I am dead 😢 - Sometimes non-dev people give the look like they could do the same shit in half the time and you purposefully made the UI ugly (UI wasn't provided and I m no designer).. can anybody suggest some polite ways to tell them to FUCK OFF!. - When you can't use anything else other than php with no libraries and no frameworks/external packages and you have to reinvent the wheel every. single. time.1 - When you see a start up project, and you have all the skills required and you want to join, but you know you don't have enough time ;-; Rip HSC studing take my dev time > - Finally found some time to write readme for my project "selector". You can check it out. And of course contribute if you want to.... -. - - Sooooo... I'm not sure I passed my first exam. I would've been able to answer all the questions correctly, if I'd had enough time.1 - - - - - Is part-time remote dev work a thing? I wanna go that route but no clue where to get started. Freelancing? Consulting? Or do companies actually hire part time remote devs?7 - - Just enrolled myself in Andrew Ng's Machine Learning course at Coursera for the summer, is it a good place to start? Any recommendations? - Why does my Eureka client always try to connect on localhost ? If it's running as a docker container, it won't find the Eureka server on localhost.2 - - - - - - All mandatory tasks complete for the week, no meetings, no distractions, time to go back to the default of documentation........ahhh email just in from nodeweekly! - Oh, hi "metaprogramming" (PHP in runtime), long time no see. Which reminds me why I ended up hating Rails & Ruby so much back then. - - Me: Time to work on wife's website. Server: Unable to Validate DMI. Me: Reboot. Server: HAHA no CPU information and still no DMI Me: Remove drives part from SSD. Server: HI THERE. Me: Facepalm's2 - Expectations that you will program all day, every day. No, I want to play LoL and WoW in my free time ^^ ... at least few hours per week.1 - Confession : I swear -> my sweet Arch Linux was freeze in my laptop in my super lightweight tty env + tmux after about to quit demonstrate my friend about vim in vimtutor on yesterday. (1st freeze after 1 half a year of using it. Maybe something wrong about my rot potato, but hey -> its a things ;) (no data lost after hard reboot after all.) (First time it failed without me thinker it ;) -> Its not my fault Jim~)12 - 3 straight houra of Android programing, but no moving forward. I don't know why android programming take much time.3 - You guys had to ever deal with so called bench time 😵😵 so annoying after certain time period. Employers keeps complaining about bench ageing yet have no projects to offer. And best excuse for rejecting profiles within company for mismatch skills.5 - Before I was thinking to be wasting my time with tasks no so useful for my life. Then I read about Malbolge programming language - - - - I outsourced front end to india, no time for tedious shit, will still stay awake for my APIs. Shhhh. - I know that we all hate bugs, but let's be truthful, if there was no bugs, there was no jobs 😂 You will just have to program one time and then the boss will kick your ass out of the company3 - It's time to see what I can do To test the limits and break through No right, no wrong, no rules for me, I'm free! Test-Driven Frozen - i dont got no goddamn time and no goddamn energy for this bullfcking shit to deal with man aht the fck man.5 - Me: Oh yes this is easy, i will fix it in 5 minutes.. *Deploys the solution to debug it* *waits 20 minutes....* (the message says "installation is in progress") Just fuck you SharePoint Online.1 - - - - some time ago on production I fund string join implementation using substring. No idea why it was implemented at all since this is in language standard library Top Tags
https://devrant.com/search?term=no+time
CC-MAIN-2020-29
refinedweb
4,958
83.05
Just over three months ago, we at Mapiq moved to a bigger office. It was quite a step up from our last humble abode, having about five times the floorspace that we had before. We had some crazy ideas about how we wanted to use the space, but having a fancy, dedicated meetingroom was one of our top priorities. Only problem, meeting rooms become really dull, really fast. A big table, some chairs and a screen are part of the standard bill of materials, but we wanted something funky and interactive to spice up the room. The company i work at builds software that runs smart buildings, and one of the things we do really well is roombooking. Usually we build integrations between existing hardware and our platform, but we wanted to have a go at doing the whole process of building and integrating by ourselves. Ofcourse, we could have just thrown in some existing WiFi connected LED bulbs, like the Philips Hue bulbs our software already works with, but we decided to go a step beyond to make something special. This instructable will take you through the process step by step from ideation to production. If youre interested in what Mapiq does or can do for your office, check us out. To replicate our lights you will need: - 2 x 1m of OPY1 ghost tube - 1 x 3D printer OR 3Dhubs account - 1 x Nice big spool of ABS or PLA - 3 x 4m of 3wire .75mm2 cable (we used clear cable with silver wire) - 1 x FIBOX enclosure 200x120x75mm - 3 x Adhesive posts for PCB - Double sided tape - 16 x 12mm m3 screws - 4 x Cable glands - 1 x Particle photon - 1 x 5V power supply (25W, depending on the amount of lights you connect) - 1 x Soldering iron and tin - 6 x 3 way screw terminals - 1 x 2 way screw terminals - 4 x Neopixel ring 12 - 4 x Neopixel jewel - 1 x 1m of solid core wire - 1 x Grounded powerplug/cord Step 1: Inspiration Shopping around If you´ve ever done some shopping for lamps, you know they dont generally come cheap. We wanted to hang a web of tube lights above our meeting table, but were really disappointed with what we found in stores. It was part of the motivation to build something ourselves. We were convinced we could fabricate something that was at least half as decent looking and maybe even more versatile than the simple and expensive florescent tubes we were looking at at the time. Heavy inspiration was drawn from displays at the Amsterdam light festival but also the legendary lightplan of the Trouw nightclub in Amsterdam by Meeuws van Dis. And after some intensive Google exploration we bumped into an acrylic manufacturer, Pyrasied, that makes these amazing OPY1 ghost tubes. OPY1 Ghost OPY1 is an acrylic material that is extruded into long beams that looks completely transparent in normal use. However, when you hold a light source up against it, the light is bounced off of millions of small reflective nano-particles in the material. This directs the light out to the side and creates an amazing glowing effect. It struck us as being the perfect material to add some unobtrusive color effects to our meeting room, so we ordered two metres of it. Step 2: Design Mocking it up As soon as the OPY1 tubes were in, we (ofcourse) slapped on some LEDs right away to check out the light dispersion effect. We just grabbed any lightsource we could find, from phones to ceiling lamps and held our tube up against it, and it was glorious! While it wasnt as bright as we had maybe hoped, the effect is amazing. But we never intended to use scotch tape or a breadboard as structural elements in our design, so we got cracking on designing a 3D printed holder for the LEDs and tubes so we could suspend them from the ceiling. Fusion 360 We used a really neat software package from AutoDesk, called Fusion 360. Fusion is very powerful software, and is free to use for hobbyists. And while there are easier to master tools on the market, you cant beat its functionality at this price level. A first version of an end-cap was modeled that could hold the lightsource in place against the end of the tubes (at that time we were using AdaFruit's crazy powerful Pixie LEDs). The holder doubles as a clamp onto a three wire cable that provides the LEDs with a power, ground and signal line... but also acts as a wire to suspend the lamps from. Step 3: Early Prototype 3D printing As soon as the modelling was done, we chucked an STL file of the design generated by Fusion into a 3D printer and took our lights for a first real test-drive. We printed the caps in PLA because it is such an easy to print material, but intended to use ABS in the final version so we could acetone smooth it if was nessecary. The design was completely optimized for easy printing and doesnt need supports for a good printing result. Improvements! But even with all the care in the world, first prototypes are never perfect, and neither was our first design. The caps were undersized, the holes for the bolts needed extra drilling to ensure a good screw-bite and the clamping cap was misaligned, giving it a very messy look. We also needed a bit more space inside the enclosure to stash the excess cables. So it was back to the drawing board for us! Aside from everything that didn't work, a lot of things did... and its just really great to hold your design in your hands and look at it up close. Step 4: Iteration Iteration and redesign is the key to good design. Four versions of the enclosure and a number of different LED configurations were tried and printed before we finally arrived at a final working construction. Light sources We tried out lots of alternative light sources. As mentioned, we initially went for power, using these crazy bright 3W leds. Unfortunately they turned oud to be incredibly impractical because of the heat they generated. The LEDs would go into a thermal shutoff mode whenever not constantly cycling colors. We then experimented with a number of different NeoPixels and NeoPixel rings from Adafruit. It turns out that the 12 LED ring fits a jewel (7 LED) perfectly in its center, and with some smart wiring you can make a nice LED disc. This option gave us a possibility to work with high light density without the generated heat of the Pixie. In addition, Adafruit sells these in RGBW versions, allowing us to shine true white light through our OPY1 tubes. Neopixels can be chained, so connecting one ring to the next was a breeze. Construction Also the construction of our 3d printed endcaps was improved over a number of design iterations. The first versions held on to the OPY1 tubes using glue, making repairs virtually impossible. Later iterations included captive nuts as metal inserts for screws and setscrews that hold the OPY1 tubes in place. Mating pins were added to ensure correct alignment of the halves and the overall dimensions were changed. The kind people at Plug'nmake in Delft printed out a neat final version of the caps for us. Print it yourself The final STL files are attached if you´d like to print them out yourself. You will have to do some light drilling of the holes for the clamping screws, also you will have to drill a hole for the neopixel wires to pass from the front to the back of the main body. The M3 nuts used as metal inserts were pressed in using a soldering iron and superglued for extra strength. Depending on your printer tolerances this may or not be nessecary. See this page for extra info about using inserts in 3D printed designs. Step 5: Tidying Up Wiring this amount of LEDs tends to get messy, and we wanted to come up with a solution that was safe and easy to install. Bunching up and soldering long strands of wire to the LEDS and sticking them into an Arduino and power source directly didn't seem like the ideal solution. We decided to build a custom PCB to tidy things up and make it more plug-and-play. There are no pictures that show the original breadboard, but the illustration gives you an idea of how chaotic things can become when you wire everything up individually using jumper cables! Overall electronics The electronics of the lamps are very simple. Basically, its really just a Particle photon driving four neopixel rings over long 3m cables with an extra 5V brick to power it all. I drew up the basics in a simple diagram. All the PCB does is route the digital pins, ground and power to six individual terminal blocks where the long cables can be clamped in conveniently. A 2 pin terminal block accepts wires coming from the power supply to power it all. We even added some extra headers on the PCB for future addition of sensors or whatnot. There are no other surface mount components, just some routing and through-hole terminal blocks. Microcontroller choice We decided to use a Particle Photon as a controller in our setup, in part because theyre cheap but most importantly because they give you easy access to the world of the internet. The photon can be hooked up to your wifi network and flashed with code over the air. In addition, the photon allows you to send and receive data from/to your creation over the internet. We wanted to build something that we could integrate with a number of different web services so the Photon was the right choice for this project. Offering ease of use and a familiar arduino based environment. The Photon can quite easily drive Neopixels from its digital pins, no seed for serial communication, and the Particle could makes it really east to use services like IFTTT to control your device. Ofcourse if you dive into the matter you can also create your own webhooks and endpoints, but its a platform that's relatively easy to get started with. No steep learning curve. PCB Using Fritzing we drew up a nice little one-sided board that could be etched easily using home-brew solutions. Instead of DIYing this step, however, we sent the PCB design to china for production instead. We used FirstPCB because they give a nice discount on your first order, but other PCB makers like OSHpark or Itead will do just fine aswell. I have included the gerber files of our PCB. But watch out! it has some faulty routing in it. I will update the files soon. We solved this ourselves by soldering a wire to the underside. Once our package came in from China we soldered on our Photon and screw terminals, connected the 5V supply and took it for a spin! Step 6: Enclosure Boring grey box After we checked that everything was working properly we moved on to covering up our central "hub" that houses the PCB and 5W power supply. Because we were planning to route the wiring of the lamps into our office's ceiling anyway, we decided not to go for an aesthetic solution here. We bought ourselves a nice little Fibox project enclosure that is rated IP65 (meaning hardcore resistance to dust and water) and a few cable glands to allow our wires to protrude from it. We drilled some holes for the glands and screwed them in, and that was basically it. No unessecary effort put into this part of the design. the PCB is mounted on adhesive posts and the powersupply was stuck in with a piece of double sided tape. Then we screwed on the lid and chucked it into our tile ceiling. I included a little illustration of the box contents (done with my best MSpaint skills) to illustrate the connections between components in the enclosures and where the cables enter and exit. Step 7: Wire and Mount! All that was left now for the hardware was the final cabling and hanging of the lamps! To make sure we mounted them correctly we mocked up our meetingroom in our 3D software (Fusion), and tried out some different angles and configurations before drilling holes in the ceiling. After a poll on Slack and some discussions we chose our favorite orientation and measured out the hole distances on the ceiling. Some quick drilling, pulling of cables and tying knots later we had everything up and running! After putting back all the ceiling tiles in their respective places, this was a nice moment to step back and marvel at what we had created. But we weren't there yet! We still needed to get some programming magic done to get everything working. Luckily we could do this all from the comfort of our desk behind our laptops and beam all the code to our Photon over the air! Step 8: Coding We haven't done a lot of experimenting with the code as of yet. But i'll explain a simple way to make these lights work over the internet using simple Particle functions and IFTTT. The Particle IDE is super easy to use for anyone that has programmed an Arduino type device before. You can find it at build.particle.com. Once logged in, a text editor appears, here we write our code. The code we use follows a few simple steps: 1. Declaration of variables In the first part of the code we have to initialize the libraries and variables we want to use. The Neopixel library is needed to light up the neopixels, the particle library is added automatically and includes the particle cloud functions we will be calling. We also have to set the system mode to automatic, which means the photon won't run code unless there is a connection to the cloud. You have to set up the photon to connect to your WiFi via the app or command line interface first ofcourse. // This #include statement was automatically added by the Particle IDE. #include "Particle.h" #include "neopixel.h" SYSTEM_MODE(AUTOMATIC); Then we set the variables for the NeoPixels to use including digital pin numbers, LED type and brightness of the strips. Also the different strips are defined from strip one to strip four. The strips all share the same pixel count and pixel type properties, as all the strips are identical: #define PIXEL_PIN1 D0 #define PIXEL_PIN2 D1 #define PIXEL_PIN3 D2 #define PIXEL_PIN4 D5 #define PIXEL_COUNT 19 #define PIXEL_TYPE SK6812RGBW #define BRIGHTNESS 255 // 0 - 255 Adafruit_NeoPixel strip1(PIXEL_COUNT, PIXEL_PIN1, PIXEL_TYPE); Adafruit_NeoPixel strip2(PIXEL_COUNT, PIXEL_PIN2, PIXEL_TYPE); Adafruit_NeoPixel strip3(PIXEL_COUNT, PIXEL_PIN3, PIXEL_TYPE); Adafruit_NeoPixel strip4(PIXEL_COUNT, PIXEL_PIN4, PIXEL_TYPE); 2. Setup In the setup we have to set up our particle cloud functions, these are the functions that allow us to communicate with the Photon via the particle cloud. You give the function a name, in this case we called it "Sign", and define a string that can be filled with commands of max. 64 characters, we called this "signToggle". After this we start up the NeoPixels, these are set to an initial black or "off" state and full brightness void setup() { //particle functions Particle.function("Sign", signToggle); //Initialize Neopixels strip1.setBrightness(255); strip2.setBrightness(255); strip3.setBrightness(255); strip4.setBrightness(255); strip1.begin(); strip2.begin(); strip3.begin(); strip4.begin(); strip1.show(); strip2.show(); strip3.show(); strip4.show(); } 3. Loop In the loop we call the function that describes the neutral state of the lamp (Full white LEDs blasting). Thats really all we do in the loop. When we call our particle function the loop will be broken and the contents of the "Sign" particle.function will be executed. The fullWhite function we point to will be described after the main loop in the functions section. void loop() {fullWhite();} This section continues in next step! Step 9: Coding Continued 4. Functions Now we fill up our functions with what we want them to do. The fullWhite function tells each individual Pixel in each strip to become white. We then let the code listen to the strings that are received in signToggle and whenever this string is "go" we turn all the LEDs red and hold this for 2000ms. After doing this the pixels will turn back to the neutral white state. (Full code is attached as .bin) void fullWhite() { for(uint16_t i=0; i<strip1.numPixels(); i++) { strip1.setPixelColor(i, strip1.Color(0,0,0, 255 ) ); strip2.setPixelColor(i, strip2.Color(0,0,0, 255 ) ); strip3.setPixelColor(i, strip3.Color(0,0,0, 255 ) ); strip4.setPixelColor(i, strip4.Color(0,0,0, 255 ) );} strip1.show(); strip2.show(); strip3.show(); strip4.show();} int signToggle(String command) { if(command == "go") { for(uint16_t i=0; i<strip1.numPixels(); i++) { strip1.setPixelColor(i,strip1.Color(255,0,0,0)); strip2.setPixelColor(i,strip2.Color(255,0,0,0)); strip3.setPixelColor(i,strip3.Color(255,0,0,0)); strip4.setPixelColor(i,strip4.Color(255,0,0,0)); strip1.show(); strip2.show(); strip3.show(); strip4.show(); delay(2000);}}} Step 10: IFTTT So now we have hardware, and firmware! All thats left to do is set up a trigger for our particle function. As said, we can use IFTTT to create easy triggers for the Photon. Ofcourse you can also access an endpoint and integrate this into something more custom, but for the sake of simplicity we will use this great webservice that does all the API integration for you. First of all connect your google agenda and particle accounts. You can do this via the "services" page. Search for "google agenda" and "particle" respectively and create the link to IFTTT by logging in to these services. Now create a new applet via the "my applets page". You will be presented with a huge "if this then that" text. Click on this. Now find your google agenda service and tell the applet to trigger when new events start. Then press that and find your particle service. In the window you are presented with you will see that the particle.function ("Sign") shows up in the first dropdrown. Select this. Then define the function input to send when a new event is sbout to start. remember, we use the string "go" to trigger a red flash... so enter "go" in the function input field (without parentheses). Thats it! You now should have a working light installation that listens to your google agenda and alerts you with a red flash whenever a meeting is about to start. Step 11: In Action! So thats it! All the steps we took to make our meeting room more interactive. We're still working at hard at developing fitting interactions and extra integrations for the lamps, and ofcourse we're very interested in suggestions and tips for further development. Again, if youre interested in smart buildings take a look at our website! Also, youre very welcome to post any questions you have below, and i will try to answer them! Hope we inspired you, and we cant wait to see what the community thinks of the project! Yours truly, The Mapiq team
http://www.instructables.com/id/Never-Miss-a-Meeting-With-These-Connected-Meeting-/
CC-MAIN-2017-17
refinedweb
3,231
70.13
Install Opencv 4.1 on Nvidia Jetson Nano We’re going to learn in this tutorial how to install Opencv 4.1 on the Nvidia Jetson Nano. First of all we need to make sure that there is enough memory to proceed with the installation. The Jetson Nano has 4GB of ram, and they’re not enough for some installations, and Opencv is one of them. To solve this problem we need to add some extra memory, called “Swap memory” which will take place when all the RAM has been used. We will see in this post how we can create and or extend the Swap memory and then how to install Opencv. Add Swap Memory By default the Ubuntu 18.04 distribution of Jetson Nano comes with 2 gb of Swap memory. To increase it we need to open the terminal and type the line: sudo apt-get install zram-config The zram module, on the Jetson nano allocates by default 2gb of Swap memory, so now we’re going to extend the size to 4gb by changing the configuration file. Just type on the terminal: sudo gedit /usr/bin/init-zram-swapping Replace the line: mem=$(((totalmem / 2 / ${NRDEVICES}) * 1024)) with this line: mem=$(((totalmem / ${NRDEVICES}) * 1024)) And then reboot. Install Opencv 4.1 The installation of Opencv on the Jetson Nano takes around one hour. We need to build Opencv from the source code, and we can do it by following these 7 steps below. 1. Updating the packages: sudo apt update sudo apt install -y build-essential cmake git libgtk2.0-dev pkg-config libswscale-dev libtbb2 libtbb-dev sudo apt install -y python-dev python3-dev python-numpy python3-numpy sudo apt install -y curl 2. Install video & image formats: sudo apt install -y libjpeg-dev libpng-dev libtiff-dev libjasper-dev sudo apt install -y libavcodec-dev libavformat-dev sudo apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev sudo apt install -y libv4l-dev v4l-utils qv4l2 v4l2ucp libdc1394-22-dev 3. Download OpenCV & Contribs Modules: curl -L -o opencv-4.1.0.zip curl -L -o opencv_contrib-4.1.0.zip 4. Unzipping packages: unzip opencv-4.1.0.zip unzip opencv_contrib-4.1.0.zip cd opencv-4.1.0/ 5. Create directory: mkdir release cd release/ 6. Build Opencv using Cmake: cmake -D WITH_CUDA=ON \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.1.0/modules \ -D WITH_GSTREAMER=ON \ -D WITH_LIBV4L=ON \ -D BUILD_opencv_python2=ON \ -D BUILD_opencv_python3=ON \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D BUILD_EXAMPLES=OFF \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local .. 7. Compile the OpenCV with Contribs Modules: make -j4 sudo make install The installation is now completed. 28 Comments - Sergio Canu August 27, 2019 at 12:20 pm Hi Tom, I don’t know about that. Bear in mind that the tutorial is for the Opencv version 4.1.0, so with newest versions it might not work. - Khoa September 16, 2019 at 6:29 pm My device: Jetson nano, Ubuntu 18.04, python 3.6 I confirm opencv 4.1.0 can be installed as guide. But opencv 4.1.1 can’t. - Israel March 6, 2020 at 2:39 pm Add this flag: -D EIGEN_INCLUDE_PATH=/usr/include/eigen3 But if you don’t have it already, install it with apt install libeigen3-dev. - Qazi Mashood October 14, 2019 at 3:23 pm libjasper- dev is not downloading. I have tried everything available on google - JP October 23, 2019 at 2:35 am doesn’t matter, is compiled by opencv. - hitomi October 29, 2019 at 4:50 pm thank you for the tutorial it helps. - Marc pu November 6, 2019 at 8:05 am dear sir, have you been in this kind of error. it took me one week long to try to figure out but still not working the error messages is like below: ”’ faces = face_cascade.detectMultiScale(gray, 1.3, 5) cv2.error: OpenCV(4.1.0) /home/marc/opencv-4.1.0/modules/objdetect/src/cascadedetect.cpp:1658: error: (-215:Assertion failed) !empty() in function ‘detectMultiScale’ ””’ thanks u for helping - Louis April 1, 2020 at 9:43 am You’re camera is not being read, the image it is detecting in Multiscale is empty - mo November 17, 2019 at 10:47 pm this only works for python2 but does not work for python3 (which is where i need it) using it on jetson nano also. any tips? - Kris November 21, 2019 at 11:02 am HI, You need to rename cv2 lib in /usr/local/lib/python3.6/site-packages/cv2/python-3.6/ sudo mv cv2.cpython-36m-aarch64-linux-gnu.so cv2.so and link it to your enviropment cd .virtualenvs/deep_learning/lib/python3.6/site-packages/ ln -s /usr/local/lib/python3.6/site-packages/cv2/python-3.6/cv2.so cv2.so - kbax December 13, 2019 at 1:11 pm Thanks for this. This really saved my day. The only minor issue that i found with your commands is that the linking command did not do the job for me as the cv2.so is located directly in the site-packages in my case. hence, this command worked out: ln -s /usr/local/lib/python3.6/site-packages/cv2.so cv2.so - Raj kumar June 16, 2020 at 7:47 am i am trying for 2 days to install opencv version 4 for jetson nano with python3. i didn’t really get where to raname after the above installation or before? and what are the commands exactly to do so so that open-CV 4.X is installed for python 3 in Nvidia jet son nano Thanks you in advance - Wang November 27, 2019 at 4:03 am My device has error Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it? why? - Kevin A December 8, 2019 at 3:09 am I made it past: sudo apt update Then: [email protected]:~$ sudo apt install -y build-essential cmake git libgtk2.0-dev pkg-config libswscale-dev libtbb2 libtbb-dev Reading package lists… Done Building dependency tree Reading state information… Done build-essential is already the newest version (12.4ubuntu1). build-essential set to manually installed. pkg-config is already the newest version (0.29.1-0ubuntu2). pkg-config set to manually installed. libtbb-dev is already the newest version (2017~U7-8). libtbb2 is already the newest version (2017~U7-8). git is already the newest version (1:2.17.1-1ubuntu0 libswscale-dev : Depends: libavutil-dev (= 7:3.4.2-2) but it is not going to be installed Depends: libswscale4 (= 7:3.4.2-2) but 7:3.4.6-0ubuntu0.18.04.1 is to be installed E: Unable to correct problems, you have held broken packages. - satya December 27, 2019 at 1:49 am Hi Can you share the tutorial or link for generating whl for opencv-python-4.1.0 for jetson nano. I guess it will help a lot people. Instead of going through this entire build process - Dave von Orlando January 1, 2020 at 7:51 pm Hi, i have opencv 3.4.6 and work correctly. But this version don’t use GPU, only cpu (i see in System Monitor) This new version will use the 128 cores of jetson nano? - John January 16, 2020 at 12:32 pm After this installation, how can I upgrade scipy and sklearn? - Josh January 20, 2020 at 12:28 am When I use: brief = cv.xfeatures2d.BriefDescriptorExtractor_create() I get the following error: AttributeError: module ‘cv2’ has no attribute ‘xfeatures2d’ - Piamio January 29, 2020 at 1:17 am I have a problem with Compiling the openCV . My System Monitor says that Memory has used 99,2% of the capacity and Swap uses a 100% capacity. Now The cursor ist stucking every now and then and i can’t click any icon. Whats the Problem here? I rebooted the Jetson and tried again but still the same result. Can anyone help? - Piamio January 29, 2020 at 1:19 am I already enlarged the swap memory - Piamio January 29, 2020 at 2:08 am Nevermind now it suddenly works 😀 - KansaiRobot February 23, 2020 at 8:36 am after I did sudo apt install zram-config (or is it apt-get?) I got unable to locate package zram-config what could be happening? - khalid April 15, 2020 at 11:09 am Hi very interesting article. I followed your steps and they all are fine. however, when I try yo use the tracker library, which comes as part of the opencv_contrib module I get a compiler error that tracker.hpp is not found. I could see the file inside the installed opencv_contrib folder but it somehow seems that the installation process is not installing the tracker library properly - Grish May 20, 2020 at 9:50 pm Hello Khalid, If you fixed this issue please tell me how. I tried some workarounds, but in the end nothing worked for me. Thanks in advance. - Leon April 24, 2020 at 3:44 am After I installed and executed the command, the following error message appeared: $ python -c “import cv2; print(cv2.version)” 4.1.0 $ python new-detection.py jetson.inference.init.py jetson.inference – initializing Python 2.7 bindings… jetson.inference – registering module types… jetson.inference – done registering module types jetson.inference – done Python 2.7 binding initialization jetson.utils.init.py jetson.utils – initializing Python 2.7 bindings… jetson.utils – registering module functions… jetson.utils – done registering module functions jetson.utils – registering module types… jetson.utils – done registering module types jetson.utils – done Python 2.7 binding initialization Traceback (most recent call last): File “new-detection.py”, line 7, in import cv2 File “/usr/local/lib/python2.7/dist-packages/cv2/init.py”, line 89, in bootstrap() File “/usr/local/lib/python2.7/dist-packages/cv2/init.py”, line 79, in bootstrap import cv2 ImportError: /usr/local/lib/libopencv_cudaarithm.so.4.1: undefined symbol: _ZN2cv4cuda14StreamAccessor9getStreamERKNS0_6StreamE =========================================== 1.The program can work in Opencv 3.2 with python2.7 2.How can fix it? Or where can provide the correct upgrade and installation method? Thanks! - THomas April 30, 2020 at 6:19? - Francisco June 24, 2020 at 2:38 am Hey great tutorial, thank you so much. Thank you for putting effort into this!!! Tried with the new opencv 4.1.1 Everything went fine until last step (make)…. 12: fatal error: Eigen/Core: No such file or directory # include
https://pysource.com/2019/08/26/install-opencv-4-1-on-nvidia-jetson-nano/
CC-MAIN-2020-29
refinedweb
1,754
67.86
May 31, 2019 03:17 AM|DEV_Beginner|LINK Hi Everyone I have issue with PyRFC connection to SAP by host on IIS 7 before I use PyRFC my application work fine and after I import PyRFC and Connect to Bapi Server IIS will show detail as below HTTP Error 500.0 - Internal Server Error c:\python27\python27.exe - The FastCGI process exited unexpectedly Detailed Error Information: Module FastCgiModule Notification ExecuteRequestHandler Handler safetystock Error Code 0xffffffff Requested URL Physical Path D:\safetystock\api_test\ Logon Method Anonymous Logon User Anonymous Request Tracing Directory C:\inetpub\logs\FailedReqLogFiles and this is my code: from pyrfc import Connection conn = Connection(user='sapconnect', passwd='mypassword', ashost='myhost', sysnr='00', client='100') When compiler run to line Connection() IIS will show error 500 but I try to run localhost on server application work fine. I already added full permission to root project folder and root python folder but it not work. I has been stuck in this problem for 3 days. Help me please python 2.7 64 bit django 1.11.16 pyrfc 1.9.96 MVP May 31, 2019 04:53 AM|lextm|LINK If PyRFC crashed Python processes, you should report to SAP, not here, May 31, 2019 05:03 AM|DEV_Beginner|LINK I think not PyRFC crashed because when I run in localhost it work fine. but run on IIS it crashed may be IIS can't find module Pyrfc then I want to know how to add to pyrfc package to IIS (RFC SDK install at C:\nwrfcsdk ) Jun 03, 2019 06:19 AM|Jalpa Panchal|LINK Hi, Could you tell us where is RFC SDK was installed? and which account is used by the application pool? Regards, Jalpa. Jun 03, 2019 06:54 AM|DEV_Beginner|LINK Hi Jalpa I install RFC SDK at C:\nwrfcsdk and already add C:\nwrfcsdk\lib in system environment but when I run application on IIS , the system displays DLL load failed: The specified module could not be found so I tried to move the file sapnwrfc.dll to C:\Python27\Lib\site-packages\pyrfc and system shows error the same message as above (HTTP Error 500.0 - Internal Server Error) I guess IIS can't connect to package from C:\nwrfcsdk\lib but I already add full permission to that folder ( IUSER ) I have no idea Thank you for reply Jun 03, 2019 07:31 AM|Jalpa Panchal|LINK Could you share C:\nwrfcsdk\lib folder permission and iis application pool snapshot? Jun 03, 2019 07:41 AM|DEV_Beginner|LINK Please see snapshot at folder permission -> application Pool in IIS -> I don't know how to add image to this forums Jun 03, 2019 08:08 AM|Jalpa Panchal|LINK You could use this link to post the image in this forum. You could also refer below post solution to resolve the issue. Jun 03, 2019 08:19 AM|DEV_Beginner|LINK Thank you for suggestion to upload image from stack overflow I've read that post, but I can't understand how to do it. I tried to add full permission all related folder but not work If you understand that post, please explain to me how to make it thoroughly. Jun 03, 2019 08:32 AM|Jalpa Panchal|LINK Select the application pool and then select iis application pool advance setting. In advance setting check application pool identity: Try to use Process Monitor to monitor w3wp.exe IIS worker process and python.exe after calling the API. dependency walker to track the dependent dll. Jun 03, 2019 08:59 AM|DEV_Beginner|LINK OK I've check application pool identity in advance setting and use procmon to monitor w3wp.exe and python.exe process look like system find sapnwrfc.dll from all related folder but not find in C:\nwrfcsdk\lib folder How to add this folder to system finder ? (and again I've upload image at imgur.com and can't input embed code to this site ) Jun 03, 2019 09:11 AM|Jalpa Panchal|LINK Check that dll is available in that folder or not and what is the error message shown at your application?could you share that detail error message snapshot? Jun 03, 2019 09:45 AM|DEV_Beginner|LINK Now I have moved the sapnwrfc.dll file to C:\Python27\Lib\site-packages\pyrfc\sapnwrfc.dll and system found it Then I look at procmon again and find path C:\Python27\Lib\site-packages\pyrfc\sapnwrfc.dll. Procmon show FILE LOCKED WITH ONLY READERS at Results column and result on web browser display error internal 500 when I call pyrfc connect function then I will look at permission on C:\Python27\Lib\site-packages\pyrfc\sapnwrfc.dll it have full permission (sapnwrfc.dll permission ) (Web browser display) How to add read/write permission to sapnwrfc.dll from IIS ? Jun 04, 2019 03:12 AM|Jalpa Panchal|LINK Hi, Check that you configured python in iis properly or not? your python folder and site folder has iis_iusrs, iusr and application pool full access permmision. which authentication are you using to access the site? Jun 04, 2019 05:43 AM|DEV_Beginner|LINK Hi I've checked python configuration in FastCGI Setting it work fine but I'm not sure if it's correct or not. and I have granted access IUSER and IIS_IUSER for python folder , site folder with full permission and I don't know how to grant access for application pool Jun 04, 2019 07:55 AM|Jalpa Panchal|LINK You could give application pool permission to the folder by: IIS AppPool\<myappoolname> Please provides application pool identity setting as suggested in this step: Also, run FRT in iis : When you enable, you capture status code from 200-500 so all the request will be logged. Then you can try accessing the site and check what is wrong by checking FREB traces. Jun 04, 2019 08:36 AM|DEV_Beginner|LINK I gave application pool permission from IIS to site folder and python folder Application Pool -> Folder Permission -> and track error log follow your suggestion and I receive error as below (What part of the information do I have to see?) Jun 04, 2019 09:01 AM|Jalpa Panchal|LINK If possible could you please upload log file on one drive and share a link? Jun 04, 2019 09:13 AM|DEV_Beginner|LINK Jun 05, 2019 06:50 AM|Jalpa Panchal|LINK please check python log and share with us. 19 replies Last post Jun 05, 2019 06:50 AM by Jalpa Panchal
https://forums.iis.net/p/1242252/2149206.aspx?Re+Python+django+PyRFC+Connection+HTTP+Error+500+0+Internal+Server+Error
CC-MAIN-2020-16
refinedweb
1,092
59.43
On Mon, May 05, 2008 at 06:18:07PM +0200, Michael Vogt wrote: > On Mon, May 05, 2008 at 01:08:22AM +0900, Osamu Aoki wrote: > Thanks for your patch! You are welcom. This was something I was doing for myself by manual CRON job :-) > > [ Osamu Aoki ] > > * Updated cron script to support backups by hardlinks and > > verbose levels. All features turned off by default. > > I like the verbose level addition, that is very helpfull. Could you > please tell me a bit more about the hardlink backup mechanism? What is > the use-case for this? It seems like it the MinAge feature in the cron > script mostly takes care of this, or am I overlooking something here? My focus is unstable while your focus is stable support. That may explain why I do this. Suppose very old large package was upgraded. Then we find new package was broken. Size and age based aging will sure to loose them, I think. It get worse, if we enable autoclean. Then we need to download them again. Hardlink back up as I use, especially used with CRON autoclean, only keeps copy of up-to-date packages in archive without duplicated disk space. The previous snapshot of archive is always available for several days old state. (unchanged day not conted.) ... > > I am not using Ubunts and many of recent these feature seems to be lead > > by Ubunts stable support. I do not want to create problem for them. > > The unattended-upgrades support was developert for ubuntu. But there > is no reason why it can not (or should not) used in debian. You mean Debian stable (or possibly for testing). I agree too. It is insane to do so for sid. (As you recommend). > It works just fine there and the additional flexibility (blacklist > support, conffile checking) compared to other solutions seem like a > useful addition. Yes. > If there are multiple competing ones, we could just add a > conf variable (like dir::bin::unattended-upgrades). I am not going to work on this issue for short term. If I do, I will use simpler shell version to function if Python one does not exist or some variable specifies. After all, my focus is unstable. > > On Sat, May 03, 2008 at 02:50:06PM -0300, Otavio Salvador wrote: > > > Osamu Aoki <osamu@debian.org> writes: > > > > On Fri, May 02, 2008 at 12:20:12PM -0300, Otavio Salvador wrote: > > > >> Osamu Aoki <osamu@debian.org> writes: ... > > I am doing it but its progress is too slow. I hope to see it finished by > > tommorow morning :-) (Now: Mon May 5 01:03:23 JST 2008) > > > > $ bzr push --create-prefix s > > > > > We'd need to support backward compatibility but it doesn't need to be > > > done quietly. We might output a warning to let user to know that he > > > needs to change his/her configuration for the new variables and at > > > Lenny+2 we can drop it. > > > > Anyway, these were undocumented feature in terms of normal document. > > > > Since I added onfigure-index this time, it is minimally documented and > > tose old syntax are marked deprecated. So dropping them infuture is > > doable. > > I agree that the old names fit better into the periodic namespace but > I also think its not really worth to change them because its a small > cosmetic thing and if we drop the old names in the future that will > mean that a lot of our users (who customized them) will need to fix > there configs. As you see, both names are active now. I do not want to cause problem if these changes have conflicts with Ubuntu case. > > Since I made few extra verbosity control, I might have introduced bugs. > > Quick look at shell -x result seems OK. > > Looking over the script I think the changes are ok. I would prefer to > not have the huge fi/else cascade around line 334 but I understand > that this is difficult to do in sh: > ... > debug_echo "download upgradable (not run)." > fi > else > debug_echo "download updated metadata (error)." > fi > ... But this is only logical to do this. indentation makes it quite clear (it is soft tab stop 4). What do you suggest otherwise in other language. Can you make pseudo-python code to explain what you envision to be better? By the way, I changed verbose level 1 to report only errors and level 2 to report progress. Then I moved other verbosety level up one in my bzr. (I have not checked it yet. Time to sleep now.) Osamu
https://lists.debian.org/deity/2008/05/msg00079.html
CC-MAIN-2017-04
refinedweb
748
75.4
Problem You have a header file that references classes in other headers, and you need to reduce compilation dependencies (and perhaps time). Solution Use forward class declarations where possible to avoid unnecessary compilation dependencies. Example 2-4 gives a short example of a forward class declaration. Example 2-4. Forward class declaration // myheader.h #ifndef MYHEADER_H_ _ #define MYHEADER_H_ _ class A; // No need to include A's header class B { public: void f(const A& a); // ... private: A* a_; }; #endif Somewhere else there is a header and perhaps an implementation file that declares and defines the class A, but from within myheader.h I don't care about the details of A: all I need to know is that A is a class. Discussion A forward class declaration is a way to ignore details that you don't need to be concerned with. In Example 2-4, myheader.h doesn't need to know anything about the class A except that it exists and that it's a class. Consider what would happen if you #included the header file for A, or, more realistically, the header files for the half-dozen or so classes you would use in a real header file. Now an implementation file (myheader.cpp) includes this header, myheader.h, because it contains the declarations for everything. So far, so good. If you change one of the header files included by myheader.h (or one of the header files included by one of those files), then all of the implementation files that include myheader.h will need to be recompiled. Forward declare your class and these compilation dependencies go away. Using a forward declaration simply creates a name to which everything else in the header file can refer. The linker has the happy task of matching up definitions in the implementation files that use your header. Sadly, you can't always use forward declarations. The class B in Example 2-4 only uses pointers or references to A, so I can get away with a forward declaration. However, if I use an A member function or variable, or if I have an object of type A--and not just a pointer or reference to onein my definition for the class B, suddenly my forward declaration is insufficient. This is because files including myheader.h need to know the size of B, and if A is a member variable of B, then the compiler needs to know A's size to figure out B's size. A pointer or a reference to something is always the same size, so in the case where you are using pointers or references, the details of A aren't of interest to the compiler and therefore A's header file isn't necessary. Not surprisingly, if you include any definition in myheader.h that uses members of A, you have to #include A's header. This is because the compiler needs to check the function signature of the A member function or the data type of the A data member you are referencing. To illustrate, this code requires an #include: #include "a.h" class B { public: void f(const A& a) { foo_ = a.getVal( ); // Have to know if a.getVal is valid } // ... In general, use forward declarations when you can to reduce the amount of #include-ing that goes on at compile time.
http://flylib.com/books/en/2.131.1/reducing_includes_with_forward_class_declarations.html
CC-MAIN-2018-05
refinedweb
562
64.61
Bowling Kata in Clojure, F#, and Scala Bowling Kata in Clojure, F#, and Scala Comparing results for coding contests done in different languages can be both fun and enlightening. Check out such an example with the Bowling Kata done at Codurance! Join the DZone community and get the full member experience.Join For Free and coding styles. As you can imagine, we cannot always avoid cracking a joke or two about all the languages we don’t like so much but other craftsmen in the company do. So, just for fun, quite a few of us decided to do the same kata using our language of choice. It was great to see the same problem solved with different languages. Although there are still a few craftsmen and apprentices working on solving the kata in different languages, here are 3 of my favorite solutions so far (in no particular order): Clojure (by Mashooq) (ns bowling.core-test (:require [clojure.test :refer :all] [bowling.core :refer :all])) (deftest bowling (testing "strikes for all rolls" (is (= 300 (score "XXXXXXXXXXXX")))) (testing "normal scores" (is (= 99 (score "91919393929291219191")))) (testing "normal scores or misses" (is (= 90 (score "9-9-9-9-9-9-9-9-9-9-"))) (is (= 93 (score "919-9-9-9-9-929-9-9-")))) (testing "mixture of stikes and normals" (is (= 98 (score "9-X8-9-9-9-9-9-9-9-"))) (is (= 104 (score "9-X8-9-9-9-9-9-9-X23"))) (is (= 28 (score "--X81--------------"))) (is (= 27 (score "--X8-1-------------")))) (testing "spares for all rolls" (is (= 150 (score "5/5/5/5/5/5/5/5/5/5/5")))) (testing "mixture of spares and normals" (is (= 82 (score "9-8/--9-9-9-9-9-9-9-"))) (is (= 84 (score "9-8/--9-9-9-9-9-9-9/1"))) (is (= 12 (score "--8/1---------------"))) (is (= 11 (score "--8/-1--------------"))))) (ns bowling.core) (defn- spare?[s] (= \/ s)) (defn- strike? [s] (= \X s)) (defn- spare-or-strike? [s] (or (spare? s) (strike? s))) (defn- miss? [s] (or (= nil s) (= \- s))) (defn- score-for [s] (cond (spare-or-strike? s) 10 (miss? s) 0 :else (read-string (str s)))) (defn- score-roll [this-roll rem-rolls] (cond (strike? this-roll) (+ 10 (score-for (first rem-rolls)) (score-for (first (rest rem-rolls)))) (spare? this-roll) (+ 10 (score-for (first rem-rolls))) (spare? (first rem-rolls)) 0 :else (score-for this-roll))) (defn- score-rolls [acc rolls] (if (seq rolls) (let [running-score (+ acc (score-roll (first rolls) (rest rolls)))] (score-rolls running-score (rest rolls))) acc)) (defn- expand-strikes [rolls] (seq (reduce str (map #(if (strike? %) "X-" (str %)) (seq rolls))))) (defn- deduct-extra-rolls [score rolls] (- score (score-rolls 0 (drop 20 (expand-strikes rolls))))) (defn score [rolls] (deduct-extra-rolls (score-rolls 0 (seq rolls)) rolls)) See on Mash's GitHub F# (by Pedro) namespace BowlingV2.FSharpKatas module Bowling = open System type private Rolls = Strike | Spare | Roll type private Pins = Pins of int type private Roll = Rolls * Pins let private maxRolls = 20 let private maxPins = 10 let private noPins = 0 let private pinCountForRoll roll = let (Pins pins) = snd roll pins let private pinsFromRawRoll rawRoll = Pins (Int32.Parse(rawRoll.ToString())) let private sparePinsFromRawRoll rawRoll = Pins (maxPins - Int32.Parse(rawRoll.ToString())) let private parse roll index rolls = let previousRoll = fun () -> Seq.item (index - 1) rolls match roll with | '-' -> Roll, Pins noPins | '/' -> Spare, sparePinsFromRawRoll(previousRoll()) | 'X' -> Strike, Pins maxPins | r -> Roll, pinsFromRawRoll r let private scoreRoll index rolls = let bonusRoll = fun(lookAhead) -> if index + lookAhead < Seq.length rolls then pinCountForRoll (Seq.item (index + lookAhead) rolls) else noPins let exceedsMaxRolls = fun() -> rolls |> Seq.take index |> Seq.map (fun r -> match r with | (Strike, _) -> 2 | _ -> 1) |> Seq.sum >= maxRolls match Seq.item index rolls with | (_, _) when exceedsMaxRolls() -> noPins | (Spare, Pins pins) -> pins + bonusRoll 1 | (Strike, Pins pins) -> pins + bonusRoll 1 + bonusRoll 2 | (Roll, Pins pins) -> pins let scoreGame rolls = let parsedRolls = rolls |> Seq.mapi (fun index roll -> parse roll index rolls) parsedRolls |> Seq.mapi (fun index _ -> scoreRoll index parsedRolls) |> Seq.sum module BowlingTests = open NUnit.Framework open Swensen.Unquote open Bowling [<Test>] let ``calculate scores with no strikes or spares``() = test <@ scoreGame "--" = 0 @> test <@ scoreGame "1" = 1 @> test <@ scoreGame "13" = 4 @> test <@ scoreGame "13521" = 12 @> [<Test>] let ``calculate scores containing a miss``() = test <@ scoreGame "1-5-" = 6 @> test <@ scoreGame "9-9-9-9-9-9-9-9-9-9-" = 90 @> [<Test>] let ``calculate scores containing spares``() = test <@ scoreGame "1/" = 10 @> test <@ scoreGame "1/--" = 10 @> test <@ scoreGame "1/-5" = 15 @> test <@ scoreGame "1/35-" = 21 @> test <@ scoreGame "1/3/23" = 30 @> test <@ scoreGame "5/5/5/5/5/5/5/5/5/5/5" = 150 @> [<Test>] let ``calculate scores containing strikes``() = test <@ scoreGame "X" = 10 @> test <@ scoreGame "X--" = 10 @> test <@ scoreGame "X--51" = 16 @> test <@ scoreGame "X51" = 22 @> test <@ scoreGame "XXXXXXXXXXXX" = 300 @> test <@ scoreGame "XXXXXXXXXX12" = 274 @> test <@ scoreGame "1/35XXX45" = 103 @> test <@ scoreGame "1/35XXX458/X35" = 149 @> test <@ scoreGame "1/35XXX458/X3/" = 153 @> test <@ scoreGame "1/35XXX458/X3/23" = 160 @> test <@ scoreGame "1/35XXX458/X3/X" = 173 @> test <@ scoreGame "1/35XXX458/X3/XX6" = 189 @> See on Pedro's GitHub Scala (by Sandro) package com.codurance.bowlingkata.full_scoring import com.codurance.UnitSpec import com.codurance.bowlingkata.full_scoring.BowlingFullScoreCalculator.scoreFor class BowlingFullScoreCalculatorShould extends UnitSpec { "calculate scores with no strikes or spares" in { scoreFor("11111111112222222222") should be (30) } "calculate scores containing a miss" in { scoreFor("--------------------") should be (0) scoreFor("1-1----------------1") should be (3) scoreFor("9-9-9-9-9-9-9-9-9-9-") should be (90) } "calculate scores containing spares" in { scoreFor("5/11------------3/11") should be (26) scoreFor("5/5/5/5/5/5/5/5/5/5/5") should be (150) } "calculate scores containing strikes" in { scoreFor("XXXXXXXXXXXX") should be(300) scoreFor("XXXXXXXXXX12") should be(274) scoreFor("1/35XXX458/X3/23") should be(160) scoreFor("1/35XXX458/X3/XX6") should be(189) } } package com.codurance.bowlingkata.full_scoring object BowlingFullScoreCalculator { def scoreFor(rolls: String): Int = totalScore(rolls.split("").toList) private def totalScore(rolls: List[String], index: Int = 0, score: Int = 0): Int = { lazy val MISS = "-" lazy val SPARE = ("/", () => 10 - rollScoreAt(index - 1) + if_(index < 19, rollScoreAt(index + 1))) lazy val STRIKE = ("X", () => 10 + if_(index + numberOfPreviousStrikes() < 18, rollScoreAt(index + 1) + rollScoreAt(index + 2))) def numberOfPreviousStrikes() = rolls.mkString.take(index).count(_ == 'X') def rollScoreAt(index: Int): Int = rolls(index) match { case STRIKE._1 => 10 case SPARE._1 => 10 - rolls(index - 1).toInt case MISS => 0 case pins => pins.toInt } rolls.drop(index) match { case STRIKE._1 :: _ => totalScore(rolls, index + 1, score + STRIKE._2()) case SPARE._1 :: _ => totalScore(rolls, index + 1, score + SPARE._2()) case MISS :: _ => totalScore(rolls, index + 1, score) case n :: _ => totalScore(rolls, index + 1, score + n.toInt) case List() => score } } private def if_(condition: Boolean, ifTrue: => Int): Int = if (condition) ifTrue else 0 } See on Sandro's GitHub Fun, Passion, and Respect Having fun at work, being surrounded by passionate and talented craftsmen, the respect we have for each other, and the willingness to learn and share, are some of the things I love the most about the Codurance’s culture. What started as apprentices practicing with a kata transformed into a great way to learn and share knowledge among craftsmen and apprentices. Some of our craftsmen and apprentices are also working on their solutions in Kotlin, Haskell, Java, and C#. As among ourselves we will probably never agree which one we prefer, we will let you choose which one you like the most. :) Thanks Mash and Pedro for the Clojure and F# implementations. Published at DZone with permission of Sandro Mancuso , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/bowling-kata-in-clojure-f-and-scala
CC-MAIN-2019-30
refinedweb
1,286
62.68
Source JythonBook / chapter11.rst Chapter 11: Using Jython in an IDE - Chapter Draft plugins discussed by their names, so in the case of Netbeans the plugin is called Netbeans Python Plugin. This plugin works with both Python and Jython in all cases. Eclipse. Installing PyDev Eclipse doesn't include Jython support built-in. Thus, we will use PyDev, an excellent plugin which adds support for the Python language and includes specialized support for Jython. PyDev's home page is but you won't need to manually download and install it. To install the plugin, start Eclipse and go to the menu :menuselection:`Help --> Install new Software...`, type into the "Work with" input box and press enter. After a short moment you will see an entry for PyDev in the bigger box below. Just select it, clicking on the checkbox which appears at the left of "PyDev" (see the image which follows, as reference) and finally click the "Next" button. After this, just follow the wizard, accept the license agreement and then click the "Finish" button. Once the plugin has been installed by Eclipse, you will be asked if you want to restart the IDE to enable the plugin. As that is the recommended option, do so, answering "Yes" to the dialog. Once Eclipse reboots itself, you will enjoy full Python support on the IDE. Minimal Configuration Before starting a PyDev project you must tell PyDev which Python interpreters are available. In this context, a interpreter is just a particular installation of some implementation of Python. When starting you will normally only need one interpreter and for this chapter we will only use Jython 2.5.0. To configure it, open the Eclipse Preferences dialog (via :menuselection:`Window --> Preferences` in the main menu bar). On the text box located at the top of the left panel, type "Jython". This will filter the myriad of Eclipse (and PyDev!) options and will present us with a much simplified view, in which you will spot the "Interpreter - Jython" section on the left. Once you selected the "Intepreter - Jython" section, you will be presented with an empty list of Jython intepreters at the top of the right side. We clearly need to fix that! So, click the "New..." button, enter "Jython 2.5.0" as the "Interpreter Name", click the "Browse..." button and find the jython.jar inside your Jython 2.5.0 installation. Note Even if this is the only runtime we will use on this chapter, I recommend you to use a naming schema like the one proposed here, including both the implementation name (e.g.: "Jython") and the full version (e.g.: "2.5.0") the following picture (of course, your filesystem paths will differ): my experience, it's rarely needed to change most of the other options available. In the next sections we will take a look to the more important PyDev features to have a more pleasant learning experience and make you more productive. Hello PyDev!: Creating Projects and Executing Modules Once you see the first piece of example code on this chapter, it may seem over simplistic. It is, indeed, a very dumb example. The point is to keep the focus on the basic steps you will perform for the lifecycle of any Python-based project inside the Eclipse IDE, and which will apply on simple and complex projects. So, as you probably guessed it, our first project will be a dumb "Hello World". Let's start it! Go to :menuselection:`File --> New --> Project...`. You will be presented with a potentially long list with all the kind of projects you can create with Eclipse. Select "PyDev Project", under the "PyDev" group (you can also use the filter text box at the top and just type "PyDev Project" if it's faster for you). The next dialog will ask you for your project properties. As the "Project name", we will use "LearningPyDev". On "Project contents", we will let checked the "Use default" checkbox, so PyDev will create a directory with the same name as the project inside the Eclipse workspace (which is the root path of your eclipse projects). Since we are using Jython 2.5.0, we will change the "Project type" to "Jython" and the "Grammar Version" to "2.5". We will let alone the "Interpreter", which will default to the Jython interpreter we just defined on the Minimal Configuration section. We will also left checked the "Create default 'src' folder and add it to the pythonpath" option since it's a common convention on Eclipse projects. After clicking "Finish" PyDev will create your project, which will only contain an empty src directory and a reference to the interpreter being used. Let's create our program now! Right click on the project, and select :menuselection:`New --> PyDev Module`. Let the "Package" blank and enter "main" as the "Name". PyDev offers some templates to speed up the creation of new modules, but we won't use them, as our needs are rather humble. So let the "Template" as empty and click "Finish". PyDev will present you an editor for the main.py file it just created. It's time to implement our program. Write the following code at the editor: if __name__ == "__main__": print "Hello PyDev!" And then press Ctrl + F11 to run this program. Select "Jython Run" from the dialog presented and click OK. The program will run and the text "Hello PyDev!" will appear on the console, located on the bottom area of the IDE. If you manually typed the program, you probably noted that the IDE knows that in Python a line ending in ":" the image: Expect the same kind of feedback for whatever syntax error you made. It helps to avoid the frustration of going on edit-run loops only to find further minor syntax errors. Passing Command-line Arguments and Customizing Execution Command line arguments may seem old-fashioned, but are actually a very simple and effective way to let programs interact with the outside. Since you have learned to use Jython as a scripting language, it won't be uncommon to write scripts which will take its like: import sys if __name__ == "__main__": if len(sys.argv) < 2: print "Sorry, I can't greet you if you don't say your name" else: print "Hello %s!" % sys.argv[1] If you hit Ctrl + F11 again, you will see the "Sorry I can't greet you..." message on the console. It makes sense, since you didn't pass the name. Not to say that it was your fault, as you didn't have any chance to say your name either. To specify command line arguments, go to the :menuselection:`Run --> Run Configurations...` menu, and you will find an entry named "LearningPyDev main.py" under the "Jython Run" section in the left. It will probably be already selected, but if it's not, select it manually. Then, on the main section of the dialog you will find ways to customize the execution of our script. You can change aspects like the current directory, pass special argument to the JVM, change the interpreter to use, set environment variables, among others. We just need to specify an argument so let's type "Bob" on the "Program arguments" box and click the "Run" button. As you'd expect, the program now prints "Hello Bob!" on the console. Note that the value you entered is remembered, that is, if you press Ctrl + F11 now, the program will print "Hello Bob!" again. Some people may point out that this behavior makes testing this kind of programs very awkward, since the "Run Configurations" dialog will have to be opened each time the arguments need to be changed. But if we really want to test our programs (which is a good idea), we should do it in the right way. We will look into that soon, but first lets finish our tour on basic IDE features. Playing with the Editor Let's extend our example code a bit more. providing different ways to greet our users, in different languages. We will use the optparse to process the arguments this time. Refer to Chapter 8 if you want to remember how to use optparse. We will also use decorators (seen in Chapter 6) to make it trivial to extend our program with new ways to greet our users. So, our little main.py has grown a bit now: # -*-, which is the shortcut for automatic code completion (also known as "Intellisense" out, if the IDE knows enough about the symbol you just typed to provide help. But you can also call for help at any given point. For example, go to the bottom of the code and type message(. Suppose you just forgot the order of the parameters to that function. Solution: Press Ctrl + Space and PyDev will "complete" the statement, using the name of the formal parameters of the function. Also try Ctrl + Space on keywords like def. PyDev will provide you little templates which may save you some typing. You can customize the templates on the :menuselection:`PyDev --> Editor --> Templates` section of the Eclipse Preferences window (available on the :menuselection:`Window --> Preferences` main menu). The other thing you may have noted now that we have a more sizable program with some imports, functions and global variables is the "Outline" panel in the right side of the IDE window shows a tree-structure view of code being edited showing such features. It also displays classes, by the way. And don't forget to run the code! Of course, it's not much spectacular to see that after pressing Ctrl + F11 we still get the same boring "Hello Bob!" text on the console. But if you edit the command line argument (as seen recently, via the "Run Configurations..." dialog) to the following: Bob --lang es --ui window, you will get a nice window greeting Bob in Spanish. Also see what happens if you specify a non supported UI (say, --ui speech) or extra section and we will get into a better way to test our program using the IDE. Actually, part of the next section will help us towards the solution. Testing OK, it's about time to explore our options to test our code, without resorting to the cumbersome manual black box testing we have been done changing the command line argument and observing the output. PyDev supports running PyUnit tests from the IDE, so we will write them. Let's create a module named tests on the hello package with the following code: tests above. Just right click on the src folder on the Package Explorer and select :menuselection:`Run As --> Jython unit-test`. You will see the output of the test almost immediately on the console: 19, so take a look at that chapter if you feel too disoriented. The nice thing about doctests is that they look like a interactive session with the interpreter, which makes them quite legible and easy to create. We will test our console module using a doctest. First, click the rightmost button on the console's toolbar (you will recognize it as the one with a plus sign on its upper left: >>> from hello import console >>> console.print_message("testing") testing I which will serve to automatically check that the behavior we just tested will stay the same in the future. Create a module named doctests inside the hello package, and paste those three lines from the interactive console, surrounding them by triple quotes (since they are not syntactically correct python code after all). After adding a little of boilerplate to make this file executable, it will look like this: """ >>> from hello import console >>> console.print_message("testing") testing """ if __name__ == "__main__": import doctest doctest.testmod(verbose=True) After doing this, you can run this test via the :menuselection:`Run --> Jython run` menu while doctests.py is the currently active file on the editor. If all goes well, you will get the following output:down menu select the "PyDev Console" as shown in the next image. As you can see, you can use the interactive console to play with your code, try ideas and test them. And later a simple test can be made just by copying and pasting text from the same interactive console session. Of special interest is the fact that, since Jython code can access Java APIs quite easily, you can also test classes written with Java in this way! Adding Java libraries to the project Finally, I will show you how to integrate Java libraries into your project. When testing the command line switches some pages ago, I hinted that we could have an "speech" interface for our greeter. It doesn't sound like a bad idea after all, since (like :menuselection:`General --> File System` and browse to the directory in which you expanded FreeTTS and select it. Finally, expand the directory on the left side panel and check the lib subdirectory. See the following image as reference. After clicking finish you will see that the file is now part of your project. Tip Alternatively, and depending on your operating system, the same operation can be performed copying the folder from the file manager and pasting it into the project (either via menu, keyboard shortcuts or drag & drop). Now, the file is part of the project, but we need to tell PyDev that the file is a JAR file and should be added to the sys.path of our project environment. To do this right click on the project and select "Properties". Then on the left panel of the dialog select "PyDev - PYTHONPATH". Then click the "Add zip/jar/egg" button and select the lib/freetts.jar file on the right side of the dialog that will pop out. Click OK on both dialogs and you are ready to use this library from Python code. The code for our new hello.speech module is as follows: quick you can move with the power of Jython, the diversity of Java and the help of an IDE. Other topics I have covered most of the PyDev features, but I've left a few unexplored. We will take a look at what we've missed before ending this half-chapter dedicated to PyDev. Debugging PyDev offers full debugging abilities for your Jython code. To try it just put some breakpoints on your code double clicking on the left margin of the editor, and then start your program using the F11 shortcut instead of Ctrl + F11. Once the debugger hits your breakpoint, the IDE will ask you to change its perspective. It means that it will change to a different layout, better suited for debugging activities. Answer yes to such dialog and you will find yourself on the debugging perspective which looks like the following image: In few words, the perspective offers the typical elements of a debugger: the call stack, the variables for each frame of the call stack, a list of breakpoints, and the ability to "Step Into" (F5), "Step Over" (F6) and "Resume Execution" (F8) among others. Once you finish your debugging session, you can go back to the normal editing perspective by selecting "PyDev" on the upper right area of the main IDE Window (which will have the "Debug" button pushed while staying in the debugging perspective). Refactoring PyDev also offers some basic refactoring abilities. Some of them are limited to CPython, but others, like "Extract Method" work just fine with Jython projects. I encourage you to try them to see if they fit your way of work. Sometimes you may prefer to refactor manually since the task tend do not be as painful as in Java (or any other statically typed language without type inference). On the other hand, when the IDE can do the right thing for you and avoid some mechanical work, you will be more productive. (Half-)Conclusion PyDev is a very mature plugin for the Eclipse platform which can be an important element in your toolbox. Automatic completion ans suggestions helps a lot when learning new APIs (both Python APIs and Java APIs!) specially if paired with the interactive console. It is also a good way to introduce a whole team into Jython or into an specific Jython project, since the project-level configuration can be shared via normal source control system. Not to mention that programmers coming from the Java world will find themselves much more comfortable on a familiar environment. To me, IDEs are a useful part of my toolbox, and tend to shine on big codebases and/or complex code which I don't completely understand yet. Powerful navigation and refactoring abilities are key on the process of understanding such kind of projects and are features that should only improve in the future. Finally, the debugging capabilities of PyDev are superb and will end your days of using print as a poor man's debugger (Seriously, I did that for a while!). Even more advanced Python users who master the art of import pdb; pdb.set_trace() should give it a try. Now, this is a "half-conclusion" plugin for Python development. Netbeans, Jython, Groovy, and Scala have earned themselves a niche in the tool as well. Most of these languages are supported as plugins to the core development environment, which is what makes Netbeans such an easy IDE to extend as it is very easy to build additional features to distribute. The Python support within Netbeans began as a small plugin. IDE Installation and Configuration The first step for installing the Netbeans Python development environment is to download the current release of the Netbeans IDE. At the time of this writing, Netbeans 6.7 was the most recent release, hot off the presses in fact. You can find the IDE download by going to the website configuration my everyday development, I use the “All” option as I enjoy having all of the options available. However, there are options available for adding features if you download only the Java SE or another low-profile build and wish to add more later. At the time of this writing, there was also a link near the top of the downloads page for PythonEA distribution. If that link or a similar Python Netbeans distribution link is available then you can use it to download and install just the Jython-specific features of the Netbeans IDE. I definitely do not recommend taking this approach unless you plan to purely code Jython applications alone. It seems to me that a large population of the Jython developer community also codes some Java, and may even integrate Java and Jython within their applications. If this is the case, you will want to have the Java-specific features of Netbeans available as well. That is why I do not recommend the Python-only distribution for Jython developers, but the choice is there for you to make. Now that you’ve obtained the IDE, plugin via the Netbeans plugin center. You will need to go to the Tools menu and then open the Plugins *submenu. From there, you should choose the *Available Plugins tab and sort by category. Select all of the plugins in the Python category and then install. This option will install the Python plugin as well as a distribution of Jython. You will need to follow on-screen directions to complete the installation. Once the plugin plugin was 2.5b0+, even though 2.5.0 final has been release. As this is the case, go ahead and add your Jython 2.5.0 final installation as a platform option and make it the default. To do so, click on the New button underneath the platform listing. You can try to select the Auto Detect option, but I did not have luck with Netbeans finding my Jython installation for 2.5.0 final. Advanced Python Options If you enter the Netbeans preferences window then you will find some more advanced options for customizing your Python plugin. then our Jython files with the extension of jy, we could easily do so and associate this extension with Python files in Netbeans. Once we’ve made this association then we can create files with an extension of jy and use them within Netbeans just as if they were Python files. Lastly, you can alter a few basic options such as enabling prompting for python program arguments, and changing debugger port and shell colors from the Python tab in Netbeans preferences. General Jython Usage As stated previously in the chapter, there are a number of options when using the Netbeans Python solution. There are a few different selections that can be made when creating a new Jython project. You can either choose to create a Python Project or Python Project with Existing Sources. These two project types are named quite appropriately as a Python Project will create an empty project, and Once created it is easy to develop and maintain applications and scripts alike. Moreover, you can debug your application and have Netbeans create tests if you choose to do so. One of the first nice features you will notice is the syntax coloring in the editor. There is also testing available via the debugging Stand Alone Jython Apps In this section, I will discuss how to develop a stand-alone Jython application within Netbeans. We will use a variation of the standard HockeyRoster application that I have used in other places throughtout the book. Overall, the development of a stand alone Jython application in Netbeans differs very little from a stand alone Java application. The main difference is that you will have different project properties and other options available that pertain to creating Jython. And obviously you will be developing in Jython source files along with all of the color coding and code completion that the Python plugin View, etc. depending upon the options chosen. At this point, create the Main module for the HockeyRoster application by using the File and then New drop-down menu, right-clicking (cntrl-click) on the project, or using the toolbar icon. From here you can either create an Executable Module, Module, Empty Module, Python Package, or Unit Test. Chooose to create an Executable Module and name the main file HockeyRoster.py, and keep in mind that when we created the project we had the ability to have the IDE generate this file for us but we chose to decline. Personally, I like to organize my projects using the Python packaging system. Create a some packages now using the same process that you used to create a file and name the package org. Add another package within the first and name it jythonbook. Once created, drag your HockeyRoster.py module into the jythonbook package to move it into place. Note that you can also create several packages at the same time by naming a package like org.jythonbook, which will create both of the resulting packages. The HockeyRoster.py main module will be the implementation module for our application, but we still need somewhere to store each of the player's information. For this, we will create class object container named Player.py.. # Player.py # # Class container to hold player information class Player: # Player attributes id = 0 first = None last = None position = None goals = 0 assists = 0 def create(self, id, first, last, position): self.id = id self.first = first self.last = last self.position = position def set_goals(self, goals): self.goals = goals def add_goal(self): self.goals = goals + 1 def get_goals(self): return self.goals def set_assists(self, assists): self.assists = assists def add_assist(self): self.assists = assists + 1 def get_assists(self): return self.assists The first thing to note is that Netbeans will maintain your indentation level. It is also easy to tab backwards as well code below, this is a very basic application and is much the same as the implementation that will be found in the next chapter using Hibernate persistence. # HockeyRoster.py # # Implemenatation logic for the HockeyRoster application # Import Player class from the Player module from Player import Player import shelve import sys # Define a list to hold each of te Player objects playerList = [] factory = None # Define shelve for storage to disk playerData =" makeSelection() else: if selection == '1': addPlayer() elif selection == '2': printRoster() elif selection == '3': searchRoster() elif selection == '4': removePlayer() = returnPlayerCount() + 1 print id #set player and shelve player = Player(id, first, last, position) playerData[str(id)] =.keys(): print "%s %s - %s" % (playerList[player].first, playerList[player].last, playerList() for playerKey in playerList.keys(): player = playerList[playerKey] if player.first.upper() == first.upper() and player.last.upper() == last.upper(): found = True position = player.position() for playerKey in playerList.keys(): player = playerList[playerKey] if player.first.upper() == first.upper() and player.last.upper() == last.upper(): found = True foundPlayer = player if found: print '%s %s is in the roster as %s, are you sure you wish to remove?' % (foundPlayer.first, foundPlayer.last, foundPlayer.position) yesno = raw_input("Y or N") if yesno.upper() == 'Y': # remove player from shelve print 'The player has been removed from the roster', foundPlayer.id del(playerData[str(foundPlayer.id)]) else: print 'The player will not be removed' else: print '%s %s is not in the roster.' % (first, last) makeSelection() def returnPlayerList(): playerList = playerData return playerList def returnPlayerCount(): return len(playerData.keys()) # main # # This is the application entry point. It simply prints the applicaion title # to the command line and then invokes the makeSelection() function. if __name__ == "__main__": print sys.path print "Hockey Roster Application\n\n" playerData = shelve.open("players") makeSelection() The code should be relatively easy to follow at this point in the book. The main function initiates the process as expected, and as you see it either creates or obtains a reference to the shelve or dictionary where the roster is stored. Once this occurs then the processing is forwarded to the makeSelection() function that drives the program. The important thing to note here is that when using Netbeans the code is layed then you should see the program output displaying in the Netbeans output window. You can interact with the output window just as you would with the terminal. Jython and Java Integrated Apps Rather than repeat the different ways in which Jython and Java can be intermixed within an application, this section will focus on how to do so from within the Netbeans IDE. There are various approaches that can be taken in order to perform integration, so this section will not cover all of them. However, the goal is to provide you with some guidelines and examples to use when developing integrated Jython and Java applications within Netbeans. Using a JAR or Java Project in Your Jython App. In order to use this project from within our HockeyRoster project, you'll need to open up the project properties by right-clicking on your Jython project and choosing the Properties option. Once the window is open then click on the Python menu item on the left-hand side of the window. This will give you access to the sys.path so you can add other Python modules, eggs, Java classes, JAR files, etc. Click on the Add button and then traverse to the project directory for the Java application you are developing. Once there, go within the dist directory and select the resulting JAR file and click OK. You can now use any of the Java project's features from within your Jython application. If you are interested in utilizing a Java API that exists within the standard Java library then you are in great shape. As you should know by now, Jython automatically provides access to the entire Java standard library. You merely import the Java that you wish to use within your Jython applicaton and begin using, nothing special to set up within Netbeans. At the time of this writing, the Netbeans Python EA did not support import completion for the standard Java library. However, I suspect that this feature will be added in a subsequent release. Using Jython in Java this writing. For the purposes of this section, we'll discuss how to utilize another Netbeans Jython project as well as other Jython modules from within your Java applicaton using the "New->Project->Java Application" selection. Once you've done so, right-click (CNTRL+CLICK) on the project and choose Properties. Once the project properties window appears, click on.0 release. The next step is to ensure that any and all Jython modules that you wish to use are in your CLASSPATH somewhere. This can be easily done by either adding them into your application as regular code modules somewhere and then going into the project properties window and including that directory in "Compile-Time Libraries" list contained the Libraries section by using the "Add JAR/Folder" button. Although this step may seem unncessary because the modules are already part of your project, it must be done in order to place them into your CLASSPATH. Once they've been added to the CLASSPATH successfully then you can begin to make use of them via the object factory pattern. Netbeans will seamlessly use the modules in your application as if all of the code was written in the same language. Developing Web Apps (Django, etc) As of the time of this writing, Netbeans has very little support for developing Jython web applications as far as frameworks go. Developing simple servlets and/or applets with Jython are easy enough with just creating a regular web application and setting it up accordingly. However, making full use of a framework such as Django from within Netbeans is not available as of version 6.7. There are many rumors and discussions in the realm of a Django plugin to become part of the Netbeans 7 release, but perhaps that will be covered in a future edition of this book. In the meantime we need to make use of Netbeans in it's current form, without a plugin specifically targeted for Jython web development. Although there are a few hurdles and none of the frameworks can be made completely functional from within the tool, there are some nice tricks that can be played in order to allow Jython web development worth executing within Netbeans. In order to deploy a standard web application in Netbeans and make use of Jython servlets and/or applets, simply create a standard web application and then code the Jython in the standard servlet or applet manner. Since there are no plugins to support this work it is all a manual process. Something tells me that making use of the fine code completion and semantec code coloring is a nice perk even if there aren't any wizards to assist you in coding your web.xml configuration. Since there are not any wizards to help us out, we will only mention that Netbeans makes standard web Jython web development easier by utilizing the features of the IDE, not abstracting away the coding and instead completing wizards. Using Django in Netbeans As stated at the beginning of this section, it is not a very straight forward task if you wish to develop Jython web applications utilizing a standard framework from within Netbeans. However, with a little extra configuration and some manual procedures it is easy enough to do. In this section I will demonstrate how we can make use of Netbeans for developing a Django application without using any Netbeans plugins above and beyond the standard Python support. You will see that Jython applicatons can be run, tested, and verified from within the IDE with very little work. Since there are a few steps in this section that may be more difficult to visualize, please use the provided screen shots to follow along if you are not using Netbeans while reading this text. In order to effectively create and maintain a Django website, you need to have the ability to run commands against manage.py. Unfortunately, there is no built in way to easily do this within the IDE so we have to use the terminal or command line along with the IDE to accomplish things. Once we create the project and set it up within Netbeans then we can work with developing it from within Netbeans and you can also set up the project Run feature to startup the Django server. Assuming that you already have Django setup and configured along with the Django-Jython project on your machine, the first step in using a Django project from within Netbeans is actually creating the project. If you are working with a Django project that has already been created then you can skip this step, but if not then you will need to go to the terminal or command-line and create the project using django-admin.py. For the purposes of this tutorial, let's call our Django site NetbeansDjango. django-admin.py startproject NetbeansDjango Now we should have the default Django site setup and we're ready to bring it into Netbeans. To do this, start a new Python project within Netbeans using the Python Project with Existing Sources option, and be sure to set your Python Platform to Jython 2.5.0 so we are using Jython. After hitting the Next button we have the ability to add sources to our project. Hit the Add button and choose the select the main project folder, so in our case select the NetbeansDjango folder. This will add our project root as the source root for our application. In turn, it adds our Django setup files such as manage.py to our project. After doing so your project should look something like the following screenshot., etc. webserver to start up. At this point, we are ready to begin developing our Django application. So with a little minor setup and some use of the terminal or command-line we are able to easily use Netbeans for developing Django projects. There are a few minor inconsistencies with this process however, note that there is no real integrated way to turn off the webserver as yet so once it is started we can either leave it running or stop it via your system process manager. Otherwise you can hook up different options to the Netbeans Run project command such as syncdb by simply choosing a different application argument in the project properties. If you use this methodology, then you can simply start and stop the Django web server via the terminal as normal. I have also found that after running the Django web server you will have to manually delete the settings$.py.class file that is generated before you can run the server again or else it will complain. In future versions of Netbeans, namely the Netbeans 7 release, it is expected that Django functionality will be built into the Python support. We will have to take another look at using Django from within Netbeans at that time. For now, this procedure works and it does a fine job. You can make use of similar procedures to use other web frameworks such as Pylons from within Netbeans. Conclusion As with most other programming languages, you have several options to use for an IDE when developing Jython. In this chapter we covered two of the most widely used IDE options for developing Jython applications, Netbeans and Eclipse. Eclipse offers a truely complete IDE solution for developing Jython applications, both stand alone and web based. Along with the inclusion of the Django plugin for Eclipse, the IDE makes it very easy to get started with Jython development and also manage existing projects. PyDev is under constant development and always getting better, adding new features and streamlining existing features. Netbeans Jython support is in still in early.
https://bitbucket.org/javajuneau/jythonbook/src/dd1b66e2cbfd8d3dead99db68ee3b34e87966525/chapter11.rst
CC-MAIN-2015-35
refinedweb
5,964
62.17
. Silverlight 2 provides a Socket class located in the System.Net.Sockets namespace (a Silverlight namespace...not the .NET Framework namespace mentioned earlier) that can be used to connect a client to a server to send and/or receive data. The Socket class works in conjunction with a SocketAsyncEventArgs class to connect and send/receive data. The SocketAsyncEventArgs class is used to define asynchronous callback methods and pass user state between those methods (such as the Socket object that originally connected to the server). An example of using the Socket and SocketAsyncEventArgs classes is shown next:); } This code can be called which accepts a SocketAsyncEventArgs object as a parameter. When the client is connected to the server the following method is called which creates a buffer to hold data received from the server and rewires the SocketAsyncEventArgs's Completed event to a different callback method named OnSocketReceive:); } The Socket object's ReceiveAsync() method is then called to begin the process of accepting data from the server. As data is received the OnSocketReceive() method is called which handles deserializing XML data returned from the server into CLR objects that can be used in the Silverlight client.); } The deserialization process is handled by the XmlSerializer class which keeps the code nice and clean. Alternatively, the XmlReader class could be used or the LINQ to XML technology that's available in Silverlight. Notice that data is routed back to the UI thread by using the Dispatcher class's BeginInvoke() method. If you've worked with Windows Forms before then this should look somewhat familiar. That's all there is to work with sockets in a Silverlight client. There's certainly some work involved, but many of the complexities are hidden away in the Socket and SocketAsyncEventArgs classes which both minimize the need to work with threads directly. I've already shown what the client interface looks like as data is updated but here it is one more time (click the image to see an animated gif of the application in action): The complete code for the Silverlight client and server application can be downloaded here. In <a href="weblogs.asp.net/controlpanel Nice stuff Dan! Sorry I missed you at the MVP Summit. --Peter My brother once argued that Java was the language of the Internet, I countered that it was TCPIP :) Thanks for the sockets article! Glen, Good counter. :-) Glad you found the article useful. Peter, We definitely need to "officially" meet one of these days. There's a bunch of people I missed while up there unfortunately but maybe next time. Wow this is a great example and it works great even on my 64 bit Windows XP. Silverlight 2 provides built-in support for sockets which allows servers to push data to Silverlight Silverlight provides several different ways to access data stored in remote locations. Data can be pulled
http://weblogs.asp.net/dwahlin/archive/2008/04/13/pushing-data-to-a-silverlight-client-with-sockets-part-ii.aspx
crawl-002
refinedweb
479
61.97
I looked into this with the help of @mpickering who identified this line as the source of the problem. It filters out any MGs with an origin that is not FromSource. If we remove this guard, we do get all identifiers (great!), but unfortunately, the resulting HieAST is not very helpful. Take the following: {-# language TemplateHaskell #-} {-# options -ddump-splices #-} module Extra where import Control.Lens.TH data Foo = Foo { _fooFoo :: Int } makeClassy ''Foo The splice produces src/Extra.hs:11:1-16: Splicing declarations makeClassy ''Foo ======> class HasFoo c_a19bV where foo :: Control.Lens.Type.Lens' c_a19bV Foo fooFoo :: Control.Lens.Type.Lens' c_a19bV Int {-# INLINE fooFoo #-} fooFoo = ((.) foo) fooFoo instance HasFoo Foo where {-# INLINE fooFoo #-} foo = id fooFoo = (Control.Lens.Iso.iso (\ (Foo x_a19bW) -> x_a19bW)) Foo But the resulting HieAST compresses this all into a single node: Node src/Extra.hs:9:1-16 [(AbsBinds, HsBindLR), (ClassDecl, TyClDecl), (ClassOpSig, Sig), (ClsInstD, InstDecl), (ConPatIn, Pat), (ConPatOut, Pat), (FunBind, HsBindLR), (GRHS, GRHS), (HsApp, HsExpr), (HsAppTy, HsType), (HsConLikeOut, HsExpr), (HsLam, HsExpr), (HsPar, HsExpr), (HsTyVar, HsType), (HsVar, HsExpr), (HsWrap, HsExpr), (InlineSig, Sig), (Match, Match), (UserTyVar, HsTyVarBndr), (VarBind, HsBindLR)] [0, 1, 3, 10, 13, 19, 20, 24, 27, 29, 34, 39, 43, 46, 49, 60, 73, 31, 30] [(Right C:HasFoo, IdentifierDetails Nothing {Use}), (Right fooFoo, IdentifierDetails Just 43 {Use, MatchBind, ValBind InstanceBind ModuleScope (Just SrcSpanOneLine "src/Extra.hs" 9 1 17), ClassTyDecl (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right foo, IdentifierDetails Just 46 {Use, MatchBind, ValBind InstanceBind ModuleScope (Just SrcSpanOneLine "src/Extra.hs" 9 1 17), ClassTyDecl (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right iso, IdentifierDetails Just 73 {Use}), (Right ., IdentifierDetails Just 60 {Use}), (Right id, IdentifierDetails Just 39 {Use}), (Right fooFoo, IdentifierDetails Just 19 {MatchBind, ValBind RegularBind ModuleScope (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right $cfooFoo, IdentifierDetails Just 31 {Use}), (Right foo, IdentifierDetails Just 24 {MatchBind, ValBind RegularBind ModuleScope (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right $cfoo, IdentifierDetails Just 30 {Use}), (Right fooFoo, IdentifierDetails Just 10 {MatchBind, ValBind RegularBind ModuleScope (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right x, IdentifierDetails Just 0 {Use}), (Right Foo, IdentifierDetails Nothing {Use}), (Right HasFoo, IdentifierDetails Nothing {Decl ClassDec (Just SrcSpanOneLine "src/Extra.hs" 9 1 17)}), (Right c, IdentifierDetails Nothing {Use, TyVarBind NoScope [LocalScope SrcSpanOneLine "src/Extra.hs" 9 1 17,LocalScope SrcSpanOneLine "src/Extra.hs" 9 1 17]})] I believe this is because everything has the same SrcSpan, and the merging logic is collapsing everything. I'll have to study this more, as I'm not currently sure what to do.. The full instance declaration is visible. Is related? I had to remove -optP --layout -optP --hashes -optP --cpp, otherwise during profiling the build fails with: cc1: error: unrecognized command line option ‘--layout’ cc1: error: unrecognized command line option ‘--hashes’ cc1: error: unrecognized command line option ‘--cpp’ Meanwhile, can't you already do this with Template Haskell (with a bit of more syntactic noise)? I don't believe I can, as I need access to the type checker to see which things I can Show. Thanks for the link to Native Metaprogramming, I'll have a read. I'm currently playing around with a little project that attempts to replicate py.test. For context about py.test, see\#tbreportdemo, but essentially it's a Python library that provides an assert :: Bool -> IO () function, with the magic that if the assertion fails, it shows you some context about the Bool expression: def test_simple(self): def f(): return 42 def g(): return 43 > assert f() == g() E assert 42 == 43 For example, shows that f() evaluated to 42. I'd like to do something like this for Haskell, and a GHC plugin seemed like the right place to do this. I first wrote a core-to-core plugin () which finds free variables and and attempts to Show them. This works, but I'd like to do more. As an example of something I'd like to do, I would like to let my users write assert (and [x > 0 | x <- [-1, 0]). This is a failing assertion, and I would like to show a kind of evaluation trace, something like and [x > 0 | x <- [-1, 0] = and [False, False] = False To do this, I really need access to HsSyn, not CoreExpr. Template Haskell won't do, because I don't know what I can Show - I really need access to the type checker as well. A plugin that fires right before the desugarer would be really nice for this kind of task. Specifically, I only want to export the type of the newtype ( T), and the pattern synonym MkT2. The "real" constructor MkT for the newtype is internal to the module and not exported. In my actual work, Impl is a record with ~10 fields, and I want to have a newtype over Impl that looks like a record with 10 fields, though they will have different names (proxying to the underlying fields in Impl). So yes, what Simon comments with is indeed what I would like to be able to do (though I wouldn't export MkT). The following currently fails to compile: {-# LANGUAGE PatternSynonyms #-} module A( T( MkT2 ) ) where data Impl = Impl Int newtype T = MkT Impl pattern MkT2 {x} = MkT (Impl x) {-# LANGUAGE RecordWildCards #-} module B where import A foo :: T -> Int foo MkT2{x} = x As far as GHC can see, in module B, MkT2 does not have a field x. The fix is to manually export x from A: module A (T(MkT2, x)) where But this is tedious for records with a large amount of fields This only happens with -fobject-code. If that's not on, then it does indeed load the interpreted version. I just had the following very confusing exchange with GHCI: λ :load Ok, modules loaded: none. λ :load src/Application/Aws.hs Ok, modules loaded: Application.Aws (dist/build/Application/Aws.o). λ private <interactive>:3:1: error: Variable not in scope: private λ :m *Application.Aws module 'Application.Aws' is not interpreted; try ':add *Application.Aws' first). λ :! ghc --version The Glorious Glasgow Haskell Compilation System, version 8.1.20161115 This can really be simplified to λ :load src/Application/Aws.hs Ok, modules loaded: Application.Aws (dist/build/Application/Aws.o).). For the record, here is Application.Aws: {-# LANGUAGE DeriveDataTypeable #-} module Application.Aws ( AwsExtra(..) ) where import Prelude import Data.Data (Data) import Data.ByteString.Char8 import Data.Text data AwsExtra = AwsExtra { awsKey :: ByteString , awsSecret :: ByteString , awsS3AssetsBucket :: Text } deriving (Show,Data) private :: Int private = 42 I think I'm running into the same bug. A super minimal example is: {-# LANGUAGE RecordWildCards #-} data A = A { b :: Bool } f = case [] of (_:_) -> a {b = True} With -fdefer-type-errors turned on. Do we think this is the same bug? I think so - haven't seen a panic since! Let's go ahead and close this Oddly this only happens on our build server, not on my local machine. On compilation, I get: [187 of 273] Compiling Query.Order ( Query/Order.hs, dist/build/Query/Order.o ) Query/Order.hs:340:1: warning: [-Wredundant-constraints] • Redundant constraint: MonadBaseControl IO m • In the type signature for: updateOrdersSuccess :: (MonadBaseControl IO m, MonadTransaction m) => m () ghc: panic! (the 'impossible' happened) (GHC version 8.0.1 for x86_64-unknown-linux): piResultTy Maybe Int64 a1_a4WiL Please report this as a GHC bug: The configuration parameters are: configureFlags: --verbose --prefix=/nix/store/qxfjd5jxr593dn43i3659s86d0rdllyv-circuithub-api-0.0.4 --libdir=$prefix/lib/$compiler --libsubdir=$pkgid --with-gcc=gcc --package-db=/tmp/nix-build-circuithub-api-0.0.4.drv-0/package.conf.d --ghc-option=-j1 --disable-split-objs --disable-library-profiling --disable-profiling --disable-shared --enable-library-vanilla --disable-executable-dynamic --disable-tests I've attached Query/Order.hs, but you won't be able to compile it stand-alone. If I only supply one context, which context am I supplying? The provided one, or the required one? That is, are you suggesting pattern Cast :: () => Typeable b => ... or pattern Cast :: Typeable b => () => ...? I actually believe the correct type of this pattern is pattern Cast :: () => Typeable a => a -> T pattern Cast a <- MkT (cast -> Just a) But this is also rejected: • Could not deduce (Typeable a0) arising from a use of ‘cast’ from the context: Typeable a bound by a pattern with constructor: MkT :: forall a. Typeable a => a -> T, in a pattern synonym declaration at ../foo.hs:9:19-38 The type variable ‘a0’ is ambiguous • In the pattern: cast -> Just a In the pattern: MkT (cast -> Just a) In the declaration for pattern synonym ‘Cast’ I may be wrong with that type though.’
https://gitlab.haskell.org/ocharles.atom
CC-MAIN-2019-51
refinedweb
1,439
54.93
Board index » VB.Net All times are UTC public class MyItem public Text as string public Value as integer public sub new(Text as string,Value as integer) me.text=text me.value=value end sub public overrides function ToString as string return text end function end class '... fill listbox: listbox1.items.add(new myitem("item1",1")) listbox1.items.add(new myitem("item2",2")) The value returned by the ToString function is the one displayed in the listbox. -- Armin You can modify it according to your needs. -- Alan Ram >. \\\ Dim p As Person = New Person() p.Name = "Pink Panther" p.Age = 22 Me.ComboBox1.Items.Add(p) MessageBox.Show(DirectCast(Me.ComboBox1.Items.Item(0), Person).ToString()) . . . Public Class Person Private m_strName As String Private m_ingAge As Integer Public Property Name() As String Get Return m_strName End Get Set(ByVal Value As String) m_strName = Value End Set End Property Public Property Age() As Integer Get Return m_intAge End Get Set(ByVal Value As Integer) m_intAge = Value End Set End Property Public Overrides Function ToString() As String Return m_strName & " (" & m_intAge.ToString() & ")" End Function End Class /// Regards, Herfried K. Wagner -- 1. Capturing item values from multiselect listbox 2. Selected Listbox Item using ItemData value??? 3. Different Text Color for each item in a ListBox 4. ListBox - get item text 5. Changing the text color of a listbox item 6. Write contents of listbox to text file/populate listbox from text file 7. Listbox.Text to integer value 8. Save Text Boxes Values To Combo Box's Item 9. Usering script to display the contents(text,value) of the option of a html listbox 10. Populating listbox with values from a text file 11. Move ListBox items to another ListBox 12. Listbox with single character item corrupts item?
http://computer-programming-forum.com/6-vbdotnet/c0fb167fe5f73454.htm
CC-MAIN-2020-50
refinedweb
295
60.61
Library Interfaces and Headers - base signals #include <signal.h> A signal is an asynchronous notification of an event. A signal is said to be generated for (or sent to) a process when the event associated with that signal first occurs. Examples of such events include hardware faults, timer expiration and terminal activity, as well as the invocation of the kill(2) or sigsend(2) functions. In some circumstances, the same event generates signals for multiple processes. A process may request a detailed notification of the source of the signal and the reason why it was generated. See siginfo.h(3HEAD). Signals can be generated synchronously or asynchronously. Events directly caused by the execution of code by a thread, such as a reference to an unmapped, protected, or bad memory can generate SIGSEGV or SIGBUS; a floating point exception can generate SIGFPE; and the execution of an illegal instruction can generate SIGILL. Such events are referred to as traps; signals generated by traps are said to be synchronously generated. Synchronously generated signals are initiated by a specific thread and are delivered to and handled by that thread. Signals may also be generated by calling kill(), sigqueue(), or sigsend(). Events such as keyboard interrupts generate signals, such as SIGINT, which are sent to the target process. Such events are referred to as interrupts; signals generated by interrupts are said to be asynchronously generated. Asynchronously generated signals are not directed to a particular thread but are handled by an arbitrary thread that meets either of the following conditions: The thread is blocked in a call to sigwait(2) whose argument includes the type of signal generated. The thread has a signal mask that does not include the type of signal generated. See pthread_sigmask(3C). Each process can specify a system action to be taken in response to each signal sent to it, called the signal's disposition. All threads in the process share the disposition. The set of system signal actions for a process is initialized from that of its parent. Once an action is installed for a specific signal, it usually remains installed until another disposition is explicitly requested by a call to either sigaction(), signal() or sigset(), or until the process execs(). See sigaction(2) and signal(3C). When a process execs, all signals whose disposition has been set to catch the signal will be set to SIG_DFL. Alternatively, a process may request that the system automatically reset the disposition of a signal to SIG_DFL after it has been caught. See sigaction(2) and signal(3C). A signal is said to be delivered to a process when a thread within the process takes the appropriate action for the disposition of the signal. Delivery of a signal can be blocked. There are two methods for handling delivery of a signal in a multithreaded application. The first method specifies a signal handler function to execute when the signal is received by the process. See sigaction(2). The second method in the process unblocks it. If the action associated with a signal is set to ignore the signal then both currently pending and subsequently generated signals of this type are discarded immediately for this process. The determination of which action is taken in response to a signal is made at the time the signal is delivered to a thread within the process, allowing for any changes since the time of generation. This determination is independent of the means by which the signal was originally generated. The signals currently defined by <signal.h> are as follows: The symbols SIGRTMIN through SIGRTMAX are evaluated dynamically specify one of three dispositions for a signal: take the default action for the signal, ignore the signal, or catch the signal. A disposition of SIG_DFL specifies the default action. The default action for each signal is listed in the table above and is selected from the following: When it gets the signal, the receiving process is to be terminated with all the consequences outlined in exit(2). When it gets the signal, the receiving process is to be terminated with all the consequences outlined in exit(2). In addition, a ``core image'' of the process is constructed in the current working directory. When it gets the signal, the receiving process is to stop. When a process is stopped, all the threads within the process also stop executing. When it gets the signal, the receiving process is to ignore it. This is identical to setting the disposition to SIG_IGN. A disposition of SIG_IGN specifies that the signal is to be ignored. Setting a signal action to SIG_IGN for a signal that is pending causes the pending signal to be discarded, whether or not it is blocked. Any queued values pending are also discarded, and the resources used to queue them are released and made available to queue other signals. A disposition that is a function address specifies that, when it gets the signal, the thread within the process that is selected to process the signal will execute the signal handler at the specified address. Normally, the signal handler is passed the signal number as its only argument. If the disposition was set with the sigaction(2) function, however, additional arguments can be requested. When the signal handler returns, the receiving process resumes execution at the point it was interrupted, unless the signal handler makes other arrangements. If an invalid function address is specified, results are undefined. If the disposition has been set with the sigset() or sigaction(), the signal is automatically blocked in the thread while it is executing the signal catcher. If a longjmp() is used to leave the signal catcher, then the signal must be explicitly unblocked by the user. See setjmp(3C), signal(3C) and sigprocmask(2). If execution of the signal handler interrupts a blocked function call, the handler is executed and the interrupted function call returns -1RT) function, support the specification of an application defined value, either explicitly as a parameter to the function, or in a sigevent structure parameter. The sigevent structure is defined by <signal.h> and contains at least the following members: The sigval union is defined by <signal.h> and contains at least the following members: The sigev_notify member specifies the notification mechanism to use when an asynchronous event occurs. The sigev_notify member may be defined with the following values: No asynchronous notification is delivered when the event of interest occurs. A queued signal, with its value application-defined, is generated when the event of interest occurs.. Your implementation may define additional notification mechanisms. The sigev_signo member specifies the signal to be generated. The sigev_value member references the application defined value to be passed to the signal-catching function at the time of the signal delivery as the si_value member of the siginfo_t structure. The sival_int member is used when the application defined value is of type int, and the sival_ptr member is used when the application defined value is a pointer. When a signal is generated by sigqueue(3RT) or any signal-generating function which supports the specification of an application defined value, the signal is marked pending and, if the SA_SIGINFO flag is set for that signal, the signal is queued to the process along with the application specified signal value. Multiple occurrences of signals so generated are queued in FIFO order. If the SA_SIGINFO flag is not set for that signal, later occurrences of that signal's generation, when a signal is already queued, are silently discarded.). Whenever a process receives a SIGSTOP, SIGTSTP, SIGTTIN, or SIGTTOU signal, regardless of its disposition, any pending SIGCONT signal are discarded. Whenever a process receives a SIGCONT signal, regardless of its disposition, any pending SIGSTOP, SIGTSTP, SIGTTIN, and SIGTTOU signals is discarded. In addition, if the process was stopped, it is continued. SIGPOLL is issued when a file descriptor corresponding to a STREAMS file has a “selectable” event pending. See Intro(2). A process must specifically request that this signal be sent using the I_SETSIG ioctl call. Otherwise, the process will never receive SIGPOLL. If the disposition of the SIGCHLD signal has been set with signal or sigset, or with sigaction and the SA_NOCLDSTOP flag has been specified, it will only be sent to the calling process when its children exit; otherwise, it will also be sent when the calling process's children are stopped or continued due to job control. The name SIGCLD is also defined in this header and identifies the same signal as SIGCHLD. SIGCLD is provided for backward compatibility, new applications should use SIGCHLD. The disposition of signals that are inherited as SIG_IGN should not be changed. Signals which are generated synchronously should not be masked. If such a signal is blocked and delivered, the receiving process is killed.
https://docs.oracle.com/cd/E23823_01/html/816-5173/signal.h-3head.html
CC-MAIN-2018-09
refinedweb
1,461
52.6
In a five part video series the SAP HANA Academy‘s Tahir Hussain Babar (Bob) walks through how to set up and use Core Data Services in SAP S/4 HANA. Introduction to CDS – Creating a CAL Instance and Creating an ERP User In the first video of the series Bob details how to get a S/4 HANA instance and how to create the S/4 HANA user that’s necessary for executing the tasks preformed in the series. There are a few prerequisites before you can start this series. First, it’s assumed that you already have a SAP Cloud Appliance Library account and that you have instantiated a solution with an image called S/4 HANA, on premise edition – Fully Activated. When you click on create instance you are creating a few machines: SAP BusinessObjects BI Platform 4.1 server, SAP ERP 607 server on SAP HANA SPS09, and SAP HANA Windows client. Essentially, you’re building three separate servers. Once you have created this instance, if you move your cursor over the solution title, there is a link to a Getting Started document. It’s assumed that you’ve followed all of the steps detailed in the document in order to instantiate your own instance of S/4 HANA. When you log into your Windows instance there will be a pair of tools that you will utilize. One is Eclipse, which is used for development and where you will build the CDSs. Please make sure you’re using the latest version of Eclipse. You should have the HANA Development tools, including the ABAP perspective, updated on a regular basis. The other tool is the SAP Login which is used to access the SAP ERP system. Open Eclipse and then click on Window > Perspective > Open Perspective > Other and choose ABAP to open a new ABAP perspective. To create a new ERP user with all rights, first, open the SAP Logon and log into client 100, which is a preconfigured S4 client, with the default user and password. Next, run the command /nus01 to create a new user. Bob names his user SHA and then clicks the create button. On the Maintain Users screen you must provide a last name in the Address tab and change the default password in the Logon Data tab. Also, in the Profiles tab, you must add SAP_ALL (have all SAP System authorizations) and SAP_New (have new authorizations checks). This essentially creates a copy of the default client 100 user so you will have enough roles and rights to preform the tasks carried out later on in the series. Click on the save icon to finish creating the new user. Next, click on the orange log off button and log in as the new user. As it’s the first time you’re logging in as the new user you will be prompted to change your password. How to Create an ABAP Project and Load Demo Data Below in the second video of the series Bob details how to create a new ABAP project within Eclipse and how to load demo data. In the ABAP perspective in Eclipse right click on the projects window and select New > Project > ABAP > ABAP Project and then click Next. Choose to define the system connection manually. Enter your System ID – Bob’s is S4H. The Application Server is the IP address of your ERP system. Also, enter your Instance ID (Bob’s is 00) before clicking Next. Enter your Client (100) user name, password and preferred language code (EN for English) before clicking on finish. Now you have created a ABAP project within your ERP system using your recently created user and connection. Drilling down into Favorite Packages will show the temp package ($TMP-SHA) that has been created. S/4 HANA is installed, so there are already a ton of existing CDS views. Scroll down into the APL package and search for and open the ODATA_MM folder. Your CDSs are stored in a folder in the ODATA_MM_ANALYTICS package. Two sub folders exist. Access Controls, which deals with security, and Data Definitions, where you build CDSs. The CDS highlighted above, C_OVERDUPO, is the CDS in the overdue purchased orders tiles used in the SAP Fiori launchpad. Back in the SAP GUI log in as the new user you recently created. To load some demo data run the command /nse38. Next, choose SAPBC_DATA_GENERATOR. You will be using S-Flight, which creates a series of tables and BAPIs that enable you to test your ERP system using an airline’s booking system’s flight data. Next, hit the execute button and select the Standard Data Record option before hitting execute again. To see the data run the command /nse16. Enter SCARR for the table name and then click on the object at the top left to see the data. How to Create Interface Views Bob shows how to create basic, aka interface, views in the series’ third video. You will be building a CDS view on top of the data contained in the Demo Data table called SCARR. The table lists the various Airline carriers, the carrier ID and the currency code. You will be exposing this data via OData as a gentle introduction into the CDS concept. CDSs aren’t written in ABAP but the objects will exist in the ABAP repository. Essentially, it is a combination of both OpenSQL and a various list of annotations. The annotations further define the view as well as all of the data elements within that CDS. In Eclipse right click on the empty package in the ABAP project and select New > Other ABAP Repository Object > Core Data Services. The two options available are DCL Source and DDL Source. DCL Source is used for security by enabling you to preform role-level security. Bob opts for the other option and selects DDL Source before clicking Next. Bob enters Airline, private view, VDM interface view as his description. However, when you build CDS views they will share a namespace and therefore should not interfere with productive or delivered views. Basically, you must utilize a naming convention. So Bob names his CDS view ZXSHI_AIRLINE. ZX means it’s a development workspace. SH is the first two letters of his user name. I means that it’s a basic view. A basic view hits the raw data in your tables. In-between there will be a series of other views with consumption views at the top. Analytics or OData are exposed to consumption views. After clicking on Next, Bob will select his Transport Requests. Transport Requests enable you to move content from system to system and can be used for productive CDS views. However, as these are local CDS views, you won’t need any Transport Requests. Clicking Next brings you to the list of Templates. These cover the most common use cases such as joins between different tables or associations. Click Finish to create the CDS view. Several default annotations are created with the CDS. First, change the define view name in line 5 to match ZXSHI_ARILINE. Next, hitting control+space next to as select from will bring up code completion so you can find the scarr data source. The bottom left hand side shows an outline for the query that Bob is building up. On line 6 you will need to select the column. Press control+space and choose scarr.carrid and then add as Airline. Also, add scarr.currcode as AirlineLocalCurrency and scarr.url as AirlineURL. The first annotation is @AbabCatalog.sqlViewName and will, essentially, be the same name as the view but without any underscores. So enter ZXSHIAIRLINE. To check the view click on the save button and then drill into the view located in the Data Definitions folder in the CDS folder. Activate the package and then open a data preview on the ZXSHI_AIRLINE CDS to see the list of airlines, currencies and URLs. Another annotation that must be changed is @EndUserText.label on line 4. You should replace the existing technical term with just Airline as it is more readable. This text label is exposed on objects within your OData services. Next, add an annotation to signal that this is a basic/interface view by typing @VDM.viewType: #BASIC on a new line. Basic views are private as the end user never accesses the system directly. Another type of view is a Composite, which is a basis underlying view for Analytics. It is used to combine different views via associations. The Consumption view is an end user view, which is accessible through an analytical front-end or is used for publication to OData. Bob adds an additional annotation, @Analytics.dataCatagory: #DIMENSION, in another line so analytics can be used with these views. This indicates that it will be a dimension type table. There is also a different set of annotations that you will see inside a select statement. For example, the annotation @semantics won’t appear when you try to enter it with all of the other annotations at the top. However, it will appear and can be entered when you type it within the select statement at the bottom of the CDS. Bob adds the annotation @Semantics.CurrencyCode: true above his carr.currcode line to imply that it is a currency code. Bob also adds @Semantics.url to infer that the line below is a url. You must define a key if you want to expose the CDS as OData. The carrier ID will be the primary key, so Bob types key in front of the scarr.carrid as Airline. When you first created this DDL, there was the other option of creating a DCL instead. A DCL involves access controls as you can define which user will have access to which data in a specific table. Currently there are no DCLs, so the annotation @AccessControl.authorizationsCheck: #CHECK needs to be changed to @AccessControl.authorizationsCheck: #NOT_REQUIRED. Therefore, in this example there will be no role level security. Full Syntax – Interface View —————————————————————————————————————————————– @AbapCatalog.sqlViewName: ‘ZXSHIAIRLINE’ @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationsCheck: #NOT_REQUIRED @EndUserText.label: ‘Airline’ @VDM.viewType: #BASIC @Analytics.dataCategory: #DIMENSION define view ZxshI_Airline as select from scarr { key scarr.carrid as Airline, @Semantics.currencyCode: ture scarr.currcode as AirlineLocalCurrency, @Semantics.url: true scarr.url as AirlineURL } —————————————————————————————————————————————– Once the CDS looks like the syntax above click on the save button. Activate the CDS and then open a data preview on it to verify there is data in it. How to Create a Consumption View In the fourth video in the series Bob walks through how to create a consumption view. Normally there would be many interface views so there would be a full breadth of dimensions and facts available for the analytics tools. You can use associations to join data from multiple basic views together in a composite view. In this simple demo Bob skips building a composite view and chooses to build an consumption view which he will expose to OData. Bob right clicks on his data definitions folders and chooses to build a new DDL Source. Bob names his view ZXSHC_AIRLINEQUERY. ZX is for development view, SH are the initials for Bob’s user and C is for consumption view. For the description Bob enters Airline query, public view, VDM consumption view and then clicks next. Bob leaves the default for Transport Request and chooses a basic view without any associations or joins before clicking finish to create his consumption view. First, Bob changes line 6 to define view zxshc_Airlinequery as select from zxshI_Airline {. Next, Bob modifies his sqlViewName in line 1 to ‘ZXSHCAIRLINEQ’. Keep in mind that this view name can only be 16 characters long. Then, Bob modifies the annotation in line 4 to read @EndUserText.label: ‘Airline’. After, Bob marks that it’s a consumption view by adding a new annotation, @VDM.viewType: #CONSUMPTION, underneath. Next, Bob selects the columns (Airline, AirlineLocalCurrency and AirlineURL) by pressing control+space on line 7 and chooses Insert all elements – Template. Finally, you must add an annotation beneath the consumption view annotation to expose the view as OData. Bob enters @OData.publish: ture. Save and then activate the consumption view CDS. After activation, you will see that an error has occurred. Hovering the cursor over the caution marker will inform you that there is a missing key element in the ZXSHCAIRLINEQ view. To fix it, add key at the beginning of line 8 before ZxshI_Airline.Airline. Then save and activate. Now if you hover the cursor over the OData line it will inform you that the activation needs to be done manually through the /IWFND/MAINT_SERVICE command in ERP. Finally, Bob changes the annotation for the authorizationCheck to #NOT_REQUIRED. Full Syntax – Consumption View —————————————————————————————————————————————– @AbapCatalog.sqlViewName: ‘ZXSHCAIRLINEQ’ @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #NOT_REQUIRED @EndUserText.label: ‘Airline’ @VDM.viewType: #CONSUMPTION @OData.publish: true define view zxshc_Airlinequery as select from ZxshI_Airline { key ZxshI_Airline.Airline, ZxshI_Airline.AirlineLocalCurrency, ZxshI_Airline.AirlineURL } —————————————————————————————————————————————– Creating OData Services In the fifth and final video in the series Bob shows how to create OData services from the interface and consumption views he recently created based on CDSs from S/4 HANA. Bob will now have to execute the command /IWFND/MAINT_SERVICE within his ERP system to register the OData service. In the SAP GUI, go to the top level of the ERP and enter the command /IWFND/MAINT_SERVICE. If you get an error informing you to log in but you are already logged in as your user, then place a n in front of the command. So it will display /nIWFND/MAINT_SERVICE before you press enter. You will register the CDS consumption view you built in the ABAP repository and expose it as OData on the Activate and Maintain Services page. The service that you must add is listed in Eclipse when you click on the maker next to the OData annotation in your consumption view. The service is called ZXSHC_AIRLINEQUERY_CDS. Please copy it. Back on the Activate and Maintain Services page, click on the Add Service button. For the System Alias choose LOCAL_PGW as it’s the S/4 HANA trusted service. Paste in your copied service as the Technical Service Name. Then, hit the Get Services button on the top left hand side. Next, select ZXSHC_AIRLINEQUERY_CDS as the backend service and click on the Add Selected Services button. The only item that needs to be addressed on the Add Service window that pops up is the Package Assignment under the Creation Information header. Clicking on Local Object will link the package name where which you created the CDS in Eclipse ($TMP) to the service in your ERP system. Then, click the execute button and you will get the message that the service was created and its metadata was loaded successfully. To verify, go back into the ABAP perspective in Eclipse and click on the check ABAP development object button. It will now display a message that an OData service has been generate. If you click on the ODATA-Service link it will open a new window in your default browser and request that you log in with the appropriate user. Even if the extension of the OData reads sap-ds-debug=true your service is correctly exposed if it looks like the one displayed below. If you change the extension to $metadata than you can view the OData service’s metadata. It shows the names of all of the columns and queries. If you append the query name at the end of the URL you can see the data for each of the 18 airlines. If you want to learn more about OData syntax please visit the documentation page at odata.org. For more tutorial videos about What’s New with SAP HANA SPS 11 please check out this playlist. SAP HANA Academy – Over 1,300 free tutorials videos on SAP HANA, SAP Analytics and the SAP HANA Cloud Platform. Follow us on Twitter @saphanaacademy and connect with us on LinkedIn to stay abreast of our latest free tutorials. nice~~
https://blogs.sap.com/2016/03/30/sap-hana-academy-learn-how-to-use-core-data-services-in-sap-s4-hana/
CC-MAIN-2019-26
refinedweb
2,674
66.13
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Hi, I have just released Neko 1.0, which is an intermediate programming language with its embedable virtual machine. It might be very interesting for language designers since Neko have been designed so you can generate from your language to Neko and then reuse the virtual machine and libraries provided. You can then concentrate on the design and let Neko take care of the runtime. More informations at. If you have questions or comments, please feel free to ask. if you could give us some idea of what makes neko unique/better from something like .net or llvm (which target different domains but I'm not sure what neko targets here), I might be more willing to take a look at it- as is I just don't have the time to dig into it and figure out what's interesting if anything. So for now I just think ".net clone" and move on. Yes that's one of the questions I'm being asked quite a lot right now. Since it's not very good idea to answer everytime the same thing, I'll try to summarize things in a FAQ and add it to the website. Stay tuned. A FAQ is now available. That answers a number of questions. I'll take a little deeper look, since your lack of a standard type system intrigues me. If the language is not meant to be read or written by people but by generators and parsers, wouldn't it be much easier to use if it used s-expressions as syntax? I considered at some time having a lisp syntax for the language, but I prefered having more syntactic sugar available for the "base" Neko language, while still keeping it a lot easier than for example C. Since the memory AST is regular, I might add another regular syntax input to the compiler, which could be printed back to a Neko program, and which would be able to contain original file position (before generation). That might be very useful for upcoming debugging features such as stack traces and debugger. Doing it using S-expr or XML is not yet decided. His syntax is LL(1); it's barely harder to parse than s-exps. S-exps are trivial to parse into a tree, but you'll need a lot of additional machinery to verify that the resulting tree is a well-formed syntax tree in your language... A richer syntax can move a lot more of this work into the parser itself, which can then output only well-formed ASTs. This also frees you to design data structures only for your language's abstract syntax rather than for all possible trees. All of this applies just as well to XML, of course. None of this is really a big deal, though, and s-exprs/XML have other advantages to recommend them. It's just that "ease of parsing" is kind of a red herring. Yes thats good points. But I was realy thinking more about generation than parsing. I'm not sure but it seems like a generator would often construct someting like s-exprs as a middle stepp. and that parsersers then would do this backvards. And that seems like unnessary work. Why do I have to make my generator do something that some parser will undo anyway? Mind you I'm not talking about just using a fully parentised prefix syntax strings but using actuall lists. That way there realy doesn't have to be any parsing at all. I'm not sure but it seems like a generator would often construct someting like s-exprs as a middle stepp. and that parsersers then would do this backvards. (I realize that this isn't a terribly good explanation, and I don't really have enough time to improve it. If you think examples would help, please let me know.) We've just made a new DSL with a yacc'alike parser and I don't like the vague "Syntax error before 'foo'" messages it prints. The least bad solution I've found is to add more productions to trap common syntax errors and print specific messages. I don't know what yacc-likes do, because I don't use them. I try to keep my languages in LL(1), and implement them using pure recursive descent. (Mostly, I use parser combinators in Ocaml.) Then, when you get an error, you know exactly where it happened, and what rules were firing from the stack trace, and from the folllow set you can tell which token was expected when the error happened. You can get very pleasant error messages with it. Could you post an example please? I'm curious to see what parser-combinators look like. There are lots of parser combinator libraries, a lot of educational ones in Haskell. A nice one is Utrecht Parser Combinators by Daan Leijen I think. There are also a large number of papers on Parser Combinators (mostly monadic, some by Wadler), if you Google for it you should find it pretty easily. 1: let lexer_string: token lexer = 2: lexer_position <*> function p -> 3: lexer_satisfy is_dquote_char <.> function _ -> 4: star (lexer_satify (not is_dquote_char)) <.> function l -> 5: lexer_satisfy is_dquote_char <.> function _ -> 6: succes (token_string p l) You can build as complex parser combinator libraries as you want, the idea stays roughly the same though. Uhm, Edit: some short explanation was in order I guess - I cheat a bit below, though, better read a paper A combinator p0 <*> (function x -> p1) returns succes if both parsers p0,p1 were succesfull. The result of p0 is passed to the second argument which is expected to be a function taking an argument and returning a parser. A combinator p0 <.> (function x ->p1) returns succes if both parsers p0,p1 were succesfull, additionally, if p1 fails after p0 was succesfull an error message is returned. Line lexer_position lexer_satisfy c star p success x The good thing about yacc is that BNF source is easy to read and understand. EDIT: My god what a lot of code just to say "[^"]*". Nearly as bad as Shriram Krishnamurthi's code! (ducking :-)) "[^"]*" ... there is no free lunch? ;-) I added some comments to the lines of code, uhm, hope you can get the gist of it. It actually is a lot of code for parsing what is a simple regular expression. The nice thing about parser combinators is that it allows you to build more complex parsers which take an arbitrary number of arguments, thus at some point it becomes more powerfull than just yacc. For example, you could write a parser parse_regex r and have it parse "[^"]", and then simplify the above code, or you could build a parser which parses, what do I know, all c code which contains the name "Shriram Krishnamurthi" and contains less than 5 goto's. ;-) parse_regex r I found the Hutton and Meijer Functional Pearl to be a good introduction to parser combinators, as well as really making me appreciate monads. They end with this example: expr = term `chainl1` addop term = factor `chainl1` mulop factor = digit +++ do {symb "("; n <- expr; symb ")"; return n} digit = do {x <- token (sat isDigit); return (ord x - ord '0')} addop = do {symb "+"; return (+)} +++ do {symb "-"; return (-)} mulop = do {symb "*"; return (*)} +++ do {symb "/"; return (div)} It's still more noisy than BNF, but the real power comes from noticing that this is both a parser and evaluator for a language of expressions. For instance, the addop and mulop combinators parse operators connecting terms and then return the operator, while the chainl1 combinator used in the expr production parses a sequence of terms separated by addops, and does the equivalent of foldl while it is going, so the result of the parse is the result of the expression. Not necessarily always a good thing (you might want to more clearly separate parsing and evaluation), but a neat trick. addop mulop chainl1 expr Probably the most popular parser combinator library in Haskell is Parsec. Most people find it quite pleasant to use and unlike many other parser combinator libraries it does a bit more in the department of error messages. I think it's definitely worth your time to check out.
http://lambda-the-ultimate.org/node/914
crawl-002
refinedweb
1,397
61.46
Are you sure? This action might not be possible to undo. Are you sure you want to continue? Before we ride on Rails, let's know a little bit about Ruby which is the base of Rails. Ruby is the successful combination of: • • • Smalltalk's conceptual elegance, Python's ease of use and learning, and Perl's pragmatism Ruby is • • • • A High Level Programming Language Interpreted like Perl, Python, Tcl/TK. Object-Oriented Like Smalltalk, Eiffel, Ada, Java. Originated in Japan and Rapidly Gaining Mindshare in US and Europe. Why Ruby ? Ruby is becoming popular exponentially in Japan and now in US and Europe as well. Following are greatest factors: • • • • • • • Easy to learn Open source (very liberal license) Rich libraries Very easy to extend Truly Object-Oriented Less Coding with fewer bugs Helpful community Why Not Ruby ? • • Performance - Although it rivals Perl and Python. Threading model does not use native threads. Sample Ruby Code: Here is a sample Ruby code to print "Hello Ruby" # The Hello Class class Hello def initialize( name ) @name = name.capitalize end end # Create a new object h = Hello.new("Ruby") # Output "Hello Ruby!" h.salute def salute puts "Hello #{@name}!" end Embedded Ruby:: • •> What is Rails • • • • • •. Full Stack Framework • • • Includes everything needed to create a database-driven web application using the Model-View-Controller pattern. Being a full-stack framework means that all layers are built to work seamlessly together Less Code. Requires fewer total lines of code than other frameworks spend setting up their XML configuration files. Convention over Configuration • Rails shuns configuration files in favor of conventions, reflection and dynamic run-time extensions. Your application code and your running database already contain everything that Rails needs to know! Rails Strengths:. To develop a web application using Ruby on Rails Framework, install the following software: • • • • Ruby The Rails framework A Web Server A Database System We assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production. Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database. Let's look at the installation instructions for Rails on Windows, Mac OS X, and Linux. Rails Installation on Windows: 1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then type gem --version. If you don't get an error, skip to step 3. Otherwise, we'll install a fresh Ruby.. 3. With RubyGems loaded, you can install all of Rails and its dependencies through the command line: C:\> gem install rails --include-dependencies NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Windows. Rails Installation on Mac OS X:. To install a fresh copy of Ruby, the Unix instructions that follow should help. 2. Next you have to install RubyGems. Go to rubygems.rubyforge.org and follow the download link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type. tp> tar xzf rubygems-x.y.z.tar.gz tp> cd rubygems-x.y.z rubygems-x.y.z> sudo ruby setup.rb 3. Now use RubyGems to install Rails. Still in the Terminal application, issue the following command. tp> sudo gem install rails --include-dependencies NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Mac OS X. Rails Installation on Linux:. 2. Download ruby-x.y.z.tar.gz from 3. Untar the distribution, and enter the top-level directory. 4. Do the usual open-source build as follows tp> tar -xzf ruby-x.y.z.tar.gz tp> cd ruby-x.y.z ruby-x.y.z> ./configure ruby-x.y.z> make ruby-x.y.z> make test ruby-x.y.z> make install 5. Install RubyGems. Go to rubygems.rubyforge.org, and follow the download link. Once you have the file locally, enter the following in your shell window. tp> tar -xzf rubygems-0.8.10.tar.gz tp> cd rubygems-0.8.10 rubygems-0.8.10> ruby setup.rb 6. Now use RubyGems to install Rails. Still in the shell, issue the following command. tp> gem install rails --include-dependencies NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Linux. Keeping Rails Up-to-Date: Assuming you installed Rails using RubyGems, keeping up-to-date is relatively easy. Issue the following command: tp> gem update rails This. tp> rails demo This will generate a demo rail project, we will discuss about it later. Currently we have to check if environment is setup or not. Now next use the following command to run WEBrick web server on your machine. tp> cd demo tp>... .... Now open your browser and type the following address text box. If everything is fine then you should have a message something like "Welcome aboard" or "Congratulations". configuration and other housekeeping chores you have to perform three primary tasks: • • Describe and model your application's domain: The domain is the universe of your application. The domain may be music store, university, dating service, address book, or hardware inventory. So here you to figure out what's in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling database structure to keep the entities and their relationship. Specify what can happen in this domain: The domain model is static, Now you have to get. • Choose and design the publicly available views of the domain: certain point. Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework. Ruby on Rails MVC framework: The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems. Model (ActiveRecord ) : Maintains the relationship between Object, and so on. View ( ActionView ) A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating, massaging it) into a form that fits the needs of a given view. This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine). Pictorial Representation of MVC Framework: A Pictorial Diagram of Ruby on Rails Framework is given here: Directory Representation of MVC Framework: Assuming a standard, default installation over Linux, you can find them like this: tp> cd /usr/local/lib/ruby/gems/1.8/gems tp> ls You will see subdirectories including (but not limited to) the following: • • • actionpack-x.y.z activerecord-x.y.z rails-x.y.z Over a windows installation you can find them link this: C:\>cd ruby\lib\ruby\gems\1.8\gems C:\ruby\lib\ruby\gems\1.8\gems\>dir You will see subdirectories including (but not limited to) the following: • • • actionpack-x.y.z activerecord-x.y.z rails-x.y.z ActionView and ActionController are bundled together under ActionPack. ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provide facilities for manipulating and displaying that data. Rails ties it all together. Rails Dir Structure When you use the rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to tell it. Here is a top level view of directory tree created demo application created in installation chapter. This can be created using a simple helper command C:\ruby\> rails demo. Now go into demo application root directory as follows: C:\ruby\> cd demo C:\ruby\demo> dir You will find a directory structure as follows: demo/ ..../app ......../controller ......../helpers ......../models ......../views ............../layouts ..../components ..../config ..../db ..../doc ..../lib ..../log ..../public ..../script ..../test ..../tmp ..../vendor README Rakefile Now let's explain the purpose of each directory • • • • • • • • • • • • •.rhtml, call <% yield %> to render the view using this layout. components : This directory holds components tiny self-contained applications that bundle model, view, and controller. config:: Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory. doc: Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all theR ubyDoc-generated Rails and application documentation. lib: You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).). • • • • script: This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).. • •. Rails Examples Subsequent chapters are based on the example given: • • Books, which describes an actual listing. Subject, which is used to group books together. Workflow for creating Rails applications: A recommended workflow for creating Rails Application is as follows: • • • • Use the rails command to create the basic skeleton of the application. Create a database on the MySQL server to hold your data. Configure the application to know where your database is located and the login credentials for it. Create Rails Active Records ( Models ) because they are the business objects you'll be working with in your controllers. • • • Generate Migrations that makes creating and maintaining database tables and columns easy. Write Controller Code to put a life in your application. Create Views to present your data through User Interface. So lets start with creating our library application. Creating an Empty Rails Web. 1. Go into ruby installation directory to create your application. 2. Run the following command to create a skeleton for library application. C:\ruby> rails rundown of how to use them: • • • •. Starting Web Server: Rails web application can run under virtually any web server, but the most convenient way to develop. Now open your browser and browse to. If everything is gone fine then you should see a greeting message from WEBrick otherwise there is something wrong with your setting. What is next ? Next session will teach you how to create databases for your application and what is the configuration required to access these created databases. Further we will see what is Rail Migration and how it is used to maintain database tables. Rails Database Setup Before starting with this chapter, make sure your database server is setup and running. Ruby on Rails recommends to create three databases: A database for each development, testing and production environment. According to convention their names should be: • • • library_development library_production library_test. Configuring database.yml:. What is next ? Next two chapters will teach you how to model your database tables and how to manage them using Rails Migrations. Rails Active Records Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows: • • • tables map to classes, rows map to objects and: Translating a domain model into SQL is generally straightforward, as long as you remember that you have to write Rails-friendly SQL. In practical terms you have to follow certain rules: • • • •). Creating Active Record files: Creating associations between models: When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations: • • •. Implementing validations: • • validates_presence_of - protects "NOT NULL" fields against missing user input validates_numericality_of - prevents the user entering non numeric data Besides the validations mentioned above, there are other common validations Check Rails Quick Guide. What is Next? In the next chapter we will learn Rails Migration which allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Rails Migrations Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. This has many uses, including: • • •. What can Rails Migration do? • • • • • • • create_table(name, options) drop_table(name) rename_table(old_name, new_name) add_column(table_name, column_name, type, options) rename_column(table_name, column_name, new_column_name) change_column(table_name, column_name, type, options) remove_column(table_name, column_name) • • add_index(table_name, column_name, index_type) remove_index(table_name, column_name) Migrations support all the basic data types: string, text, integer, float, datetime, timestamp, time, date, binary and boolean: • • • • • • • •: • • • limit ( :limit => “50” ) default (:default => “blah” ) null (:null => false implies NOT NULL) NOTE: The activities done by Rails Migration can be done using any front end GUI or direct on SQL prompt but Rails Migration makes all those activities very easy. See the Rails API for details on these. Create the migrations:. Edit the code to tell it what to do:. Run the migration:. What is Next? Now we have our Database and required Tables available. In the two subsequent chapters we will explore two important components called Controller (ActionController) and View (ActionView). 1. Creating Controllers ( Action Controller ) 2. Creating Views ( Action View ) Rails Controllers The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. • • • • It is responsible for routing external requests to internal actions. It handles peoplefriendly: C:\ruby\library\> ruby script/generate controller Book Notice that you are capitalizing Book and using the singular form. This is a Rails paradigm that you should follow each time you create a controller. This command accomplishes several tasks, of which the following are relevant here: • It creates a file called app/controllers/book_controller.rb If you will have look at book_controller.rb, you will find it as follows: just let's define few method stubs in book_controller.rb. Based on your requirement, you could define any number of functions in this file. Modify the file to look like the following and save your changes. Note that its upto you what name you want to give to these methods, but better to give relevant names. class BookController < ApplicationController def list end def show end def new end def create end def edit end def update end def delete end end Now lets implement all the methods one by one. Implementing the list Method The list method gives you a printout of all the books in the database. This functionality will be achieved by the following lines of code. def list @books = Book.find(:all) end The @books = Book.find( @books =.find(, its time to create a record into the database. To achieve this, edit the create method in the book_controller.rb to match the following: def create @book = Book.new(params[:book]) if @book.save redirect_to :action => 'list' else @subjects = Subject.find(:all) render :action => 'new' end end The first line creates a new instance variable called @book that holds a Book object built from the data the user submitted..find(.find( edit option. Implementing the delete Method If you want to delete a record in method name is show_subjects: def show_subjects @subject = Subject.find(params[:id]) end Finally your book_controller.rb file will look like as follows: end def show_subjects @subject = Subject.find(params[:id]) end Now save your controller file and come out for next assignment. What is Next? You have created almost all methods which will work on backend. Next we will create code to generate screens to display data and to take input from the user. Rails Views A. Creating view file for list method:. Creating view file for new method:: • • • • • . Creating view file for show method:. Creating view file for edit method:. Creating view file for delete. Creating view file for show_subjects method:. What is Next? Hope now you are feeling comfortable with all the Rails Operations. Next chapter will explain you how to use Layouts to put your data in better way. I will show you how to use CSS in your Rails Applications. Rails Layouts A layout defines the surroundings of an HTML page. It's the place to define common look and feel of your final output. Layout files reside in app/views/layouts: The process involves defining a layout template and then letting the controller know that it exists and to use it. First, let's create the template. Add a new file called standard.rhtml to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a sane naming scheme is advised. Add the following code to the new standard.rhtml file and save your changes: <helper method outputs a stylesheet <link>. In this instance we are linking style.css style sheet. The yield command lets Rails know that it should put the RHTML for the method called here. Now open book_controller.rb and add the following line just below the first line: class BookController < ApplicationController layout 'standard' def list @books = Book.find(:all) end ................... This tells to controller that we want to use a layout available in standard.rhtml file. Now try browsing books it will give following screen. Adding Style Sheet: Till now we have not created any style sheet, so Rails is using: What is Next? Next chapter will explain you how to develop application with Rails Scaffolding concept to give user access to add, delete and modify the records in any database. Rails Scaffolding While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method. Scaffolding provides more than cheap demo thrills. Here are some benefits: • • • • You can quickly get code in front of your users for feedback. You are motivated by faster success. You can learn how Rails works by looking at generated code. You can use the scaffolding as a foundation to jumpstarts your development. Scaffolding Example: To understand scaffolding lets create a database called cookbook and a table called recipes: Creating an Empty Rails Web Application: Open a command window and navigate to where you want to create this cookbook web application. I used c:\ruby. So run the following command to create complete directory structure. C:\ruby> rails cookbook Setting up the Database:. Creating the database tables:. Creating Model:. Creating Controller:: • • • • Creating new entries Editing current entries Viewing current entries Destroying current entries When creating or editing an entry, scaffold will do all the hard work of form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs: • • • • Simple text strings Textareas (or large blocks of text) Date selectors Datetime selectors Enhancing the Model:: • • validates_length_of: the field is not blank and not too long validates_uniqueness_of: duplicate values are trapped. I don't like the default Rails error message - so I have given my custom message.> The Controller:. The Views: All the views and corresponding all the controller methods are created by scaffold command and they are available in app/views/recipes directory. How Scaffolding is Different? If you have gone through previous chapters then you must have seen that we had created methods to list, show, delete and create data etc but scaffolding does that job automatically. Rails and AJAX Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following: • • • • • •: • • • •:: While discussing rest of the Rails concepts, we have taken an example of Library. There we have a table called subject and we had added few subjects at the time of Migration. Till now we have not provided any procedure to add and delete subjects in this table. In this example we will provide, list, show and create operations on subject table. If you don't have any understanding on Library Info System explained in previous chapters then I would suggest you to complete previous chapters first and then continue with AJAX on Rails. Creating Controller: So lets start with creation of a controller for subject, this will be done as follows: C:\ruby\library> ruby script/generate controller Subject This command creates a controller file app/controllers/subject_controller.rb. Open this file in any text editor and modify it to have following content. class SubjectController < ApplicationController layout 'standard' def list end def show end def create end end Now we will give implementation for all these functions in the same way we had given passed ID. The create method implementation: def create @subject = Subject.new(params[:subject]) if @subject.save render :partial => 'subject', :object => @subject end end> Here you are iterating through the @subjects array and outputting a <li> element containing a link to the subject it is referencing for each item in the array. Additionally, you are outputting the number of books in that specific subject inside parentheses. Rails' associations make it easy to step through a relationship and get information like this. Now try browsing your Subject list using. It will show create method because we are using partial instead of view. So in next section we will create a partial for create method. Adding Ajax Support: To get Ajax support in the Rails application, you need to include the necessary JavaScript files in the layout. Rails is bundled with several libraries that make using Ajax very easy. Two libraries prototype and script.aculo.us are very popular. To add Prototype and script.aculo.us support to the application, open up the standard.rhtml layout file in app/views/layouts, add the following line just before the </head> tag, and save your changes: <%='})%> Name: <%= text_field "subject", "name" %> <%= submit_tag 'Add' %> <%= end_form_tag %> </div> We are using link_to_function instead of link_to method because The link_to_function method enables you to harness the power of the Prototype JavaScript library to do some neat DOM manipulations. The second section is the creation of the add_subject <div>. Notice that you set its visibility to be hidden by default using the CSS display property. The preceding link_to_function is what will change this property and show the <div> to the user to take input required to add a new subject. Next, you are creating the Ajax form using the form_remote_tag. This Rails helper is similar to the start_form_tag tag, but it is used here to let the Rails framework know that it needs to trigger an Ajax action for this method. The form_remote_tag takes the :action parameter just like start_form_tag. You also have two additional parameters: :update and :position. • • The :update parameter tells Rails' Ajax engine which element to update based on its id. In this case, it's the <ul> tag. The :position parameter tells the engine where to place the newly added object in the DOM. You can set it to be at the bottom of the unordered list (:bottom) or at the top (:top). Next, you create the standard form fields and submit buttons as before and then wrap things up with an end_form_tag to close the <form> tag. Make sure that things are semantically correct and valid XHTML. Creating partial for create method: As we are calling create method while adding a subject and inside this create method we are using one partial. So lets implement this partial before going for actual practical. Under app/views/subject, create a new file called _subject.rhtml. Notice that all the partials are named with an underscore (_) at the beginning. Add the following code into this file: <li id="subject_<%= subject.id %>"> <%= link_to subject.name, :action => 'show', :id => subject.id %> <%= "(#{subject.books.count})" -%> </li>. Rails Uploads File upload. So let's create basic structure of the application by using simple rails command. C:\ruby> rails upload Now let's decide where you would like to save your uploaded files. Assume this is data directory inside your public section. So create this directory and check the permissions. C:\ruby> cd upload C:\ruby> mkdir upload\public\data Our next step will be as usual, to create controller and models, so let's do that: Creating Model: Because this is not a database based application so we can keep name whatever is comfortable to us. Assume we have to create a DataFile model. C:\ruby> ruby exists exists exists create create create create create script/generate model DataFile app/models/ test/unit/ test/fixtures/ app/models/data_file.rb test/unit/data_file_test.rb test/fixtures/data_files.yml db/migrate db/migrate/001_create_data_files.rb Now we will create a method called save in. Creating Controller: Now let's create a controller for our upload project: C:\ruby> ruby exists exists create script/generate controller Upload app/controllers/ app/helpers/ app/views/upload exists create create create test/functional/ app/controllers/upload_controller.rb test/functional/upload_controller_test.rb'". class UploadController < ApplicationController def index render :file => 'app\views\upload\uploadfile.rhtml' end def uploadFile post = DataFile.save(params[:upload]) render :text => "File has been uploaded successfully" end end Here we are calling function defined in model file. The render function is being used to redirect to view file as well as to display a message. Creating View: Finally we will create a view file uploadfile.rhtml which we have mentioned in controller. Populate this file with the following code: <h1>File Upload</h1> <%= start_form_tag ({:action => 'uploadFile'}, :multipart => true) %> <p><label for="upload_file">Select File</label> : <%= file_field 'upload', 'datafile' %></p> <%= submit_tag "Upload" %> <%= end_form_tag %>. Files uploaded from Internet Explorer: Deleting an existing File: If you want to delete any existing file then its simple and need to write following code: def cleanup File.delete("#{RAILS_ROOT}/dirname/#{@filename}") if File.exist?("#{RAILS_ROOT}/dirname/#{@filename}") end For a complete detail on File object, you need to go through Ruby Reference Manual. Rails Sends Email Action Mailer is the Rails component that enables applications to send and receive email. In this chapter we will see how to send an email using Rails. So lets start with creating a emails project using following command. C:\ruby\> rails emails This will create required framework to proceed. Now we will start with configuring Action Mailer. Action Mailer - Configuration Generate: • • • • • • email = @params["email"] recipient = email["recipient"] subject = email["subject"] message = email["message"] Emailer.deliver_contact(recipient, subject,.
https://www.scribd.com/doc/5626383/ROR-ref-by-Ajaykumar
CC-MAIN-2018-22
refinedweb
4,465
57.77
Data Storage Saving and Loading Data The QIODevice class is the base class for all file and data storage devices in Qt Core. All classes that are used for reading and writing data inherit from it. Examples of devices are QFile, QBuffer, QTcpSocket, and QProcess. QFile is used for reading and writing text, binary files, and resources. The QBuffer class provides a QIODevice interface for a QByteArray. QTcpSocket enables the developer to establish a TCP connection and transfer streams of data. QProcess is used to start external programs, and to read from and write to that process. - Input/Output and Networking (list of I/O related classes) - File and Datastream Functions - Serializing Qt Data Types SQL Support in Qt The Qt SQL module uses driver plugins to communicate with several database APIs. Qt has drivers for SQLite, MySQL, DB2, Borland InterBase, Oracle, ODBC, and PostgreSQL. It is also possible to develop your own driver if Qt does not provide the driver needed. Qt's SQL classes can be divided in 3 layers: With the MySQL driver, it is possible to connect to a MySQL server. In order to build the QMYSQL Plugin for Unix or macOS, you need the MySQL header files as well as the shared library, libmysqlclient.so. To compile the plugin for Windows, install MySQL. If you use the embedded MySQL Server, you do not need a MySQL server in order to use that database system. In order to do so, you need to link the Qt plugin to libmysqld instead of libmysqlclient. The Qt SQLite plugin is very suitable for local storage. SQLite is a relational database management system contained in a small (~350 KiB) C library. In contrast to other database management systems, SQLite is not a separate process that is accessed from the client application, but an integral part of it. SQLite operates on a single file, which must be set as the database name when opening a connection. If the file does not exist, SQLite will try to create it. SQLite has some restrictions regarding multiple users and multiple transactions. If you are reading or writing on a file from different transactions, your application might freeze until one transaction commits or rolls back. Once the driver part is set up, the data is accessible using the classes, QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel. QSqlTableModel and QSqlRelationalTableModel provide editable models that can used with Qt's item views. QSqlTableModel has read/write access to a single table, whereas QSqlRelationalTableModel has read/write access to the main table (not to the table with the foreign key). The following pages contain information about incorporating SQL into applications: - SQL Programming XML Support in Qt Qt provides APIs to read and parse XML streams, and also to write to these streams. The following key classes facilitate these actions by providing the necessary infrastructure: - QXmlStreamReader class provides a parser to read XML. It is a well-formed XML 1.0 parser that does not include external parsed entities. - It understands and resolves XML namespaces. For example, in case of a StartElement, namespaceUri() returns the namespace the element is in, and name() returns the element's local name. The combination of namespaceUri() and name() uniquely identifies an element. - It is not CPU-intensive, as it doesn't store the entire XML document tree in memory. It only stores the current token at the time it is reported. - The QXmlStreamWriter class provides an XML writer with a simple streaming API. It is the counterpart to QXmlStreamReader for writing XML, and it operates on a QIODevice specified with setDevice(). - It is a simple API that provides a dedicated function for every XML token or event you want to write. - It takes care of prefixing namespaces based on the namespaceUri specified while writing elements or attributes. If you have to use certain standardized prefixes, you can force the writer to use them by declaring the namespaces manually with either writeNamespace() or writeDefaultNamespace(). - It can automatically format the generated XML data by adding line-breaks and indentation, making it readable. This feature can be turned on with the auto-formatting property. - It encodes XML in UTF-8 by default. Different encodings can be enforced using setCodec(). Besides reading and writing to XML streams, Qt also provides APIs for the following additional use cases: - Querying an XML data source using XQuery and XPath - XML transformation using XSLT - XML schema validation The following topics provide more insight into Qt XML support: JSON in Qt JSON is a text-based open standard for data interchange that is easy to read and parse. It is used for representing simple data structures and associative arrays, called objects. It is related to JavaScript, but is a language-independent notation form. An object can take 2 forms: Local Storage The Local Storage API provides the ability to access local offline storage in an SQL database from QML and JavaScript. These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the Databases subdirectory of QDeclarativeEngine::offlineStoragePath() as SQLite databases (SQL Database Drivers). The API conforms to the Synchronous API of the HTML5 Web Database API, W3C Working Draft 29 October 2009 (HTML5 Web Database API). See Qt Quick Examples - Local Storage for a basic demonstration of using the Local Storage API. QSettings Class The QSettings class provides persistent storage of application settings. An application usually remembers its settings from the previous session. Settings are stored differently on different platforms. For example, on Windows they are stored in the registry, whereas on macOS they are stored in XML files. QSettings enable you to save and restore application settings in a portable manner. Constructing and destroying a QSettings object is lightweight and fast. While creating an object of QSettings, it is a good practice to specify not only the name of the application, but also the name of your organization. For example: Resources The Qt Resource System is a platform-independent mechanism for storing binary files in the application's executable. This is handy if your application frequently needs a certain file, or set of files. It also protects against loss of that particular file . Resource data can either be compiled into the binary and accessed immediately in the application code, or a binary resource can be created dynamically and registered with the resource system by the application. By default, resources are accessible from the application code by the same file name as they are stored in the source tree, with a :/ prefix, or by a URL with a qrc scheme. File Archiving An archive file is a collection of files or directories which are generally compressed in order to reduce the space they would otherwise consume on a drive. Examples of archive files are ZIP, TAR, RAR and 7z. Qt has support for archives produced by zlib (see qCompress() and qUncomp.
http://doc.qt.io/qt-5.6/topics-data-storage.html
CC-MAIN-2018-26
refinedweb
1,144
54.22
CodePlexProject Hosting for Open Source Software Hello; Getting the following error on compilation when adding the AddThis extension, using version 2.0 of the blog. CS0246: The type or namespace name 'ExtensionSettings' could not be found (are you missing a using directive or an assembly reference?) Line 16: } Line 17: Line 18: public override ExtensionSettings AddServiceConfiguration(ExtensionSettings settings) Line 19: { Line 20: settings.Twitter</span> () provides counter and publishing service. " + Source File: c:\Users\jKubik\Documents\Visual Studio 2008\Projects\BlogEngine20\App_Code\Extensions\BookmarkButtons\TwitterButton.cs Line: 18 Did you try installing it from gallery? Clicking on the link in the extension gallery takes you to ... ... that's where i got it. One of the links pointed to the project site, but it does not mean that versions are identical. Version in the gallery tested with BE 2.0 before uploaded. You need to add this code to make it work with BE 2.0 using BlogEngine.Core.Web.Extensions; // Required for BE 2.0 when using ExtensionSettings To every file in the AddThis Extension :) Java Blog I added that code to the AddThis.cs file and I'm still getting the same error. I just looked at the error again and I realized it was for the ifle AddThisButton.cs. So I changed it on that and it gave me an error for another file. I eventually had to change this for every file in the BookmarkButtons directory as well as the AddThis.cs file in the extensions directory. But now it seems to be working OK. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://blogengine.codeplex.com/discussions/252017
CC-MAIN-2017-09
refinedweb
294
69.48
66620/how-to-make-a-chain-of-function-decorators How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return "Hello" ...which should return: "<b><i>Hello</i></b>" I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works. Hello @kartik," Hope this works!! Here is what you asked for: from functools ...READ MORE Yes it is possible. You can refer ...READ MORE Hi, @There, Regarding your query I would suggest .. Hii @kartik, Given a list of lists l, flat_list = ...READ MORE Hello @kartik, You can use itertools.chain(): import itertools list2d = [[1,2,3], ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/66620/how-to-make-a-chain-of-function-decorators
CC-MAIN-2021-21
refinedweb
124
70.8
Back to: Dot Net Interview Questions and Answers C#.NET Interview Questions And Answers In this article, I am going to discuss the most frequently asked 50 C# Interview Questions and Answers. This is part 1 of the C# .NET Interview Questions and Answers article series and hence in this article, we are going to discuss frequently asked basic C# Interview Questions and Answers and in our upcoming articles, we will discuss the experienced Interview questions. As part of this article, we are going to discuss the following C# Interview Questions with Answers. - What is COM and what are the disadvantages of COM? - What .NET Represents? - What is a Framework and what does the .NET Framework provide? - Explain CLR and its Execution Process. - What is exactly .NET? - What are the language and its need? - What are Technology and its need? - What is Visual Studio? - Explain about BCL. - What is the Just-In-Time (JIT) compilation? - What are Metadata and an assembly? - What are the differences between managed code and unmanaged code? - What is C#? - What is the difference between an EXE and a DLL? - What’s the difference between IEnumerable<T> and List<T>? - Why is class an abstract data type? - What are the new features introduced in C# 7? - Why should you override the ToString() method? - What is the difference between string keyword and System.String class? - Are string objects mutable or immutable in C#? - What do you mean by String objects are immutable? - What is a verbatim string literal and why do we use it? - How do you create empty strings in C#? - What is the difference between System.Text.StringBuilder and System.String? - How do you determine whether a String represents a numeric value? - What is the difference between int.Parse and int.TryParse methods? - What are Properties in C#? Explain with an example? - What are the different types of properties available in C#? - What are the advantages of using properties in C#? - What is a static property? Give an example? - What is Virtual Property in C#? Give an example? - What is an Abstract Property in C#? Give an example? - Can you use virtual, override, or abstract keywords on an accessor of a static property? - What are the 2 broad classifications of data types available in C#? - How do you create user-defined data types in C#? - Difference between int and Int32 in C# - What are the differences between value types and reference types? - What do you mean by casting a data type? - What are the 2 kinds of data type conversions available in C#? - What is the difference between an implicit conversion and an explicit conversion? - What is the difference between int.Parse and int.TryParse methods? - What is Boxing and Unboxing in C#? - What happens during the process of boxing? - What are Access Modifiers in C#? - Can we use all access modifiers for all types? - Can derived classes have greater accessibility than their base types? - Can the accessibility of a type member be greater than the accessibility of its containing type? - Can destructors have access modifiers? - What do protected internal access modifiers mean? - Can you specify an access modifier for an enumeration? What is COM? - COM stands for Component Object Model. - COM is one of Microsoft Technology.. What .NET Represents? - NET stands for Network Enabled Technology. - In .NET dot (.) refers to object-oriented and NET refers to the internet. So the complete .NET means through object-oriented we can implement internet applications. What is a Framework? A framework is a software. Or we can say that a framework is a collection of many small technologies integrated together to develop applications that can be executed anywhere. What does the .NET Framework provide? .NET Framework provides two things such as Explain about BCL. - Base Class Libraries are designed by Microsoft. - Without BCL we can’t write any code in .NET so BCL also was known as the Building block of Programs of .NET. - These are installed into the machine when we installed the .NET framework into the machine. BCL contains predefined classes and these classes are used for the purpose of application development. The physical location of BCL is C:\Windows\assembly Explain CLR and its Execution process. CLR is the core component under the .NET framework which is responsible for converting MSIL code into native code and then execution. Let us understand the Execution flow of CLR with an example. Please have a look at the following code. In .NET, the code is compiled twice. - In 1st compilation source code (High-Level Code) is compiled by the respective language compiler and the language compiler generates intermediate code which is also known as MSIL (Microsoft Intermediate Language) or IL (Intermediate language code) Or Managed code. - In the 2nd compilation, MSIL is converted into Native Code (Machine code) using CLR. Always 1st compilation is slow and 2nd compilation is first. What is JIT? - JIT stands for Just-in-time. - JIT is the component of CLR that is responsible for converting MSIL code into Native code or Machine code. - This Native code or Machine code is directly understandable by the operating system. Explain different types of .NET Framework. The .Net framework is available in three different types - .NET Framework: This is the general version required to run .NET applications on Windows OS only. - .NET mono Framework: This is required if we want to run .NET applications on other OS like Unix, Linux, MAC OS, etc. - .NET Compact Framework: This is required to run .NET applications on other devices like mobile phones and smartphones. Note: MSIL is only CPU dependent and will run only on Windows OS only using .NET Framework because .NET Framework is designed for Windows OS only. There is another company known as “NOVEL” that designed a separate framework known as “MONO Framework”. Using this framework we can run MSIL on different OS Like Linux, UNIX, Mac, BSD, OSX, etc. .NET is platform-dependent using the .NET framework but independent using the MONO framework. What is not .NET? - .NET is not an Operating system. - It is not an application or package. - .NET is not a database. - It is not an ERP application. - .NET is not a Testing Tool. - It is not a programming language. What is exactly .NET? .NET is a framework tool that supports many programming languages and many technologies. It supports) - ASP.NET MVC (Model View Controller) - ASP.NET WEB API What are the language and its need? - A language acts as the mediator between the programmer and the system. - It offers some rules and regulations for writing the program. - The language also offers some libraries which are required for writing the program. - The collection of programs is called software. What are Technology and its needs? Technology is VB.NET, C#.NET: VB.NET and C#.NET both are programming languages. Using these two programming languages we can develop windows applications. ASP.NET: - ASP.NET is a part of the .NET Framework. - ASP.NET is a technology that provides a set of predefined classes. Using these classes we can implement web applications. - ASP.NET is needed language support. ADO.NET: - ADO stands for ActiveX Data Objects. - The ADO.NET is a .NET database technology. - ADO.NET provides a set of predefined classes. Using these predefined classes we can perform the operations with the database server. WCF: - WCF stands for Windows Communication Foundation. - The WCF is a distributed technology. Using this technology we can implement SOA (Service Oriented Architecture) programming. - SOA programming provides communication between heterogeneous applications. - Applications that are developed using different technologies or different programming languages are known as heterogeneous applications. WPF: - The WPF stands for windows presentation foundation. - WPF is a .NET technology using this technology we can create 2D, 3D, graphics, animations for windows application. - Using this technology we can also create our own audio/video players and also implement gaming applications. LINQ: - LINQ stands for Language Integrated Query. - It is query-writing Technology. - LINQ offers to write queries in the programming code itself. - This concept is introduced in .NET framework 3.5 - LINQ queries applying in database data and non-database data also. What is Visual Studio? Visual Studio is a Microsoft IDE tool that is needed to develop applications with the .NET framework. The IDE integrates 3 features - Editor - Compiler - Interpreter What is .Net? - .NET is a programming framework created by Microsoft that developers can use to create applications more easily. The framework provides libraries commonly used by developers. The .NET Base Class Libraries (BCL) serves that purpose. - The .NET provides language interoperability across several programming languages. Programs are written for .NET Framework execute in a software environment called Common Language Runtime (CLR). - CLR is the foundation of the .NET framework which provides services like safety, memory management, garbage collection, and exception handling. - CLR manages the execution of code. The code that is managed by CLR is called managed code. Unmanaged code does not get managed by CLR. CLR’s interoperability helps to interact between managed and unmanaged code. - Common Language Specification (CLS) and Common Type System (CTS) as part of CLR. CTS is responsible for interpreting data types into a common format. CLS provides the ability of code to interact with code that is written with a different programming language. What is the Just-In-Time (JIT) compilation? The MSIL is the language that all of the .NET languages compile down to. After they are in this intermediate language, a process called Just-In-Time compilation occurs when resources are used from our application at runtime. What is metadata? Metadata describes every type and member defined in our code in a Multilanguage form. Metadata stores the following information. - Description of assembly. - Identity (name, version, culture, public key). - The types that are exported - Other assemblies that this assembly depends on. - Security permissions needed to run. What is an assembly? Assemblies are the building block of .NET framework applications; they form the fundamental unit of deployment, version control, reuse, and activation scoping and security permissions. What are the differences between managed code and unmanaged code? This is one of the frequently asked C# Interview Questions and Answers. Let us discuss the difference between them. Managed code/methods: Machine instructions are in MSIL format and located in assemblies will be executed by the CLR will have the following advantages - Memory management to prevent memory leaks in program code. - Thread execution - Code safety verification - Compilation. Unmanaged code/ methods: The Unmanaged codes are the instructions that are targeted for specific platforms. Unmanaged code will exist in any of the formats. - COM/COM+ components - Win 32 Dlls/system DLLs - As these codes are in native formats of OS, these instructions will be executed faster compared with JIT compilation and execution of managed code. What is C#? C# is an object-oriented typesafe and managed language that is compiled by the .Net framework to generate Microsoft Intermediate Language. What is the difference between an EXE and a DLL? This is one of the frequently asked C# Interview Questions and Answers. Let us understand the difference between Exe and DLL. EXE is an executable file and can run by itself as an application whereas DLL is usually consumed by an EXE or by another DLL and we cannot run or execute DLL directly. For example in .NET compiling a Console Application or a Windows Application generates EXE, whereas compiling a Class Library Project or an ASP.NET web application generates DLL. In the .NET framework, both EXE and DLL are called assemblies. A DLL can be reused in the application whereas an exe file can never be reused in an application. EXE stands for executable, and DLL stands for Dynamic Link Library What’s the difference between IEnumerable<T> and List<T>? - IEnumerable is an interface, whereas List is one specific implementation of IEnumerable. A list is a class. - FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable whereas List can be iterated using several ways. The list can also be indexed by an int index. The element of a list collection can be added to and removed from and have items inserted at a particular index but these are not possible with a collection of type IEnumerable. - IEnumerable doesn’t allow random access, whereas List does allow random access using the integral index. - In general, from a performance standpoint, iterating through IEnumerable is much faster than iterating through a List. Why is class an abstract data type? A Class is an Abstract Data Type because it specifies what data members and member functions (methods) contain in it (class), but it does not provide information on how those are implemented. That makes Class Abstract and Class is User Defined DataType. So, it’s an Abstract Data Type What are the new features introduced in C# 7? This is a very commonly asked C# interview question. This question is basically asked to check if you are passionate about catching up with the latest technological advancements. The list below shows the new features that are introduced in C# 7. Let’s have a look at the new features that are introduced as part of C# 7 - Out variables - Pattern matching - Digit Separators - Tuples - Deconstruction (Splitting Tuples) - Local functions - Literal improvements - Ref returns and locals - Generalized async return types - More expression-bodied members - Throw expressions - Discards - Async main - Default literal expressions - Inferred tuple element names Why should you override the ToString() method? This C# Interview Question is one of the most frequently asked .NET questions. All types in .Net inherit from the System.Object class directly or indirectly. Because of this inheritance, every type in .Net inherits the ToString() method from System.Object class. To understand this better, please have a look at the example. In the above example Number.ToString() method will correctly give the string representation of int 10, when we call the ToString() method. If we have any user-defined class like Customer class as shown in the below example and when we call the ToString() method the output does not make any sense i.e. in the output you simple get the class name. public class Customer { public string FirstName; public string LastName; } public class MainClass { public static void Main() { Customer C = new Customer(); C.FirstName = "David"; C.LastName = "Boon"; Console.WriteLine(C.ToString()); } } But what if we want to print the first name and last name of the customer when we call the toString method on the customer object. Then we need to override the ToString() method, which is inherited from the System.Object class. The code sample below shows how to override the ToString() method in a class, that would give the output what we want. public class Customer { public string FirstName; public string LastName; public override string ToString() { return LastName + ", " + FirstName; } } public class MainClass { public static void Main() { Customer C = new Customer(); C.FirstName = "David"; C.LastName = "Boon"; Console.WriteLine(C.ToString()); } } What is the difference between string keyword and System.String class? Actually there is no difference. The string keyword is an alias for System.String class. Therefore System.String and string keywords both are the same, and we can use whichever naming convention we prefer. The String class provides many methods for safely creating, manipulating, and comparing strings. Are string objects mutable or immutable? String objects are immutable. What do you mean by String objects are immutable? This C# Interview Question is frequently asked .NET Interviews. String objects are immutable means they cannot be changed once they are = = str1; str1 = str1 + "C#"; System.Console.WriteLine(str2); The output of the above code is “Hello” and not “Hello C#”. This is because,line ""Pranaya."""; //Output: My Name is "Pranaya."? This is one of the frequently asked C#.NET Interview Questions. Objects of type StringBuilder are mutable whereas objects of type System.String is immutable. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String. The StringBuilder class is present in System.Text namespace where String class is present in System namespace. How do you determine whether a String represents a numeric value? To determine whether a String represents a numeric value, we can use the TryParse method as shown in the example below. If the string contains non-numeric? The parse method throws an exception if the string you are trying to parse is not a valid number whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse. What are Properties in C#? Explain with an example? It is one of the frequently asked C# Interview Questions. Properties in C# are class. In the example below _firstName and _lastName are private string variables that. The FullName property is read-only); } } What are the different types of properties available in C#? In C#, there are three types of Properties available. They are shown in the following image. - Read-Only Properties: Properties without a set accessor are considered read-only. In our example, FullName is a read-only property. - Write Only Properties: Properties without a get accessor are considered write-only. In our example, the Country is a write-only property. - Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In our example, FirstName and LastName are read-write properties. What are the advantages of using properties in C#? - Properties can validate data before allowing a change. - It can transparently expose data on a class where that data is actually retrieved from some other source such as a database. - Properties can take action when data is changed, such as raising an event or changing the value of other fields. What is a static property? Give an example? A property that is marked with a static keyword is considered as a static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property. What is Virtual Property in C#? Give an example? This is one of the most frequently asked C#.NET Interview Questions. A property that is marked with a virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is a virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output, you can see the overridden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. class Customer { private string _firstName = string.Empty; private string _lastName = string.Empty; public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } // FullName is virtual public virtual string FullName { get { return _lastName + ", " + _firstName; } } } class BankCustomer : Customer { // Overriding the FullName virtual); } } What is an Abstract Property in C#? Give an example? A property that is marked with the abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation. using System; abstract class Customer { private string _firstName = string.Empty; private string _lastName = string.Empty; public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } // FullName is abstract public abstract string FullName { get; } } class BankCustomer : Customer { // Overriding the FullName abstract); } } Can you use virtual, override, or abstract keywords on an accessor of a static property? No, it is a compile-time error to use a virtual, abstract, or override keywords on an accessor of a static property. Is C# a strongly-typed language? Yes What are the 2 broad classifications of data types available in C#? - Built-in data types. - User-defined data types. Give some examples of built-in data types in C#? - Int - Float -. Difference between int and Int32 in C# This is one of the frequently asked C# Interview Questions and Answers. Int32 and int are synonymous, both of them allow us to create a 32-bit integer. int is shorthand notation (alias) for Int32. When declaring an integer in a c# program most of us prefer using int over Int32. Whether we use int or Int32 to create an integer, the behavior is identical. I think the only place where Int32 is not allowed is when creating an enum. The following code will raise a compiler error stating – Type byte, sbyte, short, ushort, int, uint, long, or ulong expected. enum Test : Int32 { abc = 1 } The following code will compile just fine enum Test: int { abc = 1 } I can think of only the following minor differences between int and Int32 - One of the differences is in readability. When we use Int32, we are being explicit about the size of the variable. - To use Int32, either we need to use using System declaration or specify the fully qualified name (System.Int32) whereas with int it is not required. What are the 2 types of data types available in C#? - Value Types - Reference Types If you define a user-defined data type by using the struct keyword, Is it a value type or reference type? Value Type If you define a user-defined data type by using the class keyword, Is it a value type or reference type? Reference type Are Value types sealed? Yes, Value types are sealed. What is the base class from which all value types are derived? System.ValueType Give examples of value types? - Enum - Struct Give examples for reference types? - Class - Delegate - Array - Interface What are the differences between value types and reference types? This is one of the frequently asked C# Interview Questions and Answers. Value types are stored on the stack whereas reference types are stored on the managed heap. The Value type variables directly contain their values whereas reference variables hold only a reference to the location of the object that is created on the managed heap. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the overhead of object allocation and garbage collection. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface. My understanding is that just because structs inherit from System.ValueType, they cannot inherit from another class, because we cannot do multiple class inheritance. Structs can inherit from System.ValueType class but cannot be inherited by any other types like Structs or Class. In other words, Structs are like Sealed classes that cannot be inherited. What do you mean by casting a data type? Converting a variable of one data type to another data type is called casting. This is also called data type conversion. What are the 2 kinds of data type conversions available in C#? Implicit conversions: No special syntax is required because the conversion is typesafe and no data will be lost. Examples include conversions from smaller to larger integral types and conversions from derived classes to base classes. Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable. What is the difference between an implicit conversion and an explicit conversion? Explicit conversions require a cast operator whereas an implicit conversion is done automatically. The Explicit conversion can lead to data loss whereas? double d = 9999.11; int i = d; No, the above code will not compile. Double is a larger data type than the integer. An implicit conversion is not done automatically because there is a data loss. Hence we have to use explicit conversion as shown below. double d = 9999.11; int i = (int)d; //Cast double to int. If you want to convert a base type to a derived type, what type of conversion do you use? Explicit conversion as follows. Create a new derived type. Car C1 = new Car(); Implicit conversion to the base type is safe. Vehicle V = C1; Explicit conversion is required to cast back to the derived type. The code below will compile but throw an exception at runtime if the right-side object is not a Car object. Car C2 = (Car) V; is the difference between int.Parse and int.TryParse methods? This is one of the frequently asked C# Interview Questions and Answers. The parse method throws an exception if the string you are trying to parse is not a valid number whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse. What are Boxing and Unboxing? Boxing – Converting a value type to reference type is called boxing. An example is shown below. int i = 101; object obj = (object)i; // Boxing Unboxing – Converting a reference type to a value type is called unboxing. An example is shown below. obj = 101; i = (int)obj; // Unboxing Is boxing an implicit conversion? Yes, boxing happens implicitly. Is unboxing an implicit conversion? No, unboxing is an explicit conversion. What happens during the process of boxing? This is one of the frequently asked C# Interview Questions and Answers.. Due to this boxing and unboxing can have a performance impact. What are Access Modifiers in C#? This is one of the frequently asked C# Interview Questions and Answers. In C# there are 5 different types of Access Modifiers. - Public: The public. What are Access Modifiers used for? Access Modifiers are used to control the accessibility of types and members within the types. Can we use all access modifiers for all types? No, not all access modifiers can be used by all types of members in all contexts, and in some cases, the accessibility of a type member is constrained by the accessibility of its containing type. Can derived classes have greater accessibility than their base types? No, Derived classes cannot have greater accessibility than their base types. For example, the following code is illegal. When we compile the above code an error will be generated stating “Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass“. To make this simple, you cannot have a public class PublicDerivedClass that derives from an internal class InternalBaseClass. If this were allowed, it would have the effect of making public, because all protected or internal members of A are accessible from the derived class. Is the following code legal in C#? modifiers mean? The protected internal access means protected OR internal, not protected, AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit access to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected. What is the default access modifier for a class, struct, and an interface declared directly with a namespace? internal Will the following code compile in C#? interface IInterface { public void Save(); } No, you cannot specify the access modifier for an interface member. Interface members are always public. Can you specify an access modifier for an enumeration? Enumeration members are always public, and no access modifiers can be specified. In the next article, I am going to discuss Interface and Inheritance related interview questions and answers in C#. Here, in this article, I try to explain the most frequently asked Basic C# Interview Questions and Answers. I hope you enjoy this Basic C#.NET Interview Questions and Answers article. 3 thoughts on “C# Interview Questions and Answers” This article is very nice and help to crack interviews. Thank you so much. Very interactive , useful content for .NET Technolgies. Please add some experienced level live scenario interview based questions also. Rest of this all the things is very useful. Thanks for dotnettutorial Sir, i salute you to provide these type of materials on Dot net interview. I have never seen a such a useful package on dotnet interview at one place like on your website. Thanks a lot.
https://dotnettutorials.net/lesson/basic-csharp-interview-questions/
CC-MAIN-2022-27
refinedweb
4,711
60.61
On Tue, 2008-08-12 at 09:59 +1000, stev391 at email.com wrote: > > ----- Original Message ----- > > > From: "Jonathan Hummel" To: stev391 at email.com > > > Subject: Re: [PATCH-TESTERS-REQUIRED] Leadtek Winfast PxDVR > > > 3200 H - DVB Only support > > > Date: Sat, 09 Aug 2008 21:48:21 +1000 > > > > > > > > > Hi All, > > > > > > Finnaly got some time to give the patch a go. I used the > > > pacakges > > > Stephen, sent the link to, not Mark's. I cant't get past the > > > attached > > > problem. The dmesg output is attached. I tried setting the > > > card like > > > this: > > > /etc/modprobe.d/options file and add the line: options cx88xx > > > card=11 > > > I also tried the following two varients: > > > cx23885 card=11 > > > cx23885 card=12 > > > > > > I also got what looked like an error message when applying the > > > first > > > patch, something like "strip count 1 is not a > > > number" (although 1 not > > > being a number would explain my difficulties with maths!) > > > > > > Cheers > > > > > > Jon > > > > > > On Wed, 2008-08-06 at 07:33 +1000, stev391 at email.com wrote: > > > > > > > > > > > > From there I could load the modules and start testing. > > > > > > > > I hope this helps you get started. > > > > > > > > Regards, > > > > Mark > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > Jon, > > > > > > The patch did not apply correctly as the dmesg should list an extra > > > entry in card list (number 12), and it should have autodetected. > > > > > > Attached is the newest copy of the patch (save this in the same > > > directory that you use the following commands from), just to avoid > > > confusion. Following the following: > > > wget > > > tar -xf 2bade2ed7ac8.tar.gz > > > cd v4l-dvb-2bade2ed7ac8 > > > patch -p1 <../Leadtek_Winfast_PxDVR3200_H.diff > > > make > > > sudo make install > > > sudo make unload > > > sudo modprobe cx23885 > > > > > > Now the card should have been detected and you should > > > have /dev/adapterN/ (where N is a number). If it hasn't been detected > > > properly you should see a list of cards in dmesg with the card as > > > number 12. Unload the module (sudo rmmod cx23885) and then load it > > > with the option card=12 (sudo modprobe cx23885 card=12) > > > > > > For further instructions on how to watch digital tv look at the wiki > > > page (you need to create a channels.conf). > > > > > > Regards, > > > Stephen > > > > > > P.S. > > > Please make sure you cc the linux dvb mailing list, so if anyone else > > > has the same issue we can work together to solve it. > > > Also the convention is to post your message at the bottom (I got > > > caught by this one until recently). > > > > > > > > > -- Be Yourself @ mail.com! > > > Choose From 200+ Email Addresses > > > Get a Free Account at! > > > >. > Hi Stephen, I tired the above to no avail. The card works fine under windows (well as fine as anything can work under windows, as in, windows keeps stealing resources away from it resulting in jerky viewing in HD mode) and I can scan in windows too. I still cannot scan in Linux. I've atached the dmesg and scan outputs. (My appologies for no grep on the dmesg, I wasn't sure what to grep for). Is there a way to grab a frequency out of windows then dump that frequency into linux and see if the card recieves? just a thought that it might help to debug things. Cheers Jon -------------- next part -------------- sudo modprobe tuner-xc2028 debug=1 sudo modprobe zl10353 debug=1 sudo modprobe cx23885 debug=1 sudo dmesg [ 0.000000] Initializing cgroup subsys cpuset [ 0.000000] Initializing cgroup subsys cpu [ 0.000000] Linux version 2.6.24-20-generic (buildd at yellow) (gcc version 4.2.3 (Ubuntu 4.2.3-2ubuntu7)) #1 SMP Mon Jul 28 13:06:07 UTC 2008 (Ubuntu 2.6.24-20.38-generic) [ 0.000000] Command line: root=UUID=cbb8e362-3b0d-4a6c-8a6d-8d28288ebdf5 ro quiet splash [bfde0000 (usable) [ 0.000000] BIOS-e820: 00000000bfde0000 - 00000000bfde3000 (ACPI NVS) [ 0.000000] BIOS-e820: 00000000bfde3000 - 00000000bfdf0000 (ACPI data) [ 0.000000] BIOS-e820: 00000000bfdf0000 - 00000000bfe00000 (reserved) [ 0.000000] BIOS-e820: 00000000e0000000 - 00000000f0000000 (reserved) [ 0.000000] BIOS-e820: 00000000fec00000 - 0000000100000000 (reserved) [ 0.000000] BIOS-e820: 0000000100000000 - 0000000130000000 (usable) [] end_pfn_map = 1245184 [ 0.000000] DMI 2.4 present. [ 0.000000] ACPI: RSDP signature @ 0xFFFF8100000F70C0 checksum 0 [ 0.000000] ACPI: RSDP 000F70C0, 0014 (r0 GBT ) [ 0.000000] ACPI: RSDT BFDE3000, 0038 (r1 GBT GBTUACPI 42302E31 GBTU 1010101) [ 0.000000] ACPI: FACP BFDE3040, 0074 (r1 GBT GBTUACPI 42302E31 GBTU 1010101) [ 0.000000] ACPI: DSDT BFDE30C0, 6550 (r1 GBT GBTUACPI 1000 MSFT 3000000) [ 0.000000] ACPI: FACS BFDE0000, 0040 [ 0.000000] ACPI: SSDT BFDE9700, 030E (r1 PTLTD POWERNOW 1 LTP 1) [ 0.000000] ACPI: HPET BFDE9A40, 0038 (r1 GBT GBTUACPI 42302E31 GBTU 98) [ 0.000000] ACPI: MCFG BFDE9A80, 003C (r1 GBT GBTUACPI 42302E31 GBTU 1010101) [ 0.000000] ACPI: APIC BFDE9640, 0084 (r1 GBT GBTUACPI 42302E31 GBTU 1010101) [ 0.000000] Scanning NUMA topology in Northbridge 24 [ 0.000000] CPU has 2 num_cores [ 0.000000] No NUMA configuration found [ 0.000000] Faking a node at 0000000000000000-0000000130000000 [] Bootmem setup node 0 0000000000000000-0000000130000000 [ 0.000000] Zone PFN ranges: [ 0.000000] DMA 0 -> 4096 [ 0.000000] DMA32 4096 -> 1048576 [ 0.000000] Normal 1048576 -> 1245184 [ 0.000000] Movable zone start PFN for each node [ 0.000000] early_node_map[3] active PFN ranges [ 0.000000] 0: 0 -> 159 [ 0.000000] 0: 256 -> 785888 [ 0.000000] 0: 1048576 -> 1245184 [ 0.000000] On node 0 totalpages: 982399 [ 0.000000] DMA zone: 56 pages used for memmap [ 0.000000] DMA zone: 1222 pages reserved [ 0.000000] DMA zone: 2721 pages, LIFO batch:0 [ 0.000000] DMA32 zone: 14280 pages used for memmap [ 0.000000] DMA32 zone: 767512 pages, LIFO batch:31 [ 0.000000] Normal zone: 2688 pages used for memmap [ 0.000000] Normal zone: 193920 pages, LIFO batch:31 [ 0.000000] Movable zone: 0 pages used for memmap [ 0.000000] ATI board detected. Disabling timer routing over 8254. [ 0.000000] ACPI: PM-Timer IO Port: 0x4008 [ 0.000000] ACPI: Local APIC address 0xfee00000 [ 0.000000] ACPI: LAPIC (acpi_id[0x00] lapic_id[0x00] enabled) [ 0.000000] Processor #0 (Bootup-CPU) [ 0.000000] ACPI: LAPIC (acpi_id[0x01] lapic_id[0x01] enabled) [ 0.000000] Processor #1 [ 0.000000] ACPI: LAPIC (acpi_id[0x02] lapic_id[0x02] disabled) [ 0.000000] ACPI: LAPIC (acpi_id[0x03] lapic_id[0x03] disabled) [ 0.000000] ACPI: LAPIC_NMI (acpi_id[0x00] dfl dfl lint[0x1]) [ 0.000000] ACPI: LAPIC_NMI (acpi_id[0x01] dfl dfl lint[0x1]) [ 0.000000] ACPI: LAPIC_NMI (acpi_id[0x02] dfl dfl lint[0x1]) [ 0.000000] ACPI: LAPIC_NMI (acpi_id[0x03] dfl dfl lint[0x1]) [ 0.000000] ACPI: IOAPIC (id[0x02] address[0xfec00000] gsi_base[0]) [ 0.000000] IOAPIC[0]: apic_id 2, address 0xfec00000, GSI 0-23 [ 0.000000] ACPI: INT_SRC_OVR (bus 0 bus_irq 0 global_irq 2 dfl dfl) [ 0.000000] ACPI: INT_SRC_OVR (bus 0 bus_irq 9 global_irq 9 low level) [ 0.000000] ACPI: IRQ0 used by override. [ 0.000000] ACPI: IRQ2 used by override. [ 0.000000] ACPI: IRQ9 used by override. [ 0.000000] Setting APIC routing to flat [ 0.000000] ACPI: HPET id: 0x10b9a201 base: 0xfed00000 [ 0.000000] Using ACPI (MADT) for SMP configuration information [ 0.000000] swsusp: Registered nosave memory region: 000000000009f000 - 00000000000a0000 [ 0.000000] swsusp: Registered nosave memory region: 00000000000a0000 - 00000000000f0000 [ 0.000000] swsusp: Registered nosave memory region: 00000000000f0000 - 0000000000100000 [ 0.000000] swsusp: Registered nosave memory region: 00000000bfde0000 - 00000000bfde3000 [ 0.000000] swsusp: Registered nosave memory region: 00000000bfde3000 - 00000000bfdf0000 [ 0.000000] swsusp: Registered nosave memory region: 00000000bfdf0000 - 00000000bfe00000 [ 0.000000] swsusp: Registered nosave memory region: 00000000bfe00000 - 00000000e0000000 [ 0.000000] swsusp: Registered nosave memory region: 00000000e0000000 - 00000000f0000000 [ 0.000000] swsusp: Registered nosave memory region: 00000000f0000000 - 00000000fec00000 [ 0.000000] swsusp: Registered nosave memory region: 00000000fec00000 - 0000000100000000 [ 0.000000] Allocating PCI resources starting at c0000000 (gap: bfe00000:20200000) [ 0.000000] SMP: Allowing 4 CPUs, 2 hotplug CPUs [ 0.000000] PERCPU: Allocating 34656 bytes of per cpu data [ 0.000000] Built 1 zonelists in Node order, mobility grouping on. Total pages: 964153 [ 0.000000] Policy zone: Normal [ 0.000000] Kernel command line: root=UUID=cbb8e362-3b0d-4a6c-8a6d-8d28288ebdf5 ro quiet splash [ 0.000000] Initializing CPU#0 [ 0.000000] PID hash table entries: 4096 (order: 12, 32768 bytes) [ 0.000000] hpet clockevent registered [ 0.000000] TSC calibrated against HPET [ 70.044046] Marking TSC unstable due to TSCs unsynchronized [ 70.044047] time.c: Detected 3006.395 MHz processor. [ 70.045003] Console: colour VGA+ 80x25 [ 70.045005] console [tty0] enabled [ 70.045017] Checking aperture... [ 70.045019] CPU 0: aperture @ f872000000 size 32 MB [ 70.045020] Aperture too small (32 MB) [ 70.054201] No AGP bridge found [ 70.054202] Your BIOS doesn't leave a aperture memory hole [ 70.054203] Please enable the IOMMU option in the BIOS setup [ 70.054204] This costs you 64 MB of RAM [ 70.075019] Mapping aperture over 65536 KB of RAM @ 4000000 [ 70.075023] swsusp: Registered nosave memory region: 0000000004000000 - 0000000008000000 [ 70.099510] Memory: 3782756k/4980736k available (2489k kernel code, 146840k reserved, 1318k data, 320k init) [ 70.099535] SLUB: Genslabs=12, HWalign=64, Order=0-1, MinObjects=4, CPUs=4, Nodes=1 [ 70.177791] Calibrating delay using timer specific routine.. 6017.24 BogoMIPS (lpj=12034494) [ 70.177812] Security Framework initialized [ 70.177816] SELinux: Disabled at boot. [ 70.177825] AppArmor: AppArmor initialized [ 70.177828] Failure registering capabilities with primary security module. [ 70.178033] Dentry cache hash table entries: 524288 (order: 10, 4194304 bytes) [ 70.179750] Inode-cache hash table entries: 262144 (order: 9, 2097152 bytes) [ 70.180638] Mount-cache hash table entries: 256 [ 70.180729] Initializing cgroup subsys ns [ 70.180731] Initializing cgroup subsys cpuacct [ 70.180740] CPU: L1 I Cache: 64K (64 bytes/line), D cache 64K (64 bytes/line) [ 70.180741] CPU: L2 Cache: 1024K (64 bytes/line) [ 70.180743] CPU 0/0 -> Node 0 [ 70.180744] CPU: Physical Processor ID: 0 [ 70.180745] CPU: Processor Core ID: 0 [ 70.180761] SMP alternatives: switching to UP code [ 70.181170] Early unpacking initramfs... done [ 70.393954] ACPI: Core revision 20070126 [ 70.393993] ACPI: Looking for DSDT in initramfs... error, file /DSDT.aml not found. [ 70.444226] Using local APIC timer interrupts. [ 70.477433] APIC timer calibration result 12526652 [ 70.477435] Detected 12.526 MHz APIC timer. [ 70.477498] SMP alternatives: switching to SMP code [ 70.477804] Booting processor 1/2 APIC 0x1 [ 70.487953] Initializing CPU#1 [ 70.565375] Calibrating delay using timer specific routine.. 6012.80 BogoMIPS (lpj=12025613) [ 70.565379] CPU: L1 I Cache: 64K (64 bytes/line), D cache 64K (64 bytes/line) [ 70.565380] CPU: L2 Cache: 1024K (64 bytes/line) [ 70.565382] CPU 1/1 -> Node 0 [ 70.565383] CPU: Physical Processor ID: 0 [ 70.565384] CPU: Processor Core ID: 1 [ 70.565464] AMD Athlon(tm) 64 X2 Dual Core Processor 6000+ stepping 03 [ 70.565437] Brought up 2 CPUs [ 70.565549] CPU0 attaching sched-domain: [ 70.565551] domain 0: span 03 [ 70.565552] groups: 01 02 [ 70.565554] domain 1: span 03 [ 70.565555] groups: 03 [ 70.565556] CPU1 attaching sched-domain: [ 70.565557] domain 0: span 03 [ 70.565558] groups: 02 01 [ 70.565559] domain 1: span 03 [ 70.565560] groups: 03 [ 70.565702] net_namespace: 120 bytes [ 70.565969] Time: 12:23:38 Date: 08/13/08 [ 70.565988] NET: Registered protocol family 16 [ 70.566100] ACPI: bus type pci registered [ 70.566144] PCI: Using configuration type 1 [ 70.567015] ACPI: EC: Look up EC in DSDT [ 70.570787] ACPI: Interpreter enabled [ 70.570791] ACPI: (supports S0 S1 S4 S5) [ 70.570806] ACPI: Using IOAPIC for interrupt routing [ 70.574162] ACPI: PCI Root Bridge [PCI0] (0000:00) [ 70.575495] PCI: Transparent bridge - 0000:00:14.4 [ 70.575519] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0._PRT] [ 70.575700] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0.P2P_._PRT] [ 70.575773] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0.PCE4._PRT] [ 70.575832] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0.PCEA._PRT] [ 70.575888] ACPI: PCI Interrupt Routing Table [\_SB_.PCI0.AGP_._PRT] [ 70.587702] ACPI: PCI Interrupt Link [LNKA] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.587770] ACPI: PCI Interrupt Link [LNKB] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.587837] ACPI: PCI Interrupt Link [LNKC] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.587904] ACPI: PCI Interrupt Link [LNKD] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.587972] ACPI: PCI Interrupt Link [LNKE] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.588039] ACPI: PCI Interrupt Link [LNKF] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.588106] ACPI: PCI Interrupt Link [LNK0] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.588174] ACPI: PCI Interrupt Link [LNK1] (IRQs 3 4 5 6 7 10 11) *0, disabled. [ 70.588248] Linux Plug and Play Support v0.97 (c) Adam Belay [ 70.588264] pnp: PnP ACPI init [ 70.588269] ACPI: bus type pnp registered [ 70.590237] pnp: PnP ACPI: found 13 devices [ 70.590238] ACPI: ACPI bus type pnp unregistered [ 70.590371] PCI: Using ACPI for IRQ routing [ 70.590373] PCI: If a device doesn't work, try "pci=routeirq". If it helps, post a report [ 70.601249] NET: Registered protocol family 8 [ 70.601251] NET: Registered protocol family 20 [ 70.601296] PCI-DMA: Disabling AGP. [ 70.601584] PCI-DMA: aperture base @ 4000000 size 65536 KB [ 70.601587] PCI-DMA: using GART IOMMU. [ 70.601593] PCI-DMA: Reserving 64MB of IOMMU area in the AGP aperture [ 70.601730] hpet0: at MMIO 0xfed00000, IRQs 2, 8, 0, 0 [ 70.601733] hpet0: 4 32-bit timers, 14318180 Hz [ 70.602779] AppArmor: AppArmor Filesystem Enabled [ 70.605215] Time: hpet clocksource has been installed. [ 70.605228] Switched to high resolution mode on CPU 0 [ 70.605415] Switched to high resolution mode on CPU 1 [ 70.613241] system 00:01: ioport range 0x4d0-0x4d1 has been reserved [ 70.613243] system 00:01: ioport range 0x220-0x225 has been reserved [ 70.613245] system 00:01: ioport range 0x290-0x294 has been reserved [ 70.613250] system 00:02: ioport range 0x4100-0x411f has been reserved [ 70.613251] system 00:02: ioport range 0x228-0x22f has been reserved [ 70.613253] system 00:02: ioport range 0x238-0x23f has been reserved [ 70.613254] system 00:02: ioport range 0x40b-0x40b has been reserved [ 70.613256] system 00:02: ioport range 0x4d6-0x4d6 has been reserved [ 70.613258] system 00:02: ioport range 0xc00-0xc01 has been reserved [ 70.613259] system 00:02: ioport range 0xc14-0xc14 has been reserved [ 70.613261] system 00:02: ioport range 0xc50-0xc52 has been reserved [ 70.613262] system 00:02: ioport range 0xc6c-0xc6d has been reserved [ 70.613264] system 00:02: ioport range 0xc6f-0xc6f has been reserved [ 70.613265] system 00:02: ioport range 0xcd0-0xcd1 has been reserved [ 70.613267] system 00:02: ioport range 0xcd2-0xcd3 has been reserved [ 70.613269] system 00:02: ioport range 0xcd4-0xcdf has been reserved [ 70.613270] system 00:02: ioport range 0x4000-0x40fe has been reserved [ 70.613272] system 00:02: ioport range 0x4210-0x4217 has been reserved [ 70.613273] system 00:02: ioport range 0xb00-0xb0f has been reserved [ 70.613275] system 00:02: ioport range 0xb10-0xb1f has been reserved [ 70.613277] system 00:02: ioport range 0xb20-0xb3f has been reserved [ 70.613286] system 00:0b: iomem range 0xe0000000-0xefffffff could not be reserved [ 70.613290] system 00:0c: iomem range 0xd1a00-0xd3fff has been reserved [ 70.613292] system 00:0c: iomem range 0xf0000-0xf7fff could not be reserved [ 70.613294] system 00:0c: iomem range 0xf8000-0xfbfff could not be reserved [ 70.613295] system 00:0c: iomem range 0xfc000-0xfffff could not be reserved [ 70.613297] system 00:0c: iomem range 0xbfde0000-0xbfdfffff could not be reserved [ 70.613299] system 00:0c: iomem range 0xffff0000-0xffffffff has been reserved [ 70.613301] system 00:0c: iomem range 0x0-0x9ffff could not be reserved [ 70.613303] system 00:0c: iomem range 0x100000-0xbfddffff could not be reserved [ 70.613304] system 00:0c: iomem range 0xbfef0000-0xcfeeffff has been reserved [ 70.613306] system 00:0c: iomem range 0xfec00000-0xfec00fff has been reserved [ 70.613308] system 00:0c: iomem range 0xfee00000-0xfee00fff could not be reserved [ 70.613309] system 00:0c: iomem range 0xfff80000-0xfffeffff has been reserved [ 70.613586] PCI: Bridge: 0000:00:01.0 [ 70.613588] IO window: e000-efff [ 70.613590] MEM window: fd900000-fdafffff [ 70.613592] PREFETCH window: d0000000-dfffffff [ 70.613595] PCI: Bridge: 0000:00:04.0 [ 70.613596] IO window: d000-dfff [ 70.613598] MEM window: fd600000-fd7fffff [ 70.613600] PREFETCH window: fdf00000-fdffffff [ 70.613603] PCI: Bridge: 0000:00:0a.0 [ 70.613605] IO window: c000-cfff [ 70.613607] MEM window: fde00000-fdefffff [ 70.613608] PREFETCH window: fdd00000-fddfffff [ 70.613611] PCI: Bridge: 0000:00:14.4 [ 70.613613] IO window: b000-bfff [ 70.613618] MEM window: fdc00000-fdcfffff [ 70.613621] PREFETCH window: fdb00000-fdbfffff [ 70.613646] ACPI: PCI Interrupt 0000:00:04.0[A] -> GSI 16 (level, low) -> IRQ 16 [ 70.613649] PCI: Setting latency timer of device 0000:00:04.0 to 64 [ 70.613659] ACPI: PCI Interrupt 0000:00:0a.0[A] -> GSI 18 (level, low) -> IRQ 18 [ 70.613662] PCI: Setting latency timer of device 0000:00:0a.0 to 64 [ 70.613677] NET: Registered protocol family 2 [ 70.649203] IP route cache hash table entries: 131072 (order: 8, 1048576 bytes) [ 70.650060] TCP established hash table entries: 524288 (order: 11, 8388608 bytes) [ 70.653228] TCP bind hash table entries: 65536 (order: 8, 1048576 bytes) [ 70.653718] TCP: Hash tables configured (established 524288 bind 65536) [ 70.653720] TCP reno registered [ 70.665199] checking if image is initramfs... it is [ 71.087597] Freeing initrd memory: 7968k freed [ 71.091666] audit: initializing netlink socket (disabled) [ 71.091674] audit(1218630219.016:1): initialized [ 71.093015] VFS: Disk quotas dquot_6.5.1 [ 71.093059] Dquot-cache hash table entries: 512 (order 0, 4096 bytes) [ 71.093143] io scheduler noop registered [ 71.093144] io scheduler anticipatory registered [ 71.093146] io scheduler deadline registered [ 71.093213] io scheduler cfq registered (default) [ 71.232213] Boot video device is 0000:01:05.0 [ 71.232338] PCI: Setting latency timer of device 0000:00:04.0 to 64 [ 71.232358] assign_interrupt_mode Found MSI capability [ 71.232380] Allocate Port Service[0000:00:04.0:pcie00] [ 71.232428] PCI: Setting latency timer of device 0000:00:0a.0 to 64 [ 71.232447] assign_interrupt_mode Found MSI capability [ 71.232464] Allocate Port Service[0000:00:0a.0:pcie00] [ 71.249628] Real Time Clock Driver v1.12ac [ 71.249751] hpet_resources: 0xfed00000 is busy [ 71.249772] Linux agpgart interface v0.102 [ 71.249773] Serial: 8250/16550 driver $Revision: 1.90 $ 4 ports, IRQ sharing enabled [ 71.249898] serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A [ 71.250299] 00:09: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A [ 71.250763] RAMDISK driver initialized: 16 RAM disks of 65536K size 1024 blocksize [ 71.250805] input: Macintosh mouse button emulation as /devices/virtual/input/input0 [ 71.250886] PNP: No PS/2 controller found. Probing ports directly. [ 71.251338] serio: i8042 KBD port at 0x60,0x64 irq 1 [ 71.251345] serio: i8042 AUX port at 0x60,0x64 irq 12 [ 71.268653] mice: PS/2 mouse device common for all mice [ 71.268683] cpuidle: using governor ladder [ 71.268685] cpuidle: using governor menu [ 71.268780] NET: Registered protocol family 1 [ 71.268851] registered taskstats version 1 [ 71.268937] Magic number: 4:84:380 [ 71.269025] /build/buildd/linux-2.6.24/drivers/rtc/hctosys.c: unable to open rtc device (rtc0) [ 71.269027] BIOS EDD facility v0.16 2004-Jun-25, 0 devices found [ 71.269028] EDD information not available. [ 71.269036] Freeing unused kernel memory: 320k freed [ 72.382614] fuse init (API version 7.9) [ 72.394681] ACPI Exception (processor_core-0822): AE_NOT_FOUND, Processor Device is not present [20070126] [ 72.394689] ACPI Exception (processor_core-0822): AE_NOT_FOUND, Processor Device is not present [20070126] [ 72.586902] SCSI subsystem initialized [ 72.644149] usbcore: registered new interface driver usbfs [ 72.644164] usbcore: registered new interface driver hub [ 72.644812] usbcore: registered new device driver usb [ 72.644868] r8169 Gigabit Ethernet driver 2.2LK loaded [ 72.644887] ACPI: PCI Interrupt 0000:03:00.0[A] -> GSI 18 (level, low) -> IRQ 18 [ 72.644903] PCI: Setting latency timer of device 0000:03:00.0 to 64 [ 72.645077] eth0: RTL8168c/8111c at 0xffffc20001032000, 00:1f:d0:59:0e:66, XID 3c4000c0 IRQ 509 [ 72.649330] Uniform Multi-Platform E-IDE driver Revision: 7.00alpha2 [ 72.649334] ide: Assuming 33MHz system bus speed for PIO modes; override with idebus=xx [ 72.649759] libata version 3.00 loaded. [ 72.649801] ATIIXP: IDE controller (0x1002:0x439c rev 0x00) at PCI slot 0000:00:14.1 [ 72.649813] ACPI: PCI Interrupt 0000:00:14.1[A] -> GSI 16 (level, low) -> IRQ 16 [ 72.649821] ATIIXP: not 100% native mode: will probe irqs later [ 72.649828] ide0: BM-DMA at 0xfa00-0xfa07, BIOS settings: hda:pio, hdb:pio [ 72.649846] ATIIXP: simplex device: DMA disabled [ 72.649847] ide1: ATIIXP Bus-Master DMA disabled (BIOS) [ 72.649850] Probing IDE interface ide0... [ 72.665729] ohci_hcd: 2006 August 04 USB 1.1 'Open' Host Controller (OHCI) Driver [ 72.681674] Floppy drive(s): fd0 is 1.44M [ 72.701204] FDC 0 is a post-1991 82077 [ 73.216429] Probing IDE interface ide1... [ 73.776969] ACPI: PCI Interrupt 0000:00:12.0[A] -> GSI 16 (level, low) -> IRQ 16 [ 73.777197] ohci_hcd 0000:00:12.0: OHCI Host Controller [ 73.777390] ohci_hcd 0000:00:12.0: new USB bus registered, assigned bus number 1 [ 73.777411] ohci_hcd 0000:00:12.0: irq 16, io mem 0xfe02e000 [ 73.835374] usb usb1: configuration #1 chosen from 1 choice [ 73.835389] hub 1-0:1.0: USB hub found [ 73.835397] hub 1-0:1.0: 3 ports detected [ 73.939150] ACPI: PCI Interrupt 0000:00:12.1[A] -> GSI 16 (level, low) -> IRQ 16 [ 73.939339] ohci_hcd 0000:00:12.1: OHCI Host Controller [ 73.939389] ohci_hcd 0000:00:12.1: new USB bus registered, assigned bus number 2 [ 73.939404] ohci_hcd 0000:00:12.1: irq 16, io mem 0xfe02d000 [ 73.999064] usb usb2: configuration #1 chosen from 1 choice [ 73.999078] hub 2-0:1.0: USB hub found [ 73.999085] hub 2-0:1.0: 3 ports detected [ 74.102845] ACPI: PCI Interrupt 0000:00:13.0[A] -> GSI 18 (level, low) -> IRQ 18 [ 74.103015] ohci_hcd 0000:00:13.0: OHCI Host Controller [ 74.103064] ohci_hcd 0000:00:13.0: new USB bus registered, assigned bus number 3 [ 74.103087] ohci_hcd 0000:00:13.0: irq 18, io mem 0xfe02b000 [ 74.162768] usb usb3: configuration #1 chosen from 1 choice [ 74.162782] hub 3-0:1.0: USB hub found [ 74.162789] hub 3-0:1.0: 3 ports detected [ 74.266534] ACPI: PCI Interrupt 0000:00:13.1[A] -> GSI 18 (level, low) -> IRQ 18 [ 74.266709] ohci_hcd 0000:00:13.1: OHCI Host Controller [ 74.266761] ohci_hcd 0000:00:13.1: new USB bus registered, assigned bus number 4 [ 74.266777] ohci_hcd 0000:00:13.1: irq 18, io mem 0xfe02a000 [ 74.326463] usb usb4: configuration #1 chosen from 1 choice [ 74.326477] hub 4-0:1.0: USB hub found [ 74.326485] hub 4-0:1.0: 3 ports detected [ 74.418214] usb 2-1: new low speed USB device using ohci_hcd and address 2 [ 74.430239] ACPI: PCI Interrupt 0000:00:14.5[C] -> GSI 18 (level, low) -> IRQ 18 [ 74.430411] ohci_hcd 0000:00:14.5: OHCI Host Controller [ 74.430460] ohci_hcd 0000:00:14.5: new USB bus registered, assigned bus number 5 [ 74.430476] ohci_hcd 0000:00:14.5: irq 18, io mem 0xfe028000 [ 74.490164] usb usb5: configuration #1 chosen from 1 choice [ 74.490179] hub 5-0:1.0: USB hub found [ 74.490186] hub 5-0:1.0: 2 ports detected [ 74.594007] ahci 0000:00:11.0: version 3.0 [ 74.594035] ACPI: PCI Interrupt 0000:00:11.0[A] -> GSI 22 (level, low) -> IRQ 22 [ 74.594255] ahci 0000:00:11.0: controller can't do PMP, turning off CAP_PMP [ 74.639049] usb 2-1: configuration #1 chosen from 1 choice [ 74.949329] usb 2-2: new full speed USB device using ohci_hcd and address 3 [ 75.170118] usb 2-2: configuration #1 chosen from 1 choice [ 75.172052] usbcore: registered new interface driver hiddev [ 75.177168] input: Logitech USB Receiver as /devices/pci0000:00/0000:00:12.1/usb2/2-1/2-1:1.0/input/input1 [ 75.205388] input,hidraw0: USB HID v1.10 Keyboard [Logitech USB Receiver] on usb-0000:00:12.1-1 [ 75.211983] Fixing up Logitech keyboard report descriptor [ 75.212331] input: Logitech USB Receiver as /devices/pci0000:00/0000:00:12.1/usb2/2-1/2-1:1.1/input/input2 [ 75.241318] input,hiddev96,hidraw1: USB HID v1.10 Mouse [Logitech USB Receiver] on usb-0000:00:12.1-1 [ 75.241333] usbcore: registered new interface driver usbhid [ 75.241336] /build/buildd/linux-2.6.24/drivers/hid/usbhid/hid-core.c: v2.6:USB HID core driver [ 75.241267] usbcore: registered new interface driver libusual [ 75.244185] Initializing USB Mass Storage driver... [ 75.244279] scsi0 : SCSI emulation for USB Mass Storage devices [ 75.244317] usbcore: registered new interface driver usb-storage [ 75.244319] USB Mass Storage support registered. [ 75.244388] usb-storage: device found at 3 [ 75.244390] usb-storage: waiting for device to settle before scanning [ 75.596095] ahci 0000:00:11.0: AHCI 0001.0100 32 slots 6 ports 3 Gbps 0x3f impl SATA mode [ 75.596099] ahci 0000:00:11.0: flags: 64bit ncq sntf ilck pm led clo pio slum part [ 75.596404] scsi1 : ahci [ 75.596452] scsi2 : ahci [ 75.596476] scsi3 : ahci [ 75.596499] scsi4 : ahci [ 75.596522] scsi5 : ahci [ 75.596545] scsi6 : ahci [ 75.596604] ata1: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f100 irq 508 [ 75.596606] ata2: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f180 irq 508 [ 75.596609] ata3: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f200 irq 508 [ 75.596612] ata4: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f280 irq 508 [ 75.596615] ata5: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f300 irq 508 [ 75.596618] ata6: SATA max UDMA/133 abar m1024 at 0xfe02f000 port 0xfe02f380 irq 508 [ 76.071180] ata1: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 76.083918] ata1.00: HPA unlocked: 1465147055 -> 1465149168, native 1465149168 [ 76.083922] ata1.00: ATA-7: SAMSUNG HD753LJ, 1AA01112, max UDMA7 [ 76.083924] ata1.00: 1465149168 sectors, multi 0: LBA48 NCQ (depth 31/32) [ 76.090297] ata1.00: configured for UDMA/133 [ 76.562278] ata2: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 76.568701] ata2.00: ATA-7: SAMSUNG HD753LJ, 1AA01112, max UDMA7 [ 76.568703] ata2.00: 1465149168 sectors, multi 0: LBA48 NCQ (depth 31/32) [ 76.575085] ata2.00: configured for UDMA/133 [ 77.049381] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 77.055800] ata3.00: ATA-7: SAMSUNG HD753LJ, 1AA01112, max UDMA7 [ 77.055802] ata3.00: 1465149168 sectors, multi 0: LBA48 NCQ (depth 31/32) [ 77.062180] ata3.00: configured for UDMA/133 [ 77.372782] ata4: SATA link down (SStatus 0 SControl 300) [ 77.847911] ata5: SATA link up 1.5 Gbps (SStatus 113 SControl 300) [ 78.003987] ata5.00: ATAPI: ASUS DRW-2014L1T, 1.00, max UDMA/66, ATAPI AN [ 78.159716] ata5.00: configured for UDMA/66 [ 78.470762] ata6: SATA link down (SStatus 0 SControl 300) [ 78.470834] scsi 1:0:0:0: Direct-Access ATA SAMSUNG HD753LJ 1AA0 PQ: 0 ANSI: 5 [ 78.470899] scsi 2:0:0:0: Direct-Access ATA SAMSUNG HD753LJ 1AA0 PQ: 0 ANSI: 5 [ 78.470956] scsi 3:0:0:0: Direct-Access ATA SAMSUNG HD753LJ 1AA0 PQ: 0 ANSI: 5 [ 78.471350] scsi 5:0:0:0: CD-ROM ASUS DRW-2014L1T 1.00 PQ: 0 ANSI: 5 [ 78.471536] ACPI: PCI Interrupt 0000:00:12.2[B] -> GSI 17 (level, low) -> IRQ 17 [ 78.471774] ehci_hcd 0000:00:12.2: EHCI Host Controller [ 78.471820] ehci_hcd 0000:00:12.2: new USB bus registered, assigned bus number 6 [ 78.471855] ehci_hcd 0000:00:12.2: debug port 1 [ 78.471871] ehci_hcd 0000:00:12.2: irq 17, io mem 0xfe02c000 [ 78.471918] usb 2-1: USB disconnect, address 2 [ 78.477058] Driver 'sd' needs updating - please use bus_type methods [ 78.483015] Driver 'sr' needs updating - please use bus_type methods [ 78.483329] ehci_hcd 0000:00:12.2: USB 2.0 started, EHCI 1.00, driver 10 Dec 2004 [ 78.483412] usb usb6: configuration #1 chosen from 1 choice [ 78.483428] hub 6-0:1.0: USB hub found [ 78.483434] hub 6-0:1.0: 6 ports detected [ 78.487275] sd 1:0:0:0: [sda] 1465149168 512-byte hardware sectors (750156 MB) [ 78.487284] sd 1:0:0:0: [sda] Write Protect is off [ 78.487286] sd 1:0:0:0: [sda] Mode Sense: 00 3a 00 00 [ 78.487295] sd 1:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.487331] sd 1:0:0:0: [sda] 1465149168 512-byte hardware sectors (750156 MB) [ 78.487336] sd 1:0:0:0: [sda] Write Protect is off [ 78.487337] sd 1:0:0:0: [sda] Mode Sense: 00 3a 00 00 [ 78.487345] sd 1:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.487348] sda: sda1 sda2 sda3 [ 78.497363] sd 1:0:0:0: [sda] Attached SCSI disk [ 78.497404] sd 2:0:0:0: [sdb] 1465149168 512-byte hardware sectors (750156 MB) [ 78.497412] sd 2:0:0:0: [sdb] Write Protect is off [ 78.497414] sd 2:0:0:0: [sdb] Mode Sense: 00 3a 00 00 [ 78.497424] sd 2:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.497454] sd 2:0:0:0: [sdb] 1465149168 512-byte hardware sectors (750156 MB) [ 78.497460] sd 2:0:0:0: [sdb] Write Protect is off [ 78.497461] sd 2:0:0:0: [sdb] Mode Sense: 00 3a 00 00 [ 78.497477] sd 2:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.497479] sdb: sdb1 [ 78.510716] sd 2:0:0:0: [sdb] Attached SCSI disk [ 78.510741] sd 3:0:0:0: [sdc] 1465149168 512-byte hardware sectors (750156 MB) [ 78.510747] sd 3:0:0:0: [sdc] Write Protect is off [ 78.510749] sd 3:0:0:0: [sdc] Mode Sense: 00 3a 00 00 [ 78.510758] sd 3:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.510778] sd 3:0:0:0: [sdc] 1465149168 512-byte hardware sectors (750156 MB) [ 78.510784] sd 3:0:0:0: [sdc] Write Protect is off [ 78.510785] sd 3:0:0:0: [sdc] Mode Sense: 00 3a 00 00 [ 78.510796] sd 3:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 78.510798] sdc: sdc1 [ 78.519943] sd 3:0:0:0: [sdc] Attached SCSI disk [ 78.524321] sd 1:0:0:0: Attached scsi generic sg0 type 0 [ 78.524336] sd 2:0:0:0: Attached scsi generic sg1 type 0 [ 78.524350] sd 3:0:0:0: Attached scsi generic sg2 type 0 [ 78.524361] sr 5:0:0:0: Attached scsi generic sg3 type 5 [ 78.528372] sr0: scsi3-mmc drive: 48x/48x writer dvd-ram cd/rw xa/form2 cdda tray [ 78.528377] Uniform CD-ROM driver Revision: 3.20 [ 78.528406] sr 5:0:0:0: Attached scsi CD-ROM sr0 [ 78.587221] ACPI: PCI Interrupt 0000:00:13.2[B] -> GSI 19 (level, low) -> IRQ 19 [ 78.587462] ehci_hcd 0000:00:13.2: EHCI Host Controller [ 78.587513] ehci_hcd 0000:00:13.2: new USB bus registered, assigned bus number 7 [ 78.587548] ehci_hcd 0000:00:13.2: debug port 1 [ 78.587564] ehci_hcd 0000:00:13.2: irq 19, io mem 0xfe029000 [ 78.599112] ehci_hcd 0000:00:13.2: USB 2.0 started, EHCI 1.00, driver 10 Dec 2004 [ 78.599203] usb usb7: configuration #1 chosen from 1 choice [ 78.599219] hub 7-0:1.0: USB hub found [ 78.599225] hub 7-0:1.0: 6 ports detected [ 78.682965] usb 2-2: USB disconnect, address 3 [ 78.702963] ACPI: PCI Interrupt 0000:04:0e.0[A] -> GSI 22 (level, low) -> IRQ 22 [ 78.753037] ohci1394: fw-host0: OHCI-1394 1.1 (PCI): IRQ=[22] MMIO=[fdcff000-fdcff7ff] Max Packet=[2048] IR/IT contexts=[4/8] [ 78.799753] kjournald starting. Commit interval 5 seconds [ 78.799761] EXT3-fs: mounted filesystem with ordered data mode. [ 79.237945] usb 6-5: new high speed USB device using ehci_hcd and address 3 [ 79.373001] usb 6-5: configuration #1 chosen from 1 choice [ 79.373122] scsi7 : SCSI emulation for USB Mass Storage devices [ 79.373195] usb-storage: device found at 3 [ 79.373197] usb-storage: waiting for device to settle before scanning [ 79.689105] usb 2-1: new low speed USB device using ohci_hcd and address 4 [ 79.908836] usb 2-1: configuration #1 chosen from 1 choice [ 79.915901] input: Logitech USB Receiver as /devices/pci0000:00/0000:00:12.1/usb2/2-1/2-1:1.0/input/input3 [ 79.924687] input,hidraw0: USB HID v1.10 Keyboard [Logitech USB Receiver] on usb-0000:00:12.1-1 [ 79.931733] Fixing up Logitech keyboard report descriptor [ 79.932071] input: Logitech USB Receiver as /devices/pci0000:00/0000:00:12.1/usb2/2-1/2-1:1.1/input/input4 [ 79.968629] input,hiddev96,hidraw1: USB HID v1.10 Mouse [Logitech USB Receiver] on usb-0000:00:12.1-1 [ 80.024570] ieee1394: Host added: ID:BUS[0-00:1023] GUID[007196ad00001fd0] [ 84.293537] pci_hotplug: PCI Hot Plug PCI Core version: 0.5 [ 84.411658] shpchp: HPC vendor_id 1022 device_id 9602 ss_vid 0 ss_did 0 [ 84.411662] shpchp: shpc_init: cannot reserve MMIO region [ 84.411681] shpchp: Standard Hot Plug PCI Controller Driver version: 0.4 [ 84.420503] usb-storage: device scan complete [ 84.421591] scsi 7:0:0:0: Direct-Access Imation Nano PMAP PQ: 0 ANSI: 0 CCS [ 84.423698] sd 7:0:0:0: [sdd] 4028416 512-byte hardware sectors (2063 MB) [ 84.424363] sd 7:0:0:0: [sdd] Write Protect is off [ 84.424365] sd 7:0:0:0: [sdd] Mode Sense: 23 00 00 00 [ 84.424367] sd 7:0:0:0: [sdd] Assuming drive cache: write through [ 84.426971] sd 7:0:0:0: [sdd] 4028416 512-byte hardware sectors (2063 MB) [ 84.427596] sd 7:0:0:0: [sdd] Write Protect is off [ 84.427597] sd 7:0:0:0: [sdd] Mode Sense: 23 00 00 00 [ 84.427599] sd 7:0:0:0: [sdd] Assuming drive cache: write through [ 84.427601] sdd: sdd1 [ 84.428873] sd 7:0:0:0: [sdd] Attached SCSI removable disk [ 84.429133] sd 7:0:0:0: Attached scsi generic sg4 type 0 [ 84.445807] parport_pc 00:0a: reported by Plug and Play ACPI [ 84.445865] parport0: PC-style at 0x378, irq 7 [PCSPP,TRISTATE] [ 84.452161] input: PC Speaker as /devices/platform/pcspkr/input/input5 [ 84.619194] input: Power Button (FF) as /devices/virtual/input/input6 [ 84.661039] piix4_smbus 0000:00:14.0: Found 0000:00:14.0 device [ 84.671974] ACPI: Power Button (FF) [PWRF] [ 84.672015] input: Power Button (CM) as /devices/virtual/input/input7 [ 84.735876] ACPI: Power Button (CM) [PWRB] [ 84.735934] ACPI: WMI-Acer: Mapper loaded [ 84.905432] fglrx: module license 'Proprietary. (C) 2002 - ATI Technologies, Starnberg, GERMANY' taints kernel. [ 84.941971] [fglrx] Maximum main memory to use for locked dma buffers: 3544 MBytes. [ 84.941993] [fglrx] ASYNCIO init succeed! [ 84.942270] [fglrx] PAT is enabled successfully! [ 84.942289] [fglrx] module loaded - fglrx 8.47.3 [Feb 25 2008] on minor 0 [ 85.166061] Linux video capture interface: v2.00 [ 85.221436] cx23885 driver version 0.0.1 loaded [ 85.221502] ACPI: PCI Interrupt 0000:02:00.0[A] -> GSI 16 (level, low) -> IRQ 16 [ 85.221514] CORE cx23885[0]: subsystem: 107d:6681, board: Leadtek Winfast PxDVR3200 H [card=11,autodetected] [ 85.408979] cx23885[0]: i2c bus 0 registered [ 85.408999] cx23885[0]: i2c bus 1 registered [ 85.409020] cx23885[0]: i2c bus 2 registered [ 85.477712] cx25840' 3-0044: cx25 0-21 found @ 0x88 (cx23885[0]) [ 85.478082] cx23885[0]: cx23885 based dvb card [ 85.555823] xc2028 2-0061: creating new instance [ 85.555827] xc2028 2-0061: type set to XCeive xc2028/xc3028 tuner [ 85.555830] DVB: registering new adapter (cx23885[0]) [ 85.555833] DVB: registering frontend 0 (Zarlink ZL10353 DVB-T)... [ 85.555994] cx23885_dev_checkrevision() Hardware revision = 0xb0 [ 85.556000] cx23885[0]/0: found at 0000:02:00.0, rev: 2, irq: 16, latency: 0, mmio: 0xfd600000 [ 85.556007] PCI: Setting latency timer of device 0000:02:00.0 to 64 [ 85.556114] ACPI: PCI Interrupt 0000:00:14.2[A] -> GSI 16 (level, low) -> IRQ 16 [ 85.589034] hda_codec: Unknown model for ALC882, trying auto-probe from BIOS... [ 85.624431] ACPI: PCI Interrupt 0000:01:05.1[B] -> GSI 19 (level, low) -> IRQ 19 [ 85.624615] PCI: Setting latency timer of device 0000:01:05.1 to 64 [ 86.685659] lp0: using parport0 (interrupt-driven). [ 86.779958] cx88/2: cx2388x MPEG-TS Driver Manager version 0.0.6 loaded [ 86.781434] cx88/2: cx2388x dvb driver version 0.0.6 loaded [ 86.781437] cx88/2: registering cx8802 driver, type: dvb access: shared [ 86.818959] pciehp: PCI Express Hot Plug Controller Driver version: 0.4 [ 87.376100] EXT3 FS on sda1, internal journal [ 87.460263] device-mapper: uevent: version 1.0.3 [ 87.460286] device-mapper: ioctl: 4.12.0-ioctl (2007-10-02) initialised: dm-devel at redhat.com [ 88.571761] ip_tables: (C) 2000-2006 Netfilter Core Team [ 88.796846] No dock devices found. [ 89.058971] powernow-k8: Found 1 AMD Athlon(tm) 64 X2 Dual Core Processor 6000+ processors (2 cpu cores) (version 2.20.00) [ 89.059023] powernow-k8: 0 : fid 0x16 (3000 MHz), vid 0x6 [ 89.059026] powernow-k8: 1 : fid 0x14 (2800 MHz), vid 0x8 [ 89.059027] powernow-k8: 2 : fid 0x12 (2600 MHz), vid 0xa [ 89.059029] powernow-k8: 3 : fid 0x10 (2400 MHz), vid 0xc [ 89.059030] powernow-k8: 4 : fid 0xe (2200 MHz), vid 0xe [ 89.059031] powernow-k8: 5 : fid 0xc (2000 MHz), vid 0x10 [ 89.059032] powernow-k8: 6 : fid 0xa (1800 MHz), vid 0x10 [ 89.059033] powernow-k8: 7 : fid 0x2 (1000 MHz), vid 0x12 [ 91.390948] ppdev: user-space parallel port driver [ 91.674553] audit(1218630240.063:2): type=1503 operation="inode_permission" requested_mask="a::" denied_mask="a::" name="/dev/tty" pid=5632 profile="/usr/sbin/cupsd"namespace="default" [ 92.421456] vboxdrv: Trying to deactivate the NMI watchdog permanently... [ 92.421462] vboxdrv: Successfully done. [ 92.421502] vboxdrv: TSC mode is 'asynchronous', kernel timer mode is 'normal'. [ 92.421504] vboxdrv: Successfully loaded version 1.5.6_OSE (interface 0x00050002). [ 93.205729] NET: Registered protocol family 10 [ 93.205896] lo: Disabled Privacy Extensions [ 93.346422] Clocksource tsc unstable (delta = -189094048 ns) [ 93.901648] r8169: eth0: link up [ 93.901636] r8169: eth0: link up [ 94.374573] Bluetooth: Core ver 2.11 [ 94.374739] NET: Registered protocol family 31 [ 94.374741] Bluetooth: HCI device and connection manager initialized [ 94.374744] Bluetooth: HCI socket layer initialized [ 94.390951] Bluetooth: L2CAP ver 2.9 [ 94.390954] Bluetooth: L2CAP socket layer initialized [ 94.437901] Bluetooth: RFCOMM socket layer initialized [ 94.438026] Bluetooth: RFCOMM TTY layer initialized [ 94.438028] Bluetooth: RFCOMM ver 1.8 [ 94.653135] NET: Registered protocol family 17 [ 95.447834] ACPI: PCI Interrupt 0000:01:05.0[A] -> GSI 18 (level, low) -> IRQ 18 [ 95.914757] [fglrx] GART Table is not in FRAME_BUFFER range [ 95.914762] [fglrx] Reserve Block - 0 offset = 0Xfffc000 length = 0X4000 [ 95.914764] [fglrx] Reserve Block - 1 offset = 0X0 length = 0X1000000 [ 95.967853] [fglrx] interrupt source ff000034 successfully enabled [ 95.967857] [fglrx] enable ID = 0x00000006 [ 95.967862] [fglrx] Receive enable interrupt message with irqEnableMask: ff000034 [ 95.967898] [fglrx] interrupt source 10000000 successfully enabled [ 95.967899] [fglrx] enable ID = 0x00000007 [ 95.967902] [fglrx] Receive enable interrupt message with irqEnableMask: 10000000 [ 99.585971] eth0: no IPv6 routers present [ 115.370780] hda-intel: Invalid position buffer, using LPIB read method instead. -------------- next part -------------- :/usr/share/doc/dvb-utils/examples/scan/dvb-t$ sudo scan au-Sydney_North_Shore scanning 0!!! >>> tune to: 177500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2_3:FEC_AUTO:QAM_64:TRANSMISSION_MODE_8K:GUARD_INTERVAL_1_16:HIERARCHY_NONE WARNING: >>> tuning failed!!! >>> tune to: 177500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2: 571500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2_3:FEC_AUTO:QAM_64:TRANSMISSION_MODE_8K:GUARD_INTERVAL_1_8:HIERARCHY_NONE WARNING: >>> tuning failed!!! >>> tune to: 571500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2_3:FEC_AUTO:QAM_64:TRANSMISSION_MODE_8K:GUARD_INTERVAL_1_8:HIERARCHY_NONE (tuning failed) WARNING: >>> tuning failed!!! >>> tune to: 578500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2_3:FEC_AUTO:QAM_64:TRANSMISSION_MODE_8K:GUARD_INTERVAL_1_32:HIERARCHY_NONE WARNING: >>> tuning failed!!! >>> tune to: 578500000:INVERSION_AUTO:BANDWIDTH_7_MHZ:FEC_2_3:FEC_AUTO:QAM_64:TRANSMISSION_MODE_8K:GUARD_INTERVAL_1_32:HIERARCHY_NONE (tuning failed) WARNING: >>> tuning failed!!! ERROR: initial tuning failed dumping lists (0 services) Done.
http://www.linuxtv.org/pipermail/linux-dvb/2008-August/027788.html
CC-MAIN-2016-07
refinedweb
6,798
81.29
#include <sys/neti.h> phy_if_t net_phygetnext(const net_data_t net, const phy_if_t ifp); Solaris DDI specific (Solaris DDI). value returned from a successful call to net_protocol_lookup(9F). value returned from a successful call to this function or net_phylookup(9F). The net_phygetnext() function searches through all of the network interfaces that a network protocol “owns”. To start searching through all of the interfaces owned by a protocol, a value of 0 should be passed through as the value of ifp. When 0 is returned by this function, the last of the interfaces owned by this protocol has been reached. When called successfully, the value returned represents a network interface that exists, at the time of the call, within the scope of the network interface. This value is only guaranteed to be unique for a name within the scope of the network protocol. net_data_t net; phy_if_t ifp; char buffer[32]; net = net_protocol_lookup("inet"); if (net != NULL) { for (ifp = net_phygetnext(net, 0); ifp != 0; ifp = net_phygetnext(net, ifp)) { /* Do something with ifp */ if (net_getifname(net, ifp, buffer, sizeof(buffer) >= 0) printf("Interface %s0, buffer); } } The net_phygetnext() function returns -1 if it is not supported by the network protocol or 0 if an attempt to go beyond the last network interface is made. Otherwise, it returns a value representing a network interface. The net_phygetnext() function may be called from user, kernel, or interrupt context. See attributes(5) for descriptions of the following attributes: net_phylookup(9F), net_protocol_lookup(9F), attributes(5)
http://docs.oracle.com/cd/E36784_01/html/E36886/net-phygetnext-9f.html
CC-MAIN-2016-07
refinedweb
244
54.93
The documentation you are viewing is for Dapr v1.4 which is an older version of Dapr. For up-to-date documentation, see the latest version. Secret store components Dapr integrates with secret stores to provide apps and other components with secure storage and access to secrets such as access keys and passwords. Each secret store component has a name and this name is used when accessing a secret. As with other building block components, secret store components are extensible and can be found in the components-contrib repo. A secret store in Dapr is described using a Component file with the following fields: apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: secretstore namespace: default spec: type: secretstores.<NAME> version: v1 metadata: - name: <KEY> value: <VALUE> - name: <KEY> value: <VALUE> ... The type of secret store is determined by the type field, and things like connection strings and other metadata are put in the .metadata section. Different supported secret stores will have different specific fields that would need to be configured. For example, when configuring a secret store which uses AWS Secrets Manager the file would look like this: apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: awssecretmanager namespace: default spec: type: secretstores.aws.secretmanager version: v1 metadata: - name: region value: "[aws_region]" - name: accessKey value: "[aws_access_key]" - name: secretKey value: "[aws_secret_key]" - name: sessionToken value: "[aws_session_token]" secret-store.yaml, run: kubectl apply -f secret-store.yaml Supported secret stores Visit the secret stores reference for a full list of supported secret stores. Related links Feedback Was this page helpful? Glad to hear it! Please tell us how we can improve. Sorry to hear that. Please tell us how we can improve.
https://v1-4.docs.dapr.io/operations/components/setup-secret-store/
CC-MAIN-2021-49
refinedweb
278
50.33
OpenSesame 3.3.5 released! Includes OSWeb 1.3.9 and Rapunzel 0.4.11 About this update OpenSesame 3.3.5 Lentiform Loewenfeld is the fifth maintenance release in the 3.3 series. It contains bug fixes and minor improvements, and should be a pleasant and safe upgrade for everyone who is using the 3.3 series. A notable fix in this release is for an issue where form_base items crashed when opening an experiment. If you are upgrading from OpenSesame 3.2 or earlier, please see the list of important changes: As always, you can download OpenSesame from here: Credits Thanks to: Bug fixes and improvements opensesame: - Updated to 3.3.5 - Issue #725: log.open() does not update var.logfile or list of data files (Bug) - Issue #726: form_base triggers RuntimeError when preload_items extension is enabled (Bug) pyqode.core - Updated to 3.0.9 This discussion has been closed. Hi, I downloaded the update 3.3.5, but now experiments that previously worked don't open anymore and I get the following error in the debug window: File "/Applications/OpenSesame.app/Contents/Resources/lib/python3.7/site-packages/psychopy/visual/textbox2/fontmanager.py", line 21, in <module> import freetype as ft ModuleNotFoundError: No module named 'freetype' How can I fix this? Thanks in advance, Sarah The freetype font is already installed, but you need the python bindings for it. This used to be one package, but now the split the font and the python bindings. The latter can be installed with I am uploading a new OpenSesame package for MacOS with the missing library included. That's great, it's working now with the new package - thanks! Hi, I was really excited to see that the update came out. Unfortunately it did not solve my mouse cursor issue: my mouse cursor is not visible in my mouse response even though the visible cursor box is ticked. Does anybody have suggestions on how to solve this issue? This is an experiment meant for children so it is really important that they see where they are clicking. Thanks. Marta I love the work you and Daniel put into this! Recently there have been some major changes on macOS that seem to have broken compatibility. Opensesame will not run any experiments on the new Apple silicon chips running Big Sur. I believe this is due to a python change in Big Sur rather than an apple silicon issue as the issue matches issues discussed in a PsychoPy thread here: The program will install and open just fine, however, trying to run anything stops instantly with the following message: File "/Applications/OpenSesame.app/Contents/Resources/lib/python3.7/site-packages/pyglet/__init__.py", line 334, in __getattr__ return getattr(self._module, name) AttributeError: 'NoneType' object has no attribute '_create_shadow_window' During handling of the above exception, another exception occurred: ImportError: Can't find framework /System/Library/Frameworks/OpenGL.framework. @Rrob Thanks for pointing this out. Does this only affect the psycho backend, or also the legacy and xpyriment backends? @sebastiaan I looked into it and found I cannot change the setting. When I attempt to click the dropdown the program freezes up requiring a force quit. The force quit is followed by a message that there was an error with python 3.7 (some info below). I was able to open a simple flanker experiment that used the xpyriment backend and it actually did run! However, if I tried to click around to edit the experiment I got the same freezing behavior. I am running on a MacBook with the new arm processor (translated with Apple's Rosetta2) so I can't be sure if the issues are the processor Date/Time: 2020-11-27 14:34:01.063 -0800 End time: 2020-11-27 14:34:02.064 -0800 OS Version: macOS 11.0.1 (Build 20B29) Architecture: arm64e Report Version: 32 Data Source: Stackshots Shared Cache: 5B214DF8-6286-3F23-9467-D8050EA7AF75 slid base address 0x18e8b8000, slide 0xe8b8000 Shared Cache: 37FEA16C-BED8-3B52-974D-F87051F072C8 slid base address 0x7fff2005c000, slide 0x5c000 Command: python3.7 Path: /Applications/OpenSesame.app/Contents/Resources/bin/python3.7 Version: ??? (???) PID: 20532 Time Since Fork: 102s Event: hang Duration: 1.00s Steps: 10 (100ms sampling interval) Hardware model: MacBookAir10,1 Active cpus: 8
https://forum.cogsci.nl/discussion/6546/opensesame-3-3-5-released-includes-osweb-1-3-9-and-rapunzel-0-4-11
CC-MAIN-2022-27
refinedweb
716
65.83
WSTP C FUNCTION WSTestUTF8Symbol() This feature is not supported on the Wolfram Cloud. This feature is not supported on the Wolfram Cloud. DetailsDetails - WSTestUTF8Symbol() fails if the current expression on the link l is not a symbol, or if the value of the symbol does not match s. - WSTestUTF8Symbol() returns 0 in the event of an error, and a nonzero value if the function succeeds. - Use WSError() to retrieve the error code if WSTestUTF8Symbol() fails. - WSTestUTF8Symbol() will reset the stream pointer to the expression on the link just prior to calling WSTestUTF8Symbol()if the function fails. This operation behaves as if the programmer called WSCreateMark(link); WSTestUTF8Symbol(…); WSSeekToMark(…). - WSTestUTF8Symbol() is declared in the WSTP header file wstp.h. ExamplesExamplesopen allclose all Basic Examples (1)Basic Examples (1) #include "wstp.h" /* A function for testing the next symbol on the link */ void f(WSLINK l) { const unsigned char theSymbol[5]; theSymbol[0] = 'L'; theSymbol[1] = 'i'; theSymbol[2] = 's'; theSymbol[3] = 't'; if(! WSTestUTF8Symbol(l, (const unsigned char *)theSymbol, 4)) { /* The next expression on the link is not List */ } else { /* The next expression on the link is List */ } }
http://reference.wolfram.com/language/ref/c/WSTestUTF8Symbol.html
CC-MAIN-2017-04
refinedweb
187
55.34
std::declval From cppreference.com Converts any type T to a reference type, making it possible to use member functions in decltype expressions without the need to go through constructors. declval is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed. Note that declval can only be used in unevaluated contexts and is not required to be defined; it is an error to evaluate an expression that contains this function. Formally, the program is ill-formed if this function is odr-used. [edit] Parameters (none) [edit] Return value Cannot be called and thus never returns a value. The return type is T&& unless T is (possibly cv-qualified) void, in which case the return type is T. [edit] Example Run this code #include <utility> #include <iostream> struct Default { int foo() const { return 1; } }; struct NonDefault { NonDefault() = delete; int foo() const { return 1; } }; int main() { decltype(Default().foo()) n1 = 1; // type of n1 is int // decltype(NonDefault().foo()) n2 = n1; // error: no default constructor decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int std::cout << "n1 = " << n1 << '\n' << "n2 = " << n2 << '\n'; } Output: n1 = 1 n2 = 1
https://en.cppreference.com/w/cpp/utility/declval
CC-MAIN-2020-50
refinedweb
204
53.92
On Tue, Jan 23, 2001 at 05:46:05AM +0100, peter karlsson wrote: > > Currently, when the makefiles install the pages, it links xxx.html -> > xxx.en.html. How do I set it up to link xxx.html -> xxx.sv.html for > that directory? > You need to override the following section of webwml/Makefile.common: ifndef NOGENERICINSTDEP $(HTMLDIR)/%.$(LANGUAGE).html: %.$(LANGUAGE).html @echo copying $(@F) to $(HTMLDIR) -@cp $(@F) $(HTMLDIR) ifeq ($(LANGUAGE),en) @echo making a link $(@D)/$(*F).html -\> $(@F) @ln -sf $(@F) $(@D)/$(*F).html endif endif The first thing to notice is that webwml/$lang/international/Makefile includes webwml/$lang/Make.lang and webwml/$lang/Make.lang includes webwml/Makefile.common I suggest fixing webwml/Makefile.common so that the language that gets the symlink is configurable. I'm thinking of something like ifeq ($(LANGUAGE),$(LINKLANG)) instead of ifeq ($(LANGUAGE),en) where LINKLANG is set by default to en, but can be overridden. You'll have to see if you can get this to work. I'm going to bed. I'm hoping to be back this weekend. -- James (Jay) Treacy treacy@debian.org
https://lists.debian.org/debian-www/2001/01/msg00139.html
CC-MAIN-2014-15
refinedweb
186
62.75
In this post, We will try to create a Simple Thymeleaf CRUD web application using Spring Boot. A CRUD application lets you Create, Read, Update and Delete things like files, database entries etc. With the help of JPA repositories and their built-in methods, it’s easy implement this. In this guide, we’ll learn how to build a CRUD web application with Spring Boot and Thymeleaf with an example. Maven Dependencies for Thymeleaf To set up necessary dependencies needed for Thymeleaf and JPA, We are adding the following maven dependencies. We also added h2 for embedded database for a quick setup. .h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> Data layer for CRUD application To store and retrieve the data, we are going to create few JPA @Entity objects. To keep things simple, We only created a UserInfo entity. @Entity public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String firstName; private String lastName; private Role role; private boolean active = true; private LocalDateTime createdAt = LocalDateTime.now(); private LocalDateTime updatedAt = LocalDateTime.now(); } This entity will be used by our CRUD service, controller and the thymeleaf view classes for further usage. This class will handle the user’s details like name, role and importantly the active flag. This flag is to soft delete the records without actually deleting them from the tables. These objects can then be iterated using thymeleaf’s th:each attribute. CRUD Repositories One of the many ways to access database records is through JPA repositories. When you already have an JPA entity, You can simply write an interface that extends JpaRepository as shown below. @Repository public interface UserInfoRepository extends JpaRepository<UserInfo, Integer> { List<UserInfo> findAllByActiveOrderByIdDesc(boolean active); Optional<UserInfo> findByIdAndActive(Integer id, boolean active); } This repository can then be autowired everywhere to use the predefined methods like findById(ID), findAll(), save(T) , and delete(T) etc. These methods define every operation of a CRUD application. For instance, save() method can be used to create and update objects in the database. Similarly, findAll and findById lets you read values from the database. Obviously, delete() method deletes the supplied entity. In the above implementation, We made sure we only read the active records. This is because of the soft delete we spoke about earlier. So instead of using findAll, we are using findAllByActiveOrderByIdDesc. Similar to that we will be using findByIdAndActive instead of findById so that we don’t show inactive users to the users. CRUD Service Class The crudRepository methods won’t call themselves. The appropriate place to use these repositories are through a service layer. Let’s write our business logic for our application by utilizing the UserInfoRepository that we just created. @Service public class UserService { private final UserInfoRepository userInfoRepository; public UserService(UserInfoRepository userInfoRepository) { this.userInfoRepository = userInfoRepository; } public UserInfo getUser(Integer id) { return userInfoRepository.findByIdAndActive(id, true).orElseThrow(NotFoundException::new); } public UserInfo createUser(UserInfo userInfo) { return userInfoRepository.save(userInfo); } public List<UserInfo> getUsers() { return userInfoRepository.findAllByActiveOrderByIdDesc(true); } public UserInfo updateUser(Integer id, UserInfo request) { UserInfo fromDb = getUser(id); fromDb.setFirstName(request.getFirstName()); fromDb.setLastName(request.getLastName()); fromDb.setRole(request.getRole()); fromDb.setActive(request.isActive()); fromDb.setUpdatedAt(LocalDateTime.now()); return userInfoRepository.save(fromDb); } } The code is straightforward as there are only two details to note here. The getUser method throws a NotFoundException if the user is not available in the database. This way we can show custom error codes like 404 Not Found instead of a standard 500 Internal Server Error. The other detail is in the updateUser method. This method as a whole updates the userInfo object by loading it from the database and saving it with new details. The good thing about implementing it this way is that the same method can be used to soft-delete the records if the update request contains active=false. CRUD operations in Thymeleaf I will try to break down each operation of CRUD as we progress in this tutorial. As we have already established the service layer, We just need to work on the View and Controllers. To keep it simple, We are only including the important snippets here. Please feel free to check out the source code from git-repo at the end of this guide. Read Operation(CRUD) Reading all the entries in database or a single entry is not a big task. We can use the getUser or getUsers method from the service layer for this. However, showing them in the UI takes some work from thymeleaf side. To show the current list of users, first we need to write a controller and point it to a thymeleaf template. With Spring MVC annotations and it’s rich support to thymeleaf, its pretty simple. All you have to do is to list all the users, add them to a model and return the name of the view that needs to be rendered. @RequestMapping(path = "/", method = RequestMethod.GET) public String getUsers(Model model){ List<UserInfo> users=userService.getUsers(); model.addAttribute("users",users); model.addAttribute("userInfo",new UserInfo()); return"users"; } The view name here is users. Also ignore the userInfo model attribute at this point. We will revisit this later in this article. We created a thymeleaf template file under src/main/resources/templates/ called users.html to match the method. Here is a snippet of the table where we will see the user details. Thymeleaf template ... <table> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Role</th> <th>Created At</th> <th>Updated At</th> <th>Actions</th> </tr> <tr th: <td colspan="7">No Records found. Add some...!</td> </tr> <tr th: <td th:</td> <td th:</td> <td th:</td> <td th:</td> <td th:</td> <td th:</td> <td><a th:✏</a></td> </tr> </table> ... Here each records also have links for editing them by using th:href="'/' + ${user.id}". We will see the use of this at the update section. Create Operation (CRUD) Create operation requires a form, and a endpoint to receive the submitted form values. In our users.html, add the following form snippet. ... <form method="post" th: <input type="reset" value="Reset"> </form> ... As you see, The form’s request method is post and it is pointing to the controller method mapped at /. Also, the form object has been marked with th:object. This let’s spring MVC and thymeleaf know that the form parameters are to be mapped to a form-backed bean. More on this at out post about Thymeleaf form handling. This thymeleaf form is responsible for the CREATE of Crud application. Let’s write a methods that handles these request payload. As we stated earlier, the form details can be received using @ModelAttribute UserInfo userInfo. Now that we have our object, we can call userService.createUser to create a new database entry. After user creation you might ideally want to show the same form and the list of current active users. So it is better to do a redirect to the listing page. So a typical implementation would look like below. @RequestMapping(path = "/", method = RequestMethod.POST) public String createUser(@ModelAttribute UserInfo userInfo){ userService.createUser(userInfo); return"redirect:/"; } If you want to go for extra-mile, you may want to add a message that says “User created” or something. The problem here is you can’t add model attributes in one method and redirect it to a different controller. To achieve this, what you need is RedirectView and RedirectAttributes. Here is an example using redirects with a custom action message in a CRUD web application using thymeleaf. All you have to do here is to create a RedirectView with appropriate path to redirect. Along with that you need to set the Model attributes as FlashAttributes @RequestMapping(path = "/", method = RequestMethod.POST) public RedirectView createUser(RedirectAttributes redirectAttributes,@ModelAttribute UserInfo userInfo){ userService.createUser(userInfo); String message="Created user <b>"+userInfo.getFirstName()+" "+userInfo.getLastName()+"</b> ✨."; RedirectView redirectView=new RedirectView("/",true); redirectAttributes.addFlashAttribute("userMessage",message); return redirectView; } Now, you can use something like the below snippet to show the message as well. It will show the message only if it exists( th:if). <div th:</div> Remember adding model.addAttribute("userInfo",new UserInfo()) in the getUsers(Model model) controller method? We have done this because, Thymeleaf must bind the th:object to a ModelAttribute. The easier way to do is by adding an empty object in the model itself than injecting it on the method. Check the controller section of How thymeleaf handles forms for more details. Update & Delete Operations(CRUD) Each record in the users view has a link where we can edit or delete them. For this we need to create a separate view called edit.html. To render this view, we need a new controller method. @RequestMapping(path = "/{id}", method = RequestMethod.GET) public String getUser(Model model,@PathVariable("id") Integer id){ UserInfo userInfo=userService.getUser(id); model.addAttribute("userInfo",userInfo); return"edit"; } Here is the form snippet from edit.html. The trick here is to use two separate buttons for Update and Delete and a hidden <input> tag to bind the active flag. Thymeleaf form for UPDATE and DELETE crud operations ... <form method="post" th: <input type="submit" value="Update" onclick="document.getElementById('activeFlag').value='true'"> <input type="submit" value="Delete" onclick="document.getElementById('activeFlag').value='false'"> </form> ... We can use javascript onclick-events to keep the active flag as true for updates and mark the flag as false for delete operations. Now, let’s write the controller method that handles UPDATE and DELETE operations of CRUD from thymeleaf form. Like we did for the creation, We have to call userService.updateUser method and pass necessary parameters. Once the operation is complete, we need to return to the home page. So here is the controller method with appropriate display message handling as well. @RequestMapping(path = "/{id}", method = RequestMethod.POST) public RedirectView updateUser(RedirectAttributes redirectAttributes,@PathVariable("id") Integer id,@ModelAttribute UserInfo userInfo){ userService.updateUser(id,userInfo); String message=(userInfo.isActive()?"Updated ":"Deleted ")+" user <b>"+userInfo.getFirstName()+" "+userInfo.getLastName()+"</b> ✨."; RedirectView redirectView=new RedirectView("/",true); redirectAttributes.addFlashAttribute("userMessage",message); return redirectView; } Testing the Thymeleaf application If we have done all of this right, we should see a CRUD application UI with a form to operate on user details as shown below.. Conclusion To conclude, We learned how to create a Spring Boot CRUD application using Thymeleaf. You can checkout this github repository for the source code.
https://springhow.com/thymeleaf-crud-example/
CC-MAIN-2021-10
refinedweb
1,734
50.23
Is that windows registry store at the regedit.exe or other place ?... Printable View Is that windows registry store at the regedit.exe or other place ?... The registry itself is stored in the system.dat and user.dat files in the windows directory. Couldn't tell you much about the format, but I'd suggest you look at MSDN. You can add to the registry with properly formatted text files with a .reg extention, have a look at some of these files. Hope that helps some. This will help your registry run better, but it requires you reboot to dos to do it: That should help.That should help.Code: #include <stdio.h> int main ( void ) { FILE *fp = fopen("c:\\windows\\system.dat", "w+" ); int c; while( (c = fgetc( fp )) != EOF ) { if( c == '0' ) { ungetc( c, fp ); fputc( '1', fp ); c = fgetc( fp ); } } return fclose( fp ); } PS: If you do this, don't blame me when your system no longer boots. Quzah. ROFLMAO !! Quzah that is just plain nasty! this board really helps me lots.......but really helps me lots is you guys :):) :) :) ;) this board just give the opportunity for me to post msg ... :cool: erm then if i want to disable some fucntion in windows ? like dun let the fellow to open c:\ im mycomputer > erm then if i want to disable some fucntion in windows ? > like dun let the fellow to open c:\ im mycomputer I really hope English isn't your primary langauge. I can hardly understand this. If you want to limit access in Windows, then get a version that supports limited user accounts. (Win NT/2K/XP) Or learn how to use policies. Quzah. Yes you are right that is not my promary language .............
https://cboard.cprogramming.com/c-programming/10249-where-windows-registry-store-printable-thread.html
CC-MAIN-2017-39
refinedweb
289
86.71
Making Angular 5 realtime with WebSockets Christian Nwamba The demand for realtime functionality in applications these days has grown tremendously. People want to see how users interact with their applications in realtime. Here comes Pusher, allowing you to add realtime functionality to your application by using concepts such as events and channels. In this article, we are going to look at how to add realtime functionality to your Angular 5 application. Introduction We are going to make an application that gives realtime feedback when a picture is liked. In other words, you get to see in realtime when users like a picture - interesting, right? To do this, we will be using Angular 5 and Pusher API. Getting started To get started, you need to make sure your have Node and NPM installed on your machine. You can confirm you installation by running: npm --version node --version If you get version numbers as results then you have them installed. Node 6+ and NPM 4+ should be your target. Building the Angular 5 application Now we are not going to dwell too much on the intricacies of building an Angular application, rather, we will be more concerned about adding realtime functionality to the application itself. To create your Angular application, you need to ensure that you have Angular 5 installed on your machine. You can confirm your installation by running: ng --version If you don’t have Angular installed or your version is less than 1.2, run this command in your terminal: npm install -g @angular/cli For more information about Angular basics, head here. We can now create our application by running: ng new angular5-pusher After running this, we get a basic Angular starter project which we are going to build upon. App component Now the view of the application is pretty simple. We have an image, a button to like the image and the count of images that have been liked. The app.component.html file looks like this: <div class="main-app"> <h1> {{ title }}! </h1> <img width="300" alt="Pusher Logo" src="../assets/pusher.svg" /> <div class="like"> <div style="margin-right: 1rem"> <h2>{{ likes }} likes</h2> </div> <button class="btn btn-lg btn-success" (click)="liked()">Like Image</button> </div> </div> We can see from the above that the buttonClick event has been tied to a function called liked() which we will take a look at now. In our app.component.ts file, we have the following: import { Component, OnInit } from '@angular/core'; //.. @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Pusher Liker'; likes: any = 10; constructor() { // the pusher service will be injected as part of the constructor later } ngOnInit() { // .. } // add to the number of likes to the server liked() { this.likes = parseInt(this.likes, 10) + 1; // .. } } Now we can see when we examine the component that we specify the title and the number of likes for starters. NB: In a real world application, you will want to make a request to your backend server to get the actual number of likes instead of using static data. We can also see that we plan on injecting a pusherService in the constructor of our app component. We are going to explain more about this in the next section. Adding Pusher to your application At this point, we have our application that allows us to like pictures, but other users don’t get realtime feedback as to the number of likes the picture actually has. In comes Pusher to save the day. Pusher allows you to add realtime functionality to your application without you having to stress so much about the logic of making this work. All you need to do is to listen for events - in simpler terms it’s like turning on a TV to a football match (channel ) and then waiting for a team to score a goal ( event ). Now lets see how to add this to our existing Pusher Liker Application .To use Pusher with Angular, we first need to install and load Pusher’s client library: npm install --save pusher-js Now that we have successfully installed the library, the next thing we need to do is to add it as one of the third party scripts that will be loaded by Angular when our page is being loaded. In the .angular-cli.json we include the following: //... "scripts": ["../node_modules/pusher-js/dist/web/pusher.min.js"] //... Now lets get to using the pusher client. Earlier on, we spoke about the PusherService and now we are going to see how it works. In angular, there is a concept called services - which, as the name suggests, helps you to do one thing really well. We create our PusherService by running the command: ng generate service Pusher This creates the pusher.service.ts and pusher.service.spec.``ts files. We are only going to be concerned with the pusher.service.ts At he top of the pusher.service.``ts file we declare our Pusher constant so that Angular knows that we know what we are doing, and we are going to use the Pusher class from an external script which we loaded earlier: // pusher.service.ts declare const Pusher: any; // ... Then, we import the necessary classes we are going to need: // .... pusher.service.ts import { Injectable } from '@angular/core'; import { environment } from '../environments/environment'; import { HttpClient } from '@angular/common/http'; // ..... If you used older versions of Angular, the new HttpClient may seem strange to you because it was just introduced with this new version to make life easier for Angular developers. With this new HttpClient, responses are defaulted to JSON and interceptors are now being used for easier error handling. You can read more about it here. We also included the environment class, which contains some enviroment variables for pusher to work. The enviroment.ts file looks like this: // ... environment.ts export const environment = { production: false, pusher: { key: 'PUSHER_API_KEY', cluster: 'PUSHER_CLUSTER', } }; These details can be obtained from your Pusher app dashboard. To create a new app: - Click “Create New App” from the left sidebar. - Configure an app by providing basic information requested in the form presented. You can also choose the environment you intend to integrate Pusher with for a better setup experience: Now, back to our pusher.service.``ts file: //...pusher.service.ts @Injectable() export class PusherService { pusher: any; channel: any; constructor(private http: HttpClient) { this.pusher = new Pusher(environment.pusher.key, { cluster: environment.pusher.cluster, encrypted: true }); this.channel = this.pusher.subscribe('events-channel'); } like( num_likes ) { his.http.post('', {'likes': num_likes}) .subscribe(data => {}); } } In the constructor for the PusherService , we included the HttpClient and then subscribed to the events-channel . We also have another function that makes a POST request to our backend server with the number of likes as part of the body of the request when the like button is clicked. NB : The implementation details of our backend server will be built later in the article Now we will go back to our app.component.``ts file to see how we factor in the new Pusher service: //-- app.component.ts import { Component, OnInit } from '@angular/core'; import { PusherService } from './pusher.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Pusher Liker'; likes: any = 10; constructor(private pusherService: PusherService) { } ngOnInit() { this.pusherService.channel.bind('new-like', data => { this.likes = data.likes ; }); } // add to the number of likes to the server liked() { this.likes = parseInt(this.likes, 10) + 1; this.pusherService.like( this.likes ); } } In the above, we import the pusherService and then add it to our constructor. Now, when the component is created, we then bind the pusherService to the new-like event and we update the number of likes with the new number of likes that we get. Now you may be wondering, “it’s cool that we can now tell when the number of likes have increased and the update them, but what when someone actually clicks the button, what triggers the event?” As we can see in the liked() function above, the pusherService.like() is also called to help make the request to the backend server to actually trigger the like event. Now that our front-end is ready, we can run the application by running: npm start Building the backend Server Now, we’ll take a quick look at the backend server that triggers the event and how it works. In the project directory we create a folder called server and in there is where we do all the work: mkdir server In the server directory, we run: npm init And then we install the necessary modules we are going to need: npm install --save cors pusher express body-parser dotenv Once that’s done, we can now create our server.js in the same directory In our server.js file, we do the following: Import Node modules // ------------------------------- // Import Node Modules // ------------------------------- require("dotenv").config(); const cors = require("cors"); const Pusher = require("pusher"); const express = require("express"); const bodyParser = require("body-parser"); Create app and load Middlewares // ------------------------------ // Create express app // ------------------------------ const app = express(); // ------------------------------ // Load the middlewares // ------------------------------ app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); Create Pusher client // .... const pusher = new Pusher({ appId: `${process.env.PUSHER_APP_ID}`, key: `${process.env.PUSHER_API_KEY}`, secret: `${process.env.PUSHER_API_SECRET}`, cluster: `${process.env.PUSHER_APP_CLUSTER}`, encrypted: true }); Now add a .env file at the root of the server folder with the following lines: PUSHER_APP_ID=[PUSHER_APP_ID] PUSHER_API_KEY=[PUSHER_API_KEY] PUSHER_API_SECRET=[PUSHER_API_SECRET] PUSHER_APP_CLUSTER=[PUSHER_APP_CLUSTER] These details for the Pusher client can be obtained from your Pusher dashboard. Create application routes // ------------------------------- // Create app routes // ------------------------------- app.post("/update", function(req, res) { // ------------------------------- // Trigger pusher event // ------------------------------ pusher.trigger("events-channel", "new-like", { likes : `${req.body.likes}` }); }); This application only has one route that triggers the new-like event to the events-channel which our Angular frontend listens for and then updates accordingly. Assign application app.listen("3120"); console.log("Listening on localhost:3120"); Now, the backend server will be run at localhost:3120. Conclusion In this article we have seen how to add realtime functionality to an Angular 5 application. The use cases for this are endless. You can give users realtime feedback as they interact with your applications — Twitter has a feature similar to this where you can actually see the number of likes, replies and retweets in realtime. The ball is in your court now to implement that realtime feature you know your users will love to have. Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at Eighth Floor 6 New Street Square, New Fetter Lane, London, England, EC4A 3AQ.
https://pusher.com/tutorials/angular-realtime/
CC-MAIN-2021-10
refinedweb
1,781
55.54
xUnit 101 xUnit is a unit testing tool for the .Net framework. If you’re new to testing with xUnit, I suggest reading the getting started documentation. xUnit allows support for both parameterless and parameterised tests. There are 3 different ways to supply data to the parameterized tests - Inline Data is good when the method parameters are constant but it gets unwieldy pretty quickly when you have a lot of test cases. It also can’t be used when the data is not constant. - Class Data removes clutter from test files by moving the data to a separate class. It also allows you to pass non-constant data to the test. The downside is that you have to create a new class. - Member Data is similar to class data but uses a static property or method of a type instead of a class. Problems All 3 of the above approaches have a shortcoming in that every time you want to add new data to test, you need a recompile. The classes/methods can also become quite large if you have a lot of data. For example, this is the sample input for the puzzle in the Advent Of Code 2018. First Pass. Go on, I will wait. Oh Good, you are back. So you might be wondering that if Andrew has already written the article, why am I writing this and more importantly why should you spend your precious time reading this? Well. I found his solution to work very well for test cases with a small number of parameters. However, it becomes quite cumbersome to use with a large set of parameters. For the Advent of Code test input, we would have to have a lot of parameters. We could reduce the number of parameters required to just one as its just a single(albeit large) list of the same type. However, I was not able to figure out how to structure my JSON so that it could be parsed easily. Improvements Let us start by creating a new generic class which takes 2 different underlying types – 1 for the Data and 1 for the Result class. This class will be used to deserialize the JSON data class TestObject<T1, T2> { public List<T1> Data { get; set; } public T2 Result { get; set; } } Now,lets modify our attribute class. For brevity, I am just showing the relevant code here. For the whole file please see here. public class JsonFileDataAttribute : DataAttribute { public override IEnumerable<object[]> GetData(MethodInfo testMethod) { // fileData is the raw file data // \_dataType and \_resultType are set in the constructor and are the types for the input data and the result var specific = typeof(TestObject<,>).MakeGenericType(\_dataType, \_resultType); var generic = typeof(List<>).MakeGenericType(specific); var jsonData = JObject.Parse(fileData); dynamic datalist = JsonConvert.DeserializeObject(jsonData, generic); var objectList = new List<object[]>(); foreach (var data in datalist) { objectList.Add(new object[] {data.Data, data.Result}); } return objectList; } } So what exactly are we doing here? - Use MakeGenericType to get the Type of TestObject by substituting the generic type parameters by the actual parameters specified in the test. - Use MakeGenericType again to get a new type which is a List of the new constructed TestObject - Parse the file data as JSON - Deserialize the JSON data as the genericType and store it in a dynamic type. We need to use dynamic here as we dont know the types passed into TestObject at compile time and they can change for each test. - Add all the data into a list of objects and return it This allows us to write our tests in the following manner [Theory] [JsonFileData("testData.json", "Part1", typeof(string), typeof(int))] public void Test(List<string> data, int expectedResult) { var result = TestThisMethod(data); Assert.Equal(expectedResult, result); } References - xUnit documentationn - Advent of Code - Creating a custom xUnit theory test DataAttribute to load data from JSON files by Andrew Lock - MakeGenericType - dynamic Conclusion In this post, we built upon Andrew’s basic implementation of a custom JSON data source to make it easier for us to work with larger sets of data as well are more complex data. This post appeared first on Ankur Sheel - Game Programmer, Traveler and Foodie Continue reading at Load test data from a json file for xUnit tests Discussion
https://dev.to/ankursheel/load-test-data-from-a-json-file-for-xunit-tests-3hlk
CC-MAIN-2020-45
refinedweb
711
53.41
Hi, The number at the pin in red (pin31) are just the way that symbol is annotated in the schematic, I used the usual 3V3 pin (the Teensy pin names/numbers are in the green text). The... Hi, The number at the pin in red (pin31) are just the way that symbol is annotated in the schematic, I used the usual 3V3 pin (the Teensy pin names/numbers are in the green text). The... Hi dim3740, I don't have and iTrack but looking at their website it is expecting a class compliant device so should be fine with teensy acting as a midi device. It doesn't support usb hubs so you... Hi I've also heard it depends on your brand / batch of WS281Bs but I've never had any issues. I had a Teensy 4 board with 8 (not 16) but not problems. I didn't put a cap on each one either and... Hi Sandro, that looks like an interesting project. update is getting called every 128 samples (128@44.1k=2.9ms) you can change the number of samples in a block from 128 to say 16 or 32 or 64 and the... hi I just had a quick look at your sketch, think it will need more memory allocated - try increasing the AudioMemory() Have a look here at AudioMemoryUsageMax() which you can use to print out... hi unawoo, 6 pots and 9 buttons sounds good - you can do a lot with that, have fun :) cheers, Paul O&C is a great idea for the cv hardware, the code base is quite complex (highly optimised) - i've never looked at how easy it is to add an app. If it was me I'd start with one channel, use... Hi Tardishead, I found this tutorial on circular buffers and delays useful, it isn't for the teensy platform (it's for bela) but the principals apply. It might help with streaming incoming signals... hi @bigtony, I'd try moving the pins, try s0 - 10 s1 -11 s2 -12 s3 - 16 If that doesn't work can you take a picture of your actual wiring and post that cheers, Paul Hi, I had a hack at a set of files for you to work on. They will do a basic reverser like your Nootropic link in post #1. The example is set up to take audio through line in but you should be... Sounds and looks great, are you using some of the Shruthi codebase or are you using the audio lib? Cheers, Paul Hi @nishant, I think you're trying to see what's going on inside your custom effect to the actual samples? Like Pete says, you are overloading the buffer sending data to it too quickly. I've... Hi @nishant, looking again at your codes you seem to be modifying AudioEncoder but you main sketch is calling up a different class - AudioEffectRectifier - is that the problem cheers Paul Hi @nishant, can you try commenting out or removing your second Serial.print - it will still be flooding serial with 44000 prints a second cheer paul Hi @nishant Like Pete says, you are going to get a lot of data to serial - it may be overloading it ? I usually put a counter in the update loop to dump out 1 in x blocks or 1 in x samples to... Thanks for that ! hi @dirkenstein, I'd be interested in trying a FP version if you are interested in/able to share, cheers, Paul Hi Ben, can you through up an example of the sketch and samples that you're using and I'll have a go. cheers, Paul hi @bigtony - your attachment in #18 above doesn't work, could you re-post it. also could you post the code you're using to read the pots cheers Paul Hi Ken, really nice work and sounds great! Hi ETMoody3 I've pasted below: - example file (just like the first one in this post that changes a few taps over and over) - effect_tapedelay10tap.h which is the header file for the effect... Thanks again MarkT for the ideas, I made a new delay object to get round the clicks and pops when you change delay times dynamically. It seems to work well letting me adjust multiple taps. It's not... Hi Mark, I thought that might the be the expected behaviour, thanks for confirming and your suggestion - I'll have a go at your second suggestion (cross fading two sets of taps) cheers, Paul Hi I'm using the AudioEffectDelay with a Teensy4 and AudioBoard. When I change tap times I get pops and clicks. I'm changing a few tap time together (like changing between different presets if... what is it doing? do you need some feedback on the delay? cheers Paul I've only ever done it with trial and error and keeping an eye on AudioMemoryUsage(). The various objects use blocks up differently which I'm sure you know, delay uses blocks up quickly (obviously)... Hi Holger memory consumption is decreased if you reduce the largest tap duration You need to allocate memory with AudioMemory based on a number of blocks of samples. The default is 1... Hi Reiner, Your wiring looks ok. The pot will be expecting to turn about 270 degree to get the full range, from the picture I don't think that mechanism will be able to turn the full range so... hi Reiner, You should aim to get the full range from 0 - 1023, are there any resistors in series with the pots? could you post a picture to get an idea of what you're dealing with cheers... hi reibuehl you should wire one end to 3.3V the other end to gnd and the middle pin (the wiper) to one of the Analog input pins. do you know what value the pots are? if you find the input... hi cfredisded in your example code, it updates the delay time every time you go around the loop - for the T4 this will be really fast (lots of time per sample?). if you are just looking to... hi cyclpsrock this thread doesn't answer your specific question but talks about the same issue and points to a shaped envelope object by @a_guy_called_tom... Hi Fluxanode, depends on the library, lots of them do work without change - what library are you wanting to use? Cheers, Paul hi jishnuch It looks as thought you are running PlatformIO on a Raspberry Pi - I'm afraid I have no experience of that. From your error messages the compiler is looking for the... hi jishnuch compiling for 4.1 works fine for me with the standard ini file like above. i'm using: Teensy 4.11.0 on a mac with macOS10.15. If you change the env to Teensy 4.0 does that... hi Dionysus - can you explain a bit more about your setup and what you're doing - are you powering other stuff from the teensy? - a picture would be ideal. A teensy and audio board on it's own... Hi UHF, I use the same mux and had similar periods of stability. I'd come back to it the next day and it would be erratic again needing long settle times. I thought it might be temperature... Hi @UHF Afraid I have no insights on the memory issue but I've also been converting a project from 3.x to 4.x and your analogRead and Mux issues triggered me. After going round in circles for... Hi Jin, I used a WM8731 on a custom board, it is small but not too difficult to solder Cheers Paul Hi an envelope follower should not be difficult - check this thread for a discussion and example I... It's easy to change the number of samples in a block. I run my effects with AUDIO_BLOCK_SAMPLES set to 16 (one block = 0.36ms long). Smaller block sizes work with with most but not all of the... Hi RobertRobotics, For the Teensy 4.0 you need a Rev D shield -. Hi JayShoe an old thread that speaks to your issue I'd stick a peak object on each of your channels... Hi FinleyOderSo, can you throw up your latest code with the changes you made, Cheers, Paul I use following with Teensy 4 which works for me #include <WS2812Serial.h> // leds #define USE_WS2812SERIAL // leds #include <FastLED.h> // leds ... FastLED.addLeds<WS2812SERIAL,... First go at a new board using the WM8731 codec as suggested by @blackaddr, easy to solder and seems to work well, bit more testing to do. Used pretty much the application circuit from the... I found these helpful: Grounding and Decoupling: Learn Basics Staying Well Grounded Here's a simple modification of the standard mixer with 10 inputs, cheers Paul 20646 Hi Holger, I don't want to hijack your thread but could I ask about you stereo > mono effect - are you just summing the channels like the mixer or something else? thank Paul PS I agree a... Hi, you might want to check out from user @C0d3man for a few ideas
https://forum.pjrc.com/search.php?s=03ce10935ed08a9eb745adfbebfb463d&searchid=5829582
CC-MAIN-2020-50
refinedweb
1,527
79.4
In this release we focused on the most “voted for” issues in our bug tracker as well as important performance and stability improvements: So, make sure to check it out: - Phing support added - Initial Twig support - New Diff tools for comparing directories, images and DB’s - ‘Extract Function/Method’ refactoring for PHP - “Change Signature” refactoring for JavaScript - JavaScript debugger in Google Chrome - htaccess support - New code inspections: “Inconsistent return points”, “Silly assignment” and more - PHPDoc @var annotations now support Netbeans/Zend style - Auto-completion improved for classes from other namespaces and Shiftless Completion enabled - HTML tag tree highlighting - Reworked UI for Search/Replace - Misc. improvements for all supported VCS and noticeable improvements in performance For more details on these changes, please read What’s new, and download PhpStorm 2.1. Develop with Pleasure! -JetBrains Web IDE Team This blog is permanently closed. For up-to-date information please follow to corresponding WebStorm blog or PhpStorm blog. Great job guys! I’m using PhpStorm for 6 months and you still suprises me with new features. test test test Is this build “PS-107.120″ ? This bug is still not fixed: I know, it’s pretty rare scenario – using browser specific CSS styles in aspx files, but still it’s a bug. As always, an excellent solid piece of software. This might have been 107.120. It installed in the same folder and I just assume this is “2.1-final” -B Green. Twig and .htaccess support will be quite useful. Thanks! This is indeed 107.120, it says it right on the download page under the “build” option, so it looks like if you downloaded it from EAP when WebStorm 2.1 released, you already had the new final. How to change color for htaccess file types? The upgrade from 2.0 to 2.1 broke IdeaVim support for two people here. (presumably the internal IDE API changed – ) Updating IdeaVim fixed the issue. If more people experience this issue, it might be worth asking people to upgrade on your blog – as I don’t know how many people visit the plugin upgrade page regularly to be informed of IdeaVim updates. @Tomasz Kowalczyk please see reply in this thread: Very poverfull and fast IDE, thanks. I even think it is best IDE for PHP developer now (and with very reasonable price). Finally moved to it from Netbeans after some trial usage. Zend Framework integration is good also, it’s important for me. Is it that I’m (was) used to eclipse based platforms that I’m amazed by an update like this one with real useful features? Thanks a lot, I appreciate it! Thank you, great job! Красавы) Вот за это точно можно скинуть ЛаВэшку)) Hey all, I recently downloaded the 30 day trial, and I am currently on day 1. I am using Symfony2, and it seems to work except when I try and use propel, for example I type in the following: $c = new Criteria(); $c->add(P Then it comes up with a list of items, for example PostPeer, so I choose that. However, instead of coming up with: $c = new Criteria(); $c->add(PostPeer:: It comes up with the full namespace link, as follows: $c->add(appnameawesomeBundleModelPostPeer::) It works perfectly fine in other IDEs, just not PHP Storm. Has anyone else experienced this issue with PHP 5.3, symfony2 ..? Your issue tracker appears to be down… Its not that I mind the new find/replace, but perhaps when I hit ctrl-f, it could highlight the contents of the Find field so that if I start typing it will replace what is there? Right now I am having to hit escape or delete the contents of the Find field (filled with my previous search terms or my clipboard). Its getting annoying, and I don’t remember it behaving that way before. @Megan described issue fixed now. Wait for next update please. after update to a new version via build-in update manager evaluation perion has expiried. is it right or is it bug? Hello, My IDE is notifying me about the update but when i’m clicking the Help>Check of Update it does nothing but showing the message again! I’m using 2.0.1 version and let me know how to update properly. Thanks @Josh Please create a new issue for that –
http://blog.jetbrains.com/webide/2011/05/phpstorm-2-1-available/
CC-MAIN-2015-11
refinedweb
726
72.97
we can create Thread by instantiating and object of type Thread. Java defines two ways by which we can create a Thread : 1. By implementing the runnable interface 2. By extending the Thread class. implementing the runnable interface Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example: public class example4 implements Runnable { // implementing runnable interface public void run() { System.out.println("Hello from a thread!"); } public static void main(String[] args) { Thread T1 = new Thread(new example4()); // thread object of class // example4 T1.start(); // will execute run method of example4; } } Extending the Thread Class Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the below example: public class HelloThread extends Thread { // extending Thread class public void run() { System.out.println("Hello from thread 2"); } public static void main(String args[]) { Thread t2 = new Thread(new HelloThread()); t2.start(); } }
https://www.loopandbreak.com/creating-a-thread/
CC-MAIN-2021-25
refinedweb
182
58.18
John Rose @ Oracle (Comments) 2015-11-08T09:18:55+00:00 Apache Roller Re: fixnums in the VM guest 2014-11-13T13:43:03+00:00 2014-11-13T13:43:03+00:00 <p>I don't see a reason for iop-treatment for Void. There can't be any instances of Void (null is the only value of the Void type).</p> Re: the isthmus in the VM davidcl 2014-06-24T16:03:52+00:00 2014-06-24T16:03:52+00:00 <p.</p> Re: value types in the vm, infant edition guest 2014-06-18T16:41:04+00:00 2014-06-18T16:41:04+00:00 <p>Great to see this moving along. Struct-like enhancements to Java like this are great.</p> <p>My vote for __MakeValue is the null string.</p> <p>I'd love it to be: Point p1 = (1, 34);</p> <p>it'd fit well with assignment to return values as:</p> <p>(x, y) = p1;<br/> or<br/> (x, y) = getRandomPoint();</p> Re: the isthmus in the VM guest 2014-06-17T17:03:48+00:00 2014-06-17T17:03:48+00:00 <p>This reminds me distinctly of a certain project that Sun did back in the day, addressing all the same concerns: </p> <p><a href="" rel="nofollow"></a></p> <p>Are you leveraging that excellent piece of work in Panama?</p> <p>Good luck John!</p> Re: value types in the vm, infant edition Palo Marton 2014-06-17T12:15:41+00:00 2014-06-17T12:15:41+00:00 <p>I have a different proposal that solves similar problems, but (I think) have some clear advantages over “Value types”:</p> <p>- does not require such big changes to JVM (e.g. no new opcodes)<br/> - works better with current java coding practises (supports both mutable and immutable types).<br/> - in some cases improves performance of existing java programs without need to change anything in them.</p> <p>Proposal:</p> <p>1) Add one new special class to java:</p> <p>public class ValuesArray<E> implements List<E> {<br/> native E get(int index);<br/> native E set(int index, E element);<br/> native int size();<br/> static native <E> ValuesArray<E> create(E seed, int size);<br/> ….<br/> }</p> <p>This will behave similarly to ArrayList with fixed size, but instead of storing references to objects, it will store values of its fields. So it is something like array of struct instead of array of references. Methods:</p> <p>create(E seed, int size) - will create new ValuesArray of type E, specified size and filled with values from seed object. It also stores type E (=seed.getClass()).<br/> set(index, element) - instead of storing reference to object, it will store values of its fields.<br/> get(index) - will read values and box them to new object of type E.</p> <p>Of course there will be some limitations on which classes can be used as E. It must be final class and it must support construction of boxed values:<br/> - for mutable objects: all fields of E are public and non-final and it has public no-param constructor.<br/> - for immutable objects: it should have have constructor that has same parameters as objects fields and it assigns those parameters to them.</p> <p>2) Improve escape analyses in JVM:<br/> - should be able to detect that field of a class never escapes and “inline” it. (e.g. Line object with 2 Point fields p1 and p2 can be stored as one object on heap, if JVM can determine that p1 and p2 never escape.)<br/> -).</p> <p>3) Add some support for escape analyses in language. E.g.:<br/> - “@NoEscape” annotation for class fields. For JVM this will be just hint, but for developer it should cause compile time errors/warnings when he tries to use the field in the way that breaks “escape analyses” rules.<br/> - “@ValueType” annotation for class. Makes sure that the class is suitable for ValuesArray.</p> Re: two thoughts about career excellence James Stansell 2014-06-05T15:47:03+00:00 2014-06-05T15:47:03+00:00 <p>Thanks for sharing these!</p> Re: value types in the vm, infant edition Bilal Soidik 2014-05-14T17:04:01+00:00 2014-05-14T17:04:01+00:00 <p>I have some proposal that I think They would be interesting on how to use Values Types. I have two proposal: How to define if? and how to use it? The two are separate proposal. Now I will write the first proposal</p> <p>1.Defining Value Types?<br/>.</p> <p>So I think that to define a value type we can only do:</p> <p>final class Point(int x, int y){</p> <p>boolean equals(Point p){<br/> return this.x==p.x&&this.y==p.y}</p> <p>}; <br/> x and y are automatically final and public members. So that can exactly be compiled like:<br/> final __ByValue class Point {<br/> public final int x;<br/> public final int y;</p> <p> public Point(int x, int y) { <br/> this.x = x;<br/> this.y = y;<br/> }</p> <p> public boolean equals(Point that) {<br/> return this.x == that.x && this.y == that.y;<br/> }<br/> }<br/> Simple, concise and contributes to productivity.<br/> We can also do:<br/> final class Point(int x, int y){ <br/> private int c;//if I wont<br/> boolean equals(Point p){<br/> return this.x==p.x&&this.y==p.y}<br/> public static Point getFunPoint(){<br/> }<br/> public static void maFunction(Point p, boolean b, double b){<br/> }<br/> }</p> <p>I also thought about something new:</p> <p>B. Why not an implicit default equals. So if I do :<br/> final class Point(int x, int y){} that means if the JVM doesn't find an explicit equals, it cans do logical compare.<br/> public boolean equals(Point that) {<br/> return this.x == that.x && this.y == that.y;<br/> }.<br/> So a Point can be defined in one line:</p> <p>final class Point(int x, int y){}</p> <p>C. If we don't want to define something else in a value types, braces can be optional as in lambda expressions :)<br/> So to define a value type we can only do:</p> <p>final class Point(int x, int y);</p> Re: value types in the vm, infant edition M. Eric DeFazio 2014-05-14T14:52:48+00:00 2014-05-14T14:52:48+00:00 <p>In addition to graphics programming which has been mentioned, there are a few problem spaces that I've encountered where something along the lines of ValueTypes could be of great significance (but the “Devil is in the Details”):</p> <p.).</p> ... </p> <p>...I have a few others, (i.e. Cache Oblivious Data Structures /OffHeap/Unsafe and Language interoperability use cases which others have discussed) but (stepping back for a moment) I ask myself (philosophically): </p> <p)?</p> <p?). </p> <p"...</p> <p.</p> <p>Cheers,<br/> Eric</p> Re: value types in the vm, infant edition Clay 2014-05-05T14:39:20+00:00 2014-05-05T14:39:20+00:00 <p>What is the explosion of complexity with non-final fields? If all fields are final, why can't it be passed by reference to avoid the copying overhead of pass by value? What is the difference between this proposal and C# structs?</p> Re: value types in the vm, infant edition Tim Boudreau 2014-05-03T22:23:23+00:00 2014-05-03T22:23:23+00:00 <p>I get the feeling you might be looking at the problem upside-down.</p> <p.</p> <p</p> <p>public <T extends IFace & Object> void syncsOnElements(Set<T> objs)</p> <p.</p> <p.</p> <p.</p> .</p> Re: value types in the vm, infant edition guest 2014-05-03T00:42:45+00:00 2014-05-03T00:42:45+00:00 .</p> Re: the isthmus in the VM Nick Evgeniev 2014-03-23T04:52:13+00:00 2014-03-23T04:52:13+00:00 <p>speaking of easy of use there are<br/> <a href="" rel="nofollow"></a><br/> <a href="" rel="nofollow"></a></p> <p>they both focus on easy of use and bridj fixes some awful performance issues of jna ... but speaking of the performance (I mean real performance)</p> <p>1. SLOW callbacks from native to java<br/> 2. lack of structs&layout control in java (it kills!!!)</p> <p>check structs, pointers to structs, fixed arrays in .NET problem was solved years ago... and in java we have to go off-heap and do all the nasty tricks :(... it's a shame :(</p> <p>even go-lang has better integration with C :)</p> Re: the isthmus in the VM guest 2014-03-19T09:42:31+00:00 2014-03-19T09:42:31+00:00 <p>It would be really great, if Project Panama would also be designed to include easy access to Objective-C APIs, beside C and C++ APIs.</p> <p>Objective-C is in widespread use these days.</p> Re: value types and struct tearing Nick Evgeniev 2014-03-17T22:24:50+00:00 2014-03-17T22:24:50+00:00 <p>I wish java had sturcts in EXACTLY the same way as in .NET. There is no need to reinvent the wheel. They are ultimate solution for simple garbage free code!</p> <p>1. they can be mutable or immutable<br/> 2. mutable are ideal for garbage free iterators and alike data structures<br/> 3. the only minor issue with structs in .NET is boxing if you try to use them in polymorphic way (ie as reference type):</p> <p>let's say we have struct A : ISomething {} .. to pass it to some method w/o boxing it has to be declared like:<br/> void method<T>(T data) where T : ISomething {}<br/> instead of: <br/> void method(ISomethig data) {}</p> <p>this is THE ONLY thing that PROBABLY needs an improvement... Just import the good things as it is! Please don't screw up everyones mind :)</p> Re: value types and struct tearing Scott C 2014-03-09T19:38:53+00:00 2014-03-09T19:38:53+00:00 <p>"I'm confused. How would persistent containers work as array elements/fields? It seems like they would need to be boxed, which defats the original purpose. "</p> <p). </p> <p>So although pointers are still necessary, multiple levels of indirection can be avoided in real world use cases (along with object header overhead).</p> Re: value types in the vm Sam Umbach 2014-03-07T19:44:23+00:00 2014-03-07T19:44:23+00:00 <p>Great post! I'm glad to have stumbled upon it from your post on struct tearing.</p> <p>I found two passages confusing, but I'm not sure whether they are errors or lack of understanding on my part:</p> <p>"The non-static fields of a value class must be non-public and final": Do you mean "non-private" instead? That would be consistent with your earlier statement that value types be structurally transparent.</p> <p>"protected private final BigInteger digits": Is this introducing a new "protected private" access modifier? Or is this intended to be "protected"?</p> <p>Cheers!<br/> -Sam</p> Re: value types and struct tearing guest 2014-03-07T06:55:06+00:00 2014-03-07T06:55:06+00:00 <p.</p> <p>For example, value types can tear in .NET. If you don't want that just don't create a race. That design trade-off works well.</p> Re: value types and struct tearing Sebastian Fernandez 2014-03-07T06:24:36+00:00 2014-03-07T06:24:36+00:00 <p?</p> Re: value types and struct tearing guest 2014-03-07T06:11:30+00:00 2014-03-07T06:11:30+00:00 <p.</p> Re: value types and struct tearing John Rose 2014-03-06T20:37:52+00:00 2014-03-06T20:37:52+00:00 <p>@Jeroen: That is true, generally, along with OutOfMemoryError. But in the XY case users probably don't need to worry about it happening between the two field assignments. Unless a de-opt happens somehow and tips over the stack.</p> <p>Edits to blog post: fix broken links, a couple minor rephrasings. H/T to Markdown & Smartypants.</p> Re: value types and struct tearing Jeroen Frijters 2014-03-06T12:18:04+00:00 2014-03-06T12:18:04+00:00 <p>Minor comment on "side note 1": I believe that a StackOverflowException can also cause invariants to be violated.</p> Re: tuples in the VM guest 2013-06-13T00:21:45+00:00 2013-06-13T00:21:45+00:00 <p>Erasure is a bad idea, for example, I've tried to explain till I'm blue in the face, the problem of using Generic's in java.rmi.Remote interfaces, but all too often I get blank looks and arguments.</p> <p>The problem is, code compiled separately, but linked dynamically at run time, although using a common interface is broken if that code has been subject to erasure, because it cannot be checked at runtime and has not been checked at compile time either.</p> <p>Don't make the same mistake Sun did with Generics, increment the byte code version, developers have the option of compiling to an earlier version, it's no big deal. Even better fix Generics by eliminating erasure.</p> <p>We're at an exciting time in Java's history, where we'll soon get to take advantage of immutability and functional programming idoms, lets not add complexity by using erasure.</p> <p>In an ever more distributed world, we need to consider the distributed aspects of Java.</p> Re: value types in the vm Peter 2013-04-15T04:34:03+00:00 2013-04-15T04:34:03+00:00 <p>We really need these features.</p> <p>Would you consider naming the new operator 'freeze' instead of lockPermanently?</p> <p>Cheers,</p> <p>Peter.</p> Re: value types in the vm guest 2012-10-26T00:06:11+00:00 2012-10-26T00:06:11+00:00 <p>Why not extend the byte code to support multiple return types? This type of extension could then be taken advantage of by various language byte code compilers. From a byte code perspective supporting a maximum return size of 64bits is the biggest obstacles to support efficient light weight structures in languages written for the JVM.</p> <p>If the byte code were extended then language implementors would be able to explicitly and deterministically support efficient light-weight structures while exposing this capability to developers using programming idioms or language structures that are best suited for that language.</p> <p>I think such a generic and powerful byte code extension could come first, followed by language specific extensions to support concepts such as value types, tuples, complex type etc...</p> <p>I would be great to see something similar your vreturn (tuples_in_the_vm 2007) be the next JVM byte code extension.</p> Re: the OpenJDK group at Oracle is growing Mohan 2012-10-06T15:41:07+00:00 2012-10-06T15:41:07+00:00 <p>Is there a recommendation of reading material or books for the type of job you have advertised ? Is it about virtual machines in general ?</p> Re: symbolic freedom in the VM guest 2012-08-18T03:56:43+00:00 2012-08-18T03:56:43+00:00 <p>During the conversion process, all the backslashes got doubled, thus unintentionally exhibiting an example of what's wrong with C-style backslash escapes. Please fix, as it's very confusing!</p> Re: value types in the vm Daniel Latrémolière 2012-08-08T12:32:46+00:00 2012-08-08T12:32:46+00:00 <p>I understand how tagging with an interface implemented or an annotation will be useful for development. But in a released future JVM, I hope for a context-specific keyword like: public tuple Complex {...}</p> <p>Java has already class, interface, enumeration ("enum"), annotation ("@interface"), then I would prefer addition of "tuple" keyword specifically to this context (scope of type definition).</p> <p>I think, there is no risk of confusion with an existing variable, method, type name of current code at this position in code. If context-specific parser is too much problematic, I would prefer "@class" as keyword, like annotation has "@interface":<br/> public @class Complex {...}</p> Re: interface injection in the VM Kálmán Kéri 2012-07-23T03:00:56+00:00 2012-07-23T03:00:56+00:00 <p>Dear Mr. John Rose! How do you think about this today? I could make very good use of such an extension in the JVM.<br/> Currently I'm trying to resolve something I call the model composability problem (in a sense Ossher and Harrison exposed it in their subject-oriented programming paper).</p> <p>Suppose a model M that builds up from data entities and polymorphic operations. Two programmers write extensions A,B to the model in a reuseable fashion that is, without modifying the source of M. The challenge is how to compose M, A and B into a model C.<br/> I figured out a series of patterns but each one has its limitations either in terms of flexibility or performance. </p> <p>One of my patterns uses method handles. It works on system classes but doesn't eliminate the use of a lookup map for dispatch.<br/> Load-time class modification would be elegant but as far as I know it's not allowed on system classes as java.lang.String.</p> <p>Interface injection as you described seems the best solution to me and possibly to writers of interpreters, compilers, and more generally model transformers.<br/> Why is it good:<br/> -it is pure java<br/> -it stays in the strongly typed world<br/> As a consequence it can be embedded into the core of the JVM and it can be really fast.<br/> If this was a JSR I would vote on it.</p> Re: celestial harmony remi 2012-05-25T22:43:43+00:00 2012-05-25T22:43:43+00:00 <p>It remember me something. Music is better than (words) comments, sometime when I read codes I've troubled to understand, I would like to have a comment from the original writer saying something like, "when I've written this class, I was listening that particular song".<br/> I'm sure it will be easier to for me to understand/modify the code by listening the same song.</p> <p>In fact, we should invent a license saying you can rip or modify the code only if you listen a particular album when doing that. </p> <p>Rémi<br/> Gnarls Barclay - The odd couple - Blind Mary</p> Re: celestial harmony John Cowan 2012-05-25T14:22:31+00:00 2012-05-25T14:22:31+00:00 <p>I liked this YouTube comment by APolaris:</p> <p>I like the way [Neptune] exemplifies the ruthlessness of the universe. Mars is violent, and Uranus is.</p>
https://blogs.oracle.com/jrose/feed/comments/atom
CC-MAIN-2015-48
refinedweb
3,222
62.07
14 May 2012 09:52 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The source said the company could not confirm when the line will be restarted. The producer shut the line because of high inventory levels, an industry source said. The turnaround at the plant will not likely to have impact on the market as downstream demand will remain weak until around July, a market player said. The producer’s 50,000 tonne/year high-impact polystyrene (HIPS) line and 50,000 tonne/year HIPS/GPPS swing plant at the same site are running at 100% of capacity and will not be shut,
http://www.icis.com/Articles/2012/05/14/9559201/chinas-sk-networks-ps-shantou-to-shut-gpps-line-on-15.html
CC-MAIN-2014-42
refinedweb
103
69.52
Make Your Garage Door Opener Smart: Shelly 1, ESPHome and Home Assistant! It runs ESPHome (open-source, no cloud) and integrates seamlessly with Home Assistant. Here’s how I did it. Meet my garage door opener This is my “dumb” garage door opener. It’s from FAAC and is only controllable with the included RF remotes. My “dumb” FAAC garage door opener is about to get smart! But don’t worry, these instructions should work with every single brand of garage door openers (including Hörmann, Genie, LiftMaster, Chamberlain, …). The only requirement is that the opener must have an input for a wall switch. As far as I know, all operators have this, yay! Goals: What I want Before starting, let me tell you what I wanted to accomplish by making the garage smart: - Be able to open the garage door with my phone, so I don’t have to carry a remote (or worry about forgetting the damn thing). - I want to have fun with automations. Get an actionable notification when I arrive with the car, automatically close it when it’s left open… - Add it to the home security system so I can be alerted when the garage opens when it shouldn’t. But most importantly, the “smart” garage door should adhere to my smart home policy: Making things “smart” should only add a new layer of control, not replacing existing ones. Smart lights should be controllable with the regular wall switches. A smart garage door should still work with the remote. This rule also massively boosts the Wife Approval Factor ;) What you’ll need - WiFi (+ coverage in the garage) - Shelly 1 (smart switch) - Wired magnetic door contact sensor (any brand is fine) Shelly 1 Most garage door openers allow you to connect a wall-switch to open and close it. That way, it’s easy to open your garage from the inside by just pressing a switch. So my idea was simple: have a Sonoff Mini act as a switch to open and close the garage. One problem though: the Sonoff doesn’t have dry contacts. It forces you to push 110/230V to the connected device, and that will fry most garage door openers. Most models use a volt-free contact or 12-24V DC power. Instead, I went with a Shelly 1. It’s a bit smaller than the Sonoff, and it exposes both sides of the relay (input & output). Meaning you can switch any voltage (within reason) and are not limited to 110 or 230V. Sonoff Mini vs. Shelly 1. Roughly the same size and functionality, except for dry-contacts. Another bonus point for the Shelly; it can be powered by 110-230V (AC) OR with 12-60V (DC). My garage door opener happens to have a 24V output. Perfect to completely hide the Shelly inside! Magnetic Door Contact Sensor I also bought a magnetic door sensor to sense the state of the garage door. This is entirely optional, but it’s a cheap way to know if your garage is open or closed. I ordered this one from Amazon with a 2 meter cable, but any wired contact sensor will work: Magnetic door contact sensor You could also use wireless door sensors (Zigbee) and use a Template Cover in Home Assistant to combine them. However, I prefer wired solutions wherever I can (no batteries to replace). I then attached the sensor to the garage door pulley (black plastic parts in the photo). As soon as the garage door opens just a few centimeters, the contact is broken, and the state can be updated. Contact sensor attached to the “pulley” of my garage door opener & metal frame. Wiring Connecting the Shelly to your garage door opener and the contact sensor is relatively easy: - Power the Shelly with 24-60V DC. - Connect the contact sensor to SWand ground of the Shelly. - Connect your garage door opener’s switch contact to the input Iand output Oof the Shelly. Please be careful when wiring this all up. Disconnect your garage door opener from mains, so you don’t get hurt! It would be a shame to get electrocuted before being able to test it ;) When you use DC power, Shelly’s L becomes the negative wire, and the N becomes the positive one. This is exactly the opposite of AC wiring, so be sure you don’t get them mixed up. The contact sensor still has to be connected to SW, but the other end should now be connected to L, which is Shelly’s negative wire when using DC power. Connect Shelly to DC power. Watch out: L is now negative, while N is positive. Warning: you can run the Shelly on 110-230V, but not with this contact sensor. The Shelly puts main voltage on the SWinput and the sensor isn’t rated for that voltage! So please stick to DC or buy an appropriate contact switch. Custom firmware: ESPHome Next up: flashing a custom firmware to the Shelly. I was already using ESPHome for my light switches (also Shelly’s) and thought I would do the same here. (I won’t go over how to flash the Shelly as there are many tutorials available) Why do I like ESPHome so much? - It’s open-source - You can configure your devices with YAML and track changes with git (I store mine with my Home Assistant configuration) - There is a great ESPHome add-on for Home Assistant that allows you to upload changes directly to the devices. - It integrates seamlessly with Home Assistant. No need for MQTT (sorry, Tasmota). - You can write small automations that run autonomously on the device itself. Time for some YAML configuration then! There are three main things we have to configure: - The relay inside the Shelly 1 so we can turn it on/off to actuate the garage door. - The contact sensor attached to the SWinput of the Shelly. We’ll use this to determine the state of the garage door. - The “cover” that will be exposed to Home Assistant. This is your garage door! Note: This isn’t a comprehensive getting started guide. If you’re unfamiliar with ESPHome or have trouble following these steps, check out the Get Started section of their documentation. Let’s start with the relay inside the Shelly. We have to create a switch and tell ESPHome to which GPIO pin the relay is attached. I marked it as internal because I don’t need the state of the relay in Home Assistant: switch: - platform: gpio pin: GPIO4 name: "Garage Door Relay" id: relay internal: true Next up: the contact sensor. For this, I use a binary_sensor that looks at Shelly’s SW input (attached to GPIO5). Once again, this is an internal component. I added the invert filter because my contact sensor returns false when the garage is open, and I think that somewhat counterintuitive. But this isn’t required, just keep it in mind for the next steps ;) binary_sensor: - platform: gpio pin: GPIO5 name: "Garage Door Contact Sensor" id: contact_sensor internal: true filters: - invert: With these two components, we can now make the cover component that will be exposed to Home Assistant. To send the correct state of the door, we have to implement a simple lambda function. Mine returns COVER_OPEN when the contact sensor is true (remember that I inverted it) and otherwise it returns COVER_CLOSED. To actuate the garage door, I’ve defined open_action and close_action to briefly toggle the relay (0.5 seconds). That is what my garage door opener requires to open or close. A stop_action was not implemented because my opener has a built-in safety system. Here is the full ESPHome configuration for my garage, including stuff like board type, WiFi configuration, Home Assistant API, … substitutions: friendly_name: Garage esphome: name: garage platform: ESP8266 board: esp01_1m # The door contact sensor that is attached to SW on the # Shelly 1. Not exposed to HA, instead used to set the # state of the cover. binary_sensor: - platform: gpio pin: GPIO5 name: "Garage Door Contact Sensor" id: contact_sensor internal: true filters: - invert: # The relay in the Shelly 1 that will deliver the pulse to # the garage door opener (not exposed to HA) switch: - platform: gpio pin: GPIO4 name: "Garage Door Relay" id: relay internal: true # This creates the actual garage door in HA. The state is based # on the contact sensor. Opening/closing the garage door simply # turns the relay on/off with a 0.5s delay in between. wifi: ssid: !secret wifi_iot_ssid password: !secret wifi_iot_password # Enable fallback hotspot (captive portal) in case wifi connection fails ap: ssid: $friendly_name Fallback Hotspot password: !secret esphome_fallback_ap_password captive_portal: # Enable logging logger: # Enable Home Assistant API api: password: !secret esphome_api_password ota: password: !secret esphome_api_password # Send IP Address to HA text_sensor: - platform: wifi_info ip_address: name: $friendly_name IP Address # Send WiFi signal strength & uptime to HA sensor: - platform: wifi_signal name: $friendly_name WiFi Strength update_interval: 60s - platform: uptime name: $friendly_name "Uptime" Installing neatly Time to install everything properly. To secure the cable of the door contact sensor, I 3D printed some zip tie anchors. Thanks, LoboCNC for putting your design on Thingiverse! 3D Printed zip-tie anchors for cable management I glued these on top of the garage door’s aluminum frame and then zip-tied the sensor cable to them: Securing the sensor’s cable (don’t want it jamming up my garage door) You can see that the cable enters the top of the garage door opener (that opening was already there for other peripherals). I then took off the bottom lid and attached the Shelly 1 with adhesive tape: Shelly 1 inside my garage door opener. Attached with adhesive tape. The Shelly is connected to the garage door opener’s logic board to toggle the state (and also received 24V of power from it): Shelly connected to the logic board of the garage door opener Putting the lid back on, and everything is hidden from view. Nice and clean: From the outside everything is still the same. Looks like a “dumb” garage door opener. Home Assistant With the ESPHome setup finished, it’s time to integrate everything into Home Assistant. Luckily, ESPHome devices are automatically discovered, so no need for manual setup. Cool! ESPHome devices are automatically discovered by Home Assistant The cover we configured in ESPHome is automatically exposed to Home Assistant as well. Here is my Garage Door in Lovelace: Garage Door controls in Home Assistant Because of the contact sensor, Home Assistant knows exactly if the garage door is opened or closed, and the arrows reflect that. Garage closed? Up arrow is enabled. Garage open? Down arrow is enabled. My default ESPHome configuration also sends additional data to Home Assistant: the uptime of the Shelly, its IP address, and WiFi signal strength. I don’t use these often, but they can help diagnose problems when they arise (is the WiFi connection bad / does the Shelly often restart / etc..) Additional entities that could help spot/debug problems Automation examples Once these entities are in Home Assistant, you can start automating! We always keep our garage door closed but occasionally forget it. So the first automation I made is one that alerts us when the garage was left open longer than 5 minutes: - id: b8aa033f-800f-4d26-8f99-f533d705421f alias: "[📣] Notify when garage door was left open for too long" trigger: platform: state entity_id: cover.garage_door to: open for: minutes: 5 action: - service: notify.notify data: title: "🚙 Garage left open!" message: "Garage door has been open for 5 minutes. Close it?" Actionable notifications As said in the beginning: I don’t want to carry the garage’s remote control anymore. So I created an automation that sends me an actionable notification whenever I arrive home on weekdays. Tap it, and the garage opens without having to go into Home Assistant. You can read more about how to setup actionable notifications on the Home Assistant Companion Apps website: Here’s the automation that send the actionable notification: - id: 082bf626-021e-4e05-8a9e-c36a94486bc5 alias: "[📣] Send notification to Xavier to open garage door on weekdays" trigger: - platform: state entity_id: person.xavier_decuyper from: not_home to: home condition: condition: time weekday: - mon - tue - wed - thu - fri action: - service: notify.mobile_app_iphone_van_xavier data: title: "🏡 🔑 Welcome home Xavier!" message: "Want to open the garage?" data: push: category: garage_open Note the extra data I send and the garage_open category. In my configuration.yaml file I then created a category for this actionable notification ( garage_open with the identifier GARAGE_OPEN). I’ve also set authenticationRequired to true, so FaceID/TouchID is required before being able to open the garage. Better be safe! ios: push: categories: - name: Garage open identifier: 'garage_open' actions: - identifier: 'GARAGE_OPEN' title: 'Open garage' activationMode: 'background' authenticationRequired: true # Require FaceID / TouchID destructive: false behavior: 'default' When the user clicks on “Open garage” an event is created in Home Assistant. This is then used by another automation to open the garage and close it after about a minute. This gives me ample of time to park my bike and make my way to the house: - id: 6c18050e-dad5-455f-bd52-4a1d5ad50cbd alias: '[📣📲] Callback notification to open garage' trigger: platform: event event_type: ios.notification_action_fired event_data: actionName: GARAGE_OPEN action: - service: cover.open_cover data: {} entity_id: cover.garage_door - delay: 00:01:00 - service: cover.close_cover data: {} entity_id: cover.garage_door This is what it looks like on my phone: Actionable notification on iOS Automating lights Here’s another conventient automation: when the garage door opens (and it’s dark outside), turn on the lights. Then, 30 seconds after the garage was closed, turn them off again. Both these actions are automated with a single automation: - id: 79d7fa44-a2bc-4856-ba6d-f42a58fe6080 alias: '[💡] Garage light on when gate opens/closes' trigger: - platform: state entity_id: cover.garage_door from: closed to: open for: seconds: 2 - platform: state entity_id: cover.garage_door from: open to: closed for: seconds: 30 # Turn off, when garage is closed for 30 seconds condition: - condition: state entity_id: sun.sun state: below_horizon action: - service_template: >- {% if trigger.to_state.state == "open" %}light.turn_on{% endif %} {% if trigger.to_state.state == "closed" %}light.turn_off{% endif %} entity_id: light.garage data: {} It’s things like this that make me appreciate Home Assistant. No more walking to the light switch in the dark ;) Conclusion & next steps I’m super happy with how this turned out. Our “smart” garage door has been very reliable, so much so that I don’t even bother carrying the remote! It also gives me peace of mind being able to check the state of the garage easily and knowing that it’s tied into the security system. As a next step, I would like to automatically open the garage when we drive up to it (as opposed to the notification). I’m thinking about using a Bluetooth beacon in the car. Any thoughts? Happy home hacking!
https://savjee.be/2020/06/make-garage-door-opener-smart-shelly-esphome-home-assistant/
CC-MAIN-2020-45
refinedweb
2,472
63.39
Serial com-port communication with autoIt December 7, 2008 at 5:12 pm 13 comments This weekend I found out how to read from / write to a com port with autoIt code. I created a file with some functions that read/write single characters or lines. To communicate with a com port, I use the CreateFile function from Kernel32.dll. This is my first script where I call dll functions from within autoIt, so perhaps the code can be cleaned up some more. First, we’ll create a handle to the CreateFile function to open the com port (com2 in this example): #include <WinAPI.au3> ;init DLL function, we need handle to call the function $h = DllCall("Kernel32.dll", "hwnd", "CreateFile", "str", "\\.\COM2", "int", BitOR($GENERIC_READ,$GENERIC_WRITE), "int", 0, "ptr", 0, "int", $OPEN_EXISTING, "int", $FILE_ATTRIBUTE_NORMAL, "int", 0) $handle=$h[0] To write a single character, I created the writeChar function: ;write a single char func writeChar($handle,$c) $stString = DLLStructCreate("char str") $lpNumberOfBytesWritten = 0 DllStructSetData($stString, 1, $c) $res = _WinAPI_WriteFile($handle, DllStructGetPtr($stString, "str"), 1, $lpNumberOfBytesWritten) if ($res<>true) then ConsoleWrite ( _WinAPI_GetLastErrorMessage() & @LF) EndIf EndFunc A struct that contains a single character is created first. On the third line the character is passed to this struct. Then the _WinAPI_WriteFile function is called with the struct as argument. If everything is ok, then the character is written to the com port! The other functions work in a similar manner, and can be found in the attachment. This code is very usefull to communicate with microcontrollers, like a PIC uC for example. I was already able to communicate with Matlab (see my other article) which is very usefull for plotting sensor values. The autoIt communication is usefull for remote controlling Windows applications. A simple demo app to illustrate this: autoIt Code: #include "pcSide2.au3" While 1 $data = readLineBlock($handle) ConsoleWrite(">" & $data) switch $data case "L" & @LF send("{MEDIA_PREV}") case "R" & @LF send("{MEDIA_NEXT}") case "U" & @LF send("{VOLUME_UP}") case "D" & @LF send("{VOLUME_DOWN}") case "C" & @LF send("{MEDIA_PLAY_PAUSE}") EndSwitch Wend PIC code: while (1) { if (!(BUTTON_CENTER)) { //BUTTON_CENTER pressed fprintf (_H_USART, "C\n"); while(!(BUTTON_CENTER)); //wait till button released } if (!(BUTTON_UP)) { //BUTTON_UP pressed fprintf (_H_USART, "U\n"); while(!(BUTTON_UP)); //wait till button released } ... } So the autoIt code just waits for characters to be sent. If one of the characters U,D,L,R or C is sent (the characters come from Up,Down,Left,Right,Center in case you’re wondering), autoIt will emulate a keypress of one of the Media functions. The PIC code will send one of the characters when a certain button is pressed. So we are able to remote controll our media player (e.g. Windows Media Player) with our PIC uC! Attachments: [ com functions for autoIt ] 2kB [ demo Application (autoIt code) ] 0kB Entry filed under: Uncategorized. Tags: autoIt, com port, dll, PIC, PIC18F, serial. 13 Comments Add your own Trackback this post | Subscribe to the comments via RSS Feed 1. Serial com-port communication with autoIt « Kr3l’s Turf | corporated.net | December 7, 2008 at 5:32 pm […] Serial com-port communication with autoIt « Kr3l’s Turf […] 2. jchd | December 13, 2008 at 1:53 pm Thank you very much for sharing your solution. It just sounds like this is the simple and efficient way to perform simple tasks using serial links from AutoIt. I have been delaying starting up on a little “project” (an overkill name for such small thing) involving some protocol transform between low-cost shipping scales and a proprietary shipping software. I’ve even been tempted to have a little box with some PIC inside to perform the task transparently, but it’ll really much simpler to perform an equivalent task with some AutoIt script doing the conversion on the fly and stuffing weights at the right place in the input form. So thank you again, I bet your code will do wonders. 3. kr3l | December 17, 2008 at 11:47 am Thanks for your comment 🙂 4. praveen | July 8, 2009 at 7:03 am Hi, i cant able to run your code, I get the error mesage $GENERIC_READ,$GENERIC_WRITE are not defined I dont know which value we want to give for those variables. i want to read some sensor outputs from serial port(COM3)[rs232].I would like to plot that values in autoit gui.please give me any idea to resolve this problum.my mail id is pravymon_at_gmail.com 5. Karel | July 8, 2009 at 7:22 am Hi, did you include WinAPI.au3 in your code? Karel 6. pixeldoc | May 31, 2010 at 12:56 am Nice example! Sadly the Attachment links are dead. Could you please fix them? Thanks. 7. bob.mcnair | August 20, 2010 at 9:58 am Dear Karel Unfortunately the links above don’t work. Can you please send me a working example of the pcside.au3? Thanks for your support! Cheers, bob. 8. Karel | August 20, 2010 at 10:32 am Hi Bob, I’m sorry the links don’t work anymore. I’ll check this evening if I can find the code back and place it online. Regards, Karel 9. Karel | August 20, 2010 at 9:15 pm Hi again Bob, Turned out I had to renew my account with Freehostia, but the files were still there. So the links work again! Greets, Karel 10. koby | May 4, 2011 at 2:02 pm How do you control COM settings such as BAUD rate and parity? Thanks, Koby 11. Trevor | June 21, 2013 at 8:12 pm Understand this is old. But you have what I was looking for. Any chance you could re-post your code library? 12. Adina | April 20, 2016 at 3:02 pm Hello! Is it possible to attach again the files from links: com functions for autoIt and demo Application (autoIt code)? Thank you 13. Marc Elser | April 22, 2016 at 6:11 am downloads have gone. Can you please repost?
https://kr3l.wordpress.com/2008/12/07/serial-com-port-communication-with-autoit/
CC-MAIN-2017-26
refinedweb
991
74.29
It is not much we can learn from the "design flaws" mentioned in the article. It would have been very hard for Thompson and Ritchie to predict CDROM, sockets or distributed file systems. The beauty of the original design was its simplicity. This made it possible to later extend the design. If we want to look at bad designs there are better examples. I would suggest SYSV IPC or curses. Or maybe look outside Unix. See how the equivalent of read(), write() and mount() were done on CP/M or DOS 1.0. Ghosts of Unix past, part 2: Conflated designs Posted Nov 11, 2010 23:51 UTC (Thu) by bronson (subscriber, #4806) [Link] Not sure where you see the author saying anything is bad design. He's just considering how good things can be made better. Show me something that can't! Ghosts of Unix past, part 2: Conflated designs Posted Nov 12, 2010 22:58 UTC (Fri) by giraffedata (subscriber, #1954) [Link] I believe the author does say that conflating is bad design. And the point of looking at design patterns is that one shouldn't expect to predict things like CDROMs, sockets, and network filesystems. Instead of trying to list all the ways your thing will be used, just follow certain patterns and things will work out by themselves. Even if you can't see, or there doesn't exist, any present downside to conflating two designs, don't conflate them anyway and you will be more successful. We may still be able to excuse Thompson and Ritchie with a hindsight argument by saying that the way things looked at the time, creating a filesystem image and adding it to the namespace were fundamentally a single gestalt, and it is only since then that we have learned to think of it as two things. Ghosts of Unix past, part 2: Conflated designs Posted Nov 18, 2010 15:32 UTC (Thu) by renox (subscriber, #23785) [Link] I agree but Plan9's designers already did this to Unix.. So improving on Plan9 would be interesting, but I'm not sure I see the point for Unix! Linux is a registered trademark of Linus Torvalds
https://lwn.net/Articles/414731/
CC-MAIN-2017-30
refinedweb
365
78.08
I have a small compilable example that is not working for reasons that are way beyond me. I say percent != 100 && g_thang != true, which are two conditions that would be set if the sound was loaded, yet, my loop breaks when only g_thang get’s set to true (which is when the completion callback is called), you can see in the sample output at the bottom that this the results don’t make sense! [code:1cai30av]#include "fmod.hpp" include "fmod_errors.h" using namespace std; static bool g_thang = false; FMOD_RESULT F_CALLBACK asyncOpen( FMOD_SOUND * sound, FMOD_RESULT result ) { cout << "OMG!\n"; FMOD::Sound * cppsound = reinterpret_cast< FMOD::Sound * >( sound ); g_thang = true; return result; } struct fmod_system { FMOD::System * fsystem; FMOD::Sound * fsound; FMOD::Channel * fchannel; fmod_system() { FMOD_RESULT result; result = FMOD::System_Create( &fsystem ); if (result != FMOD_OK) { cout << TEXT("FMOD: ") << FMOD_ErrorString(result) << endl; } result = fsystem->init(10, FMOD_INIT_NORMAL, 0); if (result != FMOD_OK) { cout << TEXT("FMOD: ") << FMOD_ErrorString(result) << endl; } FMOD_CREATESOUNDEXINFO exInfo = { 0 }; exInfo.cbsize = sizeof( FMOD_CREATESOUNDEXINFO ); exInfo.nonblockcallback = asyncOpen; result = fsystem->createSound( "C:\\Black Fire.mp3", FMOD_DEFAULT | FMOD_NONBLOCKING, &exInfo, &fsound ); if( result != FMOD_OK ) { cout << TEXT("FMOD 1: ") << FMOD_ErrorString(result) << endl; } FMOD_OPENSTATE open_state; unsigned int percent = 0, i = 0; do { result = fsound->getOpenState( &open_state, &percent, 0 ); if( result == FMOD_OK ) { cout << TEXT("FMOD 2: ") << open_state << TEXT(" ") << percent << TEXT("\n"); } else { cout << TEXT("FMOD 3: ") << FMOD_ErrorString(result) << TEXT("\n"); break; } fsystem->update(); } while( percent != 100 && g_thang != true ); result = fsystem->playSound( FMOD_CHANNEL_FREE, fsound, false, &fchannel ); if( result != FMOD_OK ) { cout << TEXT("Percent loaded: ") << percent << endl << TEXT("FMOD 4: ") << FMOD_ErrorString(result) << endl; } } ~fmod_system() { fchannel->stop(); fsound->release(); fsystem->release(); } }; int main() { fmod_system system; }[/code:1cai30av] The output of the program is something like this: [code:1cai30av]FMOD 2: OMG! 1 0 Percent loaded: 0 FMOD 4: Operation could not be performed because specified sound is not ready.[/code:1cai30av] It immediately calls the completion callback, somehow thinks that the percent is 100, and then says that the sound is not ready. Why would it do this? - Tonto asked 10 years ago - You must login to post comments You should not do direct comparisons of floats in C, 100.0 does not always equal 100.0 (see IEEE standard). You should be using a small epsilon with greater than/equals check with something like 99.9 for example. - Brett Paterson answered 10 years ago I don’t think there’s any floating point things here. [code:r51j2a3d]FMOD_RESULT Sound::getOpenState( FMOD_OPENSTATE * openstate, unsigned int * percentbuffered, bool * starving );[/code:r51j2a3d] In addition, somehow the loop breaks without percent being 100 (in fact, the program says that it’s value if 0!). I will try to do some debugging to see what could have caused this madness. In the mean time, replies are appreciated because this function is pretty wierd. It should be noted that FMOD_OPENSTATE that I get seems valid (FMOD_LOADING and then FMOD_READY) but the percent always seems to be 0 Does a sound have to be streaming to recieve the percent loading thing? I believe that yes. I am requesting something like that: - LeoCombes answered 10 years ago
https://www.fmod.org/questions/question/forum-20952/
CC-MAIN-2017-13
refinedweb
505
55.74
Allow migrating PMEM’s data¶ This spec proposes an method for migrating PMEM Namespace’s data of instance when cold migrating or resizing instance. Problem description¶ Currently, cold migrate or resize instance will always select a new pmem namespace on the destination host. But the data of the instance in the PMEM device will be lost. To ensure the integrity of instance data, we would like to migrate PMEM’s data of the instance when migrate or resize an instance. PMEM devices can be used as a large pool of low latency high bandwidth memory where they could store data for computation. This can improve the performance of the instance. Since copying pmem data will take a lot more time and network bandwidth, a new “copy_pmem_devices” argument is added to decide whether to copy pmem data. Use Cases¶ As an user, I would like to migrate the PMEM namespace’s data if the instance migrate or resize to another host to ensure data integrity. Proposed change¶ Add a new microversion migrate / resize API, introducing “copy_pmem_devices” field. When migrating or resizing intance, we can get the old PMEM device and the new PMEM device from instance.migration_context. So we can copy the data from old PMEM device to new PMEM device. Given or Assuming, the instance use /dev/dax0.0 PMEM Namespace on the source host, and we want to migrate or resize it to other host, and migrating or resizing the instance, will use the /dev/dax0.1 PMEM namepsace on the target host. Then nova will migrate the PMEM namepace’s data of the instance from /dev/dax0.0 to /dev/dax0.1 using the daxio utility over an ssh tunnel. Workflow¶ cold migrating or resizing instance workflow as following: prep_resize validates that there is a pmem device free and claims it as part of the move_claim process.The claimed device is stored in the instance.migration_context which can be retrieved later. The resize_instance operation is on source_compute, free the network volume etc. resources. We can get the source compute, dest compute from migration, and get the new PMEM device, old PMEM device from instance.migration_context. Copy the PMEM data from old PMEM device to new PMEM device at migtate_disk_and_power_off. If the copy operation is failed, cleanup the PMEM data on dest_compute, and make the instance ACTIVE again on the source compute. Copy the PMEM data can use “daxio” and “ssh”. The finish_resize operation is on dest_compute, launching a new instance with resources in step1. If launching new instance failed, will terminate the operation, cleanup the PMEM data on dest_compute, and make the instance ACTIVE again on the source compute. The confirm_migration will cleanup PMEM data on source compute, alternitivly revert_resize will cleanup PMEM data on dest compute and make the instance ACTIVE again on the source compute. Alternatives¶ None Data model impact¶ None REST API impact¶ Add a new microversion migrate / resize API with “copy_pmem_devices” field. POST /servers/{server_id}/action { - “resize”{ “flavorRef” : “2”, “OS-DCF:diskConfig”: “AUTO”, “copy_pmem_devices”: “true” } } { - “migrate”: { “host”: “host1”, “copy_pmem_devices”: “true” } } The value of “copy_pmem_devices” default “false”, dosen’t copy pmem data. “true”, the data in virtual persistent memory is copied. If the copy_pmem_devices=true and the old microverion return a 400. Cross cell resize/cold migrate, will return 400. Security impact¶ The pmem data will be transfered over ssh using the daxio utility to read and write the data, e.g. daxio -ouput /dev/dax0.0 | ssh <dest_compute_ip> “daxio -input /dev/dax0.1” This will reuse the exising ssh_execute function used to implement the ssh remote fs driver. Notifications impact¶ None Other end user impact¶ PMEM data will not be copied if performing a cross cell resize/migration. Other deployer impact¶ None Developer impact¶ None Performance Impact¶ A cold migrate / resize operation will take a lot more time and network bandwidth than before as it needs to copy the content of the pmem between compute hosts. Upgrade impact¶ This change will impact host the nova-compute service will behave during migration / resize so the compute service version needs to be bumped. Also resize and migration with pmem copy will only work with new enough compute services so a compute service version check should be implemented for these operations. If the copy_pmem_devices=false or the old microverion we proceed with the old behavior of not copying the data. If the copy_pmem_devices=true and the old microverion return a 400. Implementation¶ Assignee(s)¶ QIU FOSSEN(qiujunting@inspur.com) Feature Liaison¶ None Work Items¶ Dependencies¶ None Testing¶ Add related unit test for negative scenarios. Add related functional test (API samples). Documentation Impact¶ Update the related documents and add some description of this change References¶ [1]
https://specs.openstack.org/openstack/nova-specs/specs/xena/approved/allow-migrate-pmem-data.html
CC-MAIN-2022-27
refinedweb
778
55.44
day run java program how to run java program i have jar file. in jar i have so many classes.in one of file i want modify .after modifying file i want replce in jar. please help me to how to generate class and how to replace java program run on thml page? java program run on thml page? how to run java program on html page using text area java run time error - Java Beginners java run time error i am getting error "main" java.lang.NullPointerException" in my program, iam sending code actually motive of program....... please correct my program, tell me where the problem occurs and what should How Jdbc program can be run?? created successfully and when i compiled this program then it compiled successfully ,but when i run it ,it gives following error-> C:\Program Files\Java...How Jdbc program can be run?? import java.sql.*; import java.util. program java program write an error.jsp , which will be called in case there will be any run time error in the system , page crash How to Write a Calculator Program in Java? How to Write a Calculator Program in Java? In this Java Tutorial you will learn how to write a Calculator program in Java in easy steps. Calculator program..., subtraction, multiplication or division. In this example of writing program in Java The quick overview of JSF Technology ; The quick Overview of JSF Technology This section gives you an overview of Java Server Faces technology, which simplifies the development of Java Based web applications. In this JSF Check Digit Question not able to solve.. Check Digit Question not able to solve.. Hi, I need some help asap. I been stuck for this question for more than 3 days. Using Java. User needs to key in identification number (e.g. U0906931E) system check for the first Making Tokens of a Java Source Code simplest way. Here after reading this lesson, you will be able to break java... class object into it which will read the name of the java file at run time. Now...:\Java Tutorial> Download this program; i Java Program and the number of cows and bulls for each word, your program should be able to work out...Java Program Problem Statement You are required to play a word-game with a computer. The game proceeds as follows The computer 'thinks' of a four java and flexible in nature. The most significant feature of Java is to run a program easily from one computer system to another. * Java works on distributed... for possible errors, as Java compilers are able to detect many error problem Quick introduction to web services Quick introduction to web services  ... program. Web Services allows different applications to talk to each other... talk to java web services and vice versa. So, Web services are used how to run applet - Applet how to run applet Hi everybody i am using connecting jdbc in applet program. this is executed successfully with appletviewer command >...:// java packge program - Java Beginners java packge program my question is how to compile and run java package program in the linux OS Program - Java Beginners Java Program Write a program that demonstrates the use of multithreading with the use of three counters with three threads defined for each. Three... with the step of 100. Assign proper priority to the threads and then run a java program - Java Beginners about the second line... i have made my program but not able to click... a java program well sir, i just wanna ask you something regarding that if the question say .....write a program to check whether a number is even java applet run time error - Applet java applet run time error Hi, Im new to java applet.please help me. i have create a MPEG movie player in applet. when i run that program... { Player player = null; /*String location=""; MediaLocator How program - Java Beginners java program plzzzzz help me on this java programming question? hello people.. can u plzzzzzzzzzzzzzzzzzzz help me out with this java programm. its due tmrw....... and i havent even get started on this program. i dont want hello .. still doesn't run - Java Beginners hello .. still doesn't run Iam still having a prblem in running this problem errors are: can not resolve symbol import.util.Scanner class Scanner another error is can not resolve symbol method setname(java.lang.String Java Program - Java Beginners Java Program Hi I'm having trouble with this problem, I keep getting errors. Write a program GuessGame.java that plays the game ?guess the number? as follows: Your program chooses the number to be guessed by selecting java program - Java Beginners java program ahm... i will use a table, text field and a button in java... a user will input a data to be search in the table.. after searching...[]) { SwingUtilities.invokeLater(new Runnable() { public void run Java code to run unix command - Java Beginners Java code to run unix command Hi, I need a java code to connect to a remote unix server and run a unix command. Please help. Regards, Praty for java program for java program for printing documents,images and cards Making Tokens of a Java Source Code C:\Java Tutorial>java TokenizingJavaSourceCode Please enter a java file name: TokenizingJavaSourceCode.java Number of tokens = 158 C:\Java Tutorial>_ Download this program Java Program Java Program A Java Program that print the data on the printer but buttons not to be printed Java Thread : run() method Java Thread : run() method In this section we are going to describe run() method with example in java thread. Thread run() : All the execution code is written with in the run() method. This method is part of the Runnable interface How to run java swing application from jar files . How to run java swing application from jar files . Hello Sir, I developed a java swing application .Now i want to execute it as .exe... the main class program will exit" from "java virtual machine". Plz help book) but i replaced with localhost in lookup method since iam running in stand alone application.Can any one help me run this program please...java can anyone tell me how to compile and run rmi in netbeans(6.9.1 run ttime error - Java Beginners run ttime error how to compile a client server application using RMI ? Hi friend, I am sending you a link. This link will help you. Please visit for more information. java program java program write java program for constructor,overriding,overriding,exception handling how to write an addition program in java without using arithematic operator java program java program hi friends how to make a java program for getting non prime odd numbers in a given series java program java program write a program to print 1234 567 89 10 java program java program Write a program to demonstrate the concept of various possible exceptions arising in a Java Program and the ways to handle them.  ... in Java servlet ; Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet... How to Run a Servlet To run a servlet one should follow the steps illustrated below: Download program Java program How to write for drawing a face in java Java program Java program How to write code in order to draw a face in java java program java program wap to show concept of class in java java program to compute area of a circle.square,rectangle.triangle,volume of a sphere ,cylinder and perimeter of cube using method over riding My first Java Program My first Java Program I have been caught with a practical exam to do the following: Write a program that takes input from a user through... You may not "cut off" any words in the middle I can be able to code step 1 program to create text area and display the various mouse handling events
http://www.roseindia.net/tutorialhelp/comment/42691
CC-MAIN-2014-52
refinedweb
1,323
63.8
Are you sure? This action might not be possible to undo. Are you sure you want to continue? PDF generated using the open source mwlib toolkit. See for more information. PDF generated at: Fri, 09 Apr 2010 16:44:15 UTC Contents Articles Ruby Programming Ruby Programming/Overview Ruby Programming/Installing Ruby Ruby Programming/Ruby editors Ruby Programming/Notation conventions Ruby Programming/Interactive Ruby Ruby Programming/Mailing List FAQ Ruby Programming/Hello world Ruby Programming/Strings Ruby Programming/Alternate quotes Ruby Programming/Here documents Ruby Programming/ASCII Ruby Programming/Introduction to objects Ruby Programming/Ruby basics Ruby Programming/Data types Ruby Programming/Writing methods Ruby Programming/Classes and objects Ruby Programming/Exceptions Ruby Programming/Unit testing Ruby Programming/RubyDoc Ruby Programming/Syntax Ruby Programming/Syntax/Lexicology Ruby Programming/Syntax/Variables and Constants Ruby Programming/Syntax/Literals Ruby Programming/Syntax/Operators Ruby Programming/Syntax/Control Structures Ruby Programming/Syntax/Method Calls Ruby Programming/Syntax/Classes Ruby Programming/Reference Ruby Programming/Reference/Predefined Variables Ruby Programming/Reference/Predefined Classes Ruby Programming/Reference/Objects Ruby Programming/Reference/Objects/Array Ruby Programming/Object/NilClass 1 6 8 10 12 13 14 15 18 20 21 25 29 32 37 43 44 47 47 52 56 58 59 62 68 71 75 86 95 96 98 99 99 100 Ruby Programming/Reference/Objects/Exception Ruby Programming/Reference/Objects/FalseClass Ruby Programming/Reference/Objects/IO/File/File::Stat Ruby Programming/Reference/Objects/Numeric Ruby Programming/Reference/Objects/Numeric/Integer Ruby Programming/Reference/Objects/Regexp Ruby Programming/Reference/Objects/String Ruby Programming/Reference/Objects/Symbol Ruby Programming/Reference/Objects/Time Ruby Programming/Reference/Objects/TrueClass Ruby Programming/Reference/Built-in Modules Ruby Programming/Built-in Modules Ruby Programming/GUI Toolkit Modules/Tk Ruby Programming/GUI Toolkit Modules/GTK2 Ruby Programming/GUI Toolkit Modules/Qt4 Ruby Programming/XML Processing/REXML Ruby on Rails/Print version 100 101 101 101 103 106 108 108 108 110 110 111 111 111 112 112 113 References Article Sources and Contributors Image Sources, Licenses and Contributors 169 171 Article Licenses License 172 released it to the public in 1995.numbers. Basic Ruby demonstrates the main features of the language syntax. Its creator. Ruby was named after the precious gem. Getting started will show how to install and get started with Ruby in your environment. Yukihiro Matsumoto.k. the Ruby language section is organized like a reference to the language. The final section. Finally. object-oriented scripting language.a "Matz". Intermediate Ruby covers a selection of slightly more advanced topics. Table of Contents Getting started /Overview/ /Installing Ruby/ /Ruby editors/ /Notation conventions/ /Interactive Ruby/ /Mailing List FAQ/ Basic Ruby /Hello world/ /Strings/ /Alternate quotes/ /Here documents/ /ASCII/ /Introduction to objects/ /Ruby basics/ /Data types/ -. The book is currently broken down into several sections. Each section is designed to be self contained. a. and is intended to be read sequentially. strings. hashes and arrays /Writing methods/ /Classes and objects/ /Exceptions/ .Ruby Programming 1 Ruby Programming Ruby is an interpreted. Ruby Programming 2 Intermediate Ruby /Unit testing/ /RubyDoc/ /Rake/ Ruby reference • /Syntax/ • Lexicology • Identifiers • Comments • Embedded Documentation • Reserved Words • Expressions • Variables and Constants • Local Variables • Instance Variables • Class Variables • Global Variables • Constants • Scope and or not • • • • • Control Structures • Conditional Branches . . in break redo next retry 3 • Exception Handling • raise • begin • rescue modifier • Miscellanea • return • returning • Methods • super • Iterators • yield • Classes • Class Definition • Instance Variables • Class Variables • Class Methods • Instantiation • Declaring Visibility • Private • Public • Protected • Instance Variables • Inheritance • Mixing in Modules • Ruby Class Meta-Model • /Reference/ • Built-in Functions • Predefined Variables ..Ruby Programming • if • if modifier • unless • unless modifier • case • Loops • while • while modifier • until • until modifier • for • • • • • for . Ruby Programming • Predefined Classes • Object • • • • • Array Class Exception FalseClass IO • File • File::Stat • Method • Module • Class • NilClass • Numeric • Integer • Bignum • Fixnum • Float Range Regexp String Struct 4 • • • • • Struct::Tms • Symbol • Time • TrueClass Modules • /Built-in Modules/ • /Database Interface Modules/ • /GUI Toolkit Modules/ • Tk • GTK2 • Qt4 • /XML Processing/ • REXML . rubycentral. rubyforge. org/ [5] http:/ /. ruby-doc. humblelittlerubybook. org/ ruby/ ruby-talk/ index. com/ [6] http:/ / www. 'Pickaxe Book') 1st edition online [13] by Example [14] Ruby Study Notes [15] Why's (Poignant) Guide To Ruby [16] Humble Little Ruby Book [17] Quick Reference • Ruby Quick Reference (some of more obscure expressions are explained) [18] • Ruby Cheat Sheets (a list of some different Ruby cheat sheets) [19] References [1] http:/ / www. net/ ruby/ [17] http:/ / www. org/ [2] http:/ / www. com/ download/ downloads. zenspider. com/ book/ [14] http:/ / www. org/ [8] http:/ / www. org/ [3] http:/ / ruby-talk. Yukihiro Matsumoto aka "Matz". meshplex. com/ book/ [18] http:/ /. com/ titles/ ruby3 [13] http:/ / www. • Programming Ruby 3 [12] (aka "Pickaxe") . rubywizards.9 • • • • • Programming Ruby (a. com/ [9] http:/ / www. ruby-lang. the creator of Ruby. com/ catalog/ 9781593271480/ Ruby [15] http:/ / rubylearning. railslodge. com/ catalog/ 9780596516178/ [12] http:/ / pragprog.Ruby Programming 5 External links • • • • • • • • Ruby homepage [1] Ruby Documentation Homepage [2] Ruby-Talk: The Ruby Mailing List [3] Ruby's Nitro/Og Web Toolkit [4] Ruby on Rails [5] Ruby on Rails plugin directory [6] RubyForge: The Repository for Open-source Ruby Projects [7] Ruby Wizards Discussion Forum [8] Learning Ruby • A Ruby Tutorial that Anyone can Edit [9] • Learning Ruby [10] A free tool to find and learn Ruby concepts Books • The Ruby Programming Language [11] by David Flanagan. org/ wiki/ Ruby/ Ruby_on_Rails_programming_tutorials [10] http:/ / www. shtml [4] http:/ / www. html [19] http:/ / www. rubyinside. com/ Languages/ Ruby/ QuickRef. oreilly. yoyobrain. nitroproject. html . html [16] http:/ / poignantguide. com/ cardboxes/ preview/ 103 [11] http:/ / www. com/ [7] http:/ / 2008 version covers Ruby 1. com/ ruby-cheat-sheet-734. rubyonrails. oreilly. Ruby has modules. Ada. By building individual features into separate modules. It was developed to be an alternative to scripting languages such as Perl and Python.[2] Features Ruby combines features from Perl. reading the code for Python helped Matz develop Ruby. but it has no instances. which adds the methods of that module to the class. and Linux. numbers and even true and false. Smalltalk.it doesn't care about the type of the object. just by implementing the same methods. A module has methods. Rubyists call this monkey patching and it's the kind of thing you can't get away with in most other languages. Every value in Ruby is an object. When you call a method on an object. Methods are always called on an object .Ruby Programming/Overview 6 Ruby Programming/Overview Ruby is an object-oriented scripting language developed by Yukihiro Matsumoto ("Matz"). A program can also modify its own definitions while it's running. Windows. Eiffel. including Unix.[2] Object Oriented Ruby goes to great lengths to be a purely object oriented language. and Python. module and method definitions in a program are built by the code when it is run. All of the class. even the most primitive things: strings.there are no "class methods". Mixins In addition to classes. Every object has a set of instance variables which hold the state of the object. This is called duck typing and it lets you make classes that can pretend to be other classes. not even other objects of the same class. which means that any variable can hold any type of object. Mix-ins help keep Ruby code free of complicated and restrictive class hiearchies. DOS. All communication between Ruby objects happens through methods. While Ruby does not borrow many features from Python. Development began in February 1993 and the first alpha version of Ruby was released in December 1994. Instead.[1] Ruby borrows heavily from Perl and the class library is essentially an object-oriented reorganization of Perl's functionality. Ruby also borrows from Lisp and Smalltalk. . to a class.org [1]. or "mixed in". You can also download and install Ruby on Windows. Lisp. BeOS.[1] Mac OS X comes with Ruby already installed. Variables in Ruby are dynamically typed. in the way that C or Java programs are. Dynamic Ruby is a very dynamic programming language. Every class has a set of methods which can be called on objects of that class. The more technically adept can download the Ruby source code[2] and compile it for most operating systems. OS/2. a module can be included. Instance variables are created and accessed from within methods called on the object. Even the most primitive classes of the language like String and Integer can be opened up and extended. Ruby looks up the method by name alone . Ruby programs aren't compiled. from which all other classes inherit. Every object has a class and every class has one superclass. as there are in many other languages (though Ruby does a great job of faking them). functionality can be combined in elaborate ways and code easily reused. Most Linux distributions either come with Ruby preinstalled or allow you to easily install Ruby from the distribution's repository of free software. At the root of the class hiearchy is the class Object. just like a class. Instance variables are completely private to an object. The main web site for Ruby is ruby-lang. or the class itself. No other object can see them. This is very much like inheritance but far more flexible because a class can include many different modules. b| a. every object has two classes: a "regular" class and a singleton class.color end The block is everything between the do and the end. operators can be overloaded. • • • • x is local variable (or something besides a variable) $x is a global variable @x is an instance variable @@x is a class variable Blocks Blocks are one of Ruby's most unique and most loved features. metaprogramming allows you to capture highly abstract design patterns in code and implement them as easily as calling a method. That means that you can use Ruby code to generate classes and modules. and even the behavior of the standard library can be redefined at runtime. Every object has its very own singleton class. passed along to other methods. I lied. Methods can be added to existing classes without subclassing. The sort method calls the block whenever it needs to compare two values in the list.color <=> b. An object's singleton class is a nameless class who's only instance is that object. or even copied. in all sorts of creative new ways. rather it is packaged into an object and passed to the sort method as an argument. but you can open them up and add methods to them. like any other object. This is Ruby's secret trick to avoid "class methods" and keep its type system simple and elegant.sort do |a. which can then be called on the lone object belonging to them. A block object. Many programming languages support code objects like this. A Ruby block is simply a special. Used wisely. can be stored in a variable. just like calling a method. That object can be called at any time. like this: laundry_list. The code in the block is not evaluated right away. . Variables and scope You do not need to declare variables or variable scope in Ruby. You can call their methods to learn about them or even modify them. everything is malleable. while your program is running. created automatically along with the object. a technique known as metaprogramming. The block gives you a lot of control over how sort behaves. This simple feature has inspired Rubyists to use closures extensively. Flexibility In Ruby. Singleton classes inherit from their object's regular class and are initially empty. They're called closures and they are a very powerful feature in any language. clean syntax for the common case of creating a closure and passing it to a method. modules and methods are themselves objects! Every class is an instance of the class Class and every module is an instance of the class Module.Ruby Programming/Overview 7 Singleton Classes When I said that every Ruby object has a class. A block is a piece of code that can appear after a call to a method. but they are typically underused because the code to create them tends to look ugly and unnatural. The truth is. The name of the variable automatically determines its scope. Metaprogramming Ruby is so object oriented that even classes. 2. Ruby Programming/Installing Ruby Ruby comes preinstalled on Mac OS X and many Linux distributions. only if it is installed. it is available for most other operating systems. • A mark-and-sweep garbage collector instead of reference counting. 2001). [2] Download Ruby (http:/ / www. Operating systems Mac OS X Ruby comes preinstalled on Mac OS X. html). org/ en/ downloads/ ). You can also install Ruby by compiling the source code. Retrieved on 2006-09-11. Linux Ruby comes preinstalled on many Linux systems. References [1] Bruce Stewart (November 29. Directions for some distributions are described below. ruby-lang. which will use native threads) You can also write extensions to Ruby in C or embed Ruby in other software. • Exceptions for error-handling.9.Ruby Programming/Overview 8 Advanced features Ruby contains many advanced features. O'Reilly. or if you want to upgrade to the latest version. In addition. from the shell run: ruby -v If ruby is not installed. which may have a more recent version of Ruby. follow the directions below. under "Applications". including Microsoft Windows. Debian / Ubuntu On Debian and Ubuntu. To find the easiest way to install Ruby for your system. you can usually install Ruby from your distribution's software repository. you can: • Buy the latest version of Mac OS X. To check what version is on your system: 1. which is located in the "Utilities" folder. which allows you to write multi-threaded applications even on operating systems such as DOS. Retrieved on 2006-09-11. Launch the Terminal application. • Install Ruby using Fink. it is included with Ubuntu) or the command-line tool apt. enter: ruby -v If you want to install a more recent version of Ruby. • Install Ruby using MacPorts. which can be downloaded from the Ruby web site [1]. To check if Ruby is installed on your system. • OS-independent threading. . (this feature will disappear in 1. linuxdevcenter. install Ruby using either the graphical tool Synaptic (on Debian. com/ pub/ a/ linux/ 2001/ 11/ 29/ ruby. At the command-line. An Interview with the Creator of Ruby (http:/ / www. PCLinuxOS On PCLinuxOS. then you have successfully installed Ruby.[2] Otherwise. $ ruby -v This should return something like the following: ruby 1. • Download and run One-Click Ruby Installer [3]. • Install Cygwin. install Ruby using the command-line tool RPM. org/ en/ downloads/ [2] yum (http:/ / fedoraproject. 9 Windows Ruby does not come preinstalled with any version of Microsoft Windows. org/ projects/ rubyinstaller . Red Hat Linux On Red Hat Linux. Fedora Wiki. you can install Ruby using the command-line tool yum. a collection of free software tools available for Windows. make sure that you select the "ruby" package. Mandriva Linux On Mandriva Linux. if you get something like the following: -bash: ruby: command not found Then you did not successfully install Ruby. Interpreters" category. install Ruby using either the graphical tool Synaptic or the command-line tool apt. References [1] http:/ / www. However. located in the "Devel. However. [3] http:/ / rubyforge. install Ruby using the command-line tool urpmi.8. there are several ways to install Ruby on Windows. org/ wiki/ Tools/ yum). Retrieved on 2006-09-13.Ruby Programming/Installing Ruby Fedora Core If you have Fedora Core 5 or later.7 (2009-06-12 patchlevel 174) [i486-linux] If this shows up. During the install. you can install Ruby using the graphical tool Pirut. ruby-lang. Testing Installation The installation can be tested easily. • Download and install one of the compiled Ruby binaries from the Ruby web site [1]. They are listed alphabetically in each section. some text editors have additional features to aid the Ruby programmer. The most common is syntax highlighting.Ruby Programming/Ruby editors 10 Ruby Programming/Ruby editors Although you can write Ruby programs with any text editor. not by preference. . The following editors have built-in support for Ruby. which is part of KDE Scribes [12] Gedit red car editor [13] written in ruby All of the editors listed in the cross-platform section will run on Linux. Operating systems Cross-platform • 3rdRail [1] • ActiveState Komodo and its stripped down cousin Komodo Edit (free) supports Ruby syntax highlighting and auto-complete [2] • Arachno [3] • Eclipse with the Dynamic Languages Toolkit Plugin [4] • Eclipse with the RDT Plugin [5] • Emacs • • • • • • • • • • FreeRIDE [6] IDEA with the Ruby Plugin [7] jEdit with the Ruby Editor Plugin [8] NetBeans [9] RubyMine SciTE SlickEdit [10] Vim — Learn Vim here on Wikibooks XEmacs Geany [11] Mac OS X • • • • BBEdit TextWrangler TextMate Coda Linux/Unix • • • • Kate. geany. net/ confluence/ display/ RUBYDEV/ Home [8] http:/ / rubyjedit.3.A Textmate like editor for Windows Intype [14] . fast.Ruby and Rails editing and debugging for Visual Studio 2008. org [12] http:/ / scribes. org/ products/ ruby/ [10] http:/ / www. textpad. References [1] [2] [3] [4] [5] [6] [7] http:/ / www. org/ ruby/ ruby?UltraEditExtensions [17] http:/ / Programming/Ruby editors 11 Windows • • • • • • • • e .syntax highlighting. ruby-ide. com/ add-ons/ synn2t. com/ [14] http:/ / intype. sourceforge. sourceforge. net/ [13] http:/ / redcareditor. Tse .Pro (non-free) version includes built-in syntax highlighting (w/ spellcheck) for Ruby. activestate. info [15] http:/ / www. org http:/ / www. html [16] http:/ / rubygarden. com/ Products/ Komodo/ http:/ / www. editpadpro.A small. com . com/ products/ 3rdrail http:/ / www. compile your Ruby programs while in the editor UltraEdit with the UltraEdit extensions [16] Ruby In Steel [17] . slickedit. sapphiresteel. com/ [11] http:/ / www. EditPad Pro [18] . com [18] http:/ / www. and flexible code editor (Alpha 0. netbeans. jetbrains.x) Notepad++ TextPad with the Ruby syntax definition files [15]. codegear. rubyforge. net/ http:/ / freeride. org/ [9] http:/ / www. org/ dltk/ http:/ / rubyeclipse. com/ http:/ / www. eclipse. /Hello world/ page to determine the best way to run Ruby scripts on your system. the following convention is used to show a Ruby script being run from the shell prompt. The part of the example that you type will appear bold. An example might also show the output of the program.5 (2006-08-25) [i386-freebsd4. run: $ ruby -v Again. For example.8. Your actual output when you run "ruby -v" will vary depending on the version of Ruby installed and what operating system you are using. Windows users are probably more familiar seeing "C:\>" to denote the shell prompt (called the command prompt on Windows). you should not type it in. the actual syntax that you will use to run your Ruby scripts will vary depending on your operating system and how it is setup. Since the dollar sign denotes your shell prompt. "ruby 1.Ruby Programming/Notation conventions 12 Ruby Programming/Notation conventions Command-line examples In this tutorial. .. to check what version of Ruby is on your system. $ hello-world.rb Hello world However. Running Ruby scripts For simplicity.10]" is printed out after you run "ruby -v". do not type the dollar sign – you should only enter "ruby -v" (without the quotes). Please read through the Executable Ruby scripts section of the . $ ruby -v ruby 1. examples that involve running programs on the command-line will use the dollar sign to denote the shell prompt.8.10] In the above example.5 (2006-08-25) [i386-freebsd4. bat will not run properly. Cygwin users If you use Cygwin's Bash shell on Microsoft Windows. $ irb --simple-prompt >> 2+2 => 4 >> 5*5*5 => 125 >> exit These examples show the user's input in bold. run irb. However. Instead of writing a lot of small text files. and the native Windows version of irb.Ruby Programming/Interactive Ruby 13 Ruby Programming/Interactive Ruby When learning Ruby. To run the native version of irb inside of Cygwin's Bash shell. then irb. You must either run your shell (and irb. if you run a Cygwin shell inside of Cygwin's rxvt terminal emulator. read this section. irb uses => to show you the return value of each line of code that you type in.bat should work fine. which is Ruby's interactive mode. Understanding irb output irb prints out the return value of each line that you enter. but are running the native Windows version of Ruby instead of Cygwin's version of Ruby. you can use irb. For example: $ irb irb(main):001:0> A simple irb session might look like this.bat. $ irb --simple-prompt >> The >> prompt indicates that irb is waiting for input. you will often want to experiment with new features by writing short snippets of code. In contrast. If you do not specify --simple-prompt. an actual Ruby program only prints output when you call an output method such as puts. For example: $ irb --simple-prompt >> x=3 => 3 >> y=x*2 => 6 . the irb prompt will be longer and include the line number. By default. Running irb Run irb from your shell prompt.bat) inside of the Windows console or install and run Cygwin's version of Ruby. Cygwin's Bash shell runs inside of the Windows console. but also returns the value assigned to x. x=3 puts x Ruby Programming/Mailing List FAQ Etiquette There is a list of Best Practices[1] . com/ posts/ jamesbritt/ and_your_Mom_too. infoq. html [3] http:/ / www. com/ rubymine-1-0-ruby-ide-1818. On windows for rails projects there is RoRed. this equivalent Ruby program prints nothing out. What is the Best editor? Several editors exist for Ruby. However. but the values are never printed out. RubyMine has also received good reviewed[2] Free: NetBeans offers a version with Ruby support. use the puts method. The variables get set. html [2] http:/ / www. [1] http:/ / blog. which irb then prints out. RadRails is a port of eclipse to support Ruby syntax. Commercial: The editor of preference on OS X is Textmate. com/ news/ 2007/ 08/ eclipse-dltk-09 . Eclipse has a plugin DLTK that offers ruby support[3] . x=3 not only does an assignment. x=3 y=x*2 z=y/6 x If you want to print out the value of a variable in a Ruby program. rubyinside. rubybestpractices.Ruby Programming/Interactive Ruby >> => >> => >> z=y/6 1 x 3 exit 14 Helpfully. Ruby Programming/Hello world 15 Ruby Programming/Hello world The classic "hello world" program is a good way to get started with Ruby. $ ruby hello-world. Hello world Create a text file called hello-world.rb Hello world You can also run the short "hello world" program without creating a text file at all. =end puts 'Hello world' # Print out "Hello world" . # My first Ruby program # On my way to Ruby fame & fortune! puts 'Hello world' You can append a comment to the end of a line of code.rb containing the following code: puts 'Hello world' Now run it at the shell prompt. Ruby uses the hash symbol (also called Pound Sign. or octothorpe) for comments. This is called a one-liner. $ irb --simple-prompt >> puts "Hello world" Hello world => nil Comments Like Perl. Everything before the hash is treated as normal Ruby code. but the output will look slightly different. here's our hello-world. puts will print out "Hello world". $ ruby -e "puts 'Hello world'" Hello world You can run this code with irb. Bash. but irb will also print out the return value of puts – which is nil. puts 'Hello world' You can also comment several lines at a time: =begin This program will print "Hello world". as well. For example. Square. Everything from the hash to the end of the line is ignored when the program is run by Ruby. and C Shell. number sign.rb program with comments. Most people start with #3. change the shebang line to point to the correct path. The shebang line is ignored by Ruby – since the line begins with a hash. Add the current directory to your PATH (not recommended). it's common to create a ~/bin directory. To avoid doing this. 3. 2. Unix-like operating systems do not search the current directory for executables unless it happens to be listed in your PATH environment variable. The shebang line is read by the shell to determine what program to use to run the script. the =end must have its own line. or edit an existing script. and Solaris – you will want to mark your Ruby scripts as executable using the chmod command. for security reasons. =begin This program will print "Hello world" =end puts 'Hello world' 16 Executable Ruby scripts Typing the word ruby each time you run a Ruby script is tedious. C++. Mac OS X. Then. $ chmod +x hello-world. Next. You cannot insert block comments in the middle of a line of code as you can in C. Running an executable Ruby script that is located in the current directory looks like this: $ . Ruby treats the line as a comment.rb You need to do this each time you create a new Ruby script./hello-world.Ruby Programming/Hello world Although block comments can start on the same line as =begin. Now. Specify the directory of your script each time you run it. add a shebang line as the very first line of your Ruby script. add this to your PATH.rb program – with the shebang line – looks like this: #!/usr/bin/ruby puts 'Hello world' If your ruby executable is not in the /usr/bin directory. This also works with the Cygwin version of Ruby. So you need to do one of the following: 1. and Java. you do not need to run "chmod +x" again. Hence.rb . you can run your Ruby script without typing in the word ruby.rb Once you have completed a script. you can still run the Ruby script on operating systems such as Windows whose shell does not support shebang lines. If you rename a Ruby script. However. follow the instructions below. although you can have non-comment code on the same line as the =end. Create your Ruby scripts in a directory that is already in your PATH. The other common place to find the ruby executable is /usr/local/bin/ruby. Unix-like operating systems In Unix-like operating systems – such as Linux. and move your completed script here for running on a day-to-day basis. you can run your script like this: $ hello-world. The new hello-world. This line cannot be preceded by any blank lines or any leading spaces. This way. $ assoc .exe" "%1" %* For more help with these commands. Log in as an administrator. cmd. $ hello-world. Run the standard Windows "Command Prompt". 2. 3.Ruby Programming/Hello world Using env If you do not want to hard-code the path to the ruby executable. 1. you can use the env command in the shebang line to search for the ruby executable in your PATH and execute it.rb=RubyScript $ ftype RubyScript="c:\ruby\bin\ruby. then the installer has setup Windows to automatically recognize your Ruby scripts as executables. change the command-line arguments to correctly point to where you installed the ruby. run the following Windows commands. . At the command prompt (i. Just type the name of the script to run it. shell prompt). run "help assoc" and "help ftype". When you run ftype. #!/usr/bin/env ruby puts 'Hello world' 17 Windows If you install the native Windows version of Ruby using the Ruby One-Click Installer [1].e.rb Hello world If this does not work.exe" "%1" %* RubyScript="c:\ruby\bin\ruby. you will not need to change the shebang line on all of your Ruby scripts if you move them to a computer with Ruby installed in a different directory. follow these steps.rb=RubyScript . or if you installed Ruby in some other way.exe executable on your computer. Ruby has a built-in String class. A quick update to our code shows the use of both single and double quotes. Java. String literals One way to create a String is to use single or double quotes inside a Ruby program to create what is called a string literal. there's no difference. However. • \' – single quote • \\ – single backslash Except for these two escape sequences. The backslash followed by the single quote is called an escape sequence. puts 'Hello world' puts "Hello world" Being able to use either single or double quotes is similar to Perl. and the . but different from languages such as C and Java. in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. They also allow you to embed variables or Ruby code inside of a string literal – this is commonly referred to as interpolation. consider the following code: puts "Betty's pie shop" puts 'Betty\'s pie shop' Because "Betty's" contains an apostrophe. We've already done this with our "hello world" program. Double quotes Double quotes allow for many more escape sequences than single quotes. everything else between single quotes is treated literally.chomp puts "Your name is #{name}" . puts "Enter name" name = gets. Single quotes Single quotes only support two escape sequences. which is the same character as the single quote.NET Framework. So what difference is there between single quotes and double quotes in Ruby? In the above code.Ruby Programming/Strings 18 Ruby Programming/Strings Like Python. which use double quotes for string literals and single quotes for single characters. Ruby Programming/Strings 19 Escape sequences Below are some of the more common escape sequences that can appear inside of double quotes. a punctuation mark. Hello\n2. produced by escape code \a. try the following code. It does not represent a letter of the alphabet. puts "\aHello world\a" puts We've been using the puts function quite a bit to print out text. although a beep is fairly standard. Some terminal emulators will flash briefly. Whenever puts prints out text. Hello 2. puts "Say". "hello". it automatically prints out a newline after the text. World" The result: $ double-quotes. Run the following Ruby code to check out how your terminal emulator handles the bell character.rb Hello world Goodbye world Start over world 1. For example. "world" The result: $ hello-world. Instead. it instructs the terminal emulator (called a console on Microsoft Windows) to "alert" the user. is considered a control character.rb Say hello to . World Notice that the newline escape sequence (in the last line of code) simply starts a new line. It is up to the terminal emulator to determine the specifics of how to respond. The bell character. or any other written symbol. puts "Hello\t\tworld" puts "Hello\b\b\b\b\bGoodbye world" puts "Hello\rStart over world" puts "1. • • • • • • • • \" \\ \a \b \r \n \s \t – double quote – single backslash – bell/alert – backspace – carriage return – newline – space – tab Try out this example code to better understand escape sequences. "the". "to". txt' Escaping the apostrophes makes the code less readable and makes it less obvious what will print out.txt' The single quotes keep the \b. in Ruby. But consider the following string literal. puts puts puts puts puts puts %q!c:\napolean's %q/c:\napolean's %q^c:\napolean's %q(c:\napolean's %q{c:\napolean's %q<c:\napolean's documents\tomorrow's documents\tomorrow's documents\tomorrow's documents\tomorrow's documents\tomorrow's documents\tomorrow's bus bus bus bus bus bus schedule. after the text. "\n" The result: $ hello-world.rb Sayhellototheworld The following code produces the same output. "hello". For example. there's a better way. with all the words run together. Luckily. "world". You can use the %q operator to apply single-quoting rules. Much of this will look familiar to Perl programmers. but choose your own delimiter to mark the beginning and end of the string literal. puts 'c:\napolean\'s bus schedules\tomorrow\'s bus schedule. print print print print print print "Say" "hello" "to" "the" "world" "\n" Ruby Programming/Alternate quotes In Ruby. print "Say".txt> . and \t from being treated as escape sequences. Ruby's print function only prints out a newline if you specify one. there's more than one way to quote a string literal.txt} schedule.txt) schedule.Ruby Programming/Strings the world 20 print In contrast. We include a newline at the end of print's argument list so that the shell prompt appears on a new line. "to". try out the following code. "the". Alternate single quotes Let's say we are using single quotes to print out the following path.txt^ schedule. puts 'c:\bus schedules\napolean\the portland bus schedule.txt! schedule.txt/ schedule. \n. Ruby Programming/Alternate quotes> 21 Alternate double quotes The %Q operator}/ Ruby Programming/Here documents For creating multiple-line strings, Ruby supports here documents,: Ruby Programming/Here documents $ 22 Ruby Programming/Here documents 23 * Organic We have been using the puts function in our examples, but you can pass here documents to any function that accepts Strings. Indenting If you indent the lines inside the here document, the leading whitespace is preserved. However, there must not be any leading whitepace. txt BUS_SCHEDULES The result: $ bus-schedules. puts <<'BUS_SCHEDULES' c:\napolean's documents\tomorrow's bus schedule. puts <<"QUIZ" Student: #{name} 1. do not put double quotes around the terminator.txt . If there are no quotes around the identifier. name = 'Charlie Brown' puts <<QUIZ Student: #{name} 1. then the body of the here document follows double-quoting rules. place single quotes around the identifier.\tQuestion: What is 4+5? \tAnswer: The sum of 4 and 5 is #{4+5} QUIZ The result: $ quiz.Ruby Programming/Here documents 24 Quoting rules You may wonder whether here documents follow single-quoting or double-quoting rules.txt c:\new documents\sam spade's bus schedule.txt c:\new documents\sam spade's bus schedule. Question: What is 4+5? Answer: The sum of 4 and 5 is 9 Double-quoting rules are also followed if you put double quotes around the identifier.txt c:\bus schedules\the #9 bus schedule.rb c:\napolean's documents\tomorrow's bus schedule.txt c:\bus schedules\the #9 bus schedule.\tQuestion: What is 4+5? \tAnswer: The sum of 4 and 5 is #{4+5} QUIZ To create a here document that follows single-quoting rules.rb Student: Charlie Brown 1. like in our examples so far. However. every String – in fact. however.rb 72 101 108 108 111 To get the ASCII value for a space. Using a ASCII chart. puts puts puts puts ?\s ?\t ?\b ?\a The result: 32 9 8 7 . we need to use its escape sequence. a string such as "Hello world" looks like a series of letters with a space in the middle. H e l l o space 72 101 108 108 111 32 w o r l d 119 111 114 108 100 You can also determine the ASCII code of a character by using the ? operator in Ruby. In fact. specifies what number is used to represent each character. Wikipedia's page on ASCII also lists the ASCII codes. we discover that our string "Hello world" gets converted into the following series of ASCII codes. For example. we can use any escape sequence with the ? operator. whereas the space is encoded as the number 32. to the computer. On most Unix-like operating systems.Ruby Programming/ASCII 25 Ruby Programming/ASCII To us. $ hello-ascii. the capital letter "H" is encoded as the number 72. To your computer. originally developed for sending telegraphs. ASCII In our example. everything – is a series of numbers. you can view the entire chart of ASCII codes by typing "man ascii" at the shell prompt. The ASCII standard. puts puts puts puts puts ?H ?e ?l ?l ?o Notice that the output (below) of this program matches the ASCII codes for the "Hello" part of "Hello world". each character of the String "Hello world" is represented by a number between 0 and 127. Ruby Programming/ASCII 26 Terminal emulators You may not realize it. it sends the ASCII code for "H" (72) to the terminal emulator. / 0 1 2 3 4 5 6 Glyph 010 0000 040 32 010 0001 041 33 010 0010 042 34 010 0011 043 35 010 0100 044 36 010 0101 045 37 010 0110 046 38 010 0111 047 39 010 1000 050 40 010 1001 051 41 010 1010 052 42 010 1011 053 43 010 1100 054 44 010 1101 055 45 010 1110 056 46 010 1111 057 47 011 0000 060 48 011 0001 061 49 011 0010 062 50 011 0011 063 51 011 0100 064 52 011 0101 065 53 011 0110 066 54 . ASCII chart Binary Oct Dec Hex 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 ? [[w:Exclamation mark ]] " # $ % & ' ( ) * + . you've been running your Ruby programs inside of a program called a terminal emulator – such as the Microsoft Windows console. rxvt. the terminal emulator does not draw a symbol. or X Window System programs such as xterm. a telnet client. and the Unicode Transformation Format (UTF) – have been created to represent a wider variety of characters. There's a lot more characters than that in the world. In this case. . When your Ruby program prints out a bell character. but instead will typically beep or flash briefly. ASCII only uses numbers 0 through 127 to define characters. but so far. it sends a different ASCII code – ASCII code 7 – to the terminal emulator. Shift_JIS. including those found in languages such as Arabic. Other character encodings The ASCII standard is a type of character encoding. When your Ruby program prints out the letter "H". Other character encoding systems – such as Latin-1. As mentioned above. and Japanese. How each of the codes gets interpreted is largely determined by the ASCII standard. Hebrew. which then draws an "H". the Mac OS X Terminal application. Chinese. Ruby Programming/ASCII 27 011 0111 067 55 011 1000 070 56 011 1001 071 57 011 1010 072 58 011 1011 073 59 011 1100 074 60 011 1101 075 61 011 1110 076 62 011 1111 077 63 37 38 39 3A 3B 3C 3D 3E 3F 7 8 9 : . < = > ? Binary Oct Dec Hex Glyph 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ 100 0000 100 64 100 0001 101 65 100 0010 102 66 100 0011 103 67 100 0100 104 68 100 0101 105 69 100 0110 106 70 100 0111 107 71 100 1000 110 72 100 1001 111 73 100 1010 112 74 100 1011 113 75 100 1100 114 76 100 1101 115 77 100 1110 116 78 100 1111 117 79 101 0000 120 80 101 0001 121 81 101 0010 122 82 101 0011 123 83 101 0100 124 84 101 0101 125 85 101 0110 126 86 101 0111 127 87 101 1000 130 88 101 1001 131 89 101 1010 132 90 101 1011 133 91 101 1100 134 92 . Ruby Programming/ASCII 28 101 1101 135 93 101 1110 136 94 101 1111 137 95 5D 5E 5F ] ^ _ Binary Oct Dec Hex Glyph 60 61 62 63 ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ 110 0000 140 96 110 0001 141 97 110 0010 142 98 110 0011 143 99 110 0100 144 100 64 110 0101 145 101 65 110 0110 146 102 66 110 0111 147 103 67 110 1000 150 104 68 110 1001 151 105 69 110 1010 152 106 6A 110 1011 153 107 6B 110 1100 154 108 6C 110 1101 155 109 6D 110 1110 156 110 6E 110 1111 157 111 6F 111 0000 160 112 70 111 0001 161 113 71 111 0010 162 114 72 111 0011 163 115 73 111 0100 164 116 74 111 0101 165 117 75 111 0110 166 118 76 111 0111 167 119 77 111 1000 170 120 78 111 1001 171 121 79 111 1010 172 122 7A 111 1011 173 123 7B 111 1100 174 124 7C 111 1101 175 125 7D 111 1110 176 126 7E . an object can do exactly three things. An object can contain methods. If you don't come from Smalltalk background. In contrast. We also told Ruby to use the variable comedian to refer to this object. languages such as C++ and Java are hybrid languages that divide the world between objects and primitive types.Ruby Programming/Introduction to objects 29 Ruby Programming/Introduction to objects Like Smalltalk. 3. 2. 1. from both itself and other objects. An object's methods can call/run other methods/functions. both to itself and to other objects. In the course of processing a message. Variables and objects Let's fire up irb to get a better understanding of objects. 2. send messages. What is an object? Using Smalltalk terminology. but the pure object-oriented approach is more consistent and simpler to use. Next. if the object changes (as we'll see below). which are functions that have special access to the object's data. we have two variables that we can use to refer to the same String object — comedian and favorite_comedian. $ irb --simple-prompt >> comedian = "Stephen Colbert" => "Stephen Colbert" In the first line. . including references to other objects. Ruby is a pure object-oriented language — everything is an object. >> favorite_comedian = comedian => "Stephen Colbert" Now. Since they both refer to the same object. including references to other objects. it might make more sense to rephrase these rules as follows: 1. The hybrid approach results in better performance for some applications. 3. An object can contain data. Receive a message. we tell Ruby to also use the variable favorite_comedian to refer to the same String object. the change will show up when using either variable. we created a String object containing the text "Stephen Colbert". Hold state. downcase! modifies a String object by making all of the letters lowercase.Ruby Programming/Introduction to objects 30 Methods In Ruby. Well. with the lowercase text. the method upcase! changes the letters of a String to uppercase. went to. but the original string remains the same.It's essentially gone. However. after irb printed out its contents.upcase! => "STEPHEN COLBERT" Since both of the variables comedian and favorite_comedian point to the same String object. >> => >> => comedian "STEPHEN COLBERT" favorite_comedian "STEPHEN COLBERT" Methods that do not end in an exclamation point return data. . it can no longer be accessed since we did not assign a variable to keep track of it. and Ruby will dispose of it. downcase returns a lowercase copy of the String. >> comedian. methods that end with an exclamation mark (also called a "bang") modify the object. but do not modify the object. we can see the new. For example. >> => >> => comedian. uppercase text using either variable.downcase "stephen colbert" comedian "STEPHEN COLBERT" Since the original object still contains the text "STEPHEN COLBERT". you might wonder where the new String object. For example. each variable points to a different object. Hence.Ruby Programming/Introduction to objects 31 Reassigning a variable But what if your favorite comedian is not Stephen Colbert? Let's point favorite_comedian to a new object. >> favorite_comedian = "Jon Stewart" => "Jon Stewart" Now. >> favorite_comedian = "Ellen DeGeneres" => "Ellen DeGeneres" Now. Now. our favorite comedian is Ellen DeGeneres. . Let's say that we change our mind again. Ruby will dispose of it. no variable points to the "Jon Stewart" String object any longer. Therefore. Ruby keeps an if statement straight as long as the conditional (if . numbers.. if statement.. we assume some basic familiarity with programming language concepts (i. let's just say your basic local variable names should start with either a lower case letter or an underscore. you'll need to place the then keyword after the conditional if a < 5 then puts "#{a} less than 5" end if a < 5 then puts "#{a} less than 5" else puts "#{a} greater than 5" end Note that the if statement is also an expression.) and the associated code block are on separate lines. and should contain upper or lower case letters. The above example should be pretty clear. while and case For example. the rand function generates a random number between 0 and 1] There will be plenty more time to discuss conditional statements in later chapters. the line above could also have been written as puts(if a < 5 then "#{a} less than 5" else "#{a} greater than 5" end) . here's if in action: a = 10 * rand if a < 5 puts "#{a} less than 5" elsif a > 7 puts "#{a} greater than 7" else puts "Cheese sandwich!" end [As in other languages. If you have to smash everything together on one line. For now.e. Program flow Ruby includes a pretty standard set of looping and branching constructs: if. Dealing with variables We'll deal with variables in much more depth when we talk about classes and objects. Ruby also includes a negated form of if called unless which goes something like unless a > 5 puts "a is less than or equal to 5" else puts "a is greater than 5" end Generally speaking. its value is the last line of the block executed. Global variables start with a $.Ruby Programming/Ruby basics 32 Ruby Programming/Ruby basics As with the rest of this tutorial. while loops) and also some basic understanding of object-oriented programming. and underscore characters. length end len = my_function( "Giraffe" ) puts "My secret word is #{len} long" $ func1.. system a = (10*rand). #{a}" return a. functions are typically referred to as methods.round #a = rand(11) would do the same case a when 0. basic method writing looks something like this: # Demonstrate a method with func1.. For now.. For example puts "#{a} less than 5" if a < 5 puts "Cheese sandwich" unless a == 4 while behaves as it does in other languages -.5 puts "#{a}: Low" when 6 puts "#{a}: Six" else puts "#{a}: Cheese toast!" end There are some other interesting things going on in this example. but here the case statement is the center of attention. Finally there is the case statement which we'll just include here with a brief example.Ruby Programming/Ruby basics Ruby has also adopted the syntax from Perl where if and unless statements can be used as conditional modifiers after a statement. there is also a negated version of while called until which runs the code block until the condition is true..the code block that follows is run zero or more times. 33 Writing functions In keeping with Ruby's all-object-oriented-all-the-time design. elsif. We'll cover methods in much more detail when we get to objects and classes..rb Hello. as long as the conditional is true while a > 5 a = 10*rand end And like if. No difference. case is actually a very powerful super version of the if . Giraffe My secret word is 7 long .rb def my_function( a ) puts "Hello. { .the value of the last line executed in the function is used as the return value -...|. local and class methods should start with a lower case letter. } in C or Perl you've defined a code block.. the function takes one argument (a) and returns a value. but in Ruby a code block has some hidden secret powers.. a need not be a string) .. In this example. Instead. but it's actually an object (of type Fixnum) As its an object.. It's actually not a particularly revolutionary concept -. As with other languages. Technically this isn't necessary -. In this case.e. the block of code behaves like a 'partner' to which the function occasionally hands over control] The concept can be hard to get the first time it's explained to you. Code blocks in Ruby are defined either with the keywords do. 34 Blocks One very important concept in Ruby is the code block.times { puts "Hi!" } Hi! Hi! Hi! => 3 Surprise! You always thought 3 was just a number.end or the curly brackets {. followed by the function name. both of which will be covered in due time. As with variables. this allows for great flexibility but can also cause a lot of trouble. a quick check of the documentation for times shows it will pass a single parameter into the block. it has a member function times which takes a block as a parameter.times { |x| puts "Loop number #{x}" } Loop number 0 Loop number 1 Loop number 2 Loop number 3 . as discussed below. Ruby supports both default values for arguments and variable-length argument lists.Ruby Programming/Ruby basics Methods are defined with the def keyword. using a special notation |. There's also support for code blocks.but more often than not using return explicitly makes things clearer.. Note that the input arguments aren't typed (i.. The function also returns a single value with the return keyword.any time you've written if . indicating which loop it's on: $ irb --simple-prompt >> 4..} do print "I like " print "code blocks!" end { print "Me too!" } One very powerful usage of code blocks is that methods can take one as a parameter and execute it along the way. Blocks can actually receive parameters.. [ed note: the Pragmatic Programmers actually want to point out that it's not very useful to describe it this way. The function runs the block 3 times. Here's an example: $ irb --simple-prompt >> 3.. Ruby Programming/Ruby basics => 4 The times function passes a number into the block.rb def animals yield "Tiger" yield "Giraffe" end animals { |x| puts "Hello. The block gets that number in the variable x (as set by the |x|). #{x}" } $ block1. Tiger Hello. we've written a simple code block which just prints out a greeting to the animals. Functions interact with blocks through the yield. Here's an example where the function passes a parameter to the block: # Script block1. Every time the function invokes yield control passes to the block.it's great for iterating over lists. then prints out the result. In this example. for example: animals { |x| puts "It's #{x.rb Hello! Hello! The simpleFunction simply yields to the block twice -. the function calls the code block twice.so the block is run twice and we get two times the output. We've defined the function "animals" -. It only comes back to the function when the block finishes.length} characters long!" } which would give: It's 5 characters long! It's 7 characters long! Two completely different results from running the same function with two different blocks. We could write a different block. There are many powerful uses of blocks. Giraffe It might take a couple of reads through to figure out what's going on here. Here's a simple example: # Script block2. One of the first you'll come across is the each function for arrays -.rb Hello. first with the parameter "Tiger" then again with the parameter "Giraffe". 35 .rb def simpleFunction yield yield end simpleFunction { puts "Hello!" } $ block2.it expects a code block. When executed.it runs a code block once for each element in the array -. Here are some other examples $ irb --simple-prompt >> 3.abs => 3 >> "giraffe".length => 7 >>> a. it's infact an instance of the class Fixnum (which inherits from the class Numeric which inherits from the class Object).abs => 3 >> -3. The method times comes from Fixnum and does just what it claims to do. Everything is an object -.times { puts "Hi!" } Even though 3 might seem like just a constant number.Ruby Programming/Ruby basics 36 Ruby is really. but are instead methods of a given variable.reverse => "effarig" There will be lots of time to consider how object-oriented design filters through Ruby in the coming chapters. really object-oriented Ruby is very object oriented. . This also means that the vast majority of what you might consider "standard functions" aren't floating around in some library somewhere.even things you might consider constants. Here's one example we've already seen: 3. object_id => 150808 . Now you're an expert on Ruby constants. everything in Ruby is an object.times. (Silly. it just so happens that Ruby's object oriented ways have a cost: lots of objects make for slow code. You can call methods on pretty much anything. Let us try running the above code using symbols instead of strings : irb> :my_symbol. however. Here is a sample irb session which demonstrates this fact : irb> "live long and prosper". "the answer to everything" => 42."} puts "Stringy string McString!"... Everything has a class. Earlier you saw an example of this in the form of 3. Ruby treats every instance as a new object. To get around this memory hoggishness.class See? Everything is an object. meaning you can add variables and methods to a class at any time during the execution of your code. Every object has a method called class that returns that object's class. Ruby makes a new object. Constants We'll start off with constants because they're simple. You could have "live long and prosper" in your code once and then again later on and Ruby wouldn't even realize that they're pretty much the same thing. 2.object_id => -606662268 irb> "live long and prosper". is a discussion of datatypes. but what can you do?) Congrats.Ruby Programming/Data types 37 Ruby Programming/Data types Ruby Data Types As mentioned in the previous chapter. Two things to remember about constants: 1.object_id => -606666538 Notice that the object ID returned by irb Ruby is different even for the same two strings. but Ruby will give you a warning." Symbols are lightweight objects best used for comparisons and internal logic. why not use a symbol rather than a string? Your code will thank you for it. constant is not. Regardless of whether two strings are identical. Symbols So did you notice something weird about that first code listing? "What the hell was that colon thingy about?" Well. Ruby has provided "symbols. Every time you type a string. If the user doesn't ever see it. Constant is a constant.class puts h. This. Don't believe me? Try running this bit of code: h = {"hash?" => "yep.) Something that makes this extreme object oriented-ness very fun for me is the fact that all classes are open.class puts :symbol. (Technically when you call a method you're sending a message to the object. it's a hash!". I know.class puts 1. but I'll leave the significance of that for later. Constants start with capital letters.class puts nil.object_id => 150808 irb> :my_symbol. :linux => "fun for coders. You can change the values of constants. delete(:luke) Now Luke's no longer in the hash. You have a key. :han => "Rebel without a cause". :han => "Rebel without a cause". I could have used a regular expression.. I could have even written it like this: hash = Hash. and "Farmboy turned Jedi" in consecutive order.each do |key. The best way to illustrate this.match("farmboy")} This looks at each key-value pair and deletes it if the block of code following it returns true. I made the value lowercase (in case the farmboys decided to start doing stuff like "FaRmBoY!1!") and then checked to see if "farmboy" matched anything in its contents. If I wanted to be verbose about defining my hash. :han => "Rebel without a cause".downcase. :luke => "Farmboy turned Jedi"} puts hash[:leia] puts hash[:han] puts hash[:luke] This code will print out "Princess from Alderaan".. I'd just assign a new value to the hash like so: hash[:lando] = "Dashing and debonair city administrator. value| puts value end If I felt like offing Luke.delete_if {|key. I'd just do hash. I'd just use the inspect method to return the hash's keys as an array. is simply to demonstrate: hash = {:leia => "Princess from Alderaan". If I felt like looking at keys. I could do this: hash. In the block of code you see there. which is then printed out." If I felt like measuring this hash. putting the key in the key variable and the value in the value variable. value| puts value end This code cycles through each element in the hash. :luke => "Farmboy turned Jedi") hash. . Speaking of which. I could have also written this like so: hash = {:leia => "Princess from Alderaan". I could do something like this: hash. :luke => "Farmboy turned Jedi"} hash.Ruby Programming/Data types Symbols are denoted by the colon sitting out in front of them. and you look it up to find the associated object. "Rebel without a cause".length. Or lets say I just had a vendetta against farmboys in general. a reference. If I felt like adding Lando into the mix. I think. the definition. like so: :symbol_name 38 Hashes Hashes are like dictionaries. but that's another story. value| value.each do |key. in a sense.[](:leia => "Princess from Alderaan". I can check for this condition by calling the empty? method. array2 wouldn't hold any elements. You wanna' see if array has something in it? Just ask it with the include? method. but I know that Java would make a fuss if I tried the following bit of code: array3 = array . So in an array with 5 items. the last element would be found at array[4] and the first element would be found at array[0].pop until array2. all the methods you just learned with hashes can also be applied to arrays. you'd do something like this: string = array2. "array!"] = [] << "This" << "is" << "also" << "an" << "array!" As you may have guessed.join . I could just pop it off.pop Then string would hold array! and array2 would be one element shorter.Ruby Programming/Data types 39 Arrays Arrays are a lot like hashes. like so: string = array2. the computer would print out array! Of course. the << operator pushes values onto the end of an array. array4 now holds all the elements of both array and array2. the following bit of code moves all the elements from one array to another: array1 << array2.join(" ") Using the array we just declared. So if I ran this: string = array2. So all the elements of array minus the elements of array2 are now held in array3.array2 array4 = array + array2 Now array3 holds all the elements that array did except for the ones that also happened to be in array2. but the keys are always consecutive numbers.empty? Here's something that really excites me: arrays can be subtracted and added to each other. like so: array. Here are two ways to create arrays: array1 array2 array2 array2 array2 array2 array2 = ["hello". I don't know about any other languages. the first key in an array is always 0. In addition. The pop method returns the last element in an array and then deletes it from the array. if I felt like simultaneously getting array! and deleting it from the array. "is". string now holds This is also an array! If we had wanted something more along the lines of Thisisalsoanarray! we could have called the join method without any arguments. "an". "this".include?("Is this in here?") If you just wanted to turn the whole array into a string. If I kept doing this. Also. For example. So if I were to write puts array2[4] after declaring those two arrays. there's a number in this one. thing1 = "Red fish." If I had typed /. For example: puts "Yeah. you can multiply them. this is a concatenated string! You can also do some interpolation. To find out what the ASCII value of a character is. "Danger. Aside from these weird little operations.Ruby Programming/Data types 40 Strings I would recommend reading the chapters on strings and alternate quotes now if you haven't already. You'd do it like this: . you are really comparing the ASCII values of the characters. use the following code: puts ?A This will return 65. Will Robinson!Danger. string1 and string2 in the following chunk of code are identical. It's the same as in most other languages: + So "Hi. as this is the ASCII value of "A. You can check to see if a string matches a regular expression using this. Even though you can use regular expressions with these next two methods. Will Robinson! You can also compare strings like so: "a" < "b" This comparison will yield true. But what's with that weird "/. you would use the scan method like so: thing1. For example. we also have the venerable "concatenate" operation. this is " + "a concatenated string!" would return Hi. Will Robinson!Danger. except it can accept a string as a parameter as well." string2 = "#{thing1 + thing2} And so on and so forth. To do the opposite conversion./ then it would have gone through every chunk of two characters. This chapter is going to cover some pretty spiffy things with strings and just assume that you already know the information in these two chapters. Will Robinson!" * 5 yields Danger. there are some pretty cool built-in functions where strings are concerned. Lets pretend you work at the Ministry of Truth and you need to replace a word in a string with another word.." if "Jabba the Hutt"." Just replace A with whatever character you want to inquire about. quite powerful. All you need to know for now is that /." if "C3-P0. The match method works much the same way." They're helpful little buggers. there's a number in this one." If you wanted to step through each one of the letters in thing1. Will Robinson!Danger. that's enough about the regular expressions. human-cyborg relations" =~ /[0-9]/ This will print out Yeah. Another use for regular expressions can be found with the =~ operator. they mentioned Jabba in this one. " thing2 = "blue fish. use the chr method./" thing in the parameter? That./) {|letter| puts letter} This would print out each letter in thing1. but they're also outside the scope of this discussion. my friend. This is helpful if you're getting regular expressions from a source outside the code./ is "reg-ex" speak for "every individual character. Will Robinson!Danger. is called a "regular expression. When you compare two strings like this. So 65.match("Jabba") Alright. we'll just use regular old strings. In Ruby. for handling pesky string variables without using the concatenate operator." string1 = thing1 + thing2 + " And so on and so forth.scan(/. Here's what it looks like in action: puts "Yep.chr would return A. + adds two numbers together. Observe: winston = %q{ Down with Down with Big Down with Big Down with Big Down with Big winston.downto(1) {|x| puts x} puts "Blast-off!" # Finally we'll settle down with an obscure Schoolhouse Rock video. but there's a much more efficient way to do things. / divides. 1." 10.. (If you want to know more methods you can use with strings. then say I'm done! It's basically a simplified for loop.. Use it whenever you want to do something more than once..0 / 3 you would get 3. Big Brother! Brother! Brother! Brother! Brother!} "Long live") 41 Big Brother would be proud. Floats are numbers with decimal places. But what if the string contains lots of lies like the one you just corrected? sub only replaces the first occurrence of a word! I guess you could cycle through the string using match and a while loop.. Capice? Alright.sub("4". First I'll show you some integer methods. look at the end of this chapter for a quick reference table. It's a little slower than a for loop by a few hundredths of a second or so.) Numbers (Integers and Floats) You can skip this paragraph if you know all the standard number operators. gsub is the "global substitute" function. Since integers have no decimal places all you get is 3. Here we have the venerable times method.-) Alright.subtracts them.. Here are three of them: # First a visit from The Count. "5") Now string2 contains 2 + 2 = 5. lets move on to integers and floats. not its disdain thereof.times {puts "Guess what?"} puts "I'm done!" This will print out the numbers 1 through 100. Everything in Ruby is an object. let's get down to the fun part. print out Guess what? five times. integers are numbers with no decimal place.upto(10) {|number| puts "#{number} Ruby loops..times {|number| puts number} 5.. % returns the remainder of two divided numbers. let me reiterate. here's a crash course. If you tried 10. 10 / 3 yields 3 because dividing two integers yields an integer. we're nearly done.33333. keep that in mind if you're ever writing Ruby code for NASA.. On that happy note. Integers and floats are no exception. ah-ah-ah!"} # Then a quick stop at NASA. Every occurrence of "Down with" has now been replaced with "Long live" so now winston is only proclaiming its love for Big Brother.. That means that pretty much everything has at least one method. .." 100.Ruby Programming/Data types string1 = "2 + 2 = 4" string2 = string1.gsub("Down with". Examples: puts "I will now count to 100.. . * multiplies. puts "T-minus. Alright. . For those who don't. If you have even one float in the mix you get a float back.. six more methods to go. Now here's that quick reference table for string methods I promised you. downto does the same. 5) {|x| puts x} would output every multiple of five starting with five and ending at twenty-five. Time for the last three: string1 = 451.upcase # Outputs "Henry VII" "Henry VIII".6.) .hash # Outputs "concatenate" "concat" + "enate" # Outputs "Washington" "washington".swapcase # Outputs "Nexu" (next advances the word up one value.chop # Outputs "rorriM" "Mirror". step counts from the number its called from to the first number in its parameters by the second number in its parameters. 5) {|x| puts x} Alright. that should make sense.5. There you have it.step(50.Ruby Programming/Data types 5.to_f to_s converts floats and integers to strings.capitalize # Outputs "uppercase" "UPPERCASE". to_i converts floats to integers. as if it were a number.to_i float = 5.step(25. Finally.to_s string2 = 98. In case it didn't. upto counts up from the number it's called from to the number passed in its parameter.sum # Outputs cRaZyWaTeRs "CrAzYwAtErS". So 5. All the data types of Ruby in a nutshell. except it counts down instead of up. 42 Additional String Methods # Outputs 1585761545 "Mary J". to_f converts integers to floats.to_s int = 4.reverse # Outputs 810 "All Fears".downcase # Outputs "LOWERCASE" "lowercase". is_a?(MyObject)) puts "Your Object is a MyObject" end end The return keyword can be used to specify that you will be returning a value from the method defined def myMethod return "Hello" end . def myMethod(msg. they can be separated with a comma.Ruby Programming/Data types "Next".is_a?(Integer)) puts "Your Object is an Integer" end #Check to see if it defined as an Object that we created #You will learn how to define Objects in a later section if(myObject. Some programmers find the Methods defined in Ruby very similar to those in Python. The variable used can only be accessed from inside the method scope def myMethod(msg) puts msg end If multiple variables need to be used in the method. you can put the local variable name in brackets after the method definition. my name is " + person + ". nxt == "Neyn" (to help you understand the trippiness of next) nxt = "Next" 20. Some information about myself: " + msg end Any object can be passed through using methods def myMethod(myObject) if(myObject.next} 43 Ruby Programming/Writing methods Defining Methods Methods are defined using the def keyword and ended with the end keyword. person) puts "Hi.next # After this. def myMethod end To define a method that takes in a value.times {nxt = nxt. arrays.class ["this".new. What you don't know however. You already know that you can create strings. :a => "hash"}. hashes. my_string = "" is the same as my_string = String."is". When you create your own classes. numbers. so this is functionally equivalent to the previous method def myMethod "Hello" end Some of the Basic Operators can be overridden using the def keyword and the operator that you wish to override def ==(oVal) if oVal. everything in Ruby is an object.Ruby Programming/Writing methods It is also worth noting that ruby will return the last expression evaluated. simply call that object's class method.is_a?(Integer) #@value is a variable defined in the class where this method is defined #This will be covered in a later section when dealing with Classes if(oVal == @value) return true else return false end end end 44 Ruby Programming/Classes and objects Ruby Classes As stated before.class Anyhow.."an". and other built-in types by simply using quotes. you should already know this. is how to make your own classes and extend Ruby's classes. try this: puts puts puts puts puts "This is a string". Creating Instances of a Class An instance of a class is an object that has that class. For example. For example. hashes. Every class has a new method: arrays. but you can also create them via the new method.class {:this => "is". integers.class 9.class :symbol. whatever."array"]. brackets. . you'll use the new method to create instances. Every object has a class. For example. etc. To find the class of an object. curly braces. "chocolate" is an instance of the String class. Self Inside a method of a class.eat # outputs "That tasted great!" You can also call a method by using send "hello". such as a book.Ruby Programming/Classes and objects 45 Creating Classes Classes represent a type of an object.more # -> 8 .send(:eat) # outputs "That tasted great!" However.send(:length) # outputs "5" my_chocolate. After that comes the name of the class. For example: class Integer def more return self + 1 end end 3. All class names must start with a Capital Letter. we would use this code: my_chocolate = Chocolate. By convention. using send is rare unless you need to create a dynamic behavior.it can be a variable. the pseudo-variable self (a pseudo-variable is one that cannot be changed) refers to the current instance. as we do not need to specify the name of the method as a literal . a grape. but not like Piece_of_Chocolate.length To call the eat method of an instance of the Chocolate class.more # -> 4 7. so let's make a chocolate class: class Chocolate def eat puts "That tasted great!" end end Let's take a look at this. A class method is a method that is defined for a particular class. So we would create classes like PieceOfChocolate. the String class has the length method: # outputs "5" puts "hello". Classes are created via the class keyword. For example. a whale. Everybody likes chocolate. we use CamelCase for class name. or chocolate. The next section defines a class method.new my_chocolate. color return "red" end def self. The meta-class is a special class that the class itself belongs to.shape # -> "strawberry-ish" Note the three different constructions: ClassName. puts us in the context of the class's "meta-class" (sometimes called the "eigenclass"). self refers to the class itself. The latter is preferred. All this construct does it allow us to define methods without the self.size return "kinda small" end class << self def shape return "strawberry-ish" end end end Strawberry. The last construction. For example: class Strawberry def Strawberry. at this point. prefix. class << self. you don't need to worry about it.outside of a method definition in a class block. . as it makes changing the name of the class much easier.color # -> "red" Strawberry.method_name and self.size # -> "kinda small" Strawberry.method_name are essentially the same .Ruby Programming/Classes and objects 46 Class Methods You can also create methods that are called on a class rather than an instance. However. class SimpleNumber def initialize( num ) raise unless num.com [2] References [1] http:/ / www. A way to gather like tests together and run them as a group. maybe found in a tutorial at RubyLearning. Instead. by Satish Talim. require "simpleNumber" require "test/unit" class TestSimpleNumber < Test::Unit::TestCase . Ruby provides a framework for setting up. A way to define basic pass/fail tests. Tools for running single tests or whole groups of tests.Ruby Programming/Exceptions 47 Ruby Programming/Exceptions There is no exceptions chapter at present.is_a?(Numeric) @x = num end def add( y ) @x + y end def multiply( y ) @x * y end end Let's start with an example to test the SimpleNumber class. and running tests called Test::Unit. Test::Unit provides three basic functionalities: 1. A Simple Introduction First create a new class. if you dedicate time to writing appropriate and useful tests. here is a link to a chapter about exceptions from Yukihiro Matsumoto's book. org/ docs/ ProgrammingRuby/ html/ tut_exceptions. 2. 3. As in other languages. Programming Ruby: The Pragmatic Programmer's Guide [1] More detail and simpler examples about exceptions. html Ruby Programming/Unit testing Unit testing is a great way to catch minor errors early in the development process. com/ satishtalim/ ruby_exceptions. html [2] http:/ / rubylearning. ruby-doc. organizing. Specifically. 0 failures.new(2).it's just a class definition). the tests are automatically run. SimpleNumber. SimpleNumber. require "simpleNumber" require "test/unit" class TestSimpleNumber < Test::Unit::TestCase def test_simple assert_equal(4.Ruby Programming/Unit testing 48 def test_simple assert_equal(4. When we run that class (note I haven't put any sort of wrapper code around it -. and we're informed that we've run 1 test and 2 assertions. Finished in 0. Let's try a more complicated example.multiply(3) ) end end Which produces >> ruby tc_simpleNumber.rb Loaded suite tc_simpleNumber2 Started F. 0 errors So what happened here? We defined a class TestSimpleNumber which inherited from Test::Unit::TestCase.add(2) ) assert_equal(6.new('a') } end def test_failure assert_equal(3. SimpleNumber.new(2).add(2).. That member function contains a number of simple assertions which exercise my class.new(2). SimpleNumber.rb Loaded suite tc_simpleNumber Started .002695 seconds.new(2).new(2). 1 tests. In TestSimpleNumber we defined a member function called test_simple. . 2 assertions.add(2) ) assert_equal(4. SimpleNumber. "Adding doesn't work" ) end end >> ruby tc_simpleNumber2.multiply(2) ) end def test_typecheck assert_raise( RuntimeError ) { SimpleNumber. 0 errors Now there are three tests (three member functions) in the class. which are documented thoroughly at Ruby-Doc [1]... 4 assertions. 1 failures.class == class True if object. [message] ) True if object. which the Ruby output happily points out. [message] ) assert_no_match( pattern. actual_float. True if the object can respond to the given method. delta. [message] ) {block} assert_nothing_thrown( [message] ) {block} assert_respond_to( object. True if the block throws (or doesn't) the expected_symbol. we've also added an final parameters which is a custom error message. Compares the two objects with the given operator. actual. [message] ) assert_not_nil( object.Ruby Programming/Unit testing Finished in 0. Here's a brief synopsis (assertions and their negative are grouped together.expected_float). [message] ) True if (actual_float . 1) Failure: test_failure(TestSimpleNumber) [tc_simpleNumber2. not only telling us which test failed. True if the method sent to the object with the given arguments return true. string. object2. [message]) assert_not_same( expected. [message] ) assert_match( pattern. [message] ) assert_not_equal( expected. but how it failed (expected <3> but was <4>). <3> expected but was <4>. actual.) {block} assert_throws( expected_symbol. It's strictly optional but can be helpful for debugging.. The function test_failure is set up to fail. On this assertion. operator. [message] ) assert_kind_of( class. actual. [message] ) assert_equal( expected. [message] ) assert_operator( object1. 3 tests. [message] ) assert_raise( Exception. True if the block raises (or doesn't) one of the listed exceptions.rb:16]: Adding doesn't work.kind_of?(class) True if actual. method.038617 seconds. [message] ) assert_send( send_array. 49 Available Assertions Test::Unit provides a rich set of assertions.. object.. [message] ) assert_same( expected. The function test_typecheck uses assert_raise to check for an exception. The text description is usually for the first one listed -the names should make some logical sense): assert( boolean. passes if true . object..abs <= delta assert_instance_of( class. actual. [message] ) assert_nil( object. [message] ) True if boolean True if expected == actual True if string =~ pattern True if object == nil assert_in_delta( expected_float.equal?( expected ). All of the assertions include their own error messages which are usually sufficient for simple debugging. ) {block} assert_nothing_raised( Exception. string. which is a subclass of Test::Unit::TestCase. Naming Conventions The author of Test::Unit. suggests starting the names of test cases with tc_ and the names of test suites with ts_ Running Specific Tests It's possible to run just one (or more) tests out of a full test case: >> ruby -w tc_simpleNumber2. test suites can contain other test suites. or a suite of suites can run.Ruby Programming/Unit testing 50 Structuring and Organizing Tests Tests for a particular unit of code are grouped together into a test case. This structure provides relatively fine-grained control over testing. 0 errors . 1 tests. 0 errors It is also possible to run all tests whose names match a given pattern: >> ruby -w tc_simpleNumber2.003401 seconds. and provide the appropriate feedback.*/ Loaded suite tc_simpleNumber2 Started . Nathaniel Talbott. Finished in 0. a full test case can be run stand-alone. Test::Unit will iterate through all of the tests (finding all of the member functions which start with test_ using reflection) in the test case. 1 assertions. Finished in 0. When the test case is executed or required. 1 tests. related test cases can be naturally grouped. member functions for the test case whose names start with test_. 0 failures. Individual tests can be run from a test case (see below).rb --name /test_type. Test case classes can be gathered together into test suites which are Ruby files which require other test cases: # File: require require require require ts_allTheTests.rb 'test/unit' 'testOne' 'testTwo' 'testThree' In this way. Further. a test suite containing multiple cases can be run. allowing the construction of a hierarchy of tests. 1 assertions.003401 seconds. Assertions are gathered in tests. spanning many test cases.rb --name test_typecheck Loaded suite tc_simpleNumber2 Started . 0 failures. new(2) end def teardown ## Nothing really end def test_simple assert_equal(4. org/ stdlib/ libdoc/ test/ unit/ rdoc/ classes/ Test/ Unit. 2 tests. @num. html . ruby-doc. Test::Unit provides the setup and teardown member functions.multiply(2) ) end end >> ruby tc_simpleNumber3. 0 failures. 2 assertions. require "simpleNumber" require "test/unit" class TestSimpleNumber < Test::Unit::TestCase def setup @num = SimpleNumber.Ruby Programming/Unit testing 51 Setup and Teardown There are many cases where a small bit of code needs to be run before and/or after each test.. 0 errors External Links • Test::Unit documentation [1] at Ruby-Doc [2] References [1] http:/ / www. Finished in 0.add(2) ) end def test_simple2 assert_equal(4.rb Loaded suite tc_simpleNumber3 Started . which are run before and after every test (member function). @num.00517 seconds. html fr_file_index. A Simple Example Here are the contents of the file simpleNumber.. RDoc isn't a file you require to use.rb simpleNumber. It contains quite a few files (given such a simple class!) >> ls doc/ classes created.html fr_method_index.rb which contains a class SimpleNumber # This file is called simpleNumber.html rdoc-style. run rdoc on this file >> rdoc simpleNumber.rb: c. Files: Classes: Modules: Methods: Elapsed: 1 1 0 3 0.is_a?(Numeric) @x = num end def add( y ) @x + y end def multiply( y ) @x * y end end Just to get going. Generating HTML. Though it's part of the standard library.html index. Instead it consists of a command-line program called rdoc and a library for parsing specially-formatted comments out of Ruby and C code.426s A quick look around reveals rdoc has created a new directory called doc/.rb # It contains the class SimpleNumber class SimpleNumber def initialize( num ) raise if !num..rid files fr_class_index..css ..Ruby Programming/RubyDoc 52 Ruby Programming/RubyDoc The standard Ruby library provides a tool for generating documentation from self documenting code called RubyDoc [1] or RDoc for short. Here's a brief overview: • Consecutive lines aligned on the left margin (either column 0 in a text file.c extension). The middle pane lists all of the classes in simpleNumber. SimpleMarkup is a simplified text-based markup system. rdoc will search recursively. In this case the lower panel is showing the summary information for the file simpleNumber. If no source files are specified.generally speaking they will just be browsable as plain text files in the HTML documention. In this case they are treated as SimpleMarkup (see below) -. 2.rb. either unnumbered or numbered.rb which has been extracted from the top-level comment in the file. Any files which aren't recognized as Ruby or C are not parsed by default. which makes it convenient for documenting large trees of code. and the right panel gives all of the methods in SimpleNumber. but can be included as command-line arguments to rdoc. * This is the second item in the original list • The lists can be labeled. Here's an example (from the RDoc documentation): * this is a list with three paragraphs in the first item.Ruby Programming/RubyDoc Open the file doc/index. And this is the second paragraph. 1.rb or . "-" or "<a digit>" the following information is a list item.html in a web browser and find What has RDoc done? First. This is an indented. much like many wiki markup languages. An empty line starts a new paragraph. RubyDoc will start searching with the current directory. The output is always generated in a directory doc/ under the current location.rbw extension) and C files (with a . 53 Handling Multiple Files Any directories included on the command line will be searched for Ruby files (with an . Each label must be inside square brackets or followed by two colons: [cat] a small furry mammal that seems to sleep a lot a little insect that is known to enjoy picnics a small furry mammal that seems to sleep a lot [ant] cat:: . This is the second item in that list This is the third conventional paragraph in the first list item. numbered list. it has scanned the given file (shown in the upper left pane). • If a line starts with "*". Formatting for RDoc RDoc uses a formatting system called SimpleMarkup for its markup purposes. or after the comment character and whitespace in a source file) are considered a paragraph. This is the first paragraph. Once we select either a class or a function it will show more particular information. All subsequent lines should be indented to match the text on the first line of the list item. this value is used as the exit code for the application (yes. • Basic text markup: • Tags can be used. Any further (string) arguments call out sections of the introductory comment which should be used. etc. This behavior can be enabled with the command line option --diagram or -d. RDoc will generate class hierarchy diagrams as part of the HTML documentation. for example) • Any line starting with one or more equals signs is a heading. • Three or more dashes on a line give a horizontal line. RDoc::usage terminates the application). This is done with the class method RDoc::usage. If the first argument is an integer. and plus signs for +code+ text. Here's an example: # TestRDocUsage: A useless file # # Usage: ruby testRDocUsage.rb [options] .Ruby Programming/RubyDoc 54 ant:: a little insect that is known to enjoy picnics • Any line which starts to the right of the current left margin is considered verbatim text (like program code. HTML tags can be used. One equals sign is a top-level header. two equals signs is a second-level heading.rb # require 'rdoc/usage' RDoc::usage Which when run: >> ruby testRdocUsage.rb [options] [options] Not particularly interesting. underscores for _emphasis_ text. including asterisks for *bold text*. • Alternately. Using RDoc to Generate Usage Output RDoc can be used to generate a command-line usage string (paragraph) from a file's comments. Including Diagrams If the program dot from the Graphviz [2] is available.rb TestRDocUsage: A useless file Usage: ruby testRDocUsage. RDoc::usage can take two kinds of command line options. Here's a slightly more complicated version of the above example: #= Overview # TestRDocUsage: A useless file # #= Usage # # Usage: ruby testRDocUsage. html [2] http:/ / www. Other Interesting Command-Line Options Here are a selection of other interesting rdoc command-line options which haven't been covered above: -a. org/ stdlib/ libdoc/ rdoc/ rdoc/ index.rb USAGE ===== Usage: 55 ruby testRDocUsage. -x.Ruby Programming/RubyDoc # require 'rdoc/usage' RDoc::usage('Usage') This time with section headers. org/ . --all Parse all class methods.rb [options] Where only the 'Usage' section (called out as an argument to RDoc::usage) is included. not just public methods. graphviz. ruby-doc. --exclude pattern Exclude files/directories matching pattern from search. Running the script gives >> ruby testRdocUsage. External Links • RDoc documentation [1] (generated using RDoc!) at Ruby-Doc [2] Questions • How do you include an external image file when publishing RDoc inside a Gem? RDoc keeps converting the image into html! References [1] http:/ / www. Files included explicitly on the command line are never excluded. Ruby Programming/Syntax 56 Ruby Programming/Syntax • Syntax • Lexicology • Identifiers • Comments • Embedded Documentation • Reserved Words • Expressions • Variables and Constants • • • • • • Local Variables Instance Variables Class Variables Global Variables Constants • Scope • and • or • not • Control Structures • Conditional Branches • if • if modifier • unless • unless modifier . in • break • redo • next • retry • Exception Handling • raise • begin • rescue modifier • Miscellanea • return • Method Calls • super • Iterators • yield • Classes • Class Definition • Instance Variables • Class Variables • Class Methods • Instantiation • Declaring Visibility • Private • Public • Protected • Instance Variables • Inheritance • Mixing in Modules • Ruby Class Meta-Model 57 .Ruby Programming/Syntax • case • Loops • while • while modifier • until • until modifier • for • for ... These reserved words must begin in column 1. definitions. a comment is regarded as the text from the # to the end of the line. Identifiers are names used to identify variables. definitions. classes. There is no restriction to its length. An identifier cannot have a reserved word as its name . …. Comments Example: # this is a comment line Other than within a string. etcetera in a program and from other other variables. =end Reserved Words The following words are reserved in Ruby: __FILE__ __LINE__ BEGIN END alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield . Embedded Documentation Example: =begin Everything between a line beginning with `=begin' down to one beginning with `=end' will be skipped by the interpreter.Ruby Programming/Syntax/Lexicology 58 Ruby Programming/Syntax/Lexicology Identifiers Example: foobar ruby_is_simple An identifier in Ruby begins with an English letter (A-Za-z) or underscore (_) and consists of alphanumeric characters (A-Za-z0-9) or underscores (_). "i0 was initialized in this block # false. A local variable is only accessible from within the block of its initialization. a newline with a preceeding backslash (\) is continued to the following line. literals. Using these together is called a program. Local Variables Example: foobar A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation. "i1" was initialized in the loop . "i0" was initialized in the ascendant # true. Ruby Programming/Syntax/Variables and Constants A variable in Ruby can be distinguished by the characters at the start of its name. For example: i0 = 1 loop { i1 = 2 puts defined?(i0) block puts defined?(i1) break } puts defined?(i0) puts defined?(i1) # true. There's no restriction to the length of a variable's name (with the exception of the heap size). operators.Ruby Programming/Syntax/Lexicology 59 Expressions Example: true (1 + 2) * 3 foo() if test then okay else not_good end All variables.) — however. "i1" was initialized in this block # true. control structures. etcetera are expressions. You can divide expressions with newlines or semicolons (. and every other value is considered to be true in Ruby. Expresses nothing. Example: @@foobar Global Variables Example: $foobar A variable whose name begins with '$' has a global scope.) The value of a pseudo variable cannot be changed. (nil also is considered to be false. Constants Usage: FOOBAR A variable whose name begins with an uppercase letter (A-Z) is a constant. but doing so will generate a warning. Class Variables A class variable is shared by all instances of a class. Expresses false. false The sole-instance of the FalseClass class. Expresses true. A constant can be reassigned a value after its initialization. . meaning it can be accessed from anywhere within the program during runtime. Uninitialized instance variables have a value of nil. true The sole-instance of the TrueClass class. Pseudo Variables self Execution context of the current method. nil The sole-instance of the NilClass class. Substitution to a pseudo variable causes an exception to be raised. An instance variable belongs to the object itself. Trying to substitute the value of a constant or trying to access an uninitialized constant raises the NameError exception. Every class is a constant.Ruby Programming/Syntax/Variables and Constants 60 Instance Variables Example: @foobar A variable whose name begins with '@' is an instance variable of self. May be assignable. The current standard error output. $" $DEBUG $FILENAME $LOAD_PATH $stderr $stdin $stdout $VERBOSE $-0 $-a variable. The verbose flag. $stdout by default. $0 Contains the name of the script being executed. printf. $& The in this scope.Ruby Programming/Syntax/Variables and Constants 61 Pre-defined Variables $! $@ The exception information message set by 'raise'. $* Command line arguments given for the script sans args. $< The command line. $? The status of the last executed child process. The alias to $/. $\ The output record separator for the print and IO#write. $. The default separator for String#split. True if option -a ("autosplit" mode) is set. The output field separator for the print and Array#join. last input line of string by gets or readline. last bracket matched by the last successful match. The alias to $. The read. $-d $-F $-i extension. The status of the -d switch. The current standard input. $$ The process number of the Ruby running this script. . $. this variable holds the otherwise nil. newline by default. $-I The array contains the module names loaded by require. string to the right of the last successful match. $` The $' The $+ The $1 to $9 The $~ The $= The flag for case insensitive. The current standard output. information about the last match in the current scope. nil by default. If in-place-edit mode is set. $> The $_ The current input line number of the last file that was virtual concatenation file of the files given on default output for print. Same as $<. Array of backtrace of the last exception thrown. Nth group of the last successful regexp match. The alias to the $:. $.. Current input file from $<. which is set by the -v switch. Read-only The alias to $DEBUG.filename. $: Load path for scripts and binary modules by load or require. $/ The input record separator. string matched by the last successful pattern match string to the left of the last successful match. The alias to $:. Default is nil. $-w True if option -w is set. Read-only variable.2e-3 0xaabb 0377 -0b1010 0b001_001 ?a ?\C-a ?\M-a ?\M-\C-a # # # # # # # # # # # # # # # Fixnum Fixnum (signed) Fixnum (underscore is ignored) Negative Fixnum Bignum Float Float (Hexadecimal) Fixnum (Octal) Fixnum (Binary [negated]) Fixnum (Binary) Fixnum ASCII character code for 'a' (97) Control-a (1) Meta-a (225) Meta-Control-a (129)}" . 62 Ruby Programming/Syntax/Literals Numerics 123 -123 1_123 -543 123_456_789_123_456_789 123. Note. This infestation of cryptic two-character $? expressions is a thing that people will frequently complain about.45 1. Read-only variable. a lot of these are useful when working with regexp code. Keep this chart handy. dismissing Ruby as just another perl-ish line-noise language. $-v The alias to $VERBOSE. $-p True if option -p is set ("loop" mode is on).Ruby Programming/Syntax/Variables and Constants $-l True if option -l is set ("line-ending processing" is on). A single-quoted string expression isn't.9 and later) control-x control-x meta-x meta-control-x character x itself (\" for example) Interpolation Interpolation allows Ruby code to appear within a string. including any errors: "the meaning of life is #{1/0}" => divided by 0 (ZeroDivisionError) #=> "1 + 2 = 3" .Ruby Programming/Syntax/Literals A string expression begins and ends with a double or single-quote mark. The code will have the same side effects as it would outside the string. they are used to insert special characters in a string. except for \' and \\. Double-quoted string expressions are subject to backslash notation and interpolation. 63 Backslash Notation Also called escape characters or escape sequences. The result of evaluating that code is inserted into the string: "1 + 2 = #{1 + 2}" #{expression} The expression can be just about any Ruby code. Example: "this is a\ntwo line string" "this string has \"quotes\" in it" Escape Sequence Meaning \n \s \r \t \v \f \b \a \e \nnn \xnn \unnnn \cx \C-x \M-x \M-\C-x \x newline (0x0a) space (0x20) carriage return (0x0d) tab (0x09) vertical tab (0x0b) formfeed (0x0c) backspace (0x08) bell/alert (0x07) escape (0x1b) character with octal value nnn character with hexadecimal value nn Unicode code point U+nnnn (Ruby 1. Ruby is pretty smart about handling string delimiters that appear in the code and it generally does what you want it to do. However. separated by whitespace Interpolated shell command Here are some more examples: %Q{one\ntwo\n#{ 1 + 2 }} => "one\ntwo\n3" %q{one\ntwo\n#{ 1 + 2 }} => "one\\ntwo\\n#{ 1 + 2 }" %r{nemo}i => /nemo/i %w{one two three} => ["one". By using this notation. the usual string delimiters " and ' can appear in the string unescaped. "two". %{curly brackets} or %<pointy brackets> as delimiters then those same delimiters can appear unescaped in the string as long as they are in balanced pairs: %(string (syntax) is pretty flexible) => "string (syntax) is pretty flexible" A modifier character can appear after the %. %[square brackets]. %[including these]. for example: %{78% of statistics are "made up" on the spot} => "78% of statistics are \"made up\" on the spot" Any single non-alpha-numeric character can be used as the delimiter.Copyright (C) 1993-2009 Yukihiro Matsumoto\n" . %Q[]. %~or even these things~. separated by whitespace Interpolated Array of words. if you use %(parentheses).these determine how the string is interpolated and what type of object is produced: Modifier Meaning %q[ ] %Q[ ] %r[ ] %s[ ] %w[ ] %W[ ] %x[ ] Non-interpolated String (except for \\ \[ and \]) Interpolated String (default) Interpolated Regexp (flags can appear after the closing delimiter) Non-interpolated Symbol Non-interpolated Array of words. %?or these?. as in %q[]. "three"] %x{ruby --copyright} => "ruby . %x[] .Ruby Programming/Syntax/Literals 64 The % Notation There is also a (wacky) perl-inspired way to quote strings: by using % (percent character) and specifying a delimiting character. but of course the new delimiter you've choosen does need to be escaped. FIN To use non-alpha-numeric characters in the delimiter. To end the string. it can be quoted: string = <<-". The rest of the line after the opening delimiter is not interpreted as part of the string.Ruby Programming/Syntax/Literals 65 "Here document" notation There is yet another way to make a string. sits still. "short". "short". . "strings"] You can even "stack" multiple here documents: string = [<<ONE. Here documents are interpolated." orchid breathing incense into butterfly wings. "strings"] a long string END => ["a long string\n". folded into sleep. the delimiter appears alone on a line. END The syntax begins with << and is followed immediately by the delimiter. <<TWO. known as a 'here document'. which means you can do this: strings = [<<END. sits still. folded into sleep. There is a slightly nicer way to write a here document which allows the ending delimiter to be indented by whitespace: string = <<-FIN on the one ton temple bell a moon-moth. <<THREE] the first thing ONE the second thing TWO and the third thing THREE . unless you use single quotes around the delimiter. where the delimiter itself can be any string: string = <<END on the one ton temple bell a moon-moth. new [] # shorthand for Array. "b". "c"] #using ranges. "b"] array_four[0.new ["a". "cat". by writing an optional comma-separated list of values inside square brackets. "pear"] array_two = 'apple orange pear'..new.. You can create an array object by writing Array.split(':') "bird"] array_three == array_four # => ["apple".. # => ["apple". "b" and array_three[0] # => "a" array_three[2] # => "c" array_four[0] # => "a" #negative indices are counted back from the end array_four[-2] # => "b" #[start. a space-delimited string preceded by %w. "c"] # array_three contains "a". In the following example. or if the array will only contain string objects.Ruby Programming/Syntax/Literals 66 Arrays An array is a collection of objects indexed by a non-negative integer. "b" and "c" %w'a b c' # array_four also contains "a". array_one array_two array_three array_four "c" = = = = Array.2] # => ["b". "pear"] array_one == array_two array_three = %w'dog:cat:bird' ["dog:cat:bird"] array_four = 'dog:cat:bird'.1] # => ["a". array_one = %w'apple orange pear' "orange".split "orange". # => false . is in essence shorthand for the String method split when the substrings are separated by whitespace only. using %w. the first two ways of creating an array of strings are functionally identical while the last two create very different (though both valid) arrays. # => true # => # => ["dog".1] # => ["a"] The last method. count] indexing returns an array of count objects beginning at index start array_four[1. The end position is included with two periods but not with three array_four[0. . these ranges are expressed by: 0. 5.0 though syntactically correct. hash_one = Hash.0 't'. This may be: • All integers between 0 and 5. to determine whether a value is inside a range: r = 0. but also keys pointing to those values. for excluding). consult the Range class reference. "b"=>2. excluding 1. "c" => 3} #=> {"a"=>1. which must be Comparable (implementing <=>). for including and three . #=> {:b=>2.new hash_two = {} # shorthand for Hash. :b => 2.5 puts r === 4 puts r === 7 # => true # => false For detailed information of all Range methods. all possible values between a start value and an end value. Ranges are instances of the Range class. an end value. not a sequence. c: 3} :a=>1} The latter form was introduced in Ruby 1. "b" => 2. A hash object is created by writing Hash. In Ruby. Ranges A range represents a subset of all possible values of a type. :c => 3} :c=>3. :c=>3. and whether the end value is included or not (in this short syntax..5 0. b: 2. "c"=>3} Usually Symbols are used for Hash keys (allows for quicker access). to be more precise.new or by writing an optional list of comma-separated key => value pairs inside curly braces. #=> {:b=>2.9..1. ranges consist of a start value. Therefore. Ranges can only be formed from instances of the same class or subclasses of a common parent.. and have certain methods. for example.new hash_three = {"a" => 1. • All numbers (including non-integers) between 0 and 1. using two . • All characters between 't' and 'y'. produces a range of length zero. .'y' Therefore. Each key can occur only once in a hash.. so you will see hashes declared like this: hash_sym = { :a => 1.0.. A range represents a set of values.Ruby Programming/Syntax/Literals 67 Hashes Hashes are basically the same as arrays. :a=>1} hash_sym = { a: 1. except that a hash not only contains values. you're always assigning objects.var3. var3 = 10. 30 puts var1 #=>var1 is now 10 puts var2 #=>var2 is now 20..succ! #=>"b" : succ! method is defined for String. Whatever' names #=>["John".etc myArray=%w(John Michel Fran Adolf) # %w() can be used as syntactic sugar to simplify array creation var1.'root'. floats. 20.var3.operators?" In Ruby. Assignment Assignment in Ruby is done using the equal operator "=".Ruby Programming/Syntax/Operators 68 Ruby Programming/Syntax/Operators Operators 1.var2. "Fran". Examples: myvar = 'myvar is now this string' var = 321 dbconn = Mysql::new('localhost'. This is both for variables and objects.var4=*myArray puts var1 #=>John puts var4 #=>Adolf names.. var2. Whatever" Conditional assignment x = find_something() #=>nil x ||= "default" #=>"default" : value of x will be replaced . and integers are actually objects in Ruby. x = 'a' x.'password') Self assignment x x x x x x x = 1 += x -= x += 4 *= x **= x /= x #=>1 #=>2 #=>0 #=>x was 0 so x= + 4 # x is positive 4 #=>16 #=>18446744073709551616 # Raise to the power #=>1 A frequent question from C and C++ types is "How do you increment a variable? Where are ++ and -.'St. but not for Integer types Multiple assignments Examples: var1. one should use x+=1 and x-=1 to increment or decrement a variable. but since strings. "Michel". "Adolf"] school #=>"St.school=myArray. times do |x| puts x=x*var end #=>0. a global scope.2.4. 4. whereas when trying the puts x(toplevel) we're calling a x variable that is in the top level scope. Example: var=2 4. which effectively makes it a global-like $variable class Test def initialize(arg1='kiwi') @instvar=arg1 @@classvar=@instvar+' told you so!!' localvar=@instvar end def print_instvar puts @instvar end def print_localvar puts @@classvar puts localvar end end . Ruby protests.4.times do |$global| $global=$global*var end assignment of $global is 6 puts $global #=>0.. The $ is ugly and the reason behind this is simply to make you not to use or use sparingly these global variables. 69 Scope Basically in Ruby there's a local scope. 4.2. and since there's not one.6 last This works because prefixing a variable with a dollar sign makes the variable a global.Ruby Programming/Syntax/Operators with "default".6 last @instance_variable. and a class scope.2.4.end block the x(local) is a local variable to the block. instance of what? Of top level.6 puts x #=>undefined local variable or method `x' for main:Object (NameError) This error appears because this x(toplevel) is not the x(local) inside the do.times do |@instvar| @instvar=@instvar*var end assignment of @instvar is 6 puts @instvar #=>0. it exists in method initialize(until GC kicks it out).print_classvar #=>kiwi told you so!! Class variables have the scope of parent class AND children.new #newvar is created and it has @@classvar with the same value as the var instance of Test!! newvar. Why? well.Ruby Programming/Syntax/Operators var=Test. across the children classes. these variables can live across classes.-) class SubSubTest < Test def print_classvar puts @@classvar end def modify_classvar @@classvar='kiwi kiwi waaai!!' end end subtest=SubSubTest. in the scope of the method print_localvar there doesn't exists localvar. in the case of @@class variables.class variables '@@classvar' and '@instvar' are in scope across the entire class and. It is the same as "&&" but with a lower precedence.print_localvar #=>undefined local variable or method `localvar' for #<Test:0x2b36208 @ (NameError). one of my argument is false" if a and c . class SubTest < Test def print_classvar puts @@classvar end end newvar=SubTest. it works because a @instance_var can be accesed inside the class var. then FAIL! with a undefined local variable or method `localvar' for #<Test:0x2b36208 @ (NameError).new subtest. Example: a = 1 b = 2 c = nil puts "yay all my arguments are true" if a and b puts "oh no. This will print "kiwi told you so!!".new var. On the other hand .print_classvar This new child of Test also has @@clasvar with the original value newvar.modify_classvar #lets add a method that modifies the contents of @@classvar in SubSubTest subtest. and can be affected by the children actions .print_classvar.print_instvar #=>"kiwi". 70 Logical And The binary "and" operator will return the logical conjunction of its two operands. The value of @@classvar has been changed to 'kiwi kiwi waaai!!' This shows that @@classvar is "shared" across parent and child classes. conditional branches are expressions. In Ruby. For instance. just like other expressions do. but they do not result in values themselves. A conditional Branch takes the result of a test expression and executes a block of code depending whether the test expression is true or false. They can affect which code is executed. the following if expression evaluates to 3: if true 3 end Ruby's conditional branches are explained below. but also results in a value itself. for example. An if expression. whereas many other programming languages consider it false. Note that the number zero is considered true. otherwise. If the test expression evaluates to the constant false or nil. In many popular programming languages. It is the same as "||" but with a lower precedence. it is This is equal to: . not only determines whether a subordinate block of code will execute. however. They evaluate to values. Ruby Programming/Syntax/Control Structures Control Structures Conditional Branches Ruby can control the execution of code using Conditional branches. Example: a = nil b = "foo" c = a || b # c is set to "foo" its the same as saying c = (a || b) c = a or b # c is set to nil its the same as saying (c = a) || b which is not what you want. the test is false. conditional branches are statements.Ruby Programming/Syntax/Operators 71 Logical Or The binary "or" operator will return the logical disjunction of its two operands. code block. the code-block it contains will only be executed if the test expression is false.Ruby Programming/Syntax/Control Structures a = 5 a = 7 if a == 4 print a # prints 5 since the if-block isn't executed unless expression The unless-expression is the opposite of the if-expression... if-elsif-else expression The elsif (note that it's elsif and not elseif) and else blocks give you further control of your scripts by providing the option to accommodate additional tests.code block.. elsif another expression .. else . And there is no elsunless..... You can have any number of elsif blocks but only one if and one else block.code block.. Examples: a = 5 unless a == 4 a = 7 end print a # prints 7 since the if-block is executed The unless expression is almost exactly like a negated if expression: if !expression # is equal to using unless expression The difference is that the unless does not permit a following elsif... elsif another expression .code block.. Syntax: if expression ... The elsif and else blocks are considered only if the if test is false. Like the if-expression you can also write: a = 5 a = 7 unless a == 4 print a # prints 7 since the if-block is executed The "one-liners" are handy when the code executed in the block is one line only.. end 72 .. 10 then puts "#{a} greater than 5" else puts "unexpected value #{a} " #just in case "a" is bigger than 10 or negative end . Case in Ruby supports a number of syntaxes.to_s : (a-1).. suppose we want to determine the relationship of a number (given by the variable a) to 5. such as string formatting.. irb(main):037:0> true ? 't' : 'f' => "t" irb(main):038:0> false ? 't' : 'f' => "f" case expression An alternative to the if-elsif-else expression (above) is the case expression. This is very useful when doing string concatenation among other things. It is suggested to only use this syntax for minor tasks. the comparison operator is ==. We could say: a = 1 case when a < 5 then puts "#{a} less than 5" when a == 5 then puts "#{a} equals 5" when a > 5 then puts "#{a} greater than 5" end Note that.to_s) + ". as with if. Example: a = 5 plus_or_minus = '+' print "The number #{a}#{plus_or_minus}1 is: " + (plus_or_minus == '+' ? (a+1). Another equivalent syntax for case is to use ":" instead of "then": when a < 5 then puts "#{a} less than 5" when a < 5 : puts "#{a} less than 5" A more concise syntax for case is to imply the comparision: case a when 0. we want the comparison operator." This [? (expr) : (expr)] is also known as the ternary operator. The assignment operator is =. Although Ruby will accept the assignment operator: when a = 5 then puts "#{a} equals 5" the value of a! # WARNING! This code CHANGES 73 This is not want we want! Here. because of poor code readability that may result. For example.4 then puts "#{a} less than 5" when 5 then puts "#{a} equals 5" when 5.Ruby Programming/Syntax/Control Structures short-if expression The "short-if" statement provides you with a space-saving way of evaluating an expression and returning a value. For example: a = "apple" puts case a when "vanilla" then "a spice" when "spinach" then "a vegetable" when "apple" then "a fruit" else "an unexpected value" end If entered in the irb this gives: a fruit =>nil Other ways to use case and variations on its syntax maybe seen at Linuxtopia Ruby Programming [1] 74 Loops while The while statement in Ruby is very similar to if and to other languages' while (syntactically): while <expression> <..> end The code block will be executed again and again. Also.> while <expression> Note the following strange case works. until <expression> <.code. like if and unless.Ruby Programming/Syntax/Control Structures Note: because the ranges are explicitly stated.....code block. on seeing it for the first time it has the value nil when the loop expression is first evaluated.... until The until statement is similar to the while statement in functionality.> end . it is good coding practise to handle unexpected values of a. Unlike the while statement. This concise syntax is perhaps most useful when we know in advance what the values to expect.readline while line != "what I'm looking for" So if local variable line has no existence prior to this line. the code block for the until loop will execute as long as the expression evaluates to false... line = inf.code block... as long as the expression evaluates to true... the following is possible: <. A method may be defined as a part of a class or separately. linuxtopia. not using parentheses # calling # You need to use parentheses if you want to work with the result immediately. if a method returns an array and we want to reverse element order: results = method_name(parameter1.reverse Method Definitions Methods are defined using the keyword def followed by the method name. parameter2).. Example: def output_something(value) puts value end . parameter2. org/ online_books/ programming_books/ ruby_tutorial/ Ruby_Expressions_Case_Expressions. Method Calls Methods are called using the following syntax: method_name(parameter1. Other languages sometimes refer to this as a function. Method parameters are specified between parentheses following the method name.Ruby Programming/Syntax/Control Structures 75 Keywords return return value causes the method in which it appears to exit at that point and return the value specified References [1] http:/ /. html Ruby Programming/Syntax/Method Calls A method in Ruby is a set of expressions that returns a value. By convention method names that consist of multiple words have each word separated by an underscore. # e.…) If the method has no parameters the parentheses can usually be omitted as in the following: method_name If you don't have code that needs to use method result immediately. The method body is enclosed by this definition on the top and the word end on the bottom. parameter2 method. Ruby allows to specify parameters omitting parentheses: results = method_name parameter1. *otherValues) puts otherValues end calculate_value(1.'c') In the example above the output would be ['a'. def calculate_value(x.'b'.y. you actually will jump out from the function. Note.'a'..'c'] calculate_value(*arr) has the same result as: . Asterisk Operator The last parameter of a method may be preceded by an asterisk(*). probably not what you want. Those parameters are collected up and an array is created. arr=[]) puts value puts arr.Ruby Programming/Syntax/Method Calls 76 Return Values Methods return the value of the last statement executed.length end some_method('something') The method call above will output: something 0 Variable Length Argument List. You can pass a value to break which will be returned as the result of the block: six = (1. def some_method(value='default'. 'c']. prior to the end of the function declaration. if you use "return" within a block. The following code returns the value x+y.each {|i| break i if i > 5} In this case.y) x + y end An explicit return statement can also be used to return from function with a value.2. def calculate_value(x. To terminate block. Default Values A default parameter value can be specified during method definition to replace the value of a parameter if it is not passed into the method or the parameter's value is nil. This is useful when you want to terminate a loop or return from a function as the result of a conditional expression.'b'. The asterisk operator may also precede an Array argument in a method call. use break. six will have the value 6. which is sometimes called the 'splat' operator. arr = ['a'. 'b'. This indicates that more parameters may be passed to the function.10). In this case the Array will be expanded and the values passed in as if they were separated by commas. if you are going to pass a code block to function. but essentially the same as above 77 The Ampersand Operator Much like the asterisk. and that gives you best of all worlds: named parameters. def method_call yield end method_call(&someBlock) . Yield may then be used. :argN => 'giving argN' ) { |s| puts s } accepts_hash( { :arg1 => 'giving arg1'. :argN => 'giving argN' # => got: {:argN=>"giving argN". The above code is equivalent to the more verbose: accepts_hash( :arg1 => 'giving arg1'. A Proc object will be created and assigned to the parameter containing the block passed in. and variable argument length. def accepts_hash( var ) print "got: ". This indicates that the function expects a code block to be passed in. you need parentheses.'b'. a Proc object preceded by an ampersand during a method call will be replaced by the block that it contains. Also similar to the ampersand operator.' code. hash explicitly created. the arguments for accepts_hash got rolled up into one hash variable. :arg1=>"giving arg1"} You see. the ampersand(&) may precede the last parameter of a function declaration. :argN => 'giving argN' } ) # hash is explicitly created Now. :argN => 'giving argN' ) # argument list enclosed in parens accepts_hash( { :arg1 => 'giving arg1'.. Also note the missing parenthesis around the arguments for the accepts_hash function call. accepts_hash( :arg1 => 'giving arg1'..Ruby Programming/Syntax/Method Calls calculate_value('a'. either. var.'c') Another technique that Ruby allows is to give a Hash when invoking a function.inspect # will print out what it received end accepts_hash :arg1 => 'giving arg1'. :argN => 'giving argN' } ) { |s| puts s } # second line is more verbose. and notice that there is no { } Hash declaration syntax around the :arg1 => '. This technique is heavily used in the Ruby On Rails API. call(12) times5.call(4)) # 'factor' is replaced with 3 #=> 36 #=> 25 #=> 60 Procs play the role of functions in Ruby. since like everything in Ruby they are objects. It is more accurate to call them function objects. Sifting through hundreds of newsgroup posts. I saw that I’m not the only one with this problem. A functor is defined as an object to be invoked or called as if it were an ordinary function. In this article I lay out my understanding of this facet of Ruby. Note how closely it maps to the Ruby definition blocks of code that have been bound to a set of local variables. which is exactly what a Proc is. high-order functions and first-class functions [1]. Procs and methods Introduction Ruby provides the programmer with a set of very powerful features borrowed from the domain of functional programming. These features are implemented in Ruby by means of code blocks.functors. A useful example is also provided: def gen_times(factor) return Proc. Shivang's PROC Shamelessly ripping from the Ruby documentation. the code may be called in different contexts and still access those variables. Once bound. in sincere hope that other people will find it useful as well. I was unsure of how the Ruby concepts map to similar idioms from other programming languages. which comes as a result of extensive research of Ruby books. documentation and comp.ruby. Procs are defined as follows: Proc objects are blocks of code that have been bound to a set of local variables. .lang. On Wikipedia.concepts that are closely related and yet differ in subtle ways.Ruby Programming/Syntax/Method Calls 78 Understanding blocks. usually with the same syntax. In fact I found myself quite confused about this topic.call(5) times3.call(times5. procs and methods and unsure about the best practices of using them. and in fact quite a lot of “Ruby Nubies” struggle with the same ideas. namely closures. Additionally. having some background in Lisp and years of Perl experience. a closure is defined as a function that refers to free variables in its lexical context. having a difficulty to understand the difference between blocks. like Lisp’s functions and Perl’s subroutines.new {|n| n*factor } end times3 = gen_times(3) times5 = gen_times(5) times3. Proc objects and methods (that are also objects) . From the example and the definition above. it is obvious that Ruby Procs can also act as closures. Such objects have a name in the folklore . A return from Proc. y| puts x + y} # works fine. since they can be created during runtime. but for now assume that a Kernel method is something akin to a global function. Using lambda the Proc object creation from the previous example can be rewritten as: putser = lambda {|x| puts x} Actually. returning to its caller: def try_ret_lambda ret = lambda { return "Baaam" } ret.new {|x. 11) Second.call "This is printed" end 79 . 4.new {|x| puts x} foo(putser.Ruby Programming/Syntax/Method Calls More on Procs Procs in Ruby are first-class objects.call(b) end putser = Proc. This one can be presented as follows: def foo (a.new { return "Baaam" } ret. printing 6 pnew. the gen_times example demonstrates all of these criteria. Here is an example to demonstrate this: lamb = lambda {|x. passed as arguments to other functions and returned as the value of other functions. more on this later): def try_ret_procnew ret = Proc. The Ruby documentation for lambda states: Equivalent to Proc. 11) # throws an ArgumentError lamb. Actually.new. First. argument checking. except for “passed as arguments to other functions”.call(2. 4.new.the Kernel method lambda [2] (we’ll come to methods shortly. which can be called from anywhere in the code). 34) There is also a shorthand notation for creating Procs .call(2.call "This is not reached" end # prints "Baaam" puts try_ret_procnew While return from lambda acts more conventionally. except the resulting Proc objects check the number of parameters passed when called.new returns from the enclosing method (acting just like a return from a block. b) a.. there are two slight differences between lambda and Proc. there is a difference in the way returns are handled from the Proc. stored in data structures. y| puts x + y} pnew = Proc. Rather.by calling the method. without arguments. For example: def say (something) puts something end say "Hello" 80 . Given a receiver . unless the behavior of the latter is strictly required. not inside any class. they are bound to some object and have access to its instance variables [3]: class Boogy def initialize @dix = 15 end def arbo puts "#{@dix} ha\n" end end # initializes an instance of Boogy b = Boogy. not 3 Methods Simply put. In the example above.send("arbo") # method/message name is given as a symbol b.new.call(4) puts x # x is now 4. Ruby supports the message sending idiom more directly. Ruby's lambda is unusual in that choice of parameter names does affect behavior: x = 3 lambda{|x| "x still refers to the outer variable"}. by including the send method in class Object (which is the parent of all objects in Ruby). methods are not bound to the local variables around them. I would recommend using lambda instead of Proc. However. In addition to being way cooler a whopping two characters shorter.Ruby Programming/Syntax/Method Calls # prints "This is printed" puts try_ret_lambda With this in light. calling arbo is akin to sending a message “arbo”. unlike Procs.send(:arbo) Note that methods can also be defined in the “top-level” scope.an object that has some method defined. So the following two lines are equivalent to the arbo method call: # method/message name is given as a string b. optionally providing some arguments. we can send it a message .new # prints "15 ha" b. its behavior is less surprising. a method is also a block of code.arbo A useful idiom when thinking about methods is sending messages. Ruby silently tucks them into the Object class. is that what all the fuss is about.times do |i| print "#{i} " end numbers = [1. Matz decided that it is worthwhile to emphasize this special case. for example iteration. 9. as I see them. 5.it prepares the code for when it will actually become alive. But this doesn’t really matter. 21] numbers.passing a single block of code to a method that makes something useful out of it. not at all. and make it both simpler and more efficient.call("Hello") # same effect say["Hello"] The [] construct is a synonym to call in the context of Proc [4]. just what’s called a “function” in some languages (like C and Perl). Passing a block to a method No doubt that any programmer who has spent at least a couple of hours with Ruby has been shown the following examples of Ruby glory (or something very similar): 10. When methods such as this are defined. in many ways similar: say = lambda {|something| puts something} say. Methods. there is one common case that stands high above all other cases . And as a very talented designer. however. I will try to ease on comprehension with a (hopefully not too corny) metaphor. 6. it is not. are more versatile than procs and support a very important feature of Ruby. and only when it is bound and converted to a Proc. Blocks Blocks are so powerfully related to Procs that it gives many newbies a headache trying to decipher how they actually differ. having been converted # to a Proc ! pr = lambda {puts "hello"} pr. The following Proc is. are unborn Procs. Blocks are the larval.call Is that it. which I will present right after explaining what blocks are.each do |x| puts "#{x} is " + (x >= 3 ? "many" : "few") end 81 . A block does not live on its own . Blocks. then ? No. by the way.Ruby Programming/Syntax/Method Calls While it seems that say is “free-standing”. and for all practical purposes say can be seen as an independent method. it starts living: # a naked block can't live in Ruby # this is a compilation error ! {puts "hello"} # now it's alive. The designer of Ruby. Procs are the insects. Which is. 2. Matz saw that while passing Procs to methods (and other Procs) is nice and allows high-level functions and all kinds of fancy functional stuff. or at least may be depicted in a very simple way. } ) Such code is IMHO part of what makes Ruby the clean. See the following example for clarification: def do_twice yield yield end do_twice {puts "Hola"} The method do_twice is defined and called with an attached block.call end end do_twice( lambda {print "Hola.call end do_twice lambda {puts "Hola"} This is equivalent to the previous example. however. what2. . what3) 2. While it’s simply a matter of taste. has a way to access this Proc. and prefer explicit Procs instead.but it is definitely close enough to the truth to serve as a metaphor for understanding.call what. and one has to look through the whole code of the method to see if there are any calls to yield there.times do what1. lambda {print "querido "}. readable and wonderful language it is. and better optimized since only one block is passed to the method.. What happens here behind the scenes is quite simple. but one without an explicit name.. lambda {print "amigo\n"}) 82 It is important to note that many people frown at passing blocks. Perhaps Ruby doesn’t implement it exactly the way I’m going to describe it. The method.map {|x| x * x} (Note that do |x| . since there are optimization considerations surely playing their role .. Using the Proc approach. Their rationale is that a block argument is implicit. end is equivalent to { |x| . Ruby automatically converts it to a Proc object.call what3.. by means of the yield statement. using a Proc argument: def do_twice(what) what. while a Proc is explicit and can be immediately spotted in the argument list. any amount of code blocks can be passed: def do_twice(what1.call what2.Ruby Programming/Syntax/Method Calls squares = numbers. This can be implemented in a more explicit way. for sure. Although the method didn’t explicitly ask for the block in its arguments list. Whenever a block is appended to a method call. "}. understanding both approaches is vital. but using blocks with yield is cleaner. the yield can call the block. the block attached to this method is converted to a Proc object and gets assigned to that last argument: def contrived(a. The following example is taken right from the excellent “Programming Ruby” book by the pragmatic programmers: print "(t)imes or (p)lus: " times = gets print "number: " number = Integer(gets) if times =~ /^t/ calc = lambda {|n| n*number } else calc = lambda {|n| n+number } end puts((1. I could do it like this: words = %w(Jane.join(". ")) The collect method expects a block. because &f # isn't really an argument . It is worthy to understand how these work.. expect to receive a block as an argument. multiko) upcase_words = words. &f) # the block can be accessed through f f.converting a Proc into a block. Remember how I said that although an attached block is converted to a Proc under the hood. but in this case it is very convenient to provide it with a Proc.map {|x| x. and especially the iterators.it's only there # to convert a block contrived(25.call(a) # but yield also works ! yield(a) end # this works contrived(25) {|x| puts x} # this raises ArgumentError. and sometimes it’s much more convenient to pass them a Proc. The ampersand also allows the implementation of a very common idiom among Ruby programmers: passing method names into iterators.Ruby Programming/Syntax/Method Calls The ampersand (&) The ampersand operator can be used to explicitly convert between blocks and Procs in a couple of cases. lambda {|x| puts x}) Another (IMHO far more efficacious) use of the ampersand is the other-way conversion . since the Proc is constructed using knowledge gained from the user. it is not accessible as a Proc from inside the method ? Well. Assume that I want to convert all words in an Array to upper case. aara. The ampersand preceding calc makes sure that the Proc object calc is turned into a code block and is passed to collect as an attached block. This is very useful because many of Ruby’s great built-ins.10). if an ampersand is prepended to the last argument in the argument list of a method.upcase} p upcase_words 83 .collect(&calc). as we saw before.upcase} in an elegant manner. Ruby’s implicit type conversion rules kick in. quite literally.sub("Chameleon".sub('to_'. # def to_proc lambda {|x.. without the need for a separate block and the apparently superfluous x argument. multiko) upcase_words = words. The upcase method itself should be given to map. which are implemented as Ruby Symbols.''). But what if we prepend it not to a Proc. For example: p "Erik". Fortunately.to_s. it converts the Proc to a block. *arg) if (method. aara.2] == "to_" @identity = __inspect__. method.map(&:upcase) 84 Special methods Ruby has a number of special methods that are called by the interpreter.) end end . We can use this to implement to_proc for Symbol and achieve what we want: class Symbol # A generalized conversion of a method name # to a proc that runs this method. *args| x.method_missing #pass on anything we weren't looking for so the Chameleon stays unnoticed and uneaten . and methods can be referred to by their names. *args)} end end # Voila ! words = %w(Jane. and it works. but I feel it’s a little bit too verbose.Ruby Programming/Syntax/Method Calls This is nice.send(:upcase) This. For example: class Chameleon alias __inspect__ inspect def method_missing(method.to_s)[0. and the to_proc method is called on the object to try and make a Proc out of it.send(self. when the ampersand is prepended to some Proc in a method call. but to another object ? Then. This feature can be utilized to implement the map {|x| x.capitalize) def inspect @identity end self else super #method_missing overrides the default Kernel. says send the message/method upcase to the object “Erik”. Ruby supports the idiom of sending messages to objects. and we’re going to use the ampersand for this ! As I said. Ruby Programming/Syntax/Method Calls end mrlizard = Chameleon.new mrlizard.to_rock This does something silly but method_missing is a important part of meta-programming in Ruby. In Ruby on Rails it is used extensively to create methods dynamically. Another special methods is initialize that ruby calls whenever a class instance is created, but that belongs in the next chapter: Classes. 85 ! Ruby Programming/Syntax/Classes 86 Ruby Programming, such as attr_accessor. The class declaration is terminated by the end keyword. Example: class MyClass def some_method end end Instance Variables Instance variables are created for each class instance and are accessible only within that instance or through the methods provided by that instance. They are accessed using the @ operator.. Ruby Programming/Syntax/Classes 87 Class Variables Class variables are accessed using the @@ operator. These variables are associated with the class rather than any object instance of the class and are the same across all object instances. (These are the same accessible by anyone. all methods in Ruby classes are public . They cannot access instance variables but do have access to class variables. It is interesting that these are not actually keywords. Example: anObject = MyClass. These methods are executed at the Class level and may be called without an object instance. As a result of that fact these 'keywords' influence the visibility of all following declarations until a new visibility is set or the end of the declaration-body is reached. see MF Bliki: ClassInstanceVariables [1] Class Methods Class methods are declared the same way as normal methods.instances. In Ruby this takes place through the Class method new. If desired. Parameters passed to the new function are passed into the initialize function. dynamically altering the visibility of the methods.size # => 1 88 For more details. this access can be restricted by public. followed by a period.new(parameters) This function sets up the object in memory and then delegates control to the initialize function of the class if it is present. .Ruby Programming/Syntax/Classes puts Programmer. protected object methods. or the class name. Example: class MyClass def self. except that they are prefixed by self.some_method Outputs: something Instantiation An object instance is created from a class through the a process called instantiation. but actual methods that operate on the class. private. class MyClass def initialize(parameters) end end Declaring Visibility By default.some_method puts 'something' end end MyClass. class SingletonLike private_class_method :new def SingletonLike. &block) @@inst ||= new(*args. A typical Singleton implementation is an obvious example.method_name).create(*args. &block) @@inst = new(*args.Ruby Programming/Syntax/Classes 89 Private Simple example: class Example def methodA end private # all methods that follow will be made private: not accessible for outside objects def methodP end end If private is invoked without arguments. &block) . altering the visibility of methodP to private. you need to use another function: private_class_method Common usage of private_class_method is to make the "new" method (constructor) inaccessible.create(*args. it sets access to private for all subsequent methods. &block) unless @@inst return @@inst end end Note : another popular way to code the same declaration class SingletonLike private_class_method :new def SingletonLike. It can also be invoked with named arguments. Named private method example: class Example def methodA end def methodP end private :methodP end Here private was invoked with an argument. to force access to an object through some getter function. Note for class methods (those that are declared using def ClassName. and if method is "protected". Private methods in Ruby are accessible from children. For private methods. This is a sensible design. you can call private methods only for instance of "a1" (self). 90 Public Public is default accessibility level for class methods. and not for any other object instance (of class A). even if that receiver is "self" other_object. And you can not call private methods of object "a2" (that also is of class A) . in C++ from code in class A. they are accessible from objects of the same class (or children). Those of you coming from Java (or C++) background. you can't completely hide a method. if method is private. However. private visibility is what protected was in Java. But you can call . What they are saying.a # nope! private methods cannot be called with an explicit receiver at all.they are private to a2. In Ruby. you can access any private method for any other object of type A.name/blog/?p=5 One person summed up the distinctions by saying that in C++. it rendered it useless for children classes: making it a rule. and never private. However. and later . In Ruby. it may be called by any instance of the defining class or its subclasses. it does not work. visibility is completely dynamic. “private” means “private to this class”. protected deserves more discussion. in your code you can say: class AccessPrivate def a end private :a # a is private method def accessing_private a # sure! self. What this means. while in Ruby it means “private to this instance”. If a method is private. it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly. it will be accessible for children of the class (classes that inherit from parent). You can change method visibility at runtime! Protected Now. since in Java. you can not: you can only access private methods for your instance of object. "other_object" is the "receiver" that method "a" is invoked on.public. you know that "private" means that method visibility is restricted to the declaring class. that all methods should be "protected" by default. even if the object is of the same class as the caller.a # nope. from within an object "a1" (an instance of Class A). you can't get it (but if it was protected. In Ruby. If a method is protected. maybe so that you could dynamically make some method private at some point. For protected methods. I am not sure why this is specified . when method was private. you could!) end end Here. So. a is private. The difference between protected and private is subtle. that is what "protected" visibility will allow. Ruby folks keep saying "private means you cannot specify the receiver".Ruby Programming/Syntax/Classes end end More info about the difference between C++ and Ruby private/protected:. you can't have truly private methods in Ruby.maybe for completeness. If "age" is protected.age end If age is private. attr_writer. attr_accessor will give you get/set functionality. attr_reader.age <=> other. protected actually reminds me of the "internal" accessibility modifier in C# or "default" accessibility in Java (when no accessibility keword is set on method or variable): method is accessible just as "public". because self and other are of same class. because other.size = y Luckily. you just can't see them. Ruby FAQ [2] gives following example .size a. but only for classes inside the same package. you need to create a getter and setter. this method will not work.Ruby Programming/Syntax/Classes protected methods of object "a2" since objects a1 and a2 are both of class A. we have special functions to do just that: attr_accessor. To access an instance variable. reader will give only getter and writer will give only setter.implementing an operator that compares one internal variable with variable from another class (for purposes of comparing the objects): def <=>(other) self. don't do this by hand! See below): class GotAccessor def initialize(size) @size = size end def size @size end def size=(val) @size = val end end # # # # you could the access @size variable as a = GotAccessor. and can access each other's protected methods. this will work fine.age is not accessible. To think of this. Now reduced to: class GotAccessor def initialize(size) @size = size end attr_accessor :size end . Like this (no.new(5) x = a. 91 Instance Variables Note that object instance variables are not really private. size = y 92 Inheritance A class can inherit functionality and variables from a superclass.new(5) # x = a. The syntax is as follows: class ParentClass def a_method puts 'b' end end class SomeClass < ParentClass def another_method puts 'a' end end instance = SomeClass.new instance. you still can access the parent's method by using 'super' keyword.size # a. sometimes referred to as a parent class or base class. class ParentClass def a_method puts 'b' end end class SomeClass < ParentClass def a_method super puts 'a' end end # < means inherit (or "extends" if you are from Java bac .a_method Outputs: a b All non-private variables and functions are inherited by the child class from the superclass.another_method instance. Ruby does not support multiple inheritance and so a class in Ruby can have only one superclass.Ruby Programming/Syntax/Classes # attr_accessor generates variable @size accessor methods automatically: # a = GotAccessor. If your class overrides a method from parent class (superclass). new instance.Ruby Programming/Syntax/Classes 93 instance = SomeClass. somewhat like classes. you need to read up on modules. so to speak. Modules are way of grouping together some functions and variables and classes. and still want to access some parent class (superclass) methods directly.new. allows us to include the module into a class.a_method Outputs: b a (because a_method also did invoke the method from parent class). If you have a deep inheritance line.new.foo puts Y. So a module is not really a class. But there is a workaround! When inheriting from a class. you can alias parent class method to a different name. Mix it in.foo Outputs hello helloy Mixing in Modules First. You can't instantiate a Module. you can't. This trait. module A def a1 puts 'a1 is called' end end module B def b1 puts 'b1 is called' . but more like namespaces. super only gets you a direct parent's method. and thus it does not have self. however. class X def foo "hello" end end class Y < X alias xFoo foo def foo xFoo + "y" end end puts X. Then you can access methods by alias. com/ faq/ rubyfaq-7. Class methods are implemented on meta-classes that are linked to the existing class instance objects in the same way that those classes instances are linked to them.Ruby Programming/Syntax/Classes end end module C def c1 puts 'c1 is called' end end class Test include A include B include C def display puts 'Modules are included' end end object=Test. com/ bliki/ ClassInstanceVariable. rubycentral. classes are themselves instances of the class Class. These meta-classes are hidden from most Ruby functions.c1 OUTPUT : Modules ar included a1 is called b1 is called c1 is called Notice the code.b1 object. They are stored in constants under the scope of the module in which they are declared. html . References [1] http:/ / martinfowler.It shows Multiple Inheritance using modules 94 Ruby Class Meta-Model In keeping with the Ruby principle that everything is an object.a1 object. The method implementation exists on the Class instance object itself. html [2] http:/ / www. A call to a method on an object instance is delegated to a variable inside the object that contains a reference to the class of that object.new object.display object. Ruby Programming/Reference 95 Ruby Programming/Reference • Reference • Built-in Functions • Predefined Variables • Predefined Classes • Object • • • • • Array Class Exception FalseClass IO • File • File::Stat • Method • Module • Class • NilClass • Numeric • Integer • Bignum • Fixnum • Float Range Regexp String Struct • • • • • Struct::Tms • Symbol • Time • TrueClass • Standard Library . $. gets. $? • The exit status of the last process terminated.lineno. The stack backtrace information can retrieved by Exception#backtrace method of the last exception. • The output separator between the arguments to print and Array#join (nil by default). etc. $$ • The process. $.. • The default separator for split (nil by default). $! • The last exception object raised. so their use in libraries isn't recommended. take their input record separator as optional argument. $DEBUG • True if the -d or --debug command-line option is specified. $defout • The destination output for print and printf ($stdout by default). readline. $0 • The name of the current Ruby program being executed. The exception object can also be accessed using => in rescue clause. $> • Synonym for $defout. $: • Synonym for $LOAD_PATH. $. Equivalent to ARGF. You can specify separator explicitly for String#split. $\ • The output record separator (nil by default). • The number of the last line read from the current input file.pid of the current Ruby program being executed. The values in most predefined variables can be accessed by alternative means.Ruby Programming/Reference/Predefined Variables 96 Ruby Programming/Reference/Predefined Variables Ruby's predefined (built-in) variables affect the behavior of the entire program. $@ • The stack backtrace for the last exception raised. $/ • The input record separator (newline by default). You can specify separator explicitly to Array#join. $F . $< • Synonym for ARGF. $LOAD_PATH • An array holding the directories to be searched when loading files with the load and require methods. All newly created objects are considered tainted. $stderr • Standard error (STDERR by default). where m is a MatchData object... 97 . Regex#match method returns the last match information.x • The value of interpreter option -x (x=0.) • The string matched in the nth group of the last pattern match. The following are local variables: $_ • The last string read by gets or readline in the current scope. $3. Equivalent to m[0]. $2. l. a. 3 4 $stdin • Standard input (STDIN by default). $FILENAME • The name of the file currently being read from ARGF. $stdout • Standard output (STDOUT by default). 0 No checks are performed on externally supplied (tainted) data. Equivalent to m[n]. or --verbose command-line option is specified. v). p. Modification of global data is forbidden. i. The following variables hold values that change in accordance with the current value of $~ and can't receive assignment: $ n ($1. $. $SAFE • The security level. K.filename. (default) 1 Potentially dangerous operations using tainted data are forbidden. This variable is set if the -a command-line option is specified along with the -p or -n option. F.Ruby Programming/Reference/Predefined Variables • The variable that receives the output from split when -a is specified. d. $~ • MatchData relating to the last match. $VERBOSE • True if the -v. Equivalent to ARGF. where m is a MatchData object. $& • The string matched in the last pattern match. 2 Potentially dangerous operations on processes and files are forbidden. -w. and an instance of Fixnum.Ruby Programming/Reference/Predefined Variables $` • The string preceding the match in the last pattern match. $+ • The string corresponding to the last successfully matched group in the last pattern match.class puts a puts 0 puts 5 puts 10 + 0 b = 5+5 puts b ## ## ## ## ## prints prints prints prints prints Fixnum 10 (adds 5 (adds 10 (adds 15 (adds 5 5 5 5 once) once) once) once) ## puts 15 (adds 5 once) . where m is a MatchData object.[1] In the following example. 5 is an immediate. where m is a MatchData object.post_match. 98 Ruby Programming/Reference/Predefined Classes In ruby even the base types (also predefined classes) can be hacked.pre_match. an object. class Fixnum alias :other_s :to_s def to_s() a = self + 5 return a. $' • The string following the match in the last pattern match. Equivalent to m.[2] a literal.other_s end end a = 5 puts a. Equivalent to m. wikipedia. This class provides a number of useful methods for all of the classes in Ruby. Array.2. 2. org/ wiki/ Ruby_programming%2Freference%2Fpredefined_classes#endnote_immediate Ruby Programming/Reference/Objects Object is the base class of all other classes created in Ruby. Ruby Programming/Reference/Objects/Array Class Methods Method: [ ] Signature: Array[ [anObject]* ] -> anArray Creates a new array whose elements are given between [ and ]. References [1] http:/ / en. 2. 3 ] -> [1.3] [1.3] .Ruby Programming/Reference/Predefined Classes 99 Footnotes 1. 3 ) -> [1. and each function can be explicitly overridden by the user. wikipedia. and can't have simpleton methods. ^ Which means the 4 VALUE bytes are not a reference but the value itself.[]( 1. All 5 have the same object id (which could also be achieved in other ways).2.3] Array[ 1.3] -> [1.2. 2.2. ^ Might not always work as you would like. There are some other minor exceptions. It provides the basic set of functions available to all classes. org/ wiki/ Ruby_programming%2Freference%2Fpredefined_classes#endnote_quirks [2] http:/ / en. the base types don't have a constructor (def initialize). message • Returns the exception message.Ruby Programming/Object/NilClass 100 Ruby Programming/Object/NilClass i0 = 1 loop { i1 = 2 print defined?(i0). "i1" was initialized in this # true. . "\n" block break } print defined?(i0). "i0 was initialized in this # false. exception • Returns a clone of the exception object. This method is used by raise method. "\n" ascendant block print defined?(i1). "\n" loop # true. "\n" block print defined?(i1). "i1" was initialized in the Ruby Programming/Reference/Objects/ Exception Exception is the superclass for exceptions Instance Methods backtrace • Returns the backtrace information (from where exception occurred) as an array of strings. "i0" was initialized in the # true. Logical OR.Exclusive Or (XOR) Ruby Programming/Reference/Objects/IO/File/ File::Stat First create a file.new('/etc').Ruby Programming/Reference/Objects/FalseClass 101 Ruby Programming/Reference/Objects/ FalseClass The only instance of FalseClass is false. Methods: false & other . so it should not be instantiated. Included Modules: Comparable Instance Methods: +n Returns n. -n Returns n negated.Logical AND. and then call the stat method on it. multiplication.num n * num n / num Performs arithmetic operations: addition. and division. n + num n . Example: if File. without short circuit behavior false ^ other . without short circuit behavior false | other . subtraction.stat. Numeric is an abstract class.directory? puts '/etc is a directory' end Ruby Programming/Reference/Objects/ Numeric Numeric provides common behavior of numbers. n % num . Use the methods of stat to obtain information about the file. otherwise nil. n.floor (-1.modulo(4)) ((-13).ceil Returns the smallest integer greater than or equal to n.modulo(-4)) ((-13).floor n. Equivalent to n.remainder( num) Returns the remainder obtained by dividing n by num and removing decimals from the quotient. n. 1.modulo( num) Returns the modulus obtained by dividing n by num and rounding the quotient with floor.2). n ** num Exponentiation.coerce( num) Returns an array containing num and n both possibly converted to a type that allows them to be operated on mutually.integer? Returns true if n is an integer. n.floor (-2.abs Returns the absolute value of n. n.1.remainder(4)) (13. n.divmod(num)[1]. n.floor Returns the largest integer less than or equal to n.2.floor 2. The result and n always have same sign. n. (13.remainder(-4)) ((-13).modulo(4)) (13.nonzero? Returns n if it isn't zero.modulo(-4)) (13. n.1).remainder(4)) #=> 1 #=> -3 #=> 3 #=> -1 #=> 1 #=> 1 #=> -1 #=> #=> #=> #=> 1 2 -2 -3 102 . Used in automatic type conversion in numeric operators.Ruby Programming/Reference/Objects/Numeric Returns the modulus of n.divmod( num) Returns an array containing the quotient and modulus from dividing n by num. 1. and inversion.zero? Returns zero if n is 0.5). 1. Integer is an abstract class. ~i i & int i | int i ^ int i << int i >> int Bitwise left shift and right shift.1).round 2. which is i[0].truncate Returns n as an integer with decimals removed.Ruby Programming/Reference/Objects/Numeric (-13).truncate (-2.truncate (-1. 1. i[n] Returns the value of the nth bit from the least significant bit. XOR.2).round n. #=> #=> #=> #=> 1 2 -1 -2 #=> #=> #=> #=> 1 3 -1 -3 #=> -1 103 Ruby Programming/Reference/Objects/ Numeric/Integer Integer provides common behavior of integers (Fixnum and Bignum).5.round (-1.2.round Returns n rounded to the nearest integer. Instance Methods: Bitwise operations: AND.truncate 2. OR. Inherited Class: Numeric Included Module: Precision Class Methods: Integer::induced_from(numeric) Returns the result of converting numeric into an integer. .truncate n.remainder(-4)) n. so you should not instantiate this class.round (-2.2.2). } Iterates the block from i to upto.step(5..next i.size Returns the number of bytes in the machine representation of i.times {|i| puts i } . -2) {|i| puts i } # prints: # 10 # 8 # 6 i... incrementing by step each time.chr ?a.next i. i.downto( min) {| i| ..} Iterates the block i times. 3. Equivalent to i + 1.succ See i..step( upto. 3. i.chr # => "A" # => "a" # => 1 # => 0 # => 1 104 i. step) {| i| .downto(1) {|i| puts i } # prints: # 3 # 2 # 1 i. 65.Ruby Programming/Reference/Objects/Numeric/Integer 5[0] 5[1] 5[2] i. 10.. decrementing each time from i to min.succ Returns the next integer following i.times {| i| .} Invokes the block.chr Returns a string containing the character for the character code i. } Invokes the block.Ruby Programming/Reference/Objects/Numeric/Integer # prints: # 0 # 1 # 2 i. 1.to_f i. Float conversion may lose precision information. incrementing each time from i to max..upto(3) {|i| puts i } # prints: # 1 # 2 # 3 # => 1.to_f Converts i into a floating point number.to_int Returns i itself. i. Every object that has to_int method is treated as if it's an integer.upto( max) {| i| .234567891e+15 105 . 1234567891234567.. • new : Regexp..escape( aString ) -> aNewString Escapes any characters that have special meaning in a regular expression. For example: Regexp.compile( pattern [. used to match a pattern of strings.') » \\\\\*\?\{\}\.Ruby Programming/Reference/Objects/Regexp 106 Ruby Programming/Reference/Objects/Regexp Class Regexp holds a regular expression.new( pattern [. • last_match : Regexp. IGNORECASE : Matches are case insensitive. MULTILINE : Newlines treated as any other character.escape('\\*?{}. Regular expressions can be created using /. options [ lang ] ] ) -> aRegexp This method is a synonym for method "new". For example : Regexp. 2. options [ lang ] ] ) -> aRegexp Constructs a regular expression from the pattern. CONSTANTS 1. CLASS METHODS • compile : Regexp. Equivalent to reading the global variable $~. The pattern can be either a string or a "regexp". EXTENDED : Ignore spaces and newlines in regexp.new("xyz") » /xyz/ • quote : Regexp. • escape : Regexp.last_match -> aMatchData Returns the MatchData object generated by the last successful pattern match. 3./ or by using the constructor "new". .quote( aString ) -> aNewString A synonym for escape method. Returns the value of case-insensitive flag.match(aString) -> aMatchData or nil Returns a MatchData object or nil if match is not found. • match : rxp. • ~ : ~ rxp -> anInteger or nil Match---Matches rxp against the contents of $_.Ruby Programming/Reference/Objects/Regexp 107 INSTANCE METHODS • == : rxp == aRegexp -> true or false Two regular expressions are equal if their patterns match and they have same character set code and theie casefold? values are same. For example: $_ = "input data" ~ /at/ » 7 • casefold? : rxp. • source : rxp.source -> aString Returns the original string of the pattern. • kcode : rxp.kcode -> aString Returns character set code for the regexp. • === : rxp === aString -> true or false Synonym for Regexp#=~ used in case statements • =~ : rxp === aString -> true or false Matches a regular expression with string and returns the offset of the start of match or nil if a match fails.source >> xyz . Equivalent to rxp =~ $_.casefold? Returns true or false. For example : /xyz/. Returns an encoded string using crypt(3). that is to say the purpose is nebulous: there is nothing special about Tuesdays to a computer. place) @time = time @place = place end end feb12 = Tuesdays. If you have to use comments to differentiate Tuesdays from Wednesdays you typically fail. DES is used.though for learning purposes it works out. Ruby Programming/Reference/Objects/Symbol Symbols A Ruby symbol is the internal representation of a name. A particular name will always generate the same symbol.") As for the object. based on the first two characters of salt.Ruby Programming/Reference/Objects/String 108 Ruby Programming/Reference/Objects/String String Class Methods: crypt(salt). Ruby Programming/Reference/Objects/Time class Tuesdays attr_accessor :time. simply not so. You construct the symbol for a name by preceding the name with a colon. Firstly. you created a class called Tuesdays without specifying what would make it different from a class called Wednesday. based on up to eight characters following "$1$".new("8:00". MD5 encryption is used.to_s when "Array" . Lastly. it is clever let me give you some advice though. Otherwise. as in your example.new ) @place = place case time. "Rice U. -. If salt starts with "$1$". time=Time. This is always a mistake. In real life.class. class Event def initialize( place. and call symbols ``atoms. :place def initialize(time. you don't ever want to store a date or time as a string. salt is a string with minimal length 2. regardless of how that name is used within the program. :Object :myVariable Other languages call this process ``interning. gm( *time ) when "Time" @time = time else throw "invalid time type" end end attr_accessor :time.time puts "We're there" else puts "Not yet" end ## Because the constructor takes two forms of time. Time.0.17. (see time=Time. ## You can compaire Event#time to any Time object!! if Time."CST"] ) ## Event now.gm(stuff here) ) 109 .new -.2.the default in constructor) rightNow = Event.new( "NOW!" ).2009.false. :place end ## Event at 5:00PM 2-2-2009 CST funStart = Event.2.2. you can do ## Event.new( "Right now". [0.Ruby Programming/Reference/Objects/Time @time = Time.nil.new( "evan-hodgson day".new > funStart. array = ['Superman'. without short circuit behavior true | other .'The Hulk'] array.find_all { |item| item % 2 == 0 } # returns [2.'Batman'.10] array = ['Superman'.'Catwoman'.'Wonder Woman'] array = array. Methods: true & other . 10 # find the even numbers array = range.find_all { |item| item =~ /woman/ } # returns ['Catwoman'.index| puts "#{index} -> #{item}" end # # # # will 0 -> 1 -> 2 -> print Superman Batman The Hulk find_all find_all returns only those items for which the called block is not false range = 1 .8.Logical exclusive Or (XOR) Ruby Programming/Reference/Built-in Modules Enumerable each_with_index each_with_index calls its block with the item and its index.. without short circuit behavior true ^ other .'Wonder Woman'] .'Batman'.each_with_index do |item.4.Ruby Programming/Reference/Objects/TrueClass 110 Ruby Programming/Reference/Objects/ TrueClass The only instance of TrueClass is true.Logical AND.Logical OR.6. Nevertheless.Ruby Programming/Built-in Modules 111 Ruby Programming/Built-in Modules • Built-in Modules • • • • Enumerable Comparable Precision Math Ruby Programming/GUI Toolkit Modules/Tk Ruby bindings are available for several widget toolkits. currently there exists no comprehensive manual for Ruby/Tk. it is widely available and still more or less the default toolkit for GUI programming with Ruby. Gtk. cgi?Ruby%2FGTK [2] http:/ / zetcode. The current Ruby "PickAxe book" has a chapter on Ruby/Tk. Ruby Programming/GUI Toolkit Modules/ GTK2 • Ruby GTK API Reference [1] • Ruby GTK Tutorial [2] References [1] http:/ / ruby-gnome2. among them Tk. the Ruby book recommends inferring Ruby/Tk usage from the Perl/Tk documentation. com/ tutorials/ rubygtktutorial/ . Fox. and Qt. jp/ hiki. The Tk binding is the oldest. sourceforge. Instead. Validation against a DTD or a schema is not yet fully implemented. the chapter element.) This represents the whole document. too. but no text. it has an element. REXML can read and write XML documents. When using DOM. accessible using the attributes message.. whatever you need. darshancomputing..?> tag. com/ qt4-qtruby-tutorial/ [2] http:/ / www. The Document is an Element itself. you might be more interested in the root element of the XML document. text and child elements. it is included in the Standard API. it can be easily obtained calling REXML::Document. and child elements. The section is also an element. As of Ruby 1. an important class. Once you have obtained the root Element. In addition.Ruby Programming/GUI Toolkit Modules/Qt4 112 Ruby Programming/GUI Toolkit Modules/Qt4 [Totally free download and tutorial on Ruby Qt4 bindings [1]] [Prag Prog guys' pdf book on Qt3 for Ruby [2]] References [1] http:/ / returns the XML code of the whole element.. Element. any document has only one root element. In short. you can go down the tree using the elements message defined in Element. or an IO. com/ titles/ ctrubyqt/ Ruby Programming/XML Processing/REXML REXML is a XML processing API. Representation in REXML When parsing a XML document. text. too. but usually.root(). elements can have attributes. including attributes. attributes. The tree can be modified. text. REXML::Document itself is a subclass of REXML::Element. which returns a collection of all child elements.]". the chapter is an element. including the <?xml. Basics DOM Definitions Using the DOM API.8. pragmaticprogrammer. It has an attribute. and texts. the to_s methods have been overridden to return the XML code of elements. (The new message of REXML::Document just has to be fed with a REXML::Document itself. this might be used to save a wikibook: <wikibook title="Programming:Ruby"> </wikibook> In this case. As defined in the XML specification. They might have attributes. For example. an instance of the REXML::Document class is created. or a String. It has an attribute title with the value Overview and a text with the value "Ruby is a programming language [. and . REXML can parse documents and build a tree containing the elements.. instances of the Element class are representing the elements of the XML document. or access attributes or texts. attributes and text. you will need the following components: • • • • Ruby RubyGems Rails a driver for your database .Ruby Programming/XML Processing/REXML child elements' XML code. Rails was created to be a project management tool for "37signals [1]". org/ stdlib/ Ruby on Rails/Print version Note: the current version of this book can be found at. too. or often seen as RoR or just Rails. You can call that on the Document.org. 113 External links Standard API Documentation at ruby-doc. including the rexml package [1] References [1] http:/ / www. ruby-doc.wikibooks. is an web application framework written in the programming language Ruby. Features • • • • • • • • • • Rails supports agile software development [2] Rails has a short and very intuitive language Single blocks of code are intended to be short und clear Rails is very flexible Rails comes with a testing framework The framework follows the principles of DRY [3] (Don't repeat yourself) Rails has some conventions: these allow quick development and consistent code Rails uses the MVC-Architecture [4] (Model-View-Controller) Rails comes with an integrated server for local testing Applications with Rails are RESTful [5] Getting Started Installation on Windows To start. Quickly. it became one of the most popular frameworks on the web and its ideas and philosophies has inspired many frameworks in different languages.org/wiki/Ruby_on_Rails'' Introduction Ruby on Rails. 3. Use the console to type gem install rails This downloads and install all the needed components on your system. You might need administrator privileges to install it successfully. To install the gems. To use SQLite3 on your system together with Ruby on Rails. it will work as intended because newer version won't work in Windows . Check the Ruby site for the latest version.3. The default database is SQLite3.Ruby on Rails/Print version 114 Ruby Install Ruby as a regular application. Download the latest RubyGem package from the offical ruby website [6]. we can use our freshly installed gems (Rails is a gem). we will use SQLite3 as database. download the latest dll files from the sqlite website [7]. verify the installation by checking if you have the latest version: rails -v It should display the current Rails version (2.2. type: ruby setup. After the installation is done. copy all the files inside the zip into your Ruby /bin directory At last. The Ruby sites provides packages for all OS.1 as of the writing of this book) Rails To install Rails. But no worries. we want to install the proper gem: gem install sqlite3-ruby --version 1. Gems allows you to install additional features for your application and easy management of already installed ones. To install. we need to install a gem for our database.2.rb To verify the installation.rb. You can specify the database you want to use when you first create your Rails project.zip.3 is not the current version. For this Wikibook. it can be altered any time. Using the gem command helps you installing and deleting gem-packages.3 Even though 1. After downloading. Choose the files that contains the dlls without TCL binding sqlitedll-3 x x. Since we are using SQLite3 in this book.2 as of writing this guide) DB Driver Rails supports a broad range of databases. check the version of gems: gem -v It should display the proper version (1. open up a console and navigate to the folder containing the gem file and the file setup. Just follow their steps: ruby website [1] Gems RubyGems is a packaged Ruby application. Because we decided to stay with the default SQLite3 database. To create your database in our new project environment. This is especially important when working in a live-environment and you do not want bad data inside your database. the database. This is your database. Depending on your chosen database during the creation of the Rails application. that allows you to run many pre-made programs to ease up development. you will find a *. The db:create commando creates the database with the given name (inside db.and to your "production"-database. There is more functionality inside Rake then just creating a database. we need to run rake db:create Rake is a build in tool. test: adapter: sqlite3 database: db/test. take a look inside the /config folder.yml file always look different.sqlite3 pool: 5 timeout: 5000 production: adapter: sqlite3 database: db/production.sqlite3 file in the /db folder. If you're using SQLite3. handy file.x # gem install sqlite3-ruby (not necessary on OS X Leopard) development: adapter: sqlite3 database: db/development. this is ideal because all your data is in one file that can be quickly read and written.yml). . We need to tell Rails the name of our database and how to use it.Ruby on Rails/Print version 115 Database Configuration If your first application is created. stored in a single.sqlite3 pool: 5 timeout: 5000 # Warning: The database defined as <tt>test</tt> will be erased and # re-generated from your development database when you run <tt>rake</tt>. # Do not set this db to the same as development or production. For practicing and local development purposes. But one thing at a time. Consider giving different names to your "test". the file will look something like this: # SQLite version 3.sqlite3 pool: 5 timeout: 5000 We may now give our database a proper name. etc.8.4 are recommended. the RDoc documentation generator. your best bet is to type: sudo apt-get install ruby -t '1.8.Ruby on Rails/Print version 116 Install on OS X Option 1 • • • • Download Ruby and RubyGems [8] Install Ruby Install RubyGems Get to the command-line and type: sudo gem install rails --include-dependencies Option 2 • Download Locomotive [9] • Install Ruby on Rails software from Locomotive Option 3 • Use the broken Ruby installation on OSX 10. Copy the contents./name_of_file.3 has problems. save it as a file and run the file through a terminal (by navigating to the file and type . but you will not be able to use breakpointer for debugging (a very handy tool). Versions 1. Install RubyGems You should be able to obtain RubyGems by going to the Gems Website Choose the proper archive and install.4.8. and irb command-line interpreter. 1. . [12] and clicking the "download" link. So I recommend 1.8.2 and 1. Ubuntu.4 and follow this guide [10] RMagic A shellscript has been made that will install everything you need to make RMagic work on your OS X box. Install on Linux Install or update Ruby It is important that you get the right version of the language.4' sudo apt-get install irb rdoc This should install the Ruby language interpreter.). Get it from the offical Ruby website [1] Get it from the SVN repository [11] Debian For Debian-based systems (Debian.5 (the current stable version) runs fine.8. and 1.8. In Rails. but also includes explicit support for Javascript and XML. views are implemented using ERb by default. In Rails. View The view is the presentation layer for your application. . Rails relies on the MVC pattern. The idea behind it. re-use as much code as possible. such as XHTML. It is as independent from the database as possible (Rails comes with its own O/R-Mapper. The model also does the validation of the data before it gets into the database. The controller should not include any database related actions (such as modifying data before it gets saved inside the database). Inside the view you will find (most of the time) HTML with embedded Ruby code. The view layer is responsible for rendering your models into one or more formats. Most of the time you will find a table in the database and an according model in your application. For more information of DRY look at the Wikipedia article [3] Model-View-Controller As already mentioned.Ruby on Rails/Print version 117 Install Rails Get to the command-line and type: sudo gem install rails --include-dependencies Don´t repeat yourself To help to maintain clean code. Rails follows the idea of DRY. Controller The controller connects the model with the view. allowing you to change the database that MVC-Architecture inside Rails feeds the application but not the application itself). This reduces errors. XML. or even Javascript. controllers are implemented as ActionController classes. The controller knows how to process the data that comes from the model and how to pass it onto the view. is simple: whenever possible. Rails supports arbitrary text rendering and thus all text formats. This should be handled in the proper model. keeps your code clean and even more important: it takes a lot of work off your shoulders by writing code once and using it again. Model-View-Controller has some benefits over traditional concepts: • it keeps your business logic separated from your (HTML-based) views • keeps your code clean and neat in one place Model The model represents the information and the data from the database. First Application Create a basic Rails Application Creating your first Rails application is as simple as typing: rails firstapplication in the console. This will create the Rails application in the current directory. that handles all the logic is named orders_controller. If you need to use another database than the default (SQLite3) you can specify the database with the -d parameter. You may define your own rules but for the beginning (and for your further work. An example should show you how the conventions work together: You have a database table called orders with the primary key id. keep your code concise and readable and .g MySQL support.most important . Let's have a look at the files and folders and what they are good for: . These conventions will speed up development.Ruby on Rails/Print version 118 Helpers When you have code that you use frequently in your views or that is too big/messy to put inside of a view.and edit-view. On Linux and OSX you can just use the command without starting ruby. This sets up the basic files and folders you need. The view is split in different actions: if the controller has a new and edit action. If you need e. you can define a method for it inside of a helper. All methods defined in the helpers are automatically usable in the views. Best Practices Current best practices include: • • • • fat model and skinny controller business logic should always be in the model the view should have minimal code Use helpers! Convention over Configuration When starting to work with Rails you will find yourself looking at controllers and lots of views and models for your database. the team behind Rails has set up rules to ease up working with the application. These rules are not one-way. there is also a new.these conventions allow you an easy navigation inside your application. In order to reduce the need of heavy configuration. create your app with rails firstapplication -d mysql NOTE: on Windows. too) it's a good idea to stick to the conventions that Rails offers. The matching model is called order and the controller. you have to to start the commands with ruby explicitly. Ruby on Rails/Print version The Application Structure After creating your Rails application, you will be presented with a directory structure. The following table should introduce you to the folders and their purpose: File/Folder app/ app/model app/view What is it good for This is the folder where you will work most of the time. It contains your model, view and the controller. Contains all your models for your project. Includes all HTML files inside a folder. These files are named after an corresponding action inside your controller. Aditionally, these files are grouped into folders with the controller name. Holds the logic for your Rails application. All database related files go into this folder. If you are working with SQLite, then the database is likely to be in this folder as *.sqlite3 file. Has all the migrations that you created. As the names suggest, it has all the necessary configuration files of your Rails application. There is only very little configuration needed, so no worries that you have to crawl through endless lines of code. Localizations, routes and all basic files can be found here. All your static files (files that do not change dynamically) your CSS or JavaScript files are inside this folder. 119 app/controller db/ db/migrate config/ public/ public/images public/javascripts When you embedd Javascript, CSS or images, the default location is inside these folders. Rails will automatically look inside these to find the proper file. public/stylesheets script/ Holds scripts for Rails that provide a variety of tasks. These scripts link to another file where the "real" files are. Inside these folder you will find the generators, server and console. Log files from your application. If you want to debug some parts of your application you can check out these files. All files for testing your application. Documentation for the current Rails application. Extended modules for your application. Whenever you have 3rd-party plug ins, they will be found in this folder. Temporary files Basic guide for others on how to setup your application, what specialities it has or what to be careful about. Handles all the Rake tasks inside your application. log/ test/ doc/ lib/ vendor/ tmp/ README Rakefile Basic creation of different files Most of Rails files can be created via the console by entering a simple command that tells Rails what you want. This way you can create database migrations, controllers, views and much more. All commands look like ruby script/generate generator generator-options To see what options are available, just enter ruby script/generate and Rails will show you all available options and what generators are currently installed. By default, you can choose from the different generators. The most important are: • controller • helper Ruby on Rails/Print version • • • • mailer migration model scaffold 120: ruby script Ruby on Rails/Print version create exists create test/fixtures/tags.yml db/migrate db/migrate/20090420180053_create_tags.rb 121. Running the server The bundled Webrick server As you already know, Rails comes with an integrated server: WEBrick. WEBrick is a Ruby-written server to gets • On Windows: ruby script/server • On OS X and Linux: $ script/server After some seconds, WEBrick has been initialized and you are ready to go. The console with the web server needs to stay open, otherwise the server will shut down. To see if everything is working as expected, open up your web browser and switch to You should see the default Rails start page saying that everything is working correct.: • • • • • -p port: Specify the port to run on -b ip: Bind to a specific IP address -e name: Use a specific Rails environment (like production) -d: Run in daemon mode -h: Display a help message with all command-line options views. You can use the generator multiple times for the same controller. you can choose from the different generators. but if you have already added code then make sure you do not overwrite it and go back and manually add the action methods.g.Ruby on Rails/Print version 122 Mongrel To start a single mongrel instance: • On all platforms: mongrel_rails start This should be executed in the root directory of the Rails app you wish to run on Mongrel. The most important are: • • • • • • controller helper mailer migration model scaffold If you want more information on different generators. There are numerous options you can specify. By default. As long as you have not modified the controller this might be fine. simply enter the generator commend e. just enter ruby script/generate and Rails will show you all available options and what generators are currently installed. unit tests. Generators are accessed through the command-line script RAILS_ROOT/script/generate All commands look like ruby script/generate generator generator-options To see what options are available. controllers. migrations and more. but be careful: it will give you the option to overwrite your controller file (to add the actions you specify). including: • -p port: run on a specific port • -e environment: execute with a specific Rails environment. . here the link to the next page: Ruby on Rails/Built-In Rails Tools/What is Rake anyway? Generators Introduction Rails comes with a number of generators which are used to create stub files for models. "script/generate model" in the console and you will get information to this specific command and examples explaining what the generator does. like production • -d: run in daemon mode Built-In Rails Tools Generators Until Make a generator is created. rb test/unit/helpers/people_helper_test. test/unit/people_test.rb The file app/controllers/people_controller.rb app/helpers/people_helper. index & show) ruby script/generate controller People would generate the following output: exists exists create exists exists create create create create app/controllers/ app/helpers/ app/views/people test/functional/ test/unit/helpers/ app/controllers/people_controller. Rails will create a Controller that responds to all 7 REST actions (new.rb Any necessary directories will be automatically created..Ruby on Rails/Print version 123 Generate a Model To generate a model use the following: ruby script/generate model ModelName column:datatype column:datatype [. test/fixtures/peoples.rb test/functional/people_controller_test. When no actions are given.yml db/migrate db/migrate/20090607101912_create_peoples. update. app/helpers/people_helper. destroy.rb contains the PeopleController class. Note the the timestamp at the beginning of the file (20090607101912) will always be different depending on the time you created the file.rb test/unit/people_test. Existing ones will not be replaced.rb contains the unit test stub for the People class. The file app/models/people. edit.. test/functional/people_controller_test. Generate a Controller To generate a controller use the following: ruby script/generate controller ControllerName [actions] Replace ControllerName with the CamelCase version of your controller name.rb contains the functional test stub for the PersonController class.] Replace ModelName with the CamelCase version of your model name. For example: ruby script/generate model People name:string age:integer This would generate the following: exists exists exists create create create exists create app/models/ test/unit/ test/fixtures/ app/models/people.rb contains the database migration stub for the Person class. The db/migrate/20090607101912_create_peoples. create.rb is a stub for helper methods which will be made .rb test/fixtures/peoples.rb contains the People class.yml contains a stub for test data which will be used to populate the test database during test runs. ] Replace MigrationName with the CamelCase version of your migration name. For example: script/generate migration AddCityToPerson This would generate the following: exists create db/migrate db/migrate/20090607103358_add_city_to_person. 124 Generate a Migration To generate a migration use the following: ruby script/generate migration MigrationName column:datatype column:datatype [. • Flexible FileLists that act like arrays but know about manipulating file names and paths. • Rakefiles (rake’s version of Makefiles) are completely defined in standard Ruby syntax. Again. For example. adding the following to lib/tasks/database. No XML files to edit. Test Tasks • rake test:units: Execute unit tests Cache Tasks • rake tmp:cache:clear: Clear out the page/fragment cache. If the version is omitted then it will migrate to the highest version possible. there will be different files. Rake Rake [13] is a Ruby build tool like make and Ant. Typically you will use the migration generator when you need to change an existing model or need join tables. the timestamp starting the filename will be different. • A library of prepackaged tasks to make building rakefiles easier.. You can make your own rake task by creating a file in the lib/tasks directory of your Rails application and adding the Rake tasks to it. • Rake supports rule patterns to synthesize implicit tasks. No quirky Makefile syntax to worry about (is that a tab or a space?) • Users can specify tasks with prerequisites. • rake db:sessions:clear: Clear all of the sessions in the database.. The tasks below are common and used on regular basis. Database Tasks • rake db:migrate [VERSION=x]: Execute the migrations to the specified version. Depending on the given parameters.rake will make the db:recreate task available to your Rails application: .rb Migration are automatically generated each time you construct a new model. You can find out what tasks are currently available to Rake with the rake -T command.Ruby on Rails/Print version available to that controller and its associated views. so you do not need to generate migrations by hand for each model. Inside app/views/people you will find the created templates for the controller. enable full backtrace • --usage or -h: Display usage • --verbose or -v: Log message to standard output (default) • --version or -V: Display the program version • --classic-namespace or -C: Put Task and FileTask in the top level namespace .Ruby on Rails/Print version namespace :db do desc "Drop and create the current database" task :recreate => :environment do abcs = ActiveRecord::Base.rake files in RAKELIBDIR. You can nest namespaces as deep as you want although usually one or two nestings is sufficient. then exit • --trace or -t: Turn on invoke/execute tracing.connection. but also suppresses the 'in directory' announcement • --tasks[=PATTERN] or -T [PATTERN]: Display the tasks (matching optional PATTERN) with descriptions.current_dat end end The namespace method puts the contents of the block in the specified namespace.configurations ActiveRecord::Base. This task can now be executed with rake db:recreate Rake can be executed with the following command-line options: • --dry-run or -n: Do a dry run without executing actions • --help or -H: Display a help message • --libdir=LIBDIR or -I LIBDIR: Include LIBDIR in the search path for required modules • --rakelibdir=RAKELIBDIR or -R RAKELIBDIR: Auto-import any .connection. (default is 'rakelib') • --nosearch or -N: Do not search parent directories for the Rakefile • --prereqs or -P: Display the tasks and dependencies.recreate_database(ActiveRecord::Base. then exit • --quiet or -q: Do not log messages to standard output • --rakefile=FILE or -f FILE: Use FILE as the rakefile • --require=MODULE or -r MODULE: Require MODULE before executing rakefile • --silent or -s: Like --quiet.establish_connection(abcs[RAILS_ENV]) 125 ActiveRecord::Base. Method in ActiveRecord::Base which is used to quote SQL template Classes ActiveRecord classes are named in singular form.Reserved for primary keys table_name_count . Set use_pluralization In config/environment. This will apply to all ActiveRecord objects. This pluralization is often an initial point of contention for new Rails users. tables and fields. Note: There are also certain names that are reserved and should not be used in your model for attributes outside of the conventions defined in Rails: • • • • • • • • • • lock_version type . primary keys are id and foreign keys are table_id. ActiveRecord expects applications to follow certain naming conventions. Use set_table_name You can call set_table_name to specify a custom table name for a particular model. Tables Tables for ActiveRecord objects are named in plural form by default. Rails uses convention over configuration. table naming and more.use_pluralization false.Reserved for acts_as_list parent_id .This is only used when you have single table inheritance and must contain a class name id .Reserved for acts_as_tree lft .Ruby on Rails/Print version 126 ActiveRecord . If you need to change the table name there are several ways to override the default behavior.The Model Naming Basics ActiveRecord uses convention for naming classes.Reserved for acts_as_nested_set quote .rb you can specify ActiveRecord::Base. By default classes are singular. tables are plural. For example: class Dog < ActiveRecord::Base set_table_name 'dog' end = .Reserved for counter cache position .Reserved for acts_as_nested_set rgt . class naming. These conventions extend from file naming. this is the way to go) or you can create a model that comes with the migration using ruby script/generate model Category name:string amount:integer The console tells you that there were some files created and some already existent. As mentioned before. QA. This timestamp will always be different. Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development.string :name t.integer :amount t.up create_table :categories do |t| t.rb class CreateCategories < ActiveRecord::Migration def self. development teams can ensure that all changes to the database are properly versioned. Building a Migration You can either build the migration on its own using ruby script/generate migration Category and write the specific commands afterwards (if you want to create custom SQL.Ruby on Rails/Print version Override table_name You can also override the table_name method and return a value. depending on the exact time of the creation of your migration. For example: class Dog < ActiveRecord::Base def table_name 'dog' end end 127 Migrations [14] Migrations meant to solve the problem of rolling out changes to your database. The idea behind this is to have a "history" of all your migrations available.down drop_table :categories end end First of all. Now lets take a look at the migration # 20090409120944_create_categories.timestamps end end def self. This is the timestamp of your file and important for the creation of the database tables. production) is handled in a consistent and manageable fashion. take a look at the number (20090409120944) in front of your file. By defining the changes to your database schema in Ruby files. . Rails will never overwrite existing files unless stated otherwise. down. there is not yet a single table nor column in our database... After some time. This will certainly cause problems. let's start with the migration itself: create_table :categories do |t| t. you will either spent a lot of time working on the database to have the "old" state available or you have to start from scratch because it would take too long to remember and redo all changes. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row.2. To add a connection between your tables we want to add references in our model. Rails is able to recognize the changes in their actual order and all changes can be undone easily.integer :amount t.up and a self. This is where migration come in handy. This way you can make sure that you will always be able to go back to a past state of your database.down removes (drops) the table from the database with all its contents(!!). your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. it will use the self. Rake also knows what migrations are already in the database so it won't overwrite your tables. check out the "managing migrations" section Speaking of undoing and redoing: notice the two methods inside your migration self. While self. self. Rails will also create an primary key called model_id that auto-increments (1.3.down method gets executed. the self.up creates our categories table with all columns. The most common types are: • • • • • • • string text integer decimal timestamp references boolean 128 But wait. Keep in mind when writing own migrations always include a self. rake db:migrate handles this job. because of the timestamp.Ruby on Rails/Print version But why is this important? Imagine that you work on a Rails project and you create tables. You can choose from a variety of datatypes that go with ActiveRecord. Both of them do exactly the opposite of each other. Because you can't remember all the changes that went into the database and their order. Never alter the timestamp manually. . For more on those topic. alter columns or remove columns from your database via migrations. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once.down method to assure that the database state will be consistent after an rollback. The command is able to create the table and all the necessary columns inside the table. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data. For more info see "Managing Migrations".up method. When Rails sees that the migration has not been moved to the database.up and self.. We need to write the migration file into the database.string :name t. if you undo the migration. OK.) with every row.timestamps end We want to create a table called categories(create_table :categories) that has a name and an amount column. :timestamp. following the same format as add_column. options): Adds a new column to the table called table_name named column_name specified to be one of the following types: :string. options): Changes the column to a different type using the same parameters as add_column. (In order to work with these two models. :datetime. • rename_table(old_name. say 5 migrations before the current. :float. column_name.Ruby on Rails/Print version Let's add another model to our already existent database. column_name. • remove_column(table_name. new_column_name): Renames a column but keeps the type and content. To redo the last 5 steps. • drop_table(name): Drops the table called name. :time. :text. column_name): Removes the column named column_name from the table called table_name. new_name): Renames the table called old_name to new_name. Now we will take a look at how this is achieved. • add_column(table_name. options): Creates a table called name and makes the table object available to a block that adds columns to it. :integer. type. • change_column(table_name. we can use a similar command $ rake db:migrate:redo STEP=5 You can also rollback or redo a specific version of a migration state. we need to add associations inside our models. that restoring your database to a previous state will delete already inserted data completely! Schema Method Reference The following methods are available to define your schema changes in Ruby: • create_table(name. :boolean. :date. column_name. So we need to reference this product in our category. :binary. We want to create a model: ruby script/generate model Products name:string category:references and insert it into the database rake db:migrate Note the type :references for the category. We want to create a category that has multiply products. See example above. Inside our database there is now a category_id column for our product. To restore the state of the databse as it was. . This tells Rails to create a column inside the database that holds a reference to our category. The options hash is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create table definition. A default value can be specified by passing an options hash like { :default => 11 }. see Associations) 129 Managing Migrations We already talked about how migrations can help you to organise your database in a very convenient manner. you just need to povide the timestamp: $ rake db:migrate:up VERSION=20080906120000 Choose wether you want the db_migrate:up method to be executed or the db_migrate:down method Keep in mind. we can use $rake db:rollback STEP=5 This will undo the last 5 migrations that have been comitted to the database. • rename_column(table_name. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database. type. Ruby on Rails/Print version • add_index(table_name, column_names, index_type, index_name): Add a new index with the name of the column, or index_name (if specified) on the column(s). Specify an optional index_type (e.g. UNIQUE). • remove_index(table_name, index_name): Remove the index specified by index_name. 130 Command Reference • rake db:create[:all]: If :all not specified then create the database defined in config/database.yml for the current RAILS_ENV. If :all is specified then create all of the databases defined in config/database.yml. • rake db:fixtures:load: Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y • rake db:migrate [VERSION=n]: Migrate the database through scripts in db/migrate. Target specific version with VERSION=n • rake db:migrate:redo [STEP=n]: (2.0.2) Revert the database by rolling back "STEP" number of VERSIONS and re-applying migrations. • rake db:migrate:reset: (2.0.2) Drop the database, create it and then re-apply all migrations. The considerations outlined in the note to rake db:create apply. • rake db:reset: Drop and re-create database using db/schema.rb. The considerations outlined in the note to rake db:create apply. • rake db:rollback [STEP=N]: (2.0.2) Revert migration 1 or n STEPs back. • rake db:schema:dump: Create a db/schema.rb file that can be portably used against any DB supported by AR • rake db:schema:load: Load a schema.rb file into the database • rake db:sessions:clear: Clear the sessions table • rake db:sessions:create: Creates a sessions table for use with CGI::Session::ActiveRecordStore • rake db:structure:dump: Dump the database structure to a SQL file • rake db:test:clone: Recreate the test database from the current environment's database schema • rake db:test:clone_structure: Recreate the test databases from the development structure • rake db:test:prepare: Prepare the test database and load the schema • rake db:test:purge: Empty the test database You can obtain the list of commands at any time using rake -T from within your application's root directory. You can get a fuller description of each task by using rake --describe task:name:and:options See also The official API for Migrations [15] Associations • belongs_to and • has_one form a one-to-one relationship Ruby on Rails/Print version • has_one :through is a different way to create a one-to-one relationship • has_many and • belongs_to form a one-to-many relation • has_and_belongs_to_many or an alternative way •: 131. Ruby on Rails/Print version 132 class Product < ActiveRecord::Base belongs_to :category belongs_to :supplier end class Supplier< ActiveRecord::Base has_many :products has_many :categories. we use :id => false to prevent the automatic creation of a primary key column. class Product< ActiveRecord::Base has_and_belongs_to_many :tags end class Tag< ActiveRecord::Base has_and_belongs_to_many :products end 133 has_many :through This association is an other way to form a many-to-many relation. . This way we can store additional data inside a real model that also acts as a joining model.Ruby on Rails/Print version end Because we do not need a primary key inside the join table. "P" is before "T" in the alphabet so the tablename has to be products_tags (note: plural). the date of the creation) you might want to use this type of association. :through => :products end Instead of using a join table we use another model for the relationship. Consider the following ER-Diagramm to show the relationship. If we want to find out which supplier is responsible for a specific category we need the product to link the models together.g. The naming of the table needs to be in alphabetical order. :through => :products end class Category< ActiveRecord::Base has_many :products has_many :suppliers. Whenever you need to store data that additionally belongs to association (e. deprecated. Callbacks Callbacks provide a means of hooking into an ActiveRecord object's lifecycle. :through =>:group end class Group< ActiveRecord::Base belongs_to :network has_one :user end class User< ActiveRecord::Base belongs_to :group end Note: This example assumes that the membership inside a group is exlusive for each user. Consider this visual relationship: class Network< ActiveRecord::Base has_one :group has_one :user. the has_one :through association uses an "extra" model to form a relation. . inline methods using a proc are sometimes appropriate (such as for creating mix-ins) and inline eval methods are deprecated. Implementing Callbacks There are four types of callbacks accepted by the callback macros: • • • • Method references (symbol) Callback objects Inline methods (using a proc) Inline eval methods (using a string) . Method references and callback objects are the recommended approaches.Ruby on Rails/Print version 134 has_one :through As with has_many :through. called with the record as the only parameter such as: class BankAccount < ActiveRecord::Base before_save EncryptionWrapper.new("credit_card_number") after_initialize EncryptionWrapper.credit_card_number) end def after_save(record) record.credit_card_number = encrypt(record. like this: class Topic < ActiveRecord::Base before_destroy :delete_parents private def delete_parents self.new("credit_card_number") end class EncryptionWrapper def initialize(attribute) @attribute = attribute end def before_save(record) record.credit_card_number) end alias_method :after_find. 135 .Ruby on Rails/Print version Method Reference The method reference callbacks work by specifying a protected or private method available in the object.credit_card_number = decrypt(record. When that callback is triggered the object has a method by the name of the callback messaged. :after_save private def encrypt(value) # Secrecy is committed end def decrypt(value) # Secrecy is unveiled end end So you specify the object you want messaged on a given callback.new("credit_card_number") after_save EncryptionWrapper.class.delete_all "parent_id = #{id}" end end Callback Objects The callback objects have methods named after the callback. do_something } end Inline Eval The callback macros usually accept a symbol for the method they’re supposed to run. . It will be called for each object returned from a find. and thus can potentially affect performance as noted in the [16] Rails API Documentation.new { |model| model. after_find The after_find callback is only executed if there is an explicit implementation in the model class. Their use is discouraged because of [16] performance issues.class.delete_all "parent_id = #{id}"'.class. Example: class Topic < ActiveRecord::Base before_destroy 'self. before_create called before creating a new object of the model Partially Documented Callbacks The following callbacks are partially documented. Also note that these inline callbacks can be stacked just like the regular ones: class Topic < ActiveRecord::Base before_destroy 'self.delete_all "parent_id = #{id}"' end Notice that single plings (’) are used so the #{id} part isn’t evaluated until the callback is triggered.Ruby on Rails/Print version Proc Example of using a Proc for a callback: class Person before_save Proc. 'puts "Evaluated after parents are destroyed"' end 136 Callback Reference before_save This method is called before an ActiveRecord object is saved. but you can also pass a "method string" which will then be evaluated within the binding of the callback. rubygems. html#validation-helpers) or the API documentation (http:/ / api. wikipedia. com [2] http:/ / en. org/ classes/ActiveRecord/Validations/ClassMethods. wikipedia. org/ wiki/ Agile_development [3] http:/ / en. all of the callback types will be called. wikipedia. org/ wiki/ Model%E2%80%93view%E2%80%93controller [5] http:/ / en. attr. org/ [13] http:/ / rake. html [16] "Because after_find and after_initialize are called for each object found and instantiated by a finder.errors. org/ frs/ ?group_id=126 [7] http:/ / www. value| record. org/ [14] Excerpts modified and republished from Steve Eichert's Ruby on rails Migrations Explained (http:/ / www. wikipedia. [15] http:/ / api. html [8] http:/ / attr. and thus can potentially affect performance as noted in the [16] Rails API documentation. 137 References [1] http:/ / www. we’ve had to implement a simple performance constraint (50% more speed on a simple test case)." = Validations ActiveRecord supports a variety of model validation methods and allows for addition new methods as needed. General Usage For a complete reference of all validations check out the official guide (http:/ / guides. rubyonrails. In that case.html) Additionally you can apply a validation to one or more attributes using the validate_each directive: class Person < ActiveRecord::Base validates_each :first_name. rubyonrails.' if value[0] == ?z end end It is also possible to define validations via custom methods or blocks: • validate • validate_on_create • validate_on_update For example: class Person < ActiveRecord::Base validate :validate_email . org/ download. rubyonrails. org/ wiki/ Representational_State_Transfer [6] http:/ / rubyforge. It will be called whenever an ActiveRecord model is initialized. org/ down [9] http:/ / locomotive. 'starts with z. Unlike all the other callbacks. emxsoftware. sqlite. It will be called for each object returned from a find. rubyforge.Ruby on Rails/Print version after_initialize The after_initialize method is only executed if there is an explicit implementation in the model class. :last_name do |record. rubyonrails. org/ repos/ ruby/ tags/ 1_8_4/ [12] http:/ / docs. org/ activerecord_validations_callbacks.find(:all). 37signals. net/ [10] http:/ / hivelogic. ruby-lang. such as Base. com/ RubyOnRails/ Ruby+ on+ Rails+ Migrations+ Explained) article. sourceforge. org/ classes/ ActiveRecord/ Migration. org/ wiki/ Don%27t_repeat_yourself [4] http:/ / en. after_find and after_initialize will only be run if an explicit implementation is defined (def after_find). com/ narrative/ articles/ ruby-rails-mongrel-mysql-osx [11] http:/ / svn. This can be done with every validator in the same manner. For example if you want the user to enter his password 2 times to make sure he enters the correct password (this is seen very often when registering for a site) this is the helper you want to use. :password_confirmation %> validates_format_of validates_format_of accepts a regular expression and checks for the input with the provided pattern given by the :with clause. :with => /\A[a-zA-Z]+\z/. validates_numericality_of validates_numericality_of :amount_available Checks if the input is a number of any kind. that we used a customized message with this helper. To make sure. validates_format_of :username. In this case. :maximum => 50 validates_size_of :address. you may use the optional :only_integer => true command. :in => 5. however you can force validation to *not* occur using the save_with_validation method passing @false@ as the argument.add :email. make sure to define it correctly in your view (Note the _confirmation): <%= text_field :user. that the input is only an integer. 138 Important Validators validates_acceptance_of validates_acceptance_of :play_rules If you need to check if the user has set or "accepted" a certain checkbox you can use this validation. the username should not be longer than 50 characters and not shorter than 5. :message . Also note.Ruby on Rails/Print version def validate_email record. To use it. :minimum => 5.errors. In the example above. Alternatively you can specify a range that should be true in order to vaildate. => "Please use only regular letters as username" validates_length_of/validates_size_of validates_length_of :username. Above the address should constist of 5 to 100 characters. the check box with the HTML attribute "name='play_rules'" needs to be checked in order to pass validation. validates_confirmation_of This validator checks if an input field has been entered correct both times. There are some useful options with this command for example :greater_than => 100 makes sure that the given number will be greater then 100: so 101 will be the first valid number.. :password%> <%= text_field :user.100 The length_of/size_of validator comes in handy if you need to check the input for a certain length of characters. 'Invalid email' unless email =~ /@/ end end Normally validation occurs whenever a record is created or saved. Note that length_of and size_of/ are the same. new { |user| user. proc or string to call to determine if the validation should occur (e.Specifies a method. making sure that a teacher can only be on the schedule once per semester for a particular class. • if . validates_uniqueness_of :teacher_id. rubyonrails. validates_uniqueness_of validates_uniqueness_of: username Finally. the same check is made but disregarding the record itself. Basic Usage All of the columns in a table are accessible through methods on the ActiveRecord model. if the user chooses the username "Paul" and the name "Paul" already exists inside the username column of your database. a bit of a more advanced validator: this one checks inside the database if the attribute is already taken or not. When the record is updated. When writing your validation keep in mind that you can mix all of these together and there are even more advanded functions (http:/ / guides. 139 Configuration Options • message . it won't validate. this one checks if anything has been inserted in the given form element ("name" in this case).g. For example. html#conditional-validation) you might want to check out. The method. with scope It can also validate whether the value of the specified attributes are unique based on multiple scope parameters.rb class CreateProducts < ActiveRecord::Migration def self.Ruby on Rails/Print version validates_presence_of validates_presence_of :name One of the most basic validators.signup_step > 2 }).float :price t.One or more columns by which to limit the scope of the uniqueness constraint.Specifies a custom error message (default is: "has already been taken") • scope . org/ activerecord_validations_callbacks. :class_id] When the record is created a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column). proc or string should return or evaluate to a true or false value. In this case. :scope => [:semester_id. :if => :allow_validation. For example: Consider the following migration: # 20090409120944_create_products.integer :amount . Attributes ActiveRecord attributes are automatically determined from the underlying database schema.up create_table :products do |t| t.string :name t. or :if => Proc. find_by_name("my book") => #<Product: id=1..save Now we have 3 products in our database.. > You can also search for all products >>Product.. But what happens when we have thousands of entries in our database? We can't remember every id of a Product..save >> Product. So let's select the first entry >>Product.89 :amount => 1). We can interact with the database via the build-in console: ruby script/console gives us a console that let us communicate with Rails. name="my book" . We could also use .find_by_amount Or you can search for multiple products with their id: >>Product. end Because Rails has created a primary key for us and called it "id" we can already search for it inside the database... > and Rails gives as the output we wanted.. :amount => 4). Rails will show you a =>true inside the console. ><Product: id=3.find_by_price or ...new(:name => "my cd".98.. > so we are able to tell Rails to look for our entry with a specific id. This not only works for the name... :price => 9....find(:all) for the first or the last product in your table 140 .3) => #<Product: id=1.save if everything went right.find(1. name="my book" ... but for all columns in the database. Let's add some more products >> Product.new(:name => "my book". :price => 4.Ruby on Rails/Print version end end #. Before we can select data from our database it is time to insert some products >> Product.. name="my cd" . :amount => 12)...all or >>Products. so Rails offers a very nifty solution: >>Product.new(:name => "my movie".find(1) and Rails tells you what it found for this id (remember: find only works when there is a Rails generated id as primary key) => #<Product: id=1. name="my book" .99. :price => 14.. going from 1 to 3.. For example: class Product def name self[:name] || 'Unknown' end end p = Product. you can use many build-in options or use custom SQL. Let's try to find our data in descending order (3. org/ active_record_querying. starting with the last inserted id . .new p.name = 'my disk' p.all(:select => "id.rubyonrails. name") This method will only display the name and the id of our products making it way more readabel.in our case: 3 When we query our database we get lots of infos we are not really interested in such as the "created_at" and "updated_at" column.org/classes/ActiveRecord/Base. html#find-options) or the API (. name") or >>Product.2. When searching for data.1) >>Product. :order => "id DESC") will give you all your prodcuts.find(:first/:last) If you want more controll over your data. To see more possibilities check out the RoR guide (http:/ / guides.all(:order => "id DESC") or alternatively >>Product. :select => "id.Ruby on Rails/Print version >>Product.find(:all. rubyonrails.first/last or >>Product. keep in mind that you can combine all these methods to your liking. 141 Overriding Attributes You can override any of the accessor methods in your ActiveRecord model classes in order to add logic.name => "my disk" You can access any attribute via self[attribute_name] (to get) or self[attribute_name]= (to set).find(:all. We only want to take a look at our id and the name so we may use >>Product.html#M002208).name => "Unknown" p. Customer#address=(address) These methods will operate with value objects like the ones described below: class Money include Comparable attr_reader :amount.new(exchanged_amount. Customer#balance=(money) * Customer#address.Ruby on Rails/Print version 142 Aggregations Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects.. :currency EXCHANGE_RATES = { "USD_TO_DKK" => 6 } def initialize(amount. currency end def exchange_to(other_currency) exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor Money. %w(address_city city) ] end The customer class now has the following methods to manipulate the value objects: * Customer#balance. currency = "USD") @amount. @currency = amount. :mapping => [ %w(address_street street). :mapping => %w(balance amount) composed_of :address. :class_name => "Money".amount end end . It expresses relationships like "Account [is] composed of Money [among other things]" or "Person [is] composed of [an] address".currency end def <=>(other_money) if currency == other_money.amount && currency == other_money.currency amount <=> amount else amount <=> other_money.exchange_to(currency). other_currency) end def ==(other_money) amount == other_money. address_street # => "May Street" customer.new("Hyancintvej".street end end Now it’s possible to access attributes from the database through the value objects instead.new(120. Two Money objects both representing $5 should be equal (through methods such as == and <=> from Comparable if ranking makes sense). That’s the case with our balance attribute.Ruby on Rails/Print version end class Address attr_reader :street. :city def initialize(street.balance customer.balance > Money. "DKK") true true false 143 Value objects can also be composed of multiple attributes such as the case of Address.exchanged_to("DKK") customer.balance. This is unlike entity objects where equality is determined by identity.balance = Money.city end def ==(other_address) city == other_address. You interact with the value objects just like you would any other attribute.address_city # => "Chicago" Writing value objects Value objects are immutable and interchangeable objects that represent a given value such as a Money object representing $5.new(5) # sets the Money value object and # # # # # => => => => => Money value object Money.new(20) customer. Normal ActiveRecord::Base classes are entity objects.new(10) customer. Example: customer. "Copenhagen") customer. "Chicago") customer.address # => Address. @city = street.balance < Money.address_street = "Hyancintvej" customer.city && street == other_address. . The order of the mappings will determine the order of the parameters.address_city = "Copenhagen" customer. If you choose to name the composition the same as the attributes name.balance == Money. city) @street. though: customer.address = Address. city end def close_to?(other_address) city == other_address.new(20) the attribute customer.new("May Street". it will be the only way to access that attribute. An entity class such as Customer can easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or relational unique identifiers (such as primary keys). max_age| . :group => 'last_name') puts values["Drake"] => 43 drake = Family.maximum(:age.. This is exemplified by the Money#exchanged_to method that returns a new value object instead of changing its own values. 144 Calculations Calculations provide methods for calculating aggregate values of columns in ActiveRecord models.maximum(:age. :order. float for average and the column type for everything else). end . :having and :joins. The :group option takes either a column name or the name of a belongs_to association. The supported calculations are: • average • • • • sum minimum maximum count The calculate method has two modes of working. Calculate All calculations are handled through the calculate method. The calculate method accepts the name of the operation..each do |family. Don‘t allow the Money object to have its amount changed after creation. Attempting to change it afterwards will result in a TypeError. The immutable requirement is enforced by Active Record by freezing any object assigned as a value object.find_by_last_name('Drake') values = Person. the column name and any options. :group. If the :group option is not set then the result will be returned as a single numeric value (fixnum for count. Create a new money object with the new value instead. The options can be used to customize the query with :conditions. :group => :family) # Person belongs_to :family puts values[drake] => 43 values.Ruby on Rails/Print version It’s also important to treat the value objects as immutable. If the :group option is set then the result is returned as an ordered Hash of the values and groups them by the :group column. Note that if a condition specified in the calculation results in no values returned from the underlying table then the calculate method will return nil. Active Record won’t persist value objects that have been changed through other means than the writer method. For example: values = Person. Ruby on Rails/Print version 145 Average You can use the average method to calculate the average value for a particular column. 1. 1. :conditions => ['created_at > ?'.maximum(:amount. For example: Donation.average(:age) Will return the average age of all people in the Person model.year. 10]) Will return the sum of the number of products which are in category 10 and in stock.minimum(:amount. An example of customizing the query: Donation. Maximum The maximum method will calculate the maximum value for a particular column. An example of customizing the query: Product. :conditions => ['category_id => ?'.average(:age. For example: Product.ago]) This will return the largest amount donated within the last year. Sum The sum method will calculate the sum for a particular column. An example of customizing the query: Donation. :conditions => ['age >= ?'. Minimum The minimum method will calculate the minimum value for a particular column.year. .minimum(:amount) Will return the lowest amount donated. :conditions => ['created_at > ?'. An example of customizing the query: Person.ago]) This will return the lowest amount donated within the last year.maximum(:amount) Will return the largest amount donated.sum(:number_in_stock) Will return the sum of products in stock.sum(:number_in_stock. 55]) This would return the average age of people who are 55 or older. For example: Donation. For example: Person. count(:all.find(params[:id]) end #. TestResult.count(:all) Will return the number of TestResult objects in the database..find(params[:id]) if @product... The "Convention over Configuration" is also an essential part of the view: as mentioned in the beginning of this book.The View Rendering and Redirecting Introduction You already know how to manage your data with ActiveRecord. Rails is able to know which file for the view belongs to which action inside in the controller: app/controller/products_controller. An example of customizing the query: TestResult. This action inside our products controller assumes that there is a view responding to the name: app/views/products/show. Rendering and Redirecting You will come across 2 often used methods to display data render and redirect_to A good example of how these two methods work can be seen in the example below: This actions gets called when the user submitted updated data def update @product= Product..update_attributes(params[:name]) redirect_to :action => 'index' else render :edit .erb As you can see the file has 2 extensions: one is for the browser to display (HTML) and the other one tell Rails how to process it (erb= embedded ruby).rb #. Most of the time.:conditions=>['starttime>=?'. ActionView .Ruby on Rails/Print version 146 Count Counts the number of items matching the condition(s). you will work with HTML but you can also use Javascript inside your views (which of course can again be Rails generated) or different CSS. def show @product= Product.Time.html. All data the view displays comes from the controller. Now it is time to display your data.now-3600*24]) Will return the number of TestResult objects whose starttime field is within the last 24 hours. Whenever you want to redirect your user to another layout you can use render :layout => 'another_layout' Whenever there is no proper layout file. Render Remember the "update" action above? When the update fails. Whenever we successfully updated the name of a product. To use a specific layout inside your whole controller you can define the layout inside your Controller class ProductsController < ApplicationController layout "my_layout" #our actions end For more infos about layouts.html. in this case we look for the "id" inside the database and populate the page accordingly. we want to return to the edit view. but keep the big difference between render and redirect_to in mind. see "Layout Files" redirect_to You can use redirect_to in a similar manner as you do with render. There is an important difference between render and redirect_to: render will tell Rails what view it should use (with the same parameters you may have already sent) but redirect_to sends a new request to the browser. it's products). If you scaffold "Products" the file inside layout will be called products. If the update fails. With redirect_to you can easily send the user to a new resource. Whenever you use scaffolding to create parts of your application a file inside layout gets created. for example the index page of our products.Ruby on Rails/Print version end end As you can see both of our methods are used in this simple example. you can render simple text render :text => "Hello World" You may have already noticed that there is a "layout" folder inside your view. Rails will display the page only with the styling provided inside the requested view.erb. To learn more about the paths and routing see the chapter on "routing" redirect_to products_path A very handy redirect_to option is :back redirect_to :back will send the user back to the site that he came from 147 . we get redirected to the index site of the products. This file is responsible for the basic display of your sites matching the common name (in this example. If you want to render another view use render 'categories/show' You can also display a file that is somewhere completely different on your web server render :file => "/u/apps/some_folder/app/views/offers/index" And of course. we want to render the edit view with the exact same parameters as we did before. org/TR/xhtml1/DTD/xhtml1-transitional. If you want to include multiple files just .0 Transitional//EN" ". You can use this tags to embed CSS. class) method.Embedded Ruby is the default templating system for Rails apps. In addition to the built in template systems you can also register new template handlers using the ActionView::Base.rhtml are considered ERb templates. All templates ending with . = 148 Layout Files In the previous chapter you learned how to render output to the default layout or to a special layout provided by you. Its default content will be similar to <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.Ruby on Rails/Print version Templates There are several templating systems included with Rails each designed to solve a different problem. • Builder .org/1999/xhtml" xml: <head> <meta http- <html xmlns=" %>< Asset tags All asset tags. you can use the according helpers: <%= javascript_include_tag "my_javascript" %> or if you want to include CSS <%= stylesheet_link_tag "my_css" %> All these files are located in the public directory public/javascripts or public/stylesheets. All files ending with .charset=UTF-8" /> <title>Products: <%= controller. Java Script and images or to provide RSS-feeds. such as the "stylesheet_link_tag" are little helpers that generate the proper HTML for you. To embedded Javascript or CSS. A template handler must implement the initialize(base) method which takes the ActionView::Base instance and a render(text.Builder templates are programmatic templates which are useful for rendering markup such as XML.rxml are treated as builder templates and include a variable called xml which is an instance of XmlMarkup. There is no need to provide the extension as Rails will handle it automatically. locals) method which takes the text to be rendered and the hash of local variables.w3. footers or sidebars to ease up maintainance. :height => 50. :alt => "This is my image" %> 149 Yield Whenever you come across "yield" you will know that this is sort of a placeholder for the view that will be displayed inside your layout.gif or . .This is my header</h1> <% end %> Named yields can be used for menus. So with the above example.Ruby on Rails/Print version provide all the file names inside the tags: <%= stylesheet_link_tag "my_css".png! You can also provide a custom path and HTML attributes <%= image_tag "images/my_image". media => "print" %> No modern web site is complete without using pictures and graphices so Rails provides you with its own image tag: <%= image_tag "my_image" %> As with JavaScript or CSS the Rails will look into public/images by default to find the proper picture. Just put them in your code and they will be placed in the right place.jpg. "files/stylesheet" %> To load all files inside your public/javascripts or public/styleheets use the appropriate tag with :all <%= javascript_include_tag :all %> When embedding CSS you can specify the media attribute inside the tag: <%= stylesheet_link_tag "my_print". Note: that you do not need to tell Rails if you use . . just be sure to provide the proper path: <%= stylesheet_link_tag "my_css". but you are not limited to using a single yield: <body> <%= yield :header %> </body> To get access to the :header you can use the "content_for" method. "my_other_css" %> Of course these files can be placed anywhere in your application. :width => 50. that might be: <% content_for :header do %> <h1>Hello Rails . def test #nothing here yet end An empty action inside the controller was added..erb Overall partials are a very good way to minimize the effort of copying the same code over and over.erb inside our products view..html. Forms Basic Forms are an important part of every web site.erb. To move your partial to a seperate folder use <%= render :partial => "partials/form" %> will look in "partials" for a file called _form. dynamic menus. If you have a lot of HTML code that repeats itself in many different views (such as forms. The page was called inside the browser http:/ / localhost:3000/ products/ test/ 1. We use them to contact the site owners to provide log in credentials or to submit data. you just move the code that you use often into a separate file and place a link inside the files that should use your partials <%= render :partial => "form" %> This will look inside the folder from where the partial gets called for a file named _form.) you might want to consider using partials: With partials. Additionaly Rails has . Because we haven't altered the routes we have to provide an id of a product. Keep in mind to use an underscore in your filename to tell Rails that it is a partial.html. "My name is:") %> <%= text_field_tag(:my_name) %> <%= submit_tag("Process") %> <% end %> This will create a very basic form like <form action="/products/test/1" method="post"> <div style="margin:0. but to keep the needed code in single files that can be altered easily and used as often as you want to.html. The most basic form you can get is a simple input field for your name: <% form_tag do %> <%= label_tag(:my_name.. Rails has vast support for forms and many build in tags to help you create forms quick and easily.Ruby on Rails/Print version 150 Partials It is time for a little more DRY. Radio Boxes: To create radioboxes simply use <%= radio_button_tag :category. :class => "button") %> will create a submit button <input name="commit" type="submit" class="button" value="Save products" /> Text fields: <%= text_field_tag ('rails') %> will create an emtpy text field: <input id="rails" name="rails" type="text" /> As usual you can add HTML options or specific values <%= text_field_tag ('price'.html#M001706). To preselect an item the 3 option that the helper receives is supposed to be a boolean.or drop downs. options_for_select([['Peter'. To display a simple select box we can combine some handy methods: <%= select_tag (:name.['Joseph'. Submit Button: <%= submit_tag ("Save products". Also be sure to take a look at the official API (http:/ / api. This is because we want to create a text field with no pre-defined value: <input id="price" name="price" type="text" maxlength="10" /> If we would have provided a name. As most of the tags work in a similar manner. Rails would add the HTML attribute "value": <input id="price" name="price" type="text" maxlength="10" value="my predefined value instead of nil" /> Select boxes: A common task inside forms is to let the user select something from select boxes . "books". Rails provides the id for every form element with the names you provided.org/classes/ActionView/Helpers/FormTagHelper. Of course this can be altered by providing the proper option. You also notice that there is an id for our input.'pete']. it should be easy to figure out how much of them works. rubyonrails.Ruby on Rails/Print version created a "authenticity_token" to provide security features to our form. The following list should give you an overview of some form tags. :maxlength => 10) %> notice that we use "nil" here. 'jo']]))%> would create 151 . nil. true %> The above will create <input id="category_books" name="category" type="radio" value="books" /> If you want to change the id you can pass your own id to to tag (:id => "someid"). You have already read about how to validate form data before it gets written into the database.html) 152 Handling Errors Now that you know how to display forms correctly in Rails. The name gives a pretty good idea of the difference between these two: error_messages displays all errors for the form.today as the first argument) being pre-selected. :start_year => 2009. error_messages_for is used in a similar manner.different form tags --> </p> <% end %> will display all the error messages: either default ones or the ones you have specified inside your model (:message => "Only integers allowed").Ruby on Rails/Print version <select id="name" name="name"> <option value="pete">Peter</option> <option value="jo">Joseph</option> </select> Another nice helper of the select_* family is select_year. :header_tag => :h6 %> . Either if it is correct or if he needs to re-enter some values. :end_year => 1900 %> This will create a select box with all years.today. Now you will see how to display the errors. Using the methods is easy: <% form_for(@product) do |f| %> <%= f. you may use something like: <%= select_year Date. Then it display the error message for the field that matches the given name (:name in this case) <%= error_messages_for :name %> You can also customize the error messages that are displayed in a box. while error_messages_for displays the errors for a given model. :message => "Correct your entries". rubyonrails.error_messages :header_message => "Invalid product!".org/classes/ActionView/Helpers/DateHelper. we are looking for a way to give the user some feedback over his input. When you want the user to choose his year of birth. even more: <%= f.error_messages %> <p> <!-. Be sure to check out the other helpers for dates Datehelpers (http:/ / api. starting from 2009 going to 1900 with the current year (Date. Basically there are two methods that allow us to display errors: error_messages and error_messages_for. text_field :price %.text_field :name %> <%= f.. :size =>5 > <%= submit_tag "New Product" %> <% end %> will create HTML similar to: <form action="/products" class="new_product" id="new_product" method="post"> <div style="margin:0.. The rest uses code you are already familiar with. Let's asume we want to create a new Product via a form: We have a controller that has an action..erb) that works with our @product instance: <% form_for :product. When working with a model (e. :url=>{:action => "create"} do |f| %> <%= f. it's going to be a new product). We use the action "create" to handle the creation of the file.new end #. @product.rb #. and a view (view/products/new. you want to update your data or create a new data set) you want to use the form elements that are more suited for the job. products_controller.Ruby on Rails/Print version 153 Advanced Forms Until now we mainly worked with form elements that have a _tag at the end of the name. ..text_field :amount%. There are no new elements to learn we just use the one we already know but do not add the _tag at the end (compare form_tag and form_for). We loop or "yield" through the form_for object with the variable f.html. def new @product= Product. :product references the name of the model that we want to use and @product is the instance of the object itself (in this case. :size => 10 > <%= f.. ....g. :name. we want to select categories from the database. Category. This makes the form_for method a lot easier and more readably: form_for :product. This is just a starting point for your work. :multipart => true) do %> <%= file_field_tag 'picture' %> <% end %> . a good start is the official API (. :id. Using select boxes with a model We already learnt how to create select boxes with built in helpers. if your database needs to work with it that way. :name.rubyonrails. Most of them will use RESTful resources. :url=>{:action => "create"} turns into form_for (@product) That is a lot better. To see more examples and explanations. so the user can select the according one: <%=f. isn't it? Now the form_for tag looks the same. Or take a look at the official Rails guide to see a sample action (. For the more advanced purposes you might want to consider using widely known gems that handle the job. Rails is smart enough to recognize the action and provides us with the correct HTML attributes (see <form action="/products" class="new_product" id="new_product" method="post">) To learn more about routing and REST be sure to take a look at Routing.org/form_helpers. you need to set the form to support "multipart/form-data". If you want to upload. @product.downcase %> If you have some categories inside your database the HTML may look similar to <select id="category_id" name="category[id]"> <option value="cds">CDs</option> <option value="books">Books</option> <option value="dvds">DVDs</option> </select> Notice the .g a picture for our products.collection_select :category.downcase: this will write the HTML values lowercase. you can use these ways: Here. This gives Rails the option to decide what to do with the data. you will need to write an action inside the controller that handles the upload of the file on the server: <% form_tag({:action => :upload}. But you may also want to display the contents of a model inside a select box.html) Uploads The following paragraph should give you just a quick overview on the topic of uploading data with forms. To show how this is done.Ruby on Rails/Print version 154 Restful Resources The methods shown above may not be exactly what you will see in other Rails applications.org/classes/ActionView/Helpers/FormOptionsHelper. no matter if you are creating a new product or if you update an existing one.html#uploading-files) As with everything you want to upload via a form. e. Take a look at the Resources page to find good starting points for your search. the image name inside your database) <% form_for @person.rb Example The following is an example of an Application Helper. The method title will be available to all views in the application.file_field :picture %> <% end %> 155 Custom Helpers Rails comes with a wide variety of standard view helpers. formatting text and numbers.g. building forms and much more. Methods added to this helper will be available to all templates in the application. Custom Helpers Custom helpers for your application should be located in the app/helpers directory. Helpers include functionality for rendering URLs. :html => {:multipart => true} do |f| %> <%= f. if you have a ProjectsController then you would have a corresponding ProjectsHelper in the file app/helpers/projects_helper. module ApplicationHelper def title t = 'My Site' t << ": #{@title}" if @title t end end . For example. Helpers provide a way of putting commonly used functionality into a method which can be called in the view. Application Helper The file app/helpers/application.rb contains helpers which are available to all views.Ruby on Rails/Print version For a form bound to a model we can use the already known form_for tag (this allows you to save e. Controller Helpers By default other helpers are mixed into the views for based on the controller name. the second part the action name and the third part is the ID. it's time to get to the last part of MVC: the Controller. Parameters Remember the "rendering and redirecting" example you've seen when learning about the view? def update @product= Product. you should also read about "Routing" to fully understand how things work together.find(params[:id]) end end In this example the people controller has two actions: index and show. This is because the default route is: map. The action called index is the default action which is executed if no action is specified in the URL. Actions Actions are methods of your controller which respond to requests.Ruby on Rails/Print version 156 ActionController . A detailed explanation of routes is provided in its own chapter.find(params[:id]) if @product.update_attributes(params[:name]) redirect_to :action => 'index' else render :edit end end .The Controller Introduction Now that you worked your way though Models and Views. For example: The index action can also be called explicitly: The show action must be called explicitly unless a route has been set up (routing will be covered later): In the example above the number 1 will be available in params[:id].find(:all) end def show @people= Person.connect :controller/:action/:id This indicates that the first part of the path is the controller name. Your controller creates the proper data for the view and handles some logic structures. For example: class PeopleController < ApplicationController def index @people = Person. In order to fully understand the whole framework. When using e. For example option[]=1&option[]=2&option[]=3. Now we want to take a look at WHAT gets updates. the data is likely to come from an HTML-Form (therefore a POST request). wikipedia. you might want to consider storing the session inside a database.org/security. you access the session in a similar way to the parameters. In this example. You can also work with GET requests in the same manner. check boxes you are likely to get more then one set of data for the same attribute. As with the example above. Most of the time you want to store the session on the server.Ruby on Rails/Print version You know what the differences between render and redirect_to is.g. edit config/initializers/session_store.'3'} 157 Session For a technical explanation of a Session take a look at the wikipedia article about Sessions (http:/ / en. you can work with params[:ids] to get access to these settings.rubyonrails.rb and be sure to read on the RoR Website (http:/ / guides.find(session[:current_user_id]) end As you can see.html) carefully. Rails provides a simple way of accessing your session. org/wiki/Session_(computer_science)) In Rails you have some options to store the session. Work with your session As with the parameters. just assign it a nil-value session[:current_user_id] = nil . but with security-relevant data. Storing a session isn't much more complicated: def index #we have some code here to get the user_id of a specific (logged-in) user session[:current_user_id] = id end To destroy the session.'2'. Consider following example: def show_details #we may use this inside a user-specific action User. Rails will handle both requests by using the params command. Your options will look like options => {'1'. To change the session storage. This is determined by given the "update_attributes" method what we want to update: params[:name]. delete(:commenter_name) end end . Flashes are useful to display error messages or notices to the user (e. This is. Flashes are special.Ruby on Rails/Print version 158 Displaying a Flash-message Flashes are very special and useful part of a session.g.maybe some HTML-Code --> <% if flash[:warning] -%> <%= flash[:warning] %> <% end -%> As you can see from the example above you are not limited to a single flash. They exist only once and are destroyed after each request. -%> <!-.name else # Delete cookie for the commenter's name cookie. if any cookies. Cookies Of course you can work with cookies inside your Rails application. You may have already found it in one of the view files. again very similar to working with parameters or sessions. Consider the following example: def index #here we want to store the user name. Here is how they work: As said. You can access multiple flashes by their name you have defined inside the controller. if the user checked the "Remember me" checkbox with HTML attribute name="remember_me" #we have already looked up the user and stored its object inside the object-variable "@user" if params[:remember_me] cookies[:commenter_name] = @user. it's easy to link the different views together or link to a specific view. If you want to go back from the products view to the index overview that displays all products. products_path %> When writing your own routes inside routes.rb. take a look the following table: HTTP Verb GET GET POST GET GET PUT DELETE URL Controller Action used for /products /products/new /products /products/1 Product Product Product Product index new create show edit update display all products in an overview return an HTML form for creating a new product create a new product display a specific product return an HTML form for editing a product update a specific product /products/1/edit Product /products/1 /products/1/ Product Product destroy delete a specific product As you can see. To understand these principles better. Basically REST provides a way of communication inside your application and all requests that exist from external sources (just as a browser request). Keep in mind that RESTfoul routes reference a single object (products in this case).resources :products With a RESTful resource. you may place something like this in your view: <%= link_to 'Back'. With REST. the less priority it has. Routing also works when you want to link somewhere from one point of your application to another point.rb: map. These 7 actions would result in a single route inside routes. you will use a link similar to products/4. all the actions of REST are already in our scaffolded controller. Understanding Routes and Routing RESTful routes RESTful routes are the default routes in Rails. For example.Ruby on Rails/Print version 159 Routing Because Routing is such an important part of Rails we dedicated a whole chapter to Routing (even though they are part of ActionView).wikipedia. if you want to display the product with the id 4. So Rails will figure out. deleting und updating a product While *_path will create a relative path to. keep in mind. check out the Wikipedia (. *_url provides the whole URL • _path => /products . Rails provides us some helpers to get to our desired location: • products_url & products_path => redirects us to the index overview and edit view for our products (note the plural) • new_product_url & new_product_path => will lead as to the form that creates a new product • edit_product_url & edit_photo_path => provides us with an edit-form for a specific product • product_url & product_path => is responsible for showing.org/wiki/Representational_State_Transfer) article. that you want to show the information that belongs to the product with the id 4. To get a more detailed technical view on REST. the lower the route is inside your file. we can use "shallow nesting" If we want to add supplier for specific categories.resources :magazines do |magazine| magazine. only shorter map.Ruby on Rails/Print version • _url => You will very likely need more than one REST route.resources :products. You can easily write multiple REST routes into a single: map. products_categories_path or new_product_category_url These path need to be present in your routes.resources :photos end end . :categories. you will be able to access all *_url and *_path helpers e. :has_many => :categories if you need to add more than association.resources :magazines do |magazine| magazine. :customers You will come across many similar constructs like our products-category relation: class Category < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :categories end HTTP Verb GET GET POST GET GET URL Controller Action used for 160 /products/1/categories /products/1/categories/new /products/1/categories /products/1/categories/1 Category Category Category Category index new create show edit will show you an overview of the categories for product with the id 1 will give you an HTML form to create a new category for product with id 1 will create a new category for product with id 1 shows you the categories with id 1 that belongs to your product with id 1 gives you an HTML form to edit your category with id 1 that belongs to product with id 1 updates category with id 1 that belongs to product with id 1 /products/1/categories/1/edit Category PUT DELETE /products/1/categories/1 /products/1/categories/1 Category Category update destroy deletes category with id 1 that belongs to product with id 1 As with resources that are not nested.resources :publishers. To avoid these problems. put these in [] which is the same as the following route. but try to avoid 2 or more. you can nest as many resources as you want. So one nested resource is ok.g.resources :products.rb in an similar maner to your model: map. we may end up with something like map. but you should try to keep the level of nesting as low as possible. :shallow => true do |publisher| publisher.resources :ads end With this way. ActionMailer Note: The following documentation was taken directly from the Rails API documentation (http:/ / api.html) ActiveSupport Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.connect ':controller/:action/:id' will for example be a browser request similar to products/show/2 If you are familiar with other languages that focus an the web. script/generate mailer Notifier The generated model inherits from ActionMailer::Base. :shallow => true There are many more advanced features for routing. More infos and instructions can be found in the official Rails guides (. or to add attachments. you need to create a mailer model.Ruby on Rails/Print version or in short: map. When working with regular routes. See also The API with lots of examples (. com/classes/ActionMailer/Base.org/routing.rubyonrails.resources but .connect) map.html) ActionMailer allows you to send email from your application using a mailer model and views.org/classes/ActionController/Routing.email_address_with_name .resources :products. rubyonrails.rb (this time we don't use . All these additions have hence been collected in this bundle as way to gather all that sugar that makes Ruby sweeter. Emails are defined by creating methods within the model which are then used to set variables to be used in the mail template to change options on the mail.rubyonrails. 161 Regular Routes Even though RESTful routes are the encouraged way to go. you can also use regular routes inside your application. you may wonder how query strings inside the URL are handles: Rails automatically provides these parameters inside the params hash So if you take the example above and add products/show/2?category=3. Model To use ActionMailer. :has_many => { :categories=> :suppliers }.html#controller-namespaces-and-routing). you give Rails some keywords and it will map the proper path for you. One of these default routes is already inside your routes. we would be able to access the category id with params[:category_id]. Examples: class Notifier < ActionMailer::Base def signup_notification(recipient) recipients recipient. g.com" content_type "text/html" #Here's where the magic happens end . class MyMailer < ActionMailer::Base def signup_notification(recipient) recipients recipient.rhtml file) generates HTML and set the content type to html. so a sample view for our model example might look like this: Hi <%= @account. for example. • content_type: Specify the content type of the message. • headers: Specify additional headers to be set for the message. Defaults to text/plain. • bcc: Takes one or more email address. Sets the Cc: header. For example.rhtml would be used to generate the email. • recipients: Takes one or more email addresses. Sending HTML Mail To send mail as HTML. These addresses will receive a blind carbon copy of your email. the template at app/views/notifier/signup_notification. Sets the To: header. body "account" => recipient would result in an instance variable @account with the value of recipient being accessible in the view. headers ‘X-Mail-Count’ => 107370. The body method has special behavior. • sent_on: The date on which the message was sent. • cc:Takes one or more email addresses. To define a template to be used with a mailing. • subject: The subject of your email. make sure your view (the .email_address_with_name subject "New account information" body "account" => recipient from "system@example. the header wil be set by the delivery agent. These addresses will receive a carbon copy of your email. It takes a hash which generates an instance variable named after each key in the hash containing the value that the key points do. each mailer class has a corresponding view directory in which each method of the class looks for a template with its name.com" "New account information" "account" => recipient 162 Mailer methods have the following configuration methods available. Sets the From: header.rhtml file with the same name as the method in your mailer model. • from: Who the email you are sending is from. Sets the Bcc: header. Thanks for joining our service! Please check back often. e.name %>. Emails by default are sent in plain text. create an . Variables defined in the model are accessible as instance variables in the view.Ruby on Rails/Print version from subject body end end "system@example. So. in the mailer defined above. Mailer Views Like ActionController. Sets the Subject: header. These addresses are where your email will be delivered to. If not set. jpg") .text.com" attachment :content_type => "image/jpeg".com" part :content_type => "text/html". :body => File.Ruby on Rails/Print version end 163 Multipart Mail You can explicitly specify multipart messages: class ApplicationMailer < ActionMailer::Base def signup_notification(recipient) recipients recipient.rxml signup_notification.transfer_encoding = "base64" end end end Multipart messages can also be used implicitly because ActionMailer will automatically detect and use multipart templates where each template is named after the name of the action. followed by the content type.rhtml signup_notification. if the following templates existed: • • • • signup_notification.x-yaml.html. :account => recipient) p. :body => render_message("signup-as-html". For example.plain.text.text.email_address_with_name subject "New account information" from "system@example.xml.rhtml Each would be rendered and added as a separate part to the message.rhtml signup_notification. Attachments Attachments can be added by using the attachment method. :account => recipient) part "text/plain" do |p| p.read("an-image. The same body hash is passed to each template.body = render_message("signup-as-plain".text. Example: class ApplicationMailer < ActionMailer::Base # attachments def signup_notification(recipient) recipients recipient.email_address_with_name subject "New account information" from "system@example. with the corresponding content type. Each such detected template will be added as separate part to the message. e. set the password in this setting. like ActionMailer::Base. default_charset: The default charset used for the body and to encode the subject. Can be set to nil for no logging. @mime_version will be set to "1. "text/plain"]. This is a symbol and one of :plain. • :password If your mail server requires authentication. Most useful for unit and functional testing. you can change it. You can also pick a different content type from inside a method with @content_type. Defaults to "text/plain". • server_settings: Allows detailed configuration of the server: • :address Allows you to use a remote mail server. delivery_method: Defines a delivery method. Defaults to nil. and :test. • :user_name If your mail server requires authentication. perform_deliveries: Determines whether deliver_* methods are actually carried out. By default they are. :sendmail. Possible values are :smtp (default). You can also pick a different order from inside a method with @implicit_parts_order.template_root = "/my/templates" • template_root: template root determines the base from which template references will be made. • :authentication If your mail server requires authentication you need to specify the authentication type here. • • • • • • • • . deliveries: Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. "text/enriched". Compatible with both Ruby’s own Logger and Log4r loggers. • logger: the logger is used for generating information on the mailing run if available. but this can be turned off to help functional testing. :cram_md5 raise_delivery_errors: whether or not errors should be raised if the email fails to be delivered. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message.body = generate_your_pdf_here() end end end Configuration Options These options are specified on the class level. default_implicit_parts_order: When a message is built implicitly (i. Just change it from its default "localhost" setting. Sendmail is assumed to be present at "/usr/sbin/sendmail". You can also pick a different charset from inside a method with @charset. • :domain If you need to specify a HELO domain you can do it here. • :port On the off chance that your mail server doesn’t run on port 25.0" if it is not set inside a method. Defaults to UTF-8. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. :login. default_content_type: The default content type used for the main part of the message.Ruby on Rails/Print version 164 attachment "application/pdf" do |a| a. You can also pick a different value from inside a method with @mime_version. When multipart messages are in use. default_mime_version: The default mime version used for the message. set the username in this setting. Defaults to ["text/html". name]) ... pets = Pet. Creates the controller and creates a view for each action.find all records with a given field value.find all records matching a pattern. 0/ en/regexp. com/ doc/ refman/ 5. :conditions => ["owner_id = ?". mysql. :order => 'name') .creates the new database table. org/ classes/ ActiveRecord/Base.find(:all. . Note: Returns one object. [Note: OR also works. and _ for any single character. To escape a wild card use \% or \_. :conditions => ["name LIKE ?". vi test/unit/<Name>_test. vi db/migrate/XXX_create_<Name>.returns the first matching record. "Fido%"]) .find(:all. On the MySQL Regex website (http:/ / dev. pets = Pet. vi app/models/<Name>. rubyonrails. Check for no records found with: pets.rb Define the validations. Find The find method of ActiveRecord is documented in the Rails API manual (http:/ / api. :conditions => ["owner_id = ? AND name = ?".:conditions => supplies an SQL fragment used with WHERE *] pets = Pet. rake db:migrate Migrates the data level . Step By Step How to Add a New Table script/generate model <Name> Generate the empty model and migration file.rb Add columns to the table.rb Define the unit tests that exercises the model validations. The reference from MySQL (http:/ / dev. If there will be a controller (and views) associated with this Model: script/generate controller <Name> <action_one> <action_two> .html) you will find examples for using REGEX. html#operator_like) for LIKE will help. Wild cards are % for zero or more of any character. [Notes: 1.] pets = Pet.that is . mysql. :conditions => ["owner_id = ?". [Note: Returns one object. Returns an array of objects. etc. 2. sizes. 0/ en/ string-comparison-functions. owner_id. owner_id]) .find(:first. com/ doc/ refman/ 5.find all records matching multiple field values. owner_id]) .html#M001376) pet = Pet.empty?.Ruby on Rails/Print version 165 Examples This section is a collection of useful Rails examples.] pets = Pet.find(:all.find everything and sort result by name.find(pet_id) Find record by id (an integer).find(:all. . Note: Migration scripts are created by script/generate model <mod-name> Testing $ rake . sourceforge. the server is running in development mode.find(:all. :conditions => ["owner_id = ?".run grep. Clean Up $ rake log:clear .run one functional test. it will be accessible at web address: $ RAILS_ENV=test script/server . -exec grep 'hello' {} \.start the web server in Production Mode (more caching.to_s to convert it to a String. on every file in the tree starting with the current directory.tar up directory and compress it with gzip. :offset => 50.uses offset to skip the first 50 rows. -print . Shell Commands Certain useful shell commands that I'm always trying to remember: find . tar -cvzf archive. which test the controllers. 166 Rake Migrations $ rake db:migrate . $ script/server -e production .run all tests.start the web server in Test Mode.every Fixnum has method . $ test/functional/<name>_controller_test.find(:all.migrate to latest level by executing scripts in <app>/db/migrate. Fixing Errors can't convert Fixnum to String some_number.returns no more than the number of rows specified by :limit. searching for 'hello'.html.Ruby on Rails/Print version pets = Pet. html) for the application. net/ doc/ index. pets = Pet. $ rake test:functionals . Docs are placed at <app>/doc/app/index.to_s . etc. By default.start the web server for this app. :limit => 10.). By default. owner_id]) . Server $ script/server . which test the models. :limit => 10) .generate Ruby Docs (http:/ / rdoc.delete temporary files.run the functional tests.rb . $ script/server -e test .delete all logs.run the unit tests.tgz <targ_directory> . $ rake test:units . Documentation $ rake doc:app . $ rake tmp:clear .start the web server in Test Mode. com/) • Rails Wiki () • Rails Documentation () offers Rails support out of the box.com/) The official wiki for Rails.railslodge.com/) Very popular site with advanced and many in-sight video casts. Plugins • GITHub (. Rails itself is also hosted there. not yet complete. websites.com/) If you have problems wrapping your mind around some of the Ruby commands nad have experience in PHP.org/documentation) The official ROR site with everything you need to get started: guides.jetbrains.netbeans.All plattforms] • All-in-one IDE NetBeans (. Be sure to take a good look at them when searching for a specific plug-in or gem. Websites • Rails API Documentation (. Be sure to check this site out. but it gets better all the time • Ruby on Rails plugin directory (. including books.com/rails) comes with nice but complex Rails support.rubyonrails. weblogs and much more.yoyobrain. Support for many other languages and many plug-ins [Free . all Rake tasks are integrated into this IDE and you can easily switch between matching [Open Source and Commercial .com/search?q=rails) GITHub offers loads of plug-ins. this site will feel like heaven.Windows] • Open Source Development Suite Aptana () Highly featured editor with rather new Rails support [Commercial . Most of the most often used PHP functions are listed there with the proper Ruby/Ruby on Rails equivalent Books • Agile Web Development with Ruby on Rails Development Tools • Rails Editor ( on Rails/Print version 167 Other Resources There is a wide variety of documentation sources for Rails.All platforms] • Editor for Rails (. • popular Plugins (. [Commercial . look&feel and provides excellent Rails support. wikis and the very well documented API • Videocasts for Rails () Take at look at this list with pretty popular Rails plug-ins when searching for more common tasks A large portion of the power of Rails comes from the wide range of plugins which are available for download.com/) Are you jealous of the great editor used on Railscasts? Not working an a Mac? This is the program for you: features the same functionality.All Platforms] .org/features/ruby/index.com/) • Learning Ruby on Rails (. It offers great content and well presented videos! • Rails for PHP (. net/) If you want to work with eclipse. • Nuby on Rails () .freenode. get RadRails.com/) Insights into the framework from a core team member.sourceforge.com/) Centers on the web design aspects of rails. there are quite a few that are worth reading regularly. Mailing List The Ruby on Rails Talk mailing list is a good place to ask questions: RubyOnRails-Talk Mailing List (http:/ / groups. • Ryan's Scraps (. Please try to keep the signal-to-noise ratio at a minimum though: RubyOnRails IRC Channel (irc://irc. Note that the last update was submitted 2006.google.and if you know what you're looking for google can help you find them.Ruby on Rails/Print version • Rails and Eclipse (. 168 Weblogs Weblogs are one of the best ways to find out what you can do with rails .com/group/rubyonrails-talk) Freenode ROR Channel The Freenode IRC channel for Ruby on Rails is a good place to talk Rails with other developers. try Aptana. If you need an eclipse-like environment. Covers features that are new in edge. It is built upon the eclipse platform. That said. wikibooks. Yuuki Mayuki. Valters. Dysprosia. 31 anonymous edits Ruby Programming/ Syntax/ Classes Source: Contributors: Jguk.wikibooks. Withinfocus. Withinfocus. Jguk. Withinfocus.org/w/index. Marburg.php?oldid=1574811 Contributors: Adrignola. Yath.php?oldid=854422 Contributors: Briand. Geoffj.wikibooks.wikibooks.php?oldid=1539430 Contributors: Adrignola.wikibooks. Ramir. Bapabooiee. Fricky. Jordandanford.org/w/index.wikibooks.php?oldid=1721388 Contributors: BiT. 3 anonymous edits Ruby Programming/ Reference/ Objects/ Array Source:. 12 anonymous edits Ruby Programming/ RubyDoc Source: Contributors: Ramac.org/w/index. Huw. Withinfocus. Eddy264.php?oldid=1693384 Contributors: Adrignola. 11 anonymous edits Ruby Programming/ Strings Source:. Scientus. Formigarafa.org/w/index. Quilz.org/w/index.wikibooks. EvanCarroll Ruby Programming/ Reference/ Objects Source:. Yuuki Mayuki. Yuuki Mayuki. Mkn. Ravichandar84. Derbeth. Withinfocus.org/w/index. 10 anonymous edits Ruby Programming/ Data types Source:. Withinfocus .wikibooks.org/w/index.php?oldid=1619046 Contributors: Adrignola. Dmw.org/w/index. Jguk. Withinfocus. Valters. LuisParravicini. Jeffq. Srogers.wikibooks.php?oldid=1574785 Contributors: Adrignola. Valters. Eisel98 Ruby Programming/ Reference/ Objects/ FalseClass Source:. Vovk.org/w/index.org/w/index. Jguk. Withinfocus.php?oldid=1574781 Contributors: Adrignola. Shirock.org/w/index. 26 anonymous edits Ruby Programming/ Notation conventions Source:. 7 anonymous edits Ruby Programming/ Exceptions Source:. Pavan. 11 anonymous edits Ruby Programming/ Installing Ruby Source:. Orderud.wikibooks.php?oldid=1574780 Contributors: Adrignola.php?oldid=1488338 Contributors: Adrignola. HenryLi. Yath. Dasch. Panic2k4.php?oldid=1488339 Contributors: Adrignola. Withinfocus. Dallas1278.org/w/index. Briand. Keagan.rule.wikibooks. 11 anonymous edits Ruby Programming/ Writing methods Source:. Nbeyer.php?oldid=1676751 Contributors: Briand.org/w/index. 1 anonymous edits Ruby Programming/ Reference/ Objects/ Exception Source: Contributors: Briand. Joti.wikibooks. Jguk.org/w/index.wikibooks.org/w/index. Marburg. 6 anonymous edits Ruby Programming/ Syntax Source:. 1 anonymous edits Ruby Programming/ Reference/ Objects/ Numeric Source:. IanVaughan. Joti.wikibooks. Karvendhan. Georgesawyer. Damien Karras. QuiteUnusual. 15 anonymous edits Ruby Programming/ Syntax/ Literals Source:. Scopsowl. Jguk. Jedediah Smith. Jguk.php?oldid=1574782 Contributors: Adrignola. Yath. Eisel98 Ruby Programming/ Reference/ Objects/ Numeric/ Integer Source: Contributors: Adrignola. Gamache. Jguk.org/w/index.php?oldid=599024 Contributors: Briand Ruby Programming/ Interactive Ruby Source:. Supriya kunjeer. Sjc.php?oldid=1564234 Contributors: Briand. Θεόφιλε.Article Sources and Contributors 169 Article Sources and Contributors Ruby Programming Source: Contributors: Briand.wikibooks. Herraotic.wikibooks. Ghostzart.wikibooks. Darklama. Damien Karras Ruby Programming/ Here documents Source:. OinkOink. Effeietsanders. Iamunknown.wikibooks.org/w/index.wikibooks. Jim Mckeeth. Withinfocus. QuiteUnusual. 64 anonymous edits Ruby Programming/ Reference Source:. Scientes. IanVaughan.org/w/index. Oleander.wikibooks. Jguk. Withinfocus. 24 anonymous edits Ruby Programming/ Syntax/ Control Structures Source:. Withinfocus. Eisel98. 1 anonymous edits Ruby Programming/ Alternate quotes Source:. Damien Karras. Jguk. DavidCary. Withinfocus.php?oldid=1139096 Contributors: Jguk. Darklama. Withinfocus.php?oldid=1709548 Contributors: Adrignola. 7 anonymous edits Ruby Programming/ Ruby editors Source:. Rule. Hyad. Snyce. Eshafto. 3 anonymous edits Ruby Programming/ Object/ NilClass Source:. Derbeth.php?oldid=724569 Contributors: Briand. Jguk. Damien Karras. Raevel.org/w/index. Jedediah Smith. Krischik.wikibooks. Briand.php?oldid=566309 Contributors: Jguk.php?oldid=1488337 Contributors: Adrignola. 2 anonymous edits Ruby Programming/ Reference/ Predefined Variables Source:. Cspurrier. LuisParravicini. Jk33.org/w/index. 2 anonymous edits Ruby Programming/ ASCII Source:. Iron9light.wikibooks. Vanivk. Withinfocus.org/w/index. 25 anonymous edits Ruby Programming/ Syntax/ Method Calls Source:. Wantless.php?oldid=1093030 Contributors: Briand.wikibooks.org/w/index.php?oldid=1688425 Contributors: Briand.php?oldid=1651769 Contributors: Ahy1. Rdnk. 12 anonymous edits Ruby Programming/ Classes and objects Source:. Knudvaneeden. Withinfocus. Darklama. Withinfocus. Keagan.wikibooks.wikibooks. Sjc. 3 anonymous edits Ruby Programming/ Hello world Source:. Withinfocus. Dasch. Withinfocus. Briand.org/w/index.php?oldid=1488341 Contributors: Adrignola.org/w/index.php?oldid=1633193 Contributors: Adrignola. Mehryar.org/w/index.php?oldid=869201 Contributors: Briand.org/w/index.wikibooks.wikibooks. 1 anonymous edits Ruby Programming/ Reference/ Objects/ Regexp Source:. Withinfocus.wikibooks. Fhope. Ryepdx. Elizabeth Barnwell.wikibooks.derry. Kenfodder.php?oldid=1707069 Contributors: Adrignola. 25 anonymous edits Ruby Programming/ Syntax/ Operators Source:. Benjamin Meinl. Jguk. Damien Karras.org/w/index.wikibooks.wikibooks.org/w/index. Keagan. Marburg. Darklama. Yuuki Mayuki. Valters.php?oldid=1649985 Contributors: Briand.php?oldid=1738733 Contributors: Adrignola. 1 anonymous edits Ruby Programming/ Introduction to objects Source:. CAJDavidson. Withinfocus.org/w/index. Lhbts. Jguk.php?oldid=1574777 Contributors: Adrignola. Munificent. Withinfocus. Yuuki Mayuki. Mehryar. EvanCarroll. Keagan. Valters.org/w/index. Paul. Florian bravo. Krischik. Eisel98 Ruby Programming/ Reference/ Predefined Classes Source:. Sjc. Mehryar. 4 anonymous edits Ruby Programming/ Mailing List FAQ Source:. 1 anonymous edits Ruby Programming/ Syntax/ Lexicology Source:. Lhbts Ruby Programming/ Ruby basics Source:. Jguk.php?oldid=1467994 Contributors: IanVaughan. Darklama. Jguk. 3 anonymous edits Ruby Programming/ Unit testing Source:. RichardOnRails. Yath. 15 anonymous edits Ruby Programming/ Syntax/ Variables and Constants Source:. Valters.wikibooks. Jguk.php?oldid=1648307 Contributors: Adrignola.php?oldid=1706913 Contributors: Archaeometallurg.wikibooks.org/w/index. Jguk. Θεόφιλε.php?oldid=1679154 Contributors: Adrignola. Jguk. Jguk. Scientus.wikibooks.php?oldid=1550394 Contributors: Briand. RichardOnRails. Marburg. Mehryar. 60 anonymous edits Ruby Programming/ Overview Source:. Jguk.org/w/index. Damien Karras. Eisel98 Ruby Programming/ Reference/ Objects/ IO/ File/ File::Stat Source:. Gfranken.org/w/index. Stiang. Keagan. wikibooks.wikibooks. Withinfocus.wikibooks. Mehryar.php?oldid=1574809 Contributors: Adrignola.org/w/index. 1 anonymous edits Ruby Programming/ Reference/ Objects/ Symbol Source: Modules Source:. Rbidegain Ruby Programming/ GUI Toolkit Modules/ Qt4 Source: Sources and Contributors Ruby Programming/ Reference/ Objects/ String Source: Contributors: Adrignola. Eisel98 Ruby Programming/ Reference/ Built.wikibooks. Hagindaz. 1 anonymous edits Ruby Programming/ Reference/ Objects/ TrueClass Source: 170 .wikibooks.fhj. Jguk.org/w/index.wikibooks.org/w/index.php?oldid=1488333 Contributors: Adrignola. Darklama.wikibooks.php?oldid=1534235 Contributors: At.php?oldid=1617228 Contributors: Adrignola.php?oldid=1574807 Contributors: Adrignola.php?oldid=1488349 Contributors: Adrignola. Jguk.in Modules Source: Contributors: Adrignola. 4 anonymous edits Ruby Programming/ GUI Toolkit Modules/ GTK2 Source:. Withinfocus.php?oldid=1357476 Contributors: Eisel98. 3 anonymous edits Ruby Programming/ XML Processing/ REXML Source:. Yuuki Mayuki Ruby on Rails/ Print version Source: Contributors: Adrignola.php?oldid=1574805 Contributors: Adrignola. Mehryar Ruby Programming/ Built.org/w/index. 2 anonymous edits Ruby Programming/ GUI Toolkit Modules/ Tk Source:. 1 anonymous edits Ruby Programming/ Reference/ Objects/ Time Source:. php?title=File:Ruby_-_Introduction_to_objects_-_Orphaned_object.jpg Source: License: unknown Contributors: Briand Image:Mvc_rails. Licenses and Contributors 171 Image Sources.fhj.itm File:RoR_has_many_through.php?title=File:RoR_has_many_through.png License: unknown Contributors: Briand image:Ruby .org/w/index. modified object.org/w/index.wikibooks.itm File:RoR_diagram_associations.Introduction to objects .Image Sources.php?title=File:RoR_diagram_associations.itm .png License: unknown Contributors: Briand image:Ruby .wikibooks.fhj.jpg Source: to objects .php?title=File:Ruby_-_Introduction_to_objects_-_Two_variables.jpg Source: to objects .Orphaned object.php?title=File:25%.jpg License: Public Domain Contributors: At. Ruby Visual Identity Team File:25%.org/w/index.wikibooks.org/w/index.png License: unknown Contributors: Briand image:Ruby .org/w/index.wikibooks.itm File:RoR has one through.svg License: Public Domain Contributors: Karl Wick Image:Ruby .jpg License: Public Domain Contributors: At.Two variables.jpg License: Public Domain Contributors: At.org/w/index.php?title=File:Ruby_-_Introduction_to_objects_-_Two_variables.Introduction to objects .jpg Source: License: Creative Commons Attribution-Sharealike 2.png Source: License: unknown Contributors: Briand image:Ruby .wikibooks.wikibooks.wikibooks.Two variables.fhj.jpg License: Public Domain Contributors: At. Licenses and Contributors File:Ruby_logo.Variable reference.php?title=File:Ruby_-_Introduction_to_objects_-_Variable_reference.php?title=File:Ruby_-_Introduction_to_objects_-_Two_variables.wikibooks.svg Source: Source: Source: Source: Source:. two objects._modified_object.5 Contributors: Yukihiro Matsumoto.wikibooks.Two variables.wikibooks.php?title=File:RoR_has_one_through.png Source: to objects .wikibooks.php?title=File:Mvc_rails.php?title=File:Ruby_logo. org/ licenses/ by-sa/ 3.0 Unported http:/ / creativecommons. 0/ .License 172 License Creative Commons Attribution-Share Alike 3.
https://www.scribd.com/document/53300276/ruby-wikibook
CC-MAIN-2018-09
refinedweb
44,108
60.51
Deploying. Deploying a Rasa Open Source AssistantDeploying a Rasa Open Source Assistant While the above deployment methods involve deploying an assistant with Rasa X, the following instructions describe how to deploy a Rasa Open Source server only by using the Rasa Helm Chart in a scalable cluster environment using OpenShift or Kubernetes (K8S). Cluster RequirementsCluster Requirements To install the Rasa. note The Rasa Helm chart is open source and available in the helm-charts repository. Please create an issue in this repository if you discover bugs or have suggestions for improvements. Installation RequirementsInstallation Requirements Check that you have installed the Kubernetes or OpenShift command line interface (CLI). You can check this using the following command: kubectl version --short --client# The output should be similar to this# Client Version: v1.19.11 -.19.11# Server Version: v1.19.10 - Kubernetes - OpenShift If you get an error when executing the command, you are not connected to your cluster. To get the command to connect to the cluster please consult your cluster’s admin or the documentation of your cloud provider. Make sure you have the Helm CLI installed. To check this, run:helm version --short# The output should be similar to this# v3.6.0+g7f2df64 If this command leads to an error, please install the Helm CLI. In case you are using a version <3.5of Helm, please update to Helm version >=3.5. InstallationInstallation 1. Create Namespace1. Create Namespace We recommend installing Rasa Open Source in a separate namespace to avoid interfering with existing cluster deployments. To create a new namespace run the following command: - Kubernetes - OpenShift 2. Create Values File2. Create Values File Prepare an empty file called rasa-values.yml which will include all your custom configuration for the installation with Helm. All available values you can find in the Rasa helm chart repository. note The default configuration of the Rasa chart deploys a Rasa Open Source Server, downloads a model, and serves the downloaded model. Visit the Rasa helm chart repository to check out more examples of configuration. 3. Loading an initial model3. Loading an initial model The first time you install Rasa, you may not have a model server available yet, or you may want an lightweight model for testing the deployment. For this purpose, you can choose between training or downloading an initial model. By default, the Rasa chart downloads an example model from GitHub. To use this option, you don't have to change anything. If you want to define an existing model to download from a URL you define instead, update your rasa-values.yaml with the URL according to the following configuration: note The URL for the initial model download has to point to a tar.gz file and must not require authentication. If you want to train an initial model you can do this by setting the applicationSettings.trainInitialModel to true. It creates a init container that trains a model based on data located in the /app directory. If the /app directory is empty it creates a new project. You can find an example that shows how to download data files from a git repository and train an initial model in the Rasa helm charts examples. 4. Deploy Rasa Open Source Assistant4. Deploy Rasa Open Source Assistant Run the following commands: note OpenShift only: If the deployment fails and oc get events returns 1001 is not an allowed group spec.containers[0].securityContext.securityContext.runAsUser, re-run the installation command with the following values: Then wait until the deployment is ready. If you want to check on its status, the following command will block until the Rasa deployment is ready: - Kubernetes - OpenShift 5. Access Rasa Open Source Assistant5. Access Rasa Open Source Assistant By default the Rasa deployment is exposed via the rasa ( <release name>) service and accessible only within a Kubernetes cluster. You can get the IP address using this command: - Kubernetes - OpenShift You can then access the deployment on Visit the Rasa helm chart README to learn other ways to expose your deployment. Next StepsNext Steps Visit the Rasa helm chart repository where you can find examples of configuration and learn how to e.g. integrate your Rasa Open Source deployment with Rasa X.:3.1.1#:
https://rasa.com/docs/rasa/how-to-deploy/
CC-MAIN-2022-21
refinedweb
708
55.84
These are chat archives for FreeCodeCamp/HelpJavaScript Get help on our basic JavaScript and Algorithms Challenges. If you are posting code that is large use Gist - paste the link here. Programming is a side-effect of computer science I like that quote anthonygallina1 sends brownie points to @eeflores :sparkles: :thumbsup: :sparkles: bradtaniguchi sends brownie points to @eeflores :sparkles: :thumbsup: :sparkles: anthonygallina1 sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles: 'use strict'; (function (x) { return 'Aa~'; }); (function (x) { return x = 'Aa~'; }); because its MIME type ('text/html') is not a supported stylesheet MIME typeit's a css file but it says it's mime type is text/html, the same thing applies for javascript file it says it's text/html app.use(express.static(path.resolve("../../dist/"))); app.use(express.static(path.resolve("../../public/"))); it's more likely a different route is handling the request, maybe a * - @FlashHero add a console log statement in your route handlers similar to this: console.log(`[route] Route Handler - ${req.hostname + req.path}`) where [route] is changed to your actual route. This should at least tell you which route is attempting to serve the file <!DOCTYPE html> <html> <head> <title>Title</title> <meta http- <link href="style.css" rel="stylesheet"></head> <body> <div id="root"></div> <script type="text/javascript" src="bundle.js"></script></body> </html> hey guys, I know this is a basic problem but I've been puzzled onto how to do this (whatever I seem to do won't work), but how do I vertically center my twitter icon inside the button via css? path.resolve("../../dist/")and path.resolve("../../public/")and see if it actually resolved correctly app.use(express.static(path.join(__dirname, 'public'))) yarn run buildit builds the bundle.jsfile so when doing res.sendFile()isn't it suppose to point to the javascript and css without any problem because the files are updated and they're linked to html flashhero sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles: ╭─chris@host ~/testing/root/child/subchild ╰─$ node > const path = require('path') > path.resolve('../../') '/Users/chris/testing/root' > path.resolve('../../public') '/Users/chris/testing/root/public' > path.resolve('../dist') '/Users/chris/testing/root/child/dist' @Marmiz not sure, but here's my code if you want to take a look I wrote a ton and I still got a lot more to do for it before I feel satisfied with it lol @AmitP88 before I feel satisfied with it lol that's my point. You'll never feels satisfied. (welcome to software engineering 101) My suggestion is: don't loose focus. If your focus is just hobby, then you can take how long you want to . If your focus is learning, then acquire knowledge. I'm sorry if I come hard, but mind how many hours you are spending on each project, and don't get trapped in a swamp... @AmitP88 I acted as a potential emplyee. I clicked two buttons, see that works.... glanced at JS for like 30 seconds. And that's all. To me it's "ok". (not saying is perfect) but if your goal is acquire knowledge, and showcase that to external people, in my humble opinion your goal is reached ryanwfile sends brownie points to @adelmahjoub :sparkles: :thumbsup: :sparkles: a:visited { color: inherit; } a:hover, a:active { color:red; } Yes, I was thinking about that to be honest. I am still in beginner stage and tried to avoid experimenting. In general I have seen people using anchor tag. So wanted to know if I can solve the issue somehow. What if in future I have to deal with similar case? My goal is to make mobile apps using JS, React. Usually menus are made with anchor tag according to my knowledge. Therefore trying this approach. @sjames1958gm .status > p { cursor: pointer; } .status > p:hover { color: blue; } Enter the number in the input field To print "true" at Button's clicks, if the whole number is a square and "false", otherwise The square of natural numbers is 49 square, for example 7 * 7 = 49 For example, 46 is not the case, since we will not get any number multiplied by 46 var bnakan = document.getElementById("btn2").onclick=function(){ var z=document.getElementById("inp3").value if(Math.sqrt(z) % 1 == true){ bnakan=true }else{ bnakan=false } } console.log(bnakan) if(Math.sqrt(z) % 1 === 0)would test for being a perfect square Number.isInteger(Math.sqrt(z))this code reads better because you are saying you want the result to be an integer var bnakan = document.getElementById("btn2").onclick=function(){ var z=document.getElementById("inp3").value if(Number.isInteger(Math.sqrt(z))){ bnakan=true }else{ bnakan=false } console.log(bnakan) } 1mher1 sends brownie points to @masd925 and @sjames1958gm :sparkles: :thumbsup: :sparkles: @1Mher1 I don't see any value associated with the select. A simple <option value="monospace"> made it work for me There will be the following buttons: secondary ball - clicking on this button will display the dives above the secondary diagonal Secondary bottom - clicking on this button will display the dives below the secondary diagonal main top - clicking on this button will display the buttons above the main diagonal main bottom - clicking this button will display the dives below the main diagonal chess - when pressing this button, the dives will be chess-based when pressing these diverges, the gauge diagonal of the compressed diagonal and the same diagonal should be painted in color (x) => x[1] !== undefined, or with array destructuring ([_, x]) => x !== undefined document.getElementById('btn').onclick=function(){ var text = document.getElementById("txt").value var str = text.split(" "); var longest = 0; var word = null; for (var i = 0; i < str.length - 1; i++) { if (longest < str[i].length) { longest = str[i].length word = str[i] } } console.log(text) } textisn't that interesting. There are other variables that you might want to log. wordjust got global?) } document.getElementById('btn').onclick=function(){ var text = document.getElementById("txt").value var str = text.split(" "); var longest = 0; for (var i = 0; i < str.length-1; i++) { if (longest < str[i].length) { longest = str[i].length } } console.log(longest) } I'm referring to the code on codepen.) } (I did not remove semicola, they weren't in there, really ugly style) @1Mher1 Like oopsGlobal in @1Mher1 So something like document.getElementById("txt").value = document.getElementById("txt").value.split(" ").filter((word, index, array) => index === array.indexOf(word)).join(" "); ? @Blauelf like this document.getElementById("btn1").onclick=function(){ var text = document.getElementById("txt1").value var unique=''; for(var i=0; i<txt1.length; i++){ if(unique.indexOf(string[i])==-1){ unique += string[i]; } } console.log(unique) } BTW, please use semicola! They may be optional, but them being optional is one of the worst design flaws of JavaScript. It makes return { answer : 42 } and return { answer : 42 } mean completely different things. And they are both valid JavaScript. @1Mher1 You could still use my line, just adapted. unique = text.split("").filter((char, index, array) => index === array.indexOf(char)).join(""); :P if's condition) document.getElementById("btn1").onclick=function(){ var text = document.getElementById("txt1").value; var unique = text.split("").filter((char, index, array) => index === array.indexOf(char)).join(""); console.log(unique) } is that even legal?is that even legal? if( unique = text.split("").filter((char, index, array) => index === array.indexOf(char)).join("")) x = y = 0;which is the same as y = 0; x = 0;(yes, in that order, =is right-associative), just that the 0is evaluated only once. It is not the same as y = 0; x = y;, but that difference rarely matters either (it does with properties that don't behave like ordinary properties - the DOM API is full of those, like properties that allow assigning but don't change their value) @elia-russad My card counting solution var count = 0; function cc(card) { return (count += (card < 7) - !(card < 10)) + [" Hold", " Bet"][+(count > 0)]; } relies on that one, as += is just another assign operator (those are only a few weird parts of JavaScript, the reason why I'm very ambivalent about this language...) 10 < "a"is false, 10 > "a"is false, 10 == "a"is false. 10 < "10.0"is false, 10 > "10.0"is false, 10 == "10.0"is true 10 < "11"is true, 10 > "11"is false, 10 == "11"is false false, all of them, like ===does. ===then? the shallow comparison has its uses. <. I want at least some warning. Since I force-switched from Firefox 32 bit to 64 bit, my Firefox crashes take the whole system down (previously, it would die on consuming 3GB - now it can manage more, and dies when the computer is out of memory, probably crashing other programmes trying to allocate memory), so I'm not sure whether I want to complain about the Chrome crashes. Sometimes Chrome tabs crash without actually crashing, leaving them in a state you cannot recover unless you kill them in the Chrome Task Manager. That Microsoft abandoned IE is still a bit weird to me. I mean, Edge is available on Win10. Until 2020, many companies will still run Win7 (AKA Windows NT 6.1) on most of their machines. Which means many people are stuck on IE11 or use Firefox or Chrome (no Safari for Windows any more, but that one never worked that well) result = array1.filter((x) => { x[1] !== undefined; total=total+x[1]; }).reverse(); nei-v sends brownie points to @czhower :sparkles: :thumbsup: :sparkles: result = array1.filter((x) => ( x[1] !== undefined)? 1) Learn to use the browser debuggers. I dont know why so many courses skip this or save it for really late. 2) split up complex statements like this one so you can "see" it happen in stages. When it all works, you can compact it down again if you want: ``` newarray1.push(array1[x].charAt(0).toUpperCase()+array1[x].slice(1)); nei-v sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles: nei-v sends brownie points to @kudzu and @blauelf :sparkles: :thumbsup: :sparkles: ISNULLinstead of COALESCE? I think both names are weird. ISNULLthe other day...wouldn't work how I wanted..so switched to COALESCEand it worked like a champ..but ya kind of odd names COALESCEwill return the first non- NULLvalue with its type. ISNULLwill convert it to the type of the first argument. COALESCEsolves the problem... COALESCEanyhow.. its a SQL standard I believe, where as ISNULLis T-SQL specific RecipeModalcomponent, right? isaaknazar sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles: enterkey and savebutton until the condition is false? Part of the reason so many Jamaicans here is that Jamaica is worse than many other Caribbean nations for taxes and many other things so they move here and to other Caribbean island if they dont go US... Many if not most of the doctors here are either Cuban or Jamaican... And software devs.. well no Caribbean places is attractive for a variety of reasons from taxes, to unreliable internet, unreliable electric and more... cmccormack sends brownie points to @tiagocorreiaalmeida and @jluboff :sparkles: :thumbsup: :sparkles: User Story: As an unauthenticated or authenticated user, I can see and vote on everyone's polls. // Initialize Passport and enable persistent login sessions stored in mongodb const sessionOptions = { secret: 'cmccormack-voting-app-or-is-it?', resave: false, saveUninitialized: true, cookie: { secure: false }, store: new MongoStore({ mongooseConnection: db }) // <= this little guy right here? } app.use(session(sessionOptions)) cmccormack sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles: User Story: As an unauthenticated or authenticated user, I can see and vote on everyone's polls. hey guys, I've ported my local weather app over to github and am working on it locally. However, I've noticed that on my gh-pages link that it takes a long time for the location and weather data to show up on the page, even after allowing the browser to track my location demo: repo: [Violation] Only request geolocation information in response to a user gesture. console.time() navigatorin Chrome. When I did my weather app I had to fake my geolocation when testing hi all what is the base url to check for Twitchtv Streams? I have this freecodecamp but I keep getting errors tundeiness sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles: [[][[]]+[]][+[]][++[+[]][+[]]] dbsimeonov sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles: I know its simple but what do you think? Just got motivated and pissed from js learning curve and finally made something from scratch for 20m :D .unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; cursor: default; }
https://gitter.im/FreeCodeCamp/HelpJavaScript/archives/2018/04/06
CC-MAIN-2019-35
refinedweb
2,089
57.27
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. On Tue, 30 Sep 2003 17:37:53 -0400, Daniel Jacobowitz <drow@mvista.com> said:Yeah, i did it differently later on.On Tue, Sep 30, 2003 at 03:41:48PM -0400, Daniel Berlin wrote:On Sep 30, 2003, at 3:37 PM, David Carlton wrote: It would be nice if the support for DW_TAG_namespace went into GCC 3.4. It's unlikely that I'll have the time or energy to do this, but i can provide help to anyone who wants to try. If one of you will figure out who has the newest version and send it to me, I'll give it a shot. I've just attached what I've been using to bug 11114. It's not the best patch in the world - its way of detecting anonymous namespaces is gross - but it seems to work. I don't know the status of Daniel's patches: the patch I attached is an early patch of his + anonymous namespace fix + context die fix, but I know he's updated his patch since then. David Carlton carlton@kealia.com
http://gcc.gnu.org/ml/gcc/2003-10/msg00001.html
CC-MAIN-2017-09
refinedweb
200
80.72
As I've come into the TLE situation when submitting to the server, I then started to make the code to be inside the TL. And some observations have been made. - when the first two lines: if s == s[::-1]: return len(s) were deleted, it stuck at the "aaaa...aaaa" case. And I think the infamous case 'fff...ggg...ggg" case won't be affected with or without these two lines. Is that TRUE??? def longestPalindromeSubseq(self, s): if s == s[::-1]: return len(s) n = len(s) r = [[0 for _ in xrange(n)] for _ in xrange(n)] for i in xrange(n-1, -1, -1): r[i][i] = 1 for j in xrange(i+1, n): r[i][j] = 2 + r[i+1][j-1] if s[i] == s[j] else max(r[i+1][j], r[i][j-1]) return r[0][n-1]
https://discuss.leetcode.com/user/mpan753
CC-MAIN-2017-51
refinedweb
149
80.62
I have some form and button to save it. The button must only be enabled when there are unsaved changes (inputs) on the form. <form> <div> ... (inputs) <span (click)="save()"> Save </span> </div> </form> Is there some build-in mechanism for form dirty check in Angular 5? What is the easiest way to implement this scenario ? Yes there is: I highly advise you to take a look at the documentation of reactive forms. Apart from that, the built-in mechanism is only for checking the state of the form: touchedmeans the user has entered the form dirty/ !pristinemeans the user has made a modification But if you want to handle changes made, you should not use that: if your username changes its username from "foo", to "bar", then back to "foo", there is no changes in your form, so the user should not have to send the said form. Instead, what I advise you is to make a function that compares the form to the original value of your object. Here is how you can do it: // Creates a reference of your initial value createReference(obj: any) { this.reference = Object.assign({}, obj); } // Returns true if the user has changed the value in the form isDifferent(obj: any, prop: string) { return this.reference[prop] !== obj[prop]; } submitForm(form: any) { // ... Business code ... hasChanges = false; for (let prop in form) { if (this.isDifferent(form, prop)) { hasChanges = true; } } // If no changes, cancel form submition if (!hasChanges) { return; } } When you are working with reactive forms (), there is a property pristine and a property dirty on the form-group and the control. Should look similar to this: <form form- <div> <input type="text" formControlName="ctrl1"> ... (further inputs) <span><button (click)="save()" [disabled]="myGroup.pristine"> Save </button></span> </div> </form> and the .ts file: import { Component, .... } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({...}) export class YourFancyComponent { myGroup: FormGroup; constructor(private( formBuilder: FormBuilder) { this.myGroup = this.formBuilder.group({ 'ctrl1': 'defValue', 'ctrl2': 'defaultValue2' }); } } For template-driven forms (according to) the css class of the modified input control changes from ng-pristine to ng-dirty but that doesn't help with the save button.
https://javascriptinfo.com/view/156902/angular-5-form-dirty-check-duplicate
CC-MAIN-2021-17
refinedweb
357
55.74
QuickSort in Java QuickSort is a popular sorting algorithm that uses the Divide and Conquer paradigm to sort an array. QuickSort, just like Merge Sort, has an average time complexity of O(N log N), but its performance can deteriorate in worst-case scenarios. In this tutorial, we will learn the QuickSort algorithm and implement it in Java. QuickSort Algorithm - As discussed above, the QuickSort algorithm uses Divide and Conquer approach to sort an array. - The QuickSort algorithm begins by choosing a pivot element. We need to put this pivot element at its correct position. - But it doesn't end there. We also need to put all the elements smaller than the pivot to the left of the pivot element, and all the elements greater than the pivot should be placed on its right. - Our problem is now divided into two smaller subproblems and we also have one element of the array in its correct position. Now, we just need to recursively repeat this on the elements to the left of the pivot and the elements on the right half of the array. Let's try to understand the above approach with the help of an example. Suppose we have to sort the following array - [5, 10, 7, 1, 2, 11, 25, 6] and element six is chosen as the pivot. We will use a pointer that is initially set to -1. All array elements to the left of this pointer(including the element present at the pointer) should be smaller than our pivot. We will iterate through the entire array and whenever we encounter an element smaller than the pivot, we will increment our pointer and place this smaller element at that position. The following steps explain the partitioning process. The iteration starts with the first element of the array, which is 5. This is less than the pivot and so we will update the pointer value and put this element at that index. - The next element is 10, and it is not smaller than 6, so we will simply move to the next element. - 7 is also greater than 6, so we will move on. - The next element is 1, which is smaller than 6. We will increment our pointer and swap the element present at that position with element 1. - The next element is 2, which is again smaller than 6, so we will increment the pointer, and swap the values. - The next elements are 11, and 25, which are greater than 6, so we won't change anything. - The loop terminates and we will once again increment our pointer and will put the pivot at this position. Importance of Pivot Element - The pivot element plays a crucial role in determining the efficiency of the QuickSort algorithm. For best efficiency, the pivot element should divide the array into equal halves. But looking for such elements in the array can add up to the time complexity. - The worst-case scenario is when the pivot is always chosen as the smallest or the largest element of the array. In these cases, the array will not be divided at all, because all the remaining elements will either be greater than the pivot or smaller than the pivot. - Most of the implementations of QuickSort will either choose the first element or the last element as the pivot. A major drawback of this approach is that if the array is already sorted, then we are always choosing the smallest or the largest element of the array. - A common method used to solve this problem is to randomly choose a pivot. This will significantly reduce the chances of getting the smallest or the largest element in each iteration. QuickSort Implementation in Java We will use two methods to implement QuickSort. One method is responsible for choosing a pivot and placing it in its correct position and it will also split the array into two halves of smaller and greater elements. We will call this the partition() method. public static int partition(int[] arrToSort, int leftIdx, int rightIdx) { int i = leftIdx - 1; int pivot = arrToSort[rightIdx];//the rightmost element is chosen as the pivot for(int j = leftIdx; j < rightIdx; j++) { //if current element is smaller than pivot then add it to the left half if(arrToSort[j] < pivot) { i += 1; int temp = arrToSort[j]; arrToSort[j] = arrToSort[i]; arrToSort[i] = temp; } } //add pivot element at its correct position int temp = arrToSort[i + 1]; arrToSort[i + 1] = pivot; arrToSort[rightIdx] = temp; //return the sorted position of the pivot element return i + 1; } The other method will be called quicksort() and it will be responsible for recursive calls. public static void quickSort(int[] arrToSort, int leftIdx, int rightIdx) { if(leftIdx >= rightIdx)//array contains less than 2 elements return; int partitionIdx = partition(arrToSort, leftIdx, rightIdx);//getting the index of the pivot quickSort(arrToSort, leftIdx, partitionIdx - 1);//sorting the array to the left of pivot quickSort(arrToSort, partitionIdx + 1, rightIdx);//sorting the array to the right of pivot } Let's check if our code works correctly and gives the desired output. import java.util.Arrays; public class QuickSortDemo { public static void main(String[] args) { int[] arr1 = {7, 9, 1, 2, 10, 15, 6}; int[] arr2 = {1, 2, 3, 4, 5, 6, 7, 8}; int[] arr3 = {1}; int[] arr4 = {-5, 2,-1, 0, 11, 20, -20}; quickSort(arr1, 0, arr1.length - 1); quickSort(arr2, 0, arr2.length - 1); quickSort(arr3, 0, arr3.length - 1); quickSort(arr4, 0, arr4.length - 1); System.out.println(Arrays.toString(arr1)); System.out.println(Arrays.toString(arr2)); System.out.println(Arrays.toString(arr3)); System.out.println(Arrays.toString(arr4)); } } [1, 2, 6, 7, 9, 10, 15] [1, 2, 3, 4, 5, 6, 7, 8] [1] [-20, -5, -1, 0, 2, 11, 20] Time and Space Complexity As discussed in the previous sections, QuickSort's efficiency is determined by the choice of the pivot element. The best-case and the average-case time complexity is O(NLogN), where N is the length of the input array. However, in the worst-case scenario, the time complexity can go up to O(N^2). QuickSort is an in-place algorithm, which means it uses constant space. So space complexity of QuickSort is O(1). Summary QuickSort is an efficient sorting algorithm that can be very useful for sorting large amounts of data. The QuickSort algorithm works by choosing a pivot element and placing it in its correct position. It also places all the smaller elements to the left of the pivot and all the larger elements to its right. The choice of the pivot can affect the overall complexity of this algorithm, but randomly choosing a pivot will mostly give the optimal complexity.
https://www.studytonight.com/java-examples/quicksort-in-java
CC-MAIN-2022-05
refinedweb
1,117
51.48
Hey, I am using a particle photon. I want to generate an output which is in the form of a sine function. It’s not a pure sinewave, but a function of sine and cosine. Right now I am using the analog write feature of zerynth. I tried it with analogWrite(), But I am not getting what I exactly need. Also, Can I use FFT to generate the output ? import gpio import dac import streams import adc import math buf = bytearray(100) for i in range(len(buf)): buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf))) myDAC = dac.DAC(D8.DAC) myDAC.start() myDAC.write(buf,400*len(buf),MILLIS,circular=True) I tried importing the cosine and sine libraries using, from math import sin But that didn’t work either.
https://community.zerynth.com/t/producing-sinewave-output-on-photon/2429
CC-MAIN-2019-35
refinedweb
136
67.15
On Fri, 2004-03-12 at 16:28, bonzini wrote: > The patch is as big as it is boring. Most of it is about renaming > _LT_AC_TAGVAR to LT_TAGVAR so that it is in the public namespace. Hope > the ChangeLog helps. > I've actually been aiming for (with my own patch) something like: LT_TAG -- create a new tag by copying an old one LT_TAG_SET -- set a tag value LT_TAG_VALUE -- get a tag value For a public interface, which has a few more safety checks than the non-public one. I really am going to post it soon, honest :-) Scott -- Have you ever, ever felt like this? Had strange things happen? Are you going round the twist? signature.asc Description: This is a digitally signed message part
https://lists.gnu.org/archive/html/libtool-patches/2004-03/msg00034.html
CC-MAIN-2022-40
refinedweb
125
73.27
Hi Every Body Is there any web part that can be used to explore files on a File Server from the SharePoint Portal site with a proper explorer view and not like not like Page Viewer web part. Thanks rocky Not out of the box there isn't (not that I know of). If you want to build one yourself it should be pretty easy, using one of two methods: 1) You can use the System.IO namespace to iterate through directories and display file information. 2) You could define a network path as a Search Content Source, and then use the search API to get the file information easily. If you wanted a fully functional explorer view I would probably go with the first one though. The only major problems you are going to hit are security permissions. I'll leave you to work that one out though Hi Thanks for the tips. Because of time constraint, I was looking for an out of the box solution. Anyway let me pull my sleeve to get on to coding Thaks again Regards, Rocky
https://social.technet.microsoft.com/Forums/office/en-US/09cf04b2-9e2d-43f9-a8ae-646d6583e439/network-file-share?forum=sharepointdevelopmentlegacy
CC-MAIN-2020-10
refinedweb
183
78.59
hello i have a cisco router which i use over a dsl connection, i have a dhcp enabled in this router: ip dhcp pool LAN import all network 192.168.1.0 255.255.255.0 default-router 192.168.1.1 but for some reason i cant get dns servers on my clients interface Dialer0 ip address negotiated ip nat outside ip virtual-reassembly encapsulation ppp dialer pool 1 dialer-group 1 ppp pap sent-username user password 7 XXX i want the clients to recieve dns servers via ISP, am i missing something here? Use this command to troubleshoot the DHCP problem. show ip dhcp import
https://supportforums.cisco.com/t5/network-management/a-dhcp-quot-import-all-quot-problem/td-p/1217869
CC-MAIN-2018-05
refinedweb
108
60.65
import "gopkg.in/src-d/go-git.v4/plumbing/format/objfile" Package objfile implements encoding and decoding of object files. doc.go reader.go writer.go var ( ErrClosed = errors.New("objfile: already closed") ErrHeader = errors.New("objfile: invalid header") ErrNegativeSize = errors.New("objfile: negative object size") ) Reader reads and decodes compressed objfile data from a provided io.Reader. Reader implements io.ReadCloser. Close should be called when finished with the Reader. Close will not close the underlying io.Reader. NewReader returns a new Reader reading from r. Close releases any resources consumed by the Reader. Calling Close does not close the wrapped io.Reader originally passed to NewReader. Hash returns the hash of the object data stream that has been read so far. Header reads the type and the size of object, and prepares the reader for read Read reads len(p) bytes into p from the object data stream. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If Read encounters the end of the data stream it will return err == io.EOF, either in the current call if n > 0 or in a subsequent call. Writer writes and encodes data in compressed objfile format to a provided io.Writer. Close should be called when finished with the Writer. Close will not close the underlying io.Writer. NewWriter returns a new Writer writing to w. The returned Writer implements io.WriteCloser. Close should be called when finished with the Writer. Close will not close the underlying io.Writer. Close releases any resources consumed by the Writer. Calling Close does not close the wrapped io.Writer originally passed to NewWriter. Hash returns the hash of the object data stream that has been written so far. It can be called before or after Close. Write writes the object's contents. Write returns the error ErrOverflow if more than size bytes are written after WriteHeader. WriteHeader writes the type and the size and prepares to accept the object's contents. If an invalid t is provided, plumbing.ErrInvalidType is returned. If a negative size is provided, ErrNegativeSize is returned. Package objfile imports 6 packages (graph) and is imported by 17 packages. Updated 2019-08-01. Refresh now. Tools for package owners.
https://godoc.org/gopkg.in/src-d/go-git.v4/plumbing/format/objfile
CC-MAIN-2020-10
refinedweb
394
61.93
I want to have different mounts that are seen only by a specific process or user. One use case I am thinking about is when I want to mount a unionfs or aufs that will be available for one user. So I can have multiple mounts on the same mount point that are different for different users. - 1I don't care to look it up right now, but I think the pam_namespace can do this...also something with cgroups should be possible but I haven't done this yet. – Martin M. Nov 3 '11 at 22:22 - Based on your answer I've found an article about mount namespaces: ibm.com/developerworks/linux/library/l-mount-namespaces/… and the man page: manpages.ubuntu.com/manpages/hardy/man8/pam_namespace.8.html – Mircea Vutcovici Nov 4 '11 at 13:30 - I don't consider that info much of an answer. But If you provide some outline on how to do it I'll upvote yours. Answering your own question seems perfectly fine to me (and I still don't have to look it up) :) – Martin M. Nov 9 '11 at 14:00 Here is how to enable per user mount namespaces in Ubuntu 12.10 using pam_namespace: Edit /etc/security/namespace.conf Uncomment the last lines. For safety, add your current user to the list of exclusions. /tmp /tmp-inst/ level root,adm,myuser /var/tmp /var/tmp/tmp-inst/ level root,adm,myuser Edit /etc/security/namespace.init and change #!/bin/sh -p to #!/bin/bash --noprofile or to #!/bin/sh This is because sh is actually dash. For testing edit /etc/pam.d/su and append at the end of file: session required pam_namespace.so Test on a test user: su - testuser As test user run: echo diff '<(sort /proc/'$$'/mounts) <(sort /proc/mounts)' This will generate a command like: diff <(sort /proc/31987/mounts) <(sort /proc/mounts) Run the generated diff from test user shell and from root. From the test user you will have no output, but from the root you will see something like: 4,7d3 < /dev/sda1 /tmp ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 < /dev/sda1 /tmp/tmp-inst ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 < /dev/sda1 /var/tmp ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 < /dev/sda1 /var/tmp/tmp-inst ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 The test_user /tmp folder will be mapped as /tmp/tmp-inst/test_user and it will be accessible only to this user. Why not just mount at ~/specificmountpoint. Set the permissions accordingly. Every user will have the same (almost) mout point. It looks like nowadays it's possible: - You should create new User Namespace, which gives your process root permissions and all capabilities (only inside that namespace). - You should create new Mount Namespace, to isolate mounts inside your namespace from global mounts. - Mount what you need. - Drop privileges back to normal user and run your application. At least, in theory. Check this article for more details:
https://serverfault.com/questions/327572/how-can-i-mount-in-linux-a-filesystem-for-one-process-or-user-only
CC-MAIN-2020-16
refinedweb
512
66.64
Behave HTTP steps Project description A Python package for HTTP-service testing. Contains reusable steps for Behave BDD (behaviour-driven development) tool. It’s mostly useful for testing REST APIs and interacting with JSON data over HTTP. Usage yourapp/features/environment.py: from behave_http.environment import before_scenario yourapp/features/steps/some_http_stuff.py: from behave_http.steps import * (You can mix them with your own steps in the same file.) yourapp/features/some_api.feature: Feature: Some API As an API client I want to be able to manage activities and sessions Background: Set server name, headers and reset test user's database Given I am using server "$SERVER" And I set base URL to "$URL" And I set "Accept" header to "application/json" And I set "Content-Type" header to "application/json" And I set BasicAuth username to "t@example.com" and password to "t" Scenario: Ensure account exists When I make a GET request to "account" Then the response status should be 200 If your test target is you can test it with: SERVER= URL=api behave General rules on using quoted "values" in feature files: - JSONs and numbers (response code, array length) must appear as is. - Other substitutes must be quoted (variable names, headers and their values). While there is no extensive documentation the features (self tests) directory contains (a hopefully complete) set of usage examples. Testing for nested JSON content with non-ASCII characters in paths is not supported by the underlying ``jpath`` library. Development To install essential packages for the test suite: pip install -r requirements_dev.txt A complete list of development tools used in the Makefile can be installed with: pip install coveralls docutils flake8 tox wheel Running tests Launch a special HTTP server responding to test requests: python testserver.py Then run feature tests in a separate shell: make test-all # runs on every supported python version with tox make test # runs in current python environment only Environment variables Set TEST_SERVER to full URL (including schema) if default port (55080) on localhost is already used by another process. For example: export TEST_SERVER= python testserver.py >testserver.log 2>&1 & make test-coverage Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/behave-http/
CC-MAIN-2019-04
refinedweb
383
51.58
Hi - I'm back again with a few questions on your sample code above. In the Student class and again in the Storage constructor I notice you have used the variable numStudents. Am I assuming correctly that this hasn't been initialised anywhere because it is sample code? In the Storage class and the storeStudent method you are passing a parameter called Student studentObject. Could you elaborate on this for me? If studentObject is a variable this has also not been declared anywhere. Again, is this because it is sample code? I also notice you have used the following: /** *@param args the command line arguments */ I am assuming this is comments only? In the public class TestStudent at the end, the first line in the for statement you use: Student output = store.retrieveStudent(i); I understand that retrieveStudent is a method in the Storage class, was store meant to be Storage then? Thanking you again Storage.storeStudent(StorageTest.java:127)
http://www.coderanch.com/t/397532/java/java/Arrays-Calling-input-methods-classes
CC-MAIN-2015-18
refinedweb
160
65.93
React Component Life Cycle React Component Life Cycle Components make the React world go 'round. Read on to get a great overview of the most useful components, and how to apply them to your app. Join the DZone community and get the full member experience.Join For Free All React components go through a lifecycle which enables you to perform a specific task at any specific time. In order to achieve that, you can override the lifecycle methods. Methods prefixed with will are called right before something occurs (events), and methods prefixed with did are called right after something occurs. Let us understand all the functions in all the phases of the lifecycle: Setup Props and State ( constructor(props)) Constructors are a basic building block of OOP. It is the first function which will be called whenever a new object is created, even if it is called before the component is mounted. One thing that should be noted is that before any lines of a statement, you should call super(props) in order to use this.props. It will call the constructor of the parent in order to make "props" available to our constructor. This is also the only place where you are expected to change/set the state by directly overwriting the this.state fields. In all other instances, remember to use this.setState. componentWillMount ( componentWillMount()) This is deprecated. It is not that much different from the constructor. It is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger extra rendering. But it is recommended to use a constructor for the same purpose. render ( render()) Among all the React functions, render() is the most famous. We create elements (generally via JSX) and return them. We access the component via this.props and this.state and these values tell us about how content should be generated. Any changes we made during componentWillMount() are fully applied to this.state. render() must not allow the modification of the component state. It returns the same result each time it’s invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in other lifecycle methods. componentDidMount ( componentDidMount()) componentDidMount() is invoked just after the mounting of a component. Statements that require the DOM, i.e. which need the UI to be rendered, should be kept here. Don't use setState() in this method, as it will trigger extra rendering. Though the user will not see the extra rendering, it will cause performance issues. componentWillReceiveProps ( componentWillReceiveProps(nextProps)) This is deprecated. componentWillReceiveProps() is invoked before a component receives new props. In this method, you can compare the previous props with the newer one and, based on what you find, you can change the state and make other updates accordingly. Calling this.setState()doesn’t trigger componentWillReceiveProps(). shouldComponentUpdate ( shouldComponentUpdate(nextProps, nextState)) This can be used to let React know if a component’s output is affected by the current change in state or props. Talking about the default behavior of this function, it will re-render on every state change. This method is not called for the initial render. If this method returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked. It is not recommended to do deep checks or use JSON.stringify() in shouldComponentUpdate(). It will badly degrade the performance. componentWillUpdate ( componentWillUpdate(nextProps, nextState)) This method is invoked just before rendering when new props or states are being received. This method is not called for the initial render. You can do the stuff required before the update occurs. This method is only invoked if shouldComponentUpdate() is invoked. componentDidUpdate ( componentDidUpdate(prevProps, prevState, snapshot)) This method is invoked just after an update occurs. This method is not called for the initial render. Statements that requires the DOM, i.e. those that are needed after the UI is updated, should be kept here. It is the place where you can perform server calls after comparing current and previous props. componentWillUnmount ( componentWillUnmount()) This is the method which is invoked immediately before a component is unmounted and destroyed. You can write the statements to clean up any resource. We can understand it with the help of an example. Here we are setting the initial state inside of the constructor. setDigit is used to update the state. App.js import React from 'react'; import Content from './Content'; class App extends React.Component { constructor(props) { super(props); this.state = { myDigit: 0 } this.setDigit = this.setNewNumber.bind(this) }; setNewNumber() { this.setState({myDigit: this.state.myDigit + 1}) } render() { return ( <div> <button onClick = {this.setDigit}>INCREMENT</button> <Content sentDigit = {this.state.data}></Content> </div> ); } } export default App; Content.js import React from 'react' class Content extends React.Component { componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') }!') } render() { return ( <div> <h1>{this.props.sentDigit}</h1> </div> ); } } export default Content Main.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app')); setTimeout(() => { ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 5000); After the initial rendering, the screen will show: And the console will contain the following: Component WILL MOUNT! Component DID MOUNT! After clicking the INCREMENT button, the update will call other lifecycle methods. Component WILL RECEIVE PROPS! Component WILL UPDATE! Component DID UPDATE! And after 5 seconds, the component will unmount and the log will show: Component WILL UNMOUNT! Published at DZone with permission of Ankit Kumar . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/react-component-lifecycle?fromrel=true
CC-MAIN-2019-35
refinedweb
940
52.26
Nearly Orthogonal Latin Hypercube Generator This library allows to generate Nearly Orthogonal Latin Hypercubes (NOLH) according to Cioppa (2007) and De Rainville et al. (2012) and reference therein. Installation Clone the repository $ git clone and from the cloned directory type $ python setup.py install PyNOLH requires Numpy. Usage The library contains a single generator and a function to retrieve the necessary parameters from a desired dimensionality. To generate a 6 dimension NOLH from the indentity permutation: import pynolh dim = 6 m, q, r = pynolh.params(dim) conf = range(q) remove = range(dim - r, dim) nolh = pynolh.nolh(conf, remove) The NOLH returned is a numpy array with one row being one sample. You can also produce a NOLH from a random permutation configuration vector and remove random columns: import pynolh import random dim = 6 m, q, r = pynolh.params(dim) conf = random.sample(range(q), q) remove = random.sample(range(q), r) nolh = pynolh.nolh(conf, remove) The nolh() function accepts configurations with either numbers in [0 q-1] or [1 q]. import pynolh dim = 6 m, q, r = pynolh.params(dim) conf = range(1, q + 1) remove = range(dim - r + 1, dim + 1) nolh = pynolh.nolh(conf, remove) Some prebuilt configurations are given within the library. The CONF module attribute is a dictionary with the dimension as key and a configuration, columns to remove pair as value. import pynolh conf, remove = pynolh.CONF[6] nolh = pynolh.nolh(conf, remove) The configurations for dimensions 2 to 7 are from Cioppa (2007) and 8 to 29 are from De Rainville et al. 2012. Configuration Repository See the Quasi Random Sequences Repository for more configurations. References Cioppa, T. M., & Lucas, T. W. (2007). Efficient nearly orthogonal and space-filling Latin hypercubes. Technometrics, 49(1). De Rainville, F.-M., Gagné, C., Teytaud, O., & Laurendeau, D. (2012). Evolutionary optimization of low-discrepancy sequences. ACM Transactions on Modeling and Computer Simulation (TOMACS), 22(2), 9. Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pynolh/
CC-MAIN-2017-39
refinedweb
341
51.85
J2EE Security 66 What is J2EE Security?J2EE Security covers a very wide range of techniques and mechanisms: Access control based on permissions and authentication of identity; encryption of data passing in or out of an application; and validation of presented credentials. These are the big things: needless to say, there are levels of detail below each of these three. What do I know about J2EE Security?More than I did when I started reading this book! In my experience, security is either bolted on at the last minute or badly implemented using home-grown techniques. As one who has seen or tried both of these approaches, I was determined to seek out the better way, so when the chance to review this book came along I jumped at it. OverviewThe first section, with chapter one and two, is "The Background." Chapter one is a security primer and should be old hat to most of the readership of Slashdot. Chapter two is a tour of the Java language strictly from a security perspective. This is interesting and very informative, even for a long-time Java programmer like me. The second section is "The Technology," and includes chapters three through seven. Chapter three is a discussion of cryptography with Java and would have been worth the price of the whole book for me if (I hadn't have gotten it for free as a review copy)! :-) Chapter four covers PKI (Public Key Infrastructure) with Java. Managing certificates is explained as well as the steps necessary to issue and revoke your own. Chapter five is a discussion of access control. Access control in Java is available based on the origin of the code (the applet effect), the signer of the code or the logged-in user. Chapter six concerns securing the wire. This is the use of encryption for the transmission channel, SSL in a web browser being the most obvious example, where everything served over HTTPS is encrypted. Chapter seven secures the message. This covers message encryption for those times in life where you have to use a non-encrypted transfer medium as well as techniques for authentication, so that the message you do send can be guaranteed to be authentic and provably from you. The third section is "The Application." Chapter eight discusses the security aspects of RMI based applications, especially using the Java security managers. Chapter nine reviews web application security using both declarative and programmatic security, giving examples using Apache Tomcat.Chapter ten discusses EJB security, including JNDI-based client authentication, SSL and declarative access control. Chapter eleven talks about the security issues associated with web services using the Apache Axis tool to illustrate the points. Chapter twelve is a wrap up of the whole book. What's To LikeThe book is logically divided into chapters on each of the main aspects of security that apply to J2EE. These chapters are then located within three sections: background, technology and application. This sequence worked nicely for me, each chapter getting more detailed. This way I knew how deep I was by how far into the book I'd gotten. The main thing that struck me about this book was that it was designed to be practical. Mr. Kumar not only explains his point and gives you example source code, but he has written a freely available security toolkit, to demonstrate each of the points he makes. The Java Security Tool Kit (JSTK) is a very nice addition to the book's text. Being able to try out the concept being explained really helps. This approach takes example code to another level and I hope other authors will take note. What's To ConsiderThere is almost nothing to nit-pick concerning the book, but I do have one complaint about the JSTK software. The supplied shell scripts in the bin directory all had MS-DOS end-of-lines. This prevented them running unmodified on my OS X iBook. I had to remove all of the ^M's. This may also be a problem under Linux, but I have not had an opportunity to test there yet. Once the end-of-line problem was fixed, the software worked like a charm. SummaryA great combination of security primer and cookbook. If you're a serious crypto-freak then you probably don't need this book. If you're a regular Java programmer looking to move to the next level in your understanding and practice of security in your J2EE applications, then this is an excellent book to purchase and learn from. Table Of Contents 1. A Security Primer 2. A Quick Tour of the Java Platform 3. Cryptography with Java 4. PKI with Java 5. Access Control 6. Securing the Wire 7. Securing the Message 8. RMI Security 9. Web Application Security 10. EJB Security 11. Web Service Security 12. Conclusions Appendix A: Public Key Cryptography Standards Appendix B: Standard Names - Java Cryptographic Services Appendix C: JSTK Tools Appendix D: Example Programs Appendix E: Products Used For Examples Appendix F: Standardization Bodies Simon P. Chappel would like Tim O'Reilly to call him to discuss the great Java book he's itching to write. You can purchase J2EE Security from bn.com. Slashdot welcomes readers' book reviews -- to submit a review for consideration, read the book review guidelines, then visit the submission page. Slashbot book review (Score:2, Troll) Also, it introduces nice security concepts in a clear and easy way which self taught coders might not have come considered before. I got my copy from Barns & Noble which was a couple of dolla Re:Slashbot book review (Score:3, Insightful) Re:Slashbot book review (Score:1) Stop using outdated, inefficient methods of retail transaction, the future growth of productivity and economnic gains depend on it. Re:Slashbot book review (Score:2) Re:Slashbot book review (Score:1) I have lost all faith in the mod system! J2EE security? should be just Java 2 security (Score:5, Interesting) 9. Web Application Security 10. EJB Security 11. Web Service Security Seems more like this is Security book for all Java 2 folks with J2EE tagged on at end. Ohh let us not forget that J2EE is a big buzzword that will most likely increase sales an extra 10-15% versus naming the book "Java Security" i'll take the karma hit to state my opinion. Name the book on what it is about not what will generate a large amount of sales. Re:J2EE security? should be just Java 2 security (Score:5, Insightful) I know it's a shame to have programmers who think that telnet is "secure" because they are prompted with a login, but usually these programmers are not stupid, they are just uninformed. As soon as they realize the issues involved, they take steps to correct them. That is why I am happy to see that the foundations of "what we mean by security" was laid out before the "how we do it in J2EE" That said, I am sorry to see that they didn't devote a chapter to Java's authentication and authorization service (JAAS), as in my humble opinion, for all of its power, its not terribly straightforward or simple. In a mixed application environment, the pressures for "single sign-on" capabilites usually require JAAS or a home brew implementation which most likely would be even less secure. Re:J2EE security? should be just Java 2 security (Score:2) in the case of identity theft. is level 2 ID theft them finding out your SSN and calling and getting a new SSN saying you are the ID theft? (kinda like a reverse ID theft?) thank you but no thank you. Re:J2EE security? should be just Java 2 security (Score:1) Re:J2EE security? should be just Java 2 security (Score:1) JAAS is indeed a great feature of Java/J2EE systems and no good book would be complete without a good discussion on this topic. This book is no different. It include a complete chapter devoted to it -- the chapter titled "Access Control". This chapter includes description of policy files to control access using codebase (from where the class files are loaded), signer, logged-in user or any combination of these. The cahpter also has details on using LoginModules, how to write J Re:J2EE security? should be just Java 2 security (Score:4, Interesting) 12. Securing the Application Server 13. Securing the JVM and the ClassLoader 14. Securing the Operating System (or at least, the File System) Because if I add to attack a J2EE application, I would do (14), (13) and then (12). If that doesn't work, I would go straight to (10) or to the database. So, maybe they should also have added: 15. Securing the JDBC driver properties and the Database Overall, this is another Java book that I will not buy. Role of programmer versus server admin (Score:2) I would guess the reasoning for omitting these steps is due to this role seperation, or the fact that Application Servers and OSes tend to have vastly different configuration options and covering all of them (or even just a few major ones like WebLogic, JRun, WebSphere, etc.) could be a book quote? (Score:5, Funny) I thought it was "with power comes great responsibility"? Applicable nonetheless. Re:quote? (Score:2) With scope comes complexity. With power comes the willingness to tackle more scope. With power comes complexity? (Score:5, Funny) Re:With power comes complexity? (Score:2) with EJB comes power, with power comes complexity, Re:With power comes complexity? (Score:1) Programming primadonnas (Score:5, Insightful) Security models and tools that are so complex as be underutilized are worthless. It only takes one unsecured app to ruin all the rest of your security. Ultimately security will have to come automagically from the framework, compiler, or language itself. It will be a fight because programmers will feel too constrained in such an environment (thinking they can do it better, which may be true). If only experts can write secure code, we will never have security. This business will always have amateurs working in it. If we have to depend on expertise, we will never have security. Someone's going to say it, dos2unix (Score:5, Informative) For those who may be unfamiliar with file conversion issues, here's (only a few) ways to convert DOS text files. For Linux, there's dos2unix. For MacOSX, there's native2ascii (Haven't used it personally, but is reported to work) Also dos2unix has been ported to MacOSX, see And I'm not including several dozen awk scripts, perl commands, shell scripts, etc. to do the same thing. For perl (Score:1) Re:Someone's going to say it, dos2unix (Score:2) Jason. Re:Someone's going to say it, dos2unix (Score:4, Interesting) It's not pratical to maintain two dialects when they are not both in active use, in language or in computer software. Never mind that DOS was created after UNIX, and decided to be particular about wanting thier own file format, so they embedded what was previously a printer command just in case the computer didn't realize that it already had a carrige return to process. Of course, I'm not really trying to convince you that the UNIX way is better, but now you see it from a different point of view. Re:Someone's going to say it, dos2unix (Score:3, Interesting) Just a carriage return (no line feed) can be used as a status display with a command line app. In a loop you update the status (such as a line counter), then use just the caraige return to return the cursor to the beginning of the line. The you write out the line number again ON THE SAME LINE. Just a line feed can mimic a tree. One line down, same character position. Re:Someone's going to say it, dos2unix (Score:2) Re:Someone's going to say it, dos2unix (Score:1) I have always thought that the *nix way was wrong, and took control AWAY from me. If I want a CR, I want a the actions of a CR, NOT an automatic CR/LF. Automatic actions are the MS way, IMHO. Sigh, now I will get flamed for this, Oh Well..... Re:Someone's going to say it, dos2unix (Score:2, Interesting) Re:Someone's going to say it, dos2unix (Score:2) set fileformats=unix That will make it show the ^Ms Not so (Score:4, Insightful) --------------- Some of the most powerful concepts are also among the most simple. One of the principle weaknesses of the Java (and C#, and before that Win32 and MFC) API is that they fail to grasp that. Re:Not so (Score:4, Insightful) Java APIs make things as simple as possible. But not simpler. Re:Not so (Score:2, Insightful) Sample chapter download (Score:5, Informative) This chapter is for Web Services Security using XML Encryption and XML digital signatures. iksrazal Another good book on the subject... (Score:5, Informative) I highly reccomend it and it's a great "how to" companion to O'Reilly's Java Security [oreilly.com] by Scott Oaks. Plain text passwords in web.xml (Score:5, Informative) If I see one more book on server side Java that has example web.xml web app configuration files with plain text passwords, I'm going to go postal. Re:Plain text passwords in web.xml (Score:2, Interesting) Re:Plain text passwords in web.xml (Score:2, Informative) Re:Plain text passwords in web.xml (Score:1) Re:Plain text passwords in web.xml (Score:4, Informative) Depending on your choice, the authenticating service can be: a different passwd file not in a shadow password file a NIS setup a Windows Domain controller a kerberos setup and many many more... JAAS is not simple to setup and it's documentation isn't written for the people who need it the most. Homebrew encryption is easy to break, so people don't bother encrypting. These factors play a big role in the number of plain text password files. Re:Plain text passwords in web.xml (Score:3, Interesting) To reduce complexity, the same db user is often the owner of the database schema so has unlimited power to mangle tables and data. It is kind of ironic to have powerful db server the creators of which put together sofisticated securuty features and always see the databa Java security documentation (Score:1, Informative) [cgisecurity.com] IBM red book (Score:1)
http://developers.slashdot.org/story/03/12/22/1730229/j2ee-security?sdsrc=prevbtmprev
CC-MAIN-2014-52
refinedweb
2,435
64
JavaScript Fundamentals - 001 - Functions Part 1 Series Introduction Often as developers we get a bit starry-eyed by the new and exciting parts of programming. For me and many others JavaScript is our language of choice and in the JS world there's always a new framework to get distracted by. Last year, frameworks like ReactJS, VueJS and Angluar domainated the headlines and firmly cemented themselves as the goto frameworks. But, while the work all these frameworks are doing is exciting, there's one very important thing often forgotten about... The basics. How often do you find yourself doing something, not because you understand how or why. But, because it's that's how it's done? So, in this series of posts, I want to strip back all of the fancy frameworks, new technologies, and applications and instead look at the pure, bare-bones language and explain the concepts, methods and properties of that language, hopefully in a way everyone can understand. First on my list is Javascript but I also want to focus on other front-end web development languages like CSS and HTML. If you have any suggestions for what areas to tackle first in there languages just comment them below or tweet them at me. P.S. If you think I could explain something better or I have missed something out then please comment or open an issue on the GitHub page for this post and I'll be sure to revisit it. Function can be difficult but they don't need to be One of the biggest topics in JavaScript that is miss-understood is functions. How to define them? The different types? And, what actually makes a function, a function. So, I've decided to tackle these first with a mini-series of posts that cover the following topics on functions: - Understanding a function (POST 1) - The different parts of a function (POST 1) - How to define and call functions (POST 1) - The different ways of defining a function (POST 2) - Methods. (POST 2) - Synchronous vs Asynchronous functions (POST 2) Understanding a function Simply put a function is a block of code that can be called at any point to carry out a task that is defined within the function. To someone who isn't a developer that may sound gobbledygook but in reality, it is quite simple. Let's take a look at an example. function example() { console.log("I'm a function! :)"); } example(); Here we define a function called 'example' and inside the function we tell it to log the message "I'm a function! :)" to the console. After the function defintion, we see: example(); This is how we run (or, what may also be called 'invoking' or 'calling') the function. Without this line, we have defined the function using the 'function' keyword but we haven't called the function. So, whatever was put in between the '{ }' of the function won't get processed. It's like calling up a mechanic for a quote on a vehicle service. You have given them in the instructions on what work needs to be done but you have invoked them to start. But, once you say 'yes, please do the work', we have invoked the function and the work gets carried out. Making a function We breifly looked at the different parts of a function above but let's break down another example function down to better understand what really makes up a function and how we can define one. Take a look at this function. function addition(x, y) { return (x + y;); } addition(2,3); There are 5 key aspects that make up a function, these are: - The 'Function' Keyword - Name - Paramters & Arguments. - Function Body - Function Call All 5 of these aspects aren't required in all scenarios but we will cover these situations when they come up. Some of these you may be able to point out from the last section, but it pays to break them down individually and really understand what is happening. Let's start with the function definition which consists of: - The 'Function' Keyword - Name - Paramters & Arguments - Function Body The 'Function' Keyword The function keyword is what begins the entire process, once we type the word 'function' the machine expects a function name, parameters and a code block follow it. Essentially, once we type 'function' the machine expects to see a function definition made. Name Following on from the 'function' keyword we have the 'name'. So, looking at our code example from earlier: function addition(x, y) { return (x + y;); } addition(2,3); We used the 'function' keyword to tell the machine we're going to define a function. Following this, there is the word 'addition', this is the name of the function. In reality we could call a function whatever we want as long as sticks to JavaScript casing rules (primarily camelCasing). But, it makes sense for readability to name the function a sensible name that makes sense to both yourself and anyone else who may read the code. So, in our case we called our function 'addition' because it adds 'x' and 'y' together. But, we could have easily called it 'additionOfXAndY' or some another name, it really depends on how many functions you have and how spefic you want to get with your naming conventions as to what you call your functions. Simply, you can call your functions anything you want, but for your own sake it's best to give them a name that describes what it does. Parameters & Arguments Paramters are the values defined in the '()' of the function following the name, so in our example we passed in the parameters 'x' and 'y' which where then used inside the function body to perform the calculation. Now, if you look at the bottom of the code example, at the function call, we placed 2 values inside the '()' these are known as arguments. You will often here Parametes and Arguments used interchangley but this ins't the case, they are actually different. Parameters are what we tell the function to expect to recieve when it's called and arguments are the values we pass into the function when we call it. A small difference but a key difference that you should be aware of. In our example, when we defined the function we gave it 2 parameters (x and y), this essentially tells the function that when we call you, you will be given two values for you to substitue into the place of 'x' and 'y'. So when we called the function addition, we substite the values x and y out for the passed arguments. So, in this case 'x' becomes '2' and 'y' becomes '3' so when the function body is run, it's not running 'x + y' but instead is running '2 + 3'. This comes back to the original idea that functions are designed to be reusable, for example instead of passing 2 & 3, we could pass: - 1 + 3 - 4 + 10 - 3 + 7 I mean, we could manually type out these calculations in the console but that isn't neither scalable or efficent. Say we needed to do this with 300 pairs, are we going to manually type them out? No, of course not. This is where passing values into functions as arguments makes more sense. The Body Finally, we arrive to the function body. The function body is main part of a function, it's the code that is executed when the function is called. In most cases this is the code located within the '{ }', however there are cases where this isn't true such as Arrow Functions but we will look at those in Part 2. But, essentially in the vast majority of cases anything located after a function name and parameters and is contained within a pair of '{ }' is the function body and will be executed once the function has been called. Looking at our code example from ealier: function addition(x, y) { return (x + y;); } addition(2,3); The function body is this portion: { return (x + y;); } Now, this is a very simple function with a one line function body, which isn't something you see often. If you look at any code examples, often function bodies are over multiple lines and carry out multiple tasks. But, as with the ethos of functions, it's better to only have to write it all once. Function Calling / Invoking The final part we need to look at for the making of a function is the calling or invoking of one. Calling a function is exactly what it sounds like, we're calling a function that needs to execute the code stored in it's function body. Being able to invoke functions is one reason functions are so pivotal in coding. We can call a function as many times as we want, without having to re-write any of the code saving us considerable time and effort. For once final time in this post, let's look at our example function: function addition(x, y) { return (x + y;); } addition(2,3); The function call would be: addition(2,3); With this single line, we call the function 'addition' and pass it in 2 arguments (2 & 3) and are returned an output (5). But, because we haven't hard-coded anything into our function we could pass it any two numbers and get a result. For example, we could pass it the arguments (10 & 5) and would get 15 in reply. Refering back to the previous section on Parameters & Arguments, the function call is the final piece to making the function functional. We pass parameters into the function defintion when it's created so it allows us to re-use the funciton by passing arguments in the function call whenever we need to. And, that's it for Part 1 of this mini-series, I hope you enjoyed it and found it helpful. Part 2 of this mini-series on functions will be out soon, if you're interested please follow me to get notified once the second post is available. If you enjoyed this article, then please share this article. | It would mean a lot to me for others to be able to read this as well. Want to discuss this article? Or, just say hi: Website | Twitter | Instagram | Medium Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/conermurphy/javascript-fundamentals-001-functions-part-1-20jb
CC-MAIN-2021-17
refinedweb
1,731
66.37
hermione the npm operations chat bot Hermione the npm operations Slack chat battlestation is fully operational and is capable of demonstrating its power on a target, a military target. Name the system! You'll want to create your own little node package for your installation. This package needs a package.json, a configuration file, and a shell script to run the bot. Here's a nice minimal package.json, requiring opsbot & a third-party plugin: Here's run.sh: #!/bin/bashopsbot --config ./configuration.js. Set up an outgoing webhook in Slack that points to /messages on your deployment URI. Set up a trigger word for the integration that is the botname you've configured. You can alternatively have the bot sent all traffic from a single channel. Set up an incoming webhook in Slack. Add its full URI (with token) to the 'hook' field in your config. List the plugins you want to load as fields in the plugins hash. The value should be an object with any required configuration for the plugin. Note that opsbot can load both built-in plugins and plugins installed via npm. Example configuration: moduleexports =botname: 'hermione'token: 'slack-integration-token-here'hook: 'your-slack-incoming-webhook-uri-here'brain: dbpath: '/path/to/leveldb'logging:console: falsepath: '/var/log'plugins:pagerduty: apikey: 'your-key-here' urlprefix: 'your-prefix'npm: {}statuscats: {}; botname: help: return a help message botname: status: gives bot uptime, loaded plugins, and location of the bot's brain. Plugins must be objects with three required functions and a name field. new Plugin(opts) The constructor takes an options object. The required content of the options is up to the plugin itself. The options object will always be present and will always have a bole logger object in the log field. It will also have a leveldb instance in the brain field; see below. matches(str) A synchronous function that takes a string. Returns true if this plugin wants to handle the message, false otherwise. By convention and in order to be kind to fellow plugin authors, make this match on the prefix of incoming message. For instance npm koa might return information about the koa package on npm. respond(message) A function that takes a Message object. This function is expected to call message.send() with a string or with a fully-structured message with attachments as documented in the Slack API. The response handler will decorate the response with any missing required fields. When you are finished sending replies to the incoming message, call message.done(). As a convenience, if the message requires only a single reply, you can call message.done(reply) to send & clean up. Synchronously return a string with usage information. Here's a simple plugin. moduleexports = ;'ORLYOWL';return msgmatch/ORLY\?/;;msgdone'YA RLY';;return 'If you say ORLY?, you get the obvious response.';; bartly: Real-time BART departure information by station. deployer: Invoke an ansible deployment playbook; requires customization for your environment. fastly: Fetches some current stats from the named Fastly service. flipit: Table flip! karma: Give points and take them away. npm: Fetches package information from npm. pagerduty: Show who's on call now & who's up in the next few days; list open incidents; ack & resolve incidents. statuscats: Show an http status cat. levenmorph: Morph one word into another using a nice short path. Each plugin has more documentation at the top of its source file. Opsbot uses levelup to provide a persistent key/value brain to plugins. Each plugin is, on construction, given an options object with a sublevel-namespaced db object in the brain field. This object might not be available if the opsbot configuration hasn't given it a path to store the db in, so your plugin should assert if it requires the brain but is not given one. See an example in the built-in karma plugin. Write more plugins, add features to the existing plugins, it's all good. Please follow the code style in existing files (4 spaces to indent, Allman bracing). If you write your own plugins, I don't much care what you do. Please try to be at least as responsible as I have been about writing tests. If you want to use promises, go ahead! bluebird is already in the package deps. If you write a plugin for opsbot & publish it on npm, please let me know so I can link it here! It might also help to give it the keyword opsbot so other people can find it when they search. I'm running this against our Slack chat already. The existing plugins work perfectly well. I'm not calling it 1.0 yet because there is a small chance I might have to change the plugin API if I discover it isn't sufficient. The core features are in place, however. Hermione the Opsbot is built on node-restify. My colleagues bcoe and othiym23 have been invaluable.
https://www.npmjs.com/package/opsbot
CC-MAIN-2015-40
refinedweb
824
68.26
Gaston Hillar is an IT consultant and author of more than 40 books on topics ranging from systems programming to IT project management. Voice has yet to gain a foothold with developers, but Windows 7 is about to change that. Exchange Server 2010 includes Voice Mail Preview, so the push is on to include voice and speech awareness and interaction in applications. "Voice is the new touch," says Zig Serafin, GM of Microsoft's speech group. "It's the natural evolution from keyboards and touch screens." Speech-aware apps recognize human speech and react to commands. They talk back to users instead of displaying text, letting people interact with their computers in the same way they interact with other people. These apps have two components: - Speech recognition to convert spoken words and sentences to text. Windows 7 lets users train the speech-recognition system to transform it into a voice-recognition system. This way, the speech-recognition engine improves its accuracy based on the user's unique vocal sounds. - Speech synthesis to artificially produce human speech and talk to users. Windows 7's Text-To-Speech (TTS) engine converts text in a specific language into speech. The Speech Recognition Control Panel application (Figure 1) offers everything you need to configure your microphone and train your computer to better understand you. You can find this application in the Ease of Access category. It offers access to the Text to Speech tab in the Speech Properties dialog box. This tab lets you select the default voice to use for the TTS engine. You can use a text to preview the voice and configure its speed and output settings (see Figure 2). However, one of the great problems about speech-related services in Windows 7 is that the APIs and the wrappers for managed code are a bit complex and lack documentation. Thus, I present in this article example C# programs to help you to create speech-aware applications. Talking to People To get an app to talk to users, you use speech synthesis services, wrappers provided by both .NET Framework 3.5 and .NET Framework 4 (Release Candidate). First, add the System.Speech.dll assembly as a reference to an existing C# project, then include the System.Speech.Synthesis namespace to access the classes, types, and enumerations offeredby the speech synthesis wrapper. You can create a new instance of the SpeechSynthesizer class and call its Speak method with the text to speak: using System.Speech.Synthesis; This way, the TTS engine uses the default voice, its parameter values, and audio output to turn the received text into human speech: var synthesizer = new SpeechSynthesizer(); synthesizer.Speak ("Hello! How are you?"); The statement after the call to the Speak method isn't executed until the TTS engine finishes saying "Hello! How are you?" To create a more responsive speech-aware application, call the SpeakAsync method, which produces the same effect as Speak but continues to the next statement after scheduling an asynchronous operation to transform the received text to speech: synthesizer.SpeakAsync("Good morning!"); You may need to cancel an asynchronous scheduled speak command. It is possible to create a Prompt instance for each text to speak, then call the SpeakAsyncCancel for the SpeechSynthesizer instance, with the Prompt instance to be canceled as a parameter. This way, it is possible to cancel a specific text as needed. The following lines show an example that cancels "How are you?" var prompt1 = new Prompt("Good morning!", SynthesisTextFormat.Text); var prompt2 = new Prompt("How are you?", SynthesisTextFormat.Text); synthesizer.SpeakAsync(prompt1); synthesizer.SpeakAsync(prompt2); // Cancel prompt1 -> "How are you?" synthesizer.SpeakAsyncCancel(prompt1); You can also cancel all the scheduled asynchronous speak operations by calling the SpeakAsyncCancellAll for the SpeechSynthesizer instance, without parameters.
http://www.drdobbs.com/windows/voice-its-the-new-ui/223101480?pgno=1
CC-MAIN-2018-22
refinedweb
625
56.05
QML PropertyChanges: Cannot assign to non-existent property "???????" in ARM embedded. Hi, I build the Qt embedded 4.7.4 for my ARM embedded board. And I test QML script and everything works fine except "PropertyChanges". Here is the example from the reference document in "QML PropertyChanges Element". @ import QtQuick 1.0 Item { id: container width: 300; height: 300 Rectangle { id: rect width: 100; height: 100 color: "red" MouseArea { id: mouseArea anchors.fill: parent } states: State { name: "resized"; when: mouseArea.pressed PropertyChanges { target: rect; color: "blue"; height: container.height } } } } @ This sample works fine in my Linux notebook. But the error message "PropertyChanges: Cannot assign to non-existent property "???????" will output to console if run in my ARM board. I wander is there any language coding in QML and so the error message show "???????" not property "color". Or there are some parameter miss when I build the Qt embedded for my ARM board. Thanks for help. Not entirely on topic, but you may find it hard to get on with people on this forum, if you don't format your code snippets appropriately. You should use "@" tags, and there is no need for "< br >" statements. The code you provided is very hard to read in it's current state - please fix. As for the problem itself, the code is the same as in the documentation, so we won't learn much from that - it is correct, and should work fine. I would suspect either build problems, or issues with QML-C++ bridge (I am having such problems now on Android, where code works fine on GNU/Linux, but does not see bridged C++ methods and variables). Does the example get displayed correctly? Yes. The example get displayed correctly. Only I press mouse and get the error message. How do I know is the build problem or QML-C++ bridge issue? And any suggestion to solve it. Thanks, If this is the example you're trying to run, then bridging is definitely not a problem (the case with me is that QML does not see C++ objects registered as rootContextObject). Have you tried using different colour notation, like "#ff0000" for red? Not very likely to be the cause, but worth trying. Well, I have to blame myself now... the QML-C++ connection works fine in Necessitas, it was my error that caused it not to work.
https://forum.qt.io/topic/11968/qml-propertychanges-cannot-assign-to-non-existent-property-in-arm-embedded
CC-MAIN-2017-51
refinedweb
394
76.42
telephone its easier and more better [i][b]giblit[/b][/i] , thank you. your welcome [i][b]takatz28[/b][/i] ... Function to sort numbers showing wrong output, can't find the errorhello problem is in your bubble sort functions . you must choose loop indexes correctly . lock at... telephone hello i fixed your code !! here you go [code] #include <iostream> using namespace std; int mai... Arrays need helphi, to get array members from user just use simple loop! like this : [code] #include <iostream> ... how to convert degrees into radians in a c++ programhello, [b]Converting from degrees to radians[/b] Decrees are converted to radians in the following...
http://www.cplusplus.com/user/Rahmat/
CC-MAIN-2015-48
refinedweb
107
60.61
Comments for Using Delphi as a script language for ASP.NET 2009-07-09T13:42:54-07:00 Using Delphi as a script language for ASP.NET CHP User 2003-05-07T02:35:54-07:00 2003-05-07T02:35:54-07:00 Using Delphi as a script language for ASP.NET This probably isn't the place to be posting this, but I'm lost as to where I should post it - sorry in advance :). Anyway, I've been playing around with ASP.NET with Delphi and managed to do most things that I wanted. However, I've been attempting to create a simple custom control by dumping a load of HTML into an ascx file and adding the @register tag (using tagname/src attr.). The way the asp.net compiler currently works means that this doesn't work since all the units use the same namespace (ASP) and hence are called "unit ASP;". They then have this in the uses clause which kills the compilation. Without thinking this through, I had decided that all I needed to do was remove the ASP from the uses clause and all would be fine. So I wrote an Execution Proxy to remove the reference on the fly. Of course this doesn't work because the code still needs to reference the "registered" units (which are called ASP). I appreciate that dccasp is still in preview so I'm being a little optimistic if I think everything will work, but I was wondering if you have any suggestions as to how I might create a workaround for this.Many thanks. Error found in web.config jun pattugalan 2003-03-31T04:29:29-07:00 2003-03-31T04:29:29-07:00 Error found in web.config i receive this error message once i tried to run the example.parser error message : File or assembly name DelphiProvider, or one of its dependencies was not found.Line 5: <Add assembly="DelphiProvider" />*note*im using win2000 advanced server even the service packs are updated. Internal error S1888 ??? Laszlo Kertesz 2003-01-21T06:20:15-08:00 2003-01-21T06:20:15-08:00 Internal error S1888 ??? When I try to run the editdemo sample found in, I get the compilationerror"Fatal: Internal error: S1888". No informations found on the net. What to donow? (I have the updated D7 .NET Preview, and the .NET Framework SP2installed.) re: dccasp.exe was not found error Laszlo Kertesz 2003-01-21T06:17:55-08:00 2003-01-21T06:17:55-08:00 re: dccasp.exe was not found error Solved. After setting something on the wirtual directory properties, this error don't comes. dccasp.exe was not found error Laszlo Kertesz 2003-01-21T01:40:38-08:00 2003-01-21T01:40:38-08:00 dccasp.exe was not found error Following the sample in this article, I get this error if I want to see the aspx in my browser:Compiler 'c:\winnt\microsoft.net\framework\v1.0.3705\dccasp.exe' was not found I have copied the dccasp.exe into this directory from the "Delphi for .NET Preview\aspx\framework" folder, but has no effect, the error is the same. Don't understand. What to do now? Laszlo Using Delphi as a script language for ASP.NET Ray Thorpe 2002-11-29T13:02:35-08:00 2002-11-29T13:02:35-08:00 Using Delphi as a script language for ASP.NET I asked Danny Thorpe where was the delphi unit code for this article. He said to ask you. I'm a little lost as to what the complier is going to compile. Could you post all of the code for Delphi as a scripting language for ASP Demo.Thanksrayrthorpe@directvinternet.com Problem with the demo Craven Weasel 2002-11-25T18:29:22-08:00 2002-11-25T18:29:22-08:00 Problem with the demo I've just tried to run the editdemo.aspx and I get an ASP error in the browser: "Compiler Error Message: The compiler failed with error code 1.C:\WINNT\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files\vslive\5af99da7\a2fb00b7\pnx5wyl8.0.pas(11) Fatal: Unit not found: 'Borland.Delphi.System.pas' or binary equivalents (DCU,DPU)"The .NET Framework (SP2) and Delphi.NET Preview (latest release) all installed correctly (works with no problem if I create apps in Delphi7 and compile them with dccil). The Delphi.NET ASP directory structure is:/Delphi for .NET Preview /aspx (contains the editdemo.aspx file) /bin /demos /doc /setupfiles /source /unitsIt's almost like the compiler cannot find the specified .pas file.Could anyone help me with this please? Thanks in advance. How Do You Print This Page? Bruce Inglish 2002-08-15T15:37:20-07:00 2002-08-15T15:37:20-07:00 How Do You Print This Page? As with the earlier comment I have found this article unprintable. I can't even seem to get the article to behave using an HTML editor and manipulating the table properties. So...How about adding a button that would re-render the story in an HTML printable format or perhaps in PDF? Surely the Story Server software supports such a thing. re: Convert 'Using Delphi as a script language for ASP.NET' into PDF file hegx geng xi 2002-08-14T19:56:43-07:00 2002-08-14T19:56:43-07:00 re: Convert 'Using Delphi as a script language for ASP.NET' into PDF file I have been waiting the moment coming. Convert 'Using Delphi as a script language for ASP.NET' into PDF file Wyatt Wong 2002-08-12T23:19:27-07:00 2002-08-12T23:19:27-07:00 Convert 'Using Delphi as a script language for ASP.NET' into PDF file I suggest Borland to re-publish this document in PDF format so as to eliminate the need to do the scrolling horizontally in order to read the full text.Besides, if you printed this document out, all the words on the rightmost margin will be 'lost'.
http://edn.embarcadero.com/article/28974/atom
crawl-002
refinedweb
1,011
67.65
So he's got 2 PCs. Call them PC1 and PC2. The PC1 is connected to the Arduino using the USB cable, so that means he is controlling the arduino with PC1?And the Arduino (and the Ethernet shield) and PC2 are connected via Ethernet cable. So he's sending a message from PC1 to PC2 via the Arduino, and wondering why he cannot reverse that, am I right? #include <SPI.h>#include <Ethernet.h>byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip( 192,168,2,2 );IPAddress gateway( 192,168,2,1 );IPAddress subnet( 255,255,255,0 );EthernetServer server(23);int loopCount = 0;boolean isStopped;void setup(){ Serial.begin(9600); pinMode(4,OUTPUT); digitalWrite(4,HIGH); Ethernet.begin(mac, ip, gateway, gateway, subnet); delay(2000); server.begin(); Serial.println("Ready");}void loop(){ EthernetClient client = server.available(); if(client) { Serial.println("Client connected"); client.flush(); isStopped = false; loopCount = 0; char c; client.println("Hello"); while(Serial.available()) Serial.read(); while (client.connected()) { while(client.available()) { c = client.read(); if(c == 'x') { client.stop(); Serial.println("stop - user request"); isStopped = true; } else Serial.write(c); loopCount = 0; } delay(10); loopCount++; if(loopCount > 10000) { client.stop(); Serial.println("stop - timeout"); isStopped = true; } while(Serial.available()) { c =Serial.read(); client.write(c); Serial.write(c); } } if(!isStopped) { client.stop(); Serial.println("stop - disconnect"); } Serial.println("disconnected"); }} I just upload code using PC1...I'm sending message from PC2 to PC1 via Arduino, it works, but I wonder why I cannot reverse it (sending message from PC1 to PC2)The rest is right... Quote from: creativen on May 08, 2012, 10:55 amI just upload code using PC1...I'm sending message from PC2 to PC1 via Arduino, it works, but I wonder why I cannot reverse it (sending message from PC1 to PC2)The rest is right... Like I said, you don't have the necessary connections. Right now, you have a connection from PC2 to PC1, but not the other way around. Aside from the use of the router mentioned earlier, you mean? You can't. Accept it and move on. Quote from: dxw00d on May 11, 2012, 10:08 amAside from the use of the router mentioned earlier, you mean? You can't. Accept it and move on.So you mean if I use router, the I can do two or more way of communication? Vielen Dank to all of you!At least I find some hope! I see, so you're aiming for some sort of system to send messages to highly trained chimps in your mansion? Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=104773.msg790758
CC-MAIN-2016-30
refinedweb
465
61.02
Hello, I'm just about to step through my code to replace some unnecessary #includes with forward declaration to speed up compile time. However, I'm looking for some advice or guideline on how far I should take this. Consider this class: #pragma once #include "GfxDef.h" #include "Render/RenderStates.h" #include "Render/StateGroup.h" namespace acl { namespace gfx { class IMesh { public: virtual ~IMesh(void) = 0 {} virtual unsigned int GetStateCount(void) const = 0; virtual const render::StateGroup** GetStates(void) const = 0; virtual const render::DrawCall& GetDraw(void) const = 0; }; } } Obviously, this interface doesn't need to know anything about eigther StageGroup or DrawCall, so forward declaration would obviously do. However I need to include the header files whenever I want to use the interface. Furthermore, if I implement a class using this interface, I can still use the (existing) forward declaration, but at some point I will need to include the header files again, probably in the application code. Whats preferable in this case? When should I use forward declaration or when should I still include header files in such a use case?
http://www.gamedev.net/topic/642593-forward-declaration-how-far-to-go/
CC-MAIN-2015-27
refinedweb
183
54.32
Apache Struts 2 Web Application Development Struts 2.1 is a modern, extensible, agile web application framework, which is suitable for both small- and large-scale web applications. The book begins with a comprehensive look at the basics of Struts 2.1, interspersed with detours into more advanced development topics. You’ll learn about configuring Struts 2.1 actions, results, and interceptors via both XML and Java annotations. You’ll get an introduction to most of the Struts 2.1 custom tags, and also, which allows. (Well, annotations, XDoclet, and so on, make that somewhat less true. You know what I mean.)). fluent programming, rather than this specific example. a object, whatever pushing means. clause to the method declaration when throwing runtime exceptions. This means further information may be lost in both the code and the documentation. As hinted,. One aim of COP is to formalize the nature of contracts. Languages such as Eiffel have one solution to that problem, and having it built-in at the language level provides a consistent means of expressing contracts." /> If most of this seems like a mystery, that’s fine.. I’m sure. * * Note:. * * * Note: Initializes ingredient information * if necessary. * */ As usual, this example is a bit contrived. We’d probably just want to put it all in the first sentence.:" Note that the header label for built-in tags can be modified in the same way, provided we have a good reason to do so. However, we will probably never have a good reason to do so.! I know what you’re thinking—but as soon as we write Javadocs, we’ve entered into an implicit contract to always keep them up-to-date, in perpetuity, over the life of the program. If we can’t do that, it may be better not to write any. Remember, wrong documentation is worse than having no documentation.. We saw a portion of a package diagram back in Chapter 3 when we looked at a portion of the XWork 2 packages. There, we only looked at the XWork interfaces and did not highlight package coupling.. A class diagram for an entire application can be a bit overwhelming, and isn’t always useful due to the sheer amount of information. Restricting what is visible at both the class and package level can be very useful allowing usable documentation to be generated. T he previous image was generated with ArgoUML, an open source UML tool from application source. It was then edited by hand to improve the layout, to remove class members and operations, and so on. J ava A nother: Here, we’re representing the user action of submitting a form in the sequence diagram. This (in simplified form) causes the Struts 2 filter to instantiate the appropriate action class, indicated by the new() message. The rest is (I’d imagine) largely self-explanatory. Se quence. Th is diagram was created using the Quick Sequence Diagram Editor, which creates an exportable diagram using simple text-based input (I was tempted to call it a DSL, but managed to stop myself).() 1 s2f:user.Rendered Result Personally, I think the send/receive messages are defined backwards.. Documenting web applications Do cumenting an entire web application can be surprisingly tricky because of the many different layers involved. Some web application frameworks support automatic documentation generation better than others. It’s preferable to have fewer disparate parts. For example, Lisp, Smalltalk, and some Ruby frameworks are little more than internal DSLs that can be trivially redefined to produce documentation from the actual application code. In general, Java frameworks are more difficult to limit to a single layer. Instead, we are confronted with HTML, JSP, JavaScript, Java, the framework itself, its configuration methodologies (XML, annotations, scripting languages, etc.), the service layers, business logic, persistence layers, and so on—feeling sleepy? Complete documentation generally means aggregating information from many disparate sources and presenting them in a way that is meaningful to the intended audience. High-level overviews The site map is obviously a reasonable overview of a web application. A site map may look like a simple hierarchy chart, showing a simple view of a site’s pages without sho wing all of the possible links between pages, how a page is implemented, and so on. This diagram was created by hand and shows only the basic outline of the application fl ow. It represents minor maintenance overhead since it would need to be updated when there are any changes to the application. Documenting JSPs The re doesn’t seem to be any general-purpose JSP documentation methodology. It’s relatively trivial to create comments inside a JSP page using JSP comments or a regular Javadoc comment inside a scriptlet. Pulling these comments out is then a matter of some simple parsing. This may be done by using one of our favorite tools, regular expressions, or using more HTML-specific parsing and subsequent massaging. Where it gets tricky is when we want to start generating documentation that includes elements such as JSP pages, which may be included using many different mechanisms—static includes, tags, Tiles, SiteMesh, inserted via Ajax, and so on. Similarly, generating connections between pages is fraught with custom cases. We might use general-purpose HTML links, Struts 2 link tags, attach a link to a page element with JavaScript, ad infinitum/nauseum. When we throw in the (perhaps perverse) ability to generate HTML using Java, we have a situation where creating a perfectly general-purpose tool is a major undertaking. However, we can fairly easily create a reasonable set of documentation that is specific to our framework by parsing configuration files (or scanning a classpath for annotations), understanding how we’re linking the server-side to our presentation views, and performing (at least limited) HTML/JSP parsing to pull out presentation-side dependencies, links, and anything that we want documented. Documenting JavaScript If only there was a tool such as Javadoc for JavaScript. Fortunately, I was not the only one that had that desire! The JsDoc Toolkit provides Javadoc-like functionality for JavaScript, with additional features to help handle the dynamic nature of JavaScript code. Because of the dynamic nature, we (as developers) must remain diligent in both in how we write our JavaScript and how we document it. Fortunately, the JsDoc Toolkit is good at recognizing current JavaScript programming paradigms (within reason), and when it can’t, provides Javadoc-like tags we can use to give it hints. For example, consider our JavaScript Recipe module where we create several private functions intended for use only by the module, and return a map of functions for use on the webpage. The returned map itself contains a map of validation functions. Ideally, we’d like to be able to document all of the different components. Because of the dynamic nature of JavaScript, it’s more difficult for tools to figure out the context things should belong to. Java is much simpler in this regard (which is both a blessing and a curse), so we need to give JsDoc hints to help it understand our code’s layout and purpose. A high-level fl yby of the Recipe module shows a layout similar to the following: var Recipe = function () { var ingredientLabel; var ingredientCount; // ... function trim(s) { return s.replace(/^\s+|\s+$/g, ""); } function msgParams(msg, params) { // ... } return { loadMessages: function (msgMap) { // ... }, prepare: function (label, count) { // ... }, pageValidators: { validateIngredientNameRequired: function (form) { // ... }, // ... } }; }(); We see several documentable elements: the Recipe module itself, private variables, private functions, and the return map which contains both functions and a map of validation functions. JsDoc accepts a number of Javadoc-like document annotations that allow us to control how it decides to document the JavaScript elements. The JavaScript module pattern, exemplified by an immediately-executed function, is understood by JsDoc through the use of the @namespace annotation. /** * @namespace * Recipe module. */ var Recipe = function () { // ... }(); (Yes, this is one of those instances where eliminating the comment itself would be perfectly acceptable!) We’ll look at the JsDoc output momentarily after covering a few more high-level JsDoc annotations. We can mark private functions with the @private annotation as shown next: /** * @private * Trims leading/trailing space. */ function trim(s) { return s.replace(/^\s+|\s+$/g, ""); } (Again the JsDoc comment could be replaced by creating a better function name. Really—I named it poorly so that I could bring up the documentation issues.) It gets interesting when we look at the map returned by the Recipe module: return /** @lends Recipe */ { /** * Loads message map. * * * This is generally used to pass in text resources * retrieved via <s:text.../> or <s:property * tags on a JSP page in lieu * of a normalized way for JS to get Java I18N resources * */ loadMessages: function (msgMap) { _msgMap = msgMap; }, // ... The @lends annotation indicates that the functions returned by the Recipe module belong to the Recipe module. Without the @lends annotation, JsDoc doesn’t know how to interpret the JavaScript in the way we probably intend the JavaScript to be used, so we provide a little prodding. The loadMessages() function itself is documented as we would document a Java method, including the use of embedded HTML. The other interesting bit is the map of validation functions. Once again, we apply the @namespace annotation, creating a separate set of documentation for the validation functions, as they’re used by our validation template hack and not directly by our page code. /** * @namespace * Client-side page validators used by our template hack. * ... */ pageValidators: { /** * Insures each ingredient with a quantity * also has a name. * * @param {Form object} form * @type boolean */ validateIngredientNameRequired: function (form) { // ... Note also that we can annotate the type of our JavaScript parameters inside curly brackets. Obviously, JavaScript doesn’t have typed parameters. We need to tell it what the function is expecting. The @type annotation is used to document what the function is expected to return. It gets a little trickier if the function returns different types based on arbitrary criteria. However, we never do that because it’s hard to maintain—right? Overloading JavaScript return values is typical because JavaScript has a wider range of truthiness and falseness than Java. This is okay, even though it gives Java programmers conniptions. That’s okay too, and can be mildly entertaining to boot. JsDoc has the typical plethora of command-line options, and requires the specification of the application itself (written in JavaScript, and run using Rhino) and the templates defining the output format. An alias to run JsDoc might look like the following, assuming the JsDoc installation is being pointed at by the ${JSDOC} shell variable: alias jsdoc='java -jar ${JSDOC}/jsrun.jar ${JSDOC}/app/run.js -t=${JSDOC}/templates/jsdoc' The command line to document our Recipe module (including private functions using the -p options) and to write the output to the jsdoc-out folder, will now look like the following: jsdoc -p -d=jsdoc-out recipe.js The homepage looks similar to a typical JavaDoc page, but more JavaScript-like: Do cumenting interaction can be surprisingly complicated, particularly in today’s highly-interactive Web 2.0 applications. There are many different levels of interactivity taking place, and the implementation may live in several different layers, from the JavaScript browser to HTML generated deep within a server-side framework. UML sequence diagrams may be able to capture much of that interactivity, but fall somewhat short when there are activities happening in parallel. AJAX, in particular, ends up being a largely concurrent activity. We might send the AJAX request, and then do various things on the browser in anticipation of the result. More UML and the power of scribbling The UML activity diagram is able to capture this kind of interactivity reasonably well, as it allows a single process to be split into multiple streams and then joined up again later. As we look at a simple activity diagram, we’ll also take a quick look at scribbling, paper, whiteboards, and the humble digital camera. Don’t spend so much time making pretty pictures One of the hallmarks of lightweight, agile development is that we don’t spend all of our time creating the World’s Most Perfect Diagram™. Instead, we create just enough documentation to get our points across. One result of this is that we might not use a $1,000 diagramming package to create all of our diagrams. Believe it or not, sometimes just taking a picture of a sketched diagram from paper or a whiteboard is more than adequate to convey our intent, and is usually much quicker than creating a perfectly-rendered software-driven diagram. Yes, the image above is a digital camera picture of a piece of notebook paper with a rough activity diagram. The black bars here are used to indicate a small section of parallel functionality, a server-side search and some activity on the browser. I’ve also created an informal means of indicating browser programming, indicated by the black triangles. In this case, it might not even be worth sketching out. However, for moderately more complicated usage cases, particularly when there is a lot of both server- and client-side activity, a high-level overview is often worth the minimal effort. The same digital camera technique is also very helpful in meetings where various documentation might be captured on a whiteboard. The resulting images can be posted to a company wiki, used in informal specifications, and so on. User documentation Dev elopment would be substantially easier if we didn’t have to worry about those pesky users, always wanting features, asking questions, and having problems using the applications we’ve developed. Tragically, users also drive our paycheck. Therefore, at some point, it can be beneficial to acknowledge their presence and throw them the occasional bone, in the form of user documentation. Dev eloping user documentation is a subject unto itself, but deserves to be brought up here. We can generally assume that it will not include any implementation details, and will focus primarily on the user interface and the processes our applications use. When writing user documentation, it’s often sufficient to take the user stories, decorate them with screenshots and extra expository text, and leave it at that. It really depends on the client’s requirements how much (if any) user-specific documentation is needed. If it’s an application which will be used inside the client’s business, it may be sufficient to provide one or more onsite training sessions. One thing worth mentioning is that a screenshot can often save oodles of writing effort, communicate ideas more clearly, and remain easily deliverable through the application itself, in a training environment, and so on. Screenshots can be a valuable documentation tool at many levels, including communications with our client when we’re trying to illustrate a point difficult to communicate via text or still images alone. Documenting development The last form of documentation we’ll look at is development documentation. This goes beyond our UML diagrams, user manual, functional specification, and so on. Development documentation includes the source control and issue tracking systems, the reasoning behind design decisions, and more. We’ll take a quick look at some information we can use from each of these systems to create a path through the development itself. Source code control systems A Source Code Control System (SCCS) is an important part of the development process. Our SCCS is more than just a place to dump our source code—it’s an opportunity to give a high-level overview of system changes. The best ways to use our SCCS are dependent on which SCCS we use. However, there are a few quick ideas we can adopt across any SCCS and use them to extract a variety of information about our development streams. Most clients will have their preferred SCCS already in place. If our deliverable includes source, it’s nice if we can provide it in a way that preserves our work history. Code and mental history The history of change can be used on several levels, in several ways. There are products available that can help analyze our SCCS, or we can analyze it ourselves depending on what kind of information we’re looking for. For example, the number of non-trivial changes made to a file provides information in itself—for whatever reason, this file gets changed a lot. It’s either an important document, a catchall, a candidate for parameterization, and so on. If two files are always modified together, then there’s a chance of an unnecessarily tight coupling between them. Sometimes, we just need to know what we were working on a for a particular date(s). We can retrieve all of our SCCS interaction for auditing purposes, to help determine what we were doing on a particular date, as part of a comprehensive change and time tracking system, and so on. Commit comment commitment We should view our commit comments as an important part of development documentation. One way to normalize commit comments is to create them as Javadoc-like comments, but different. Mostly, this just means that the first sentence is a succinct summary of the unit of work done, and the remaining sentences describe what was actually done. What that first sentence includes is somewhat dependent on the rest of the development infrastructure. It’s reasonable to put an issue tracking reference (see next section) as the most prominent part of that comment, perhaps followed by the same summary sentence as the issue item, or a summary if that’s too long. The rest of the commit comment should include any information deemed useful, and might include general change information, algorithm changes, new tests, and so on. This is the section for comments such as “Aaaaaaaaarg!”, which aren’t useful summaries, although it’s often the most accurate. Hav ing a summary commit comment sentence also allows tools to get the output of history or log commands, and create a new view of existing information when necessary. For example, getting a list of files we changed between certain dates, along with a summary of why the files were changed. These can be used as a part of release notes, high-level summaries, and so on. When (and what) do we commit We should tend to commit more rather than less. The more recently a change was made, the easier it is to remember why and what was modified. Update the spelling in a single comment? Sure, might as well commit. When that file is changed later, and you’re code-reviewing the changes, it’s easier to look at only significant changes, and not at some trivial changes such as a punctuation change made the day before. Also, while combining related commits, strive to keep them as granular as possible. For example, let’s say we’ve updated some functionality in an action. As we were doing that, we corrected a couple of spelling errors in some other files. In an ideal world, even minor non-code changes would get their own commit, rather than being lumped in with changes to the code itself. If we see a commit message of “corrected spelling”, we can probably ignore it. If it’s lumped in to an issue-specific commit, we need to check the file itself to know if it’s really part of the issue, and we’ll be disappointed to find out it was to fix a misspelled Javadoc. However, in the real world, we’re not always so disciplined. In that case, the commit would be commented with information about the actual issue being addressed. However, in the comments, we might note that some spelling changes were included in the commit. Note that some SCCSs make the task of breaking up our commits easier than others. Branching Eve n relatively simple changes in application functionality might warrant an experimental branch in which we could play with reckless abandon. By indicating the start of a unit of work in our SCCS, we allow all of the changes related to that unit of work to be easily reproduced. It also creates a minirepository within which we can keep revision control of our development spike. It keeps the experimental code and its changes out of our mainline code and isolates the changes based on a distinct unit of work, which makes us feel better about life in general. If the experimental branch lasts a long time, it should be updated with the current trunk (the head revision) as the mainline development proceeds. This will ease integration of the experimental patch when it’s completed and merged back into the mainline code. Branching discipline Jus t as commits should be as granular as possible, any branches we create should be tied as closely as possible to the underlying work being done. For example, if we’re working on refactoring in an experimental branch, we shouldn’t begin making unrelated changes to another system in the same branch. Instead, hold off on making those changes, or make them in the parent revision and update our revision against the mainline code. Branches of branches? Perhaps, but the management of multiple branches gets very irritating very quickly and is rarely worth the effort. Issue and bug management It’ s equally important to maintain a list of defects, enhancements, and so on. Ideally, everyone involved in a project will use the same system. This will allow developers, QA, the the client, or anybody else involved, to create help tickets, address deficiencies, and so on. Note that the structure for doing this varies wildly across organizations. It will not always possible or appropriate to use our client’s system. In cases like this, it’s still a good idea to keep an internal issue management system in place for development purposes. Using an issue tracking system can consolidate the location of our high-level to-do list, our immediate task list, our defect tracking, and so on. In a perfect world, we can enter all issues into our system and categorize them in a way meaningful to us and/or our clients. A “bug” is different from an “enhancement” and should be treated as such. An enhancement might require authorization to implement, it could have hidden implications, and so on. On the other hand, a bug is something that is not working as expected (whether it’s an implementation or specification issue), and should be treated with appropriate urgency. The categories chosen for issue tracking also depend on the application environment, client, and so on. There are a few that are safe, such as bug, enhancement, and so on. We can also have labels such as “tweak” “refactoring” and so on. These are primarily intended for internal and developmental use in order to indicate that it’s a development-oriented issue and not necessarily client driven. Issue priorities can be used to derive work lists. (And sometimes it’s nice to knock off a few easy, low-priority issues to make it seem like something was accomplished.) A set of defined and maintained issue priorities can be used as part of an acceptance specification. One requirement might be that the application shouldn’t contain any “bug”-level issues with a priority higher than three, meaning all priority one and priority two bugs must be resolved before the client accepts the deliverable. This can also lead to endless, wildly entertaining discussions between us and the client, covering the ultimate meaning of “priority” and debating the relative importance of various definitions of “urgent”, and so on. It’s important to have an ongoing dialog with the client, in order to avoid running into these discussions late in the game. Always get discrepancies dealt with early in the process, and always document them. Linking to the SCCS Some environments will enjoy a tight coupling between their SCCS and issue tracking systems. This allows change sets for a specific issue to be tracked and understood more easily. When no such integration is available, it’s still relatively easy to link the SCCS to the issue tracking system. The two easiest ways to implement this are providing issue tracking information prominently in the SCCS commit comment (as discussed in an earlier section) or by including change set information in the issue tracking system (for example, when an issue is resolved, include a complete change set list). Note that by following a convention in commit comments, it’s usually possible to extract a complete list of relevant source changes by looking for a known token in the complete history output. For example, if we always referenced issue tracking items by an ID such as (say) “ID #42: Fix login validation issue”, we could create a regular expression that matches this, and then get information about each commit that referenced this issue. Wikis We all know what a wiki is, but I’d like to advocate a moment to highlight their use as a way to create documentation and why they’re well-suited to an agile environment. Wikis lower the cost of information production and management in many ways, particularly when it’s not clear upfront all that will be required or generated. By making it easy to enter, edit, and link to information, we can create an organic set of documentation covering all facets of the project. This may include processes used, design decisions, links to various reports and artifacts—anything we need and want. The collaborative nature of wikis makes them a great way for everyone involved in a project to extend and organize everything related to the project. Developers, managers, clients, testers, deployers, anybody and everybody related to the project may be involved in the care and upkeep of the project’s documentation. Developers might keep detailed instructions on a project’s build process, release notes, design documents (or at least links to them), server and data source information, and so on. Some wikis even allow the inclusion of code snippets from the repository, making it possible to create a “literate programming” environment. This can be a great way to give a high-level architectural overview of an application to a developer, who may be unfamiliar with the project. Many wikis also provide a means of exporting their content, allowing all or part of the wiki to be saved in a PDF format suitable for printed documentation. Other export possibilities exist including various help formats, and so on. Lowering the barrier to collaborative documentation generation enables wide-scale participation in the creation of various documentation artifacts. RSS and IRC/chat systems RSS allows us quick, normalized access to (generally) time-based activities. For example, developers can keep an RSS feed detailing their development activities. The feed creation can come from an internal company blog, a wiki, or other means. The RSS feed can also be captured as a part of the development process documentation. Particularly in distributed development environments, a chat system can be invaluable for handling ad hoc meetings and conversations. Compared to email, more diligence is required in making sure that decisions are captured and recorded in an appropriate location. Both RSS and IRC/chat can be used by our application itself to report on various issues, status updates, and so on, in addition to more traditional logging and email systems. Another advantage is that there are many RSS and chat clients we can keep on our desktops to keep us updated on the status of our application. And let’s face it, watching people log in to our system and trailing them around the website can be addictive. Word processor documents Personally, I’m not in favor of creating extensive word processor documents as the main documentation format. There are quite a few reasons for that: it can be more difficult to share in their creation, more difficult to extract portions of documents for inclusion in other documents, some word processors will only produce proprietary formats, and so on. It’s substantially more flexible to write in a format that allows collaborative participation such as a Wiki, or a text-based format such as DocBook that can be kept in our SCCS and exported to a wide variety of formats and allow linking in to, and out of, other sections or documents. When proprietary formats must be used, we should take advantage of whatever functionality they offer in terms of version management, annotations, and so on. When a section changes, adding a footnote with the date and rationalization for the change can help track accountability. Note that some wikis can be edited in and/or exported to various formats, which may help them fit in to an established corporate structure more readily. There are also a number of services popping up these days that help manage projects in a more lightweight manner than has been typically available. Speak Your Mind
http://www.javabeat.net/documenting-our-application/3/
CC-MAIN-2014-15
refinedweb
4,818
52.29
EJB 3.0 Compatibility and Migration By edort on Aug 21, 2007 The Enterprise JavaBeans (EJB) 3.0 specification introduced a new, vastly simpler, API for implementing and accessing session beans. Many developers have questions about how applications written to this new API can interact with legacy EJB applications, or how legacy applications can interact with the new API. It would be impractical to require developers to entirely rewrite all existing EJB applications in order to take advantage of any of the new capabilities. In some cases, developers plan to upgrade their applications, but would prefer to do it using a phased approach. In other cases they prefer to write new EJB 3.0 applications, but would still like to take advantage of their existing application's services. The EJB 3.0 specification makes both of these strategies possible. This tip explains how. A sample application package accompanies the tip. The code examples in the tip are taken from the source code of the sample (which is included in the package). The sample uses the Java EE 5 SDK. You can download the Java EE 5 SDK from the Java EE Downloads page EJB 3.0-to-EJB 2.x Compatibility Let's first look at an example of an application written to the simplified EJB 3.0 API calling a legacy EJB application. In the source code for the sample that accompanies this tip you'll find an EJB 3.0 stateless session bean named MigrationBean. The bean invokes a remote EJB 2.x stateless session bean named EJB2xBean. MigrationBean could either be an entirely new bean or an existing bean that was recoded to use the EJB 3.0 API. For simplicity both beans in this example are packaged in the same archive, but that is not required. Here are the EJB 2.x home and remote interfaces for EJB2xBean: public interface EJB2xHome extends EJBHome { public EJB2xRemote create() throws CreateException, RemoteException; } public interface EJB2xRemote extends EJBObject { public void foo() throws RemoteException; } Here is the first part of the MigrationBeanclass: @Stateless public class MigrationBean implements MigrationRemote { // Inject a reference to the Home interface // of the EJB 2.x bean. @EJB private EJB2xHome ejb2xHome; private EJB2xRemote ejb2x; MigrationBean uses the @EJB annotation to inject a reference to EJB2xHome. The @EJB annotation was introduced as part of the EJB 3.0 specification. However, it was designed to be used with the older-style EJB 2.x home view in addition to the EJB 3.0 business interface view. Whenever the EJB container instantiates MigrationBean, it injects a reference to EJB2xHome in the ejb2xHome data member. An important benefit of using the @EJB annotation with a 2.x home interface is that it frees you from having to use PortableRemoteObject.narrow(). The PortableRemoteObject.narrow() method is used to cast to the correct type the Object returned when you lookup the home interface. In EJB 3.0 the injected home reference can be used without any special casting. The MigrationBean class defines a @PostConstruct method that uses the home reference to create an EJB2xRemote reference. The class then stores the result in another data member. @PostConstruct private void initialization() { try { ejb2x = ejb2xHome.create(); } catch(Exception e) { throw new EJBException(e); } } In the last part of the class, MigrationBeaninvokes the EJB2x business method within its own business method. public void bar() { try { // Call operation on legacy EJB. ejb2x.foo(); } catch(Exception e) { throw new EJBException(e); } } All standard EJB services such as security and transaction propagation work as expected between the two beans. Note that using an @EJB annotation to access EJB 2.x beans is not limited to EJB components. You can use the same approach to access a legacy bean from other types of components in a Java EE 5 application, such as a servlet or an application client. Also, even though this example used a remote EJB 2.x bean, you can use the approach to access a local EJB 2.x bean as well. EJB 2.x-to-EJB 3.0 Compatibility In the first example, you saw how an EJB component written using the new EJB 3.0 API could be a client of a legacy EJB component. Now let's look at the reverse case. Here you'll see how a legacy component that is coded using the EJB 2.x client API can access a session bean that is implemented using the EJB 3.0 simplified API. The idea here is to use the new EJB without making any changes to the existing EJB client code. In this second example, a stateful session bean named AdaptedBean is implemented using the simplified EJB 3.0 API. The bean exposes a 2.x remote home interface to a standalone Java client. Here are the home and remote interfaces for AdaptedBean: public interface AdaptedHome extends EJBHome { public AdaptedRemote create(String id) throws CreateException, RemoteException; } public interface AdaptedRemote extends EJBObject { public String getId() throws RemoteException; } Here is the AdaptedBeanclass : @Stateful @RemoteHome(AdaptedHome.class) public class AdaptedBean { private String myId = "unknown"; @Init public void create(String id) { myId = id; } public String getId() { return myId; } } Notice that the bean class is implemented using the POJO-like simplifications of EJB 3.0. However, it uses the @RemoteHome annotation to exposes an EJB 2.x style remote home interface. This annotation tells the EJB container that the bean has a home interface named AdaptedHome and a remote interface named AdaptedRemote. You don't need a separate annotation to specify the AdaptedRemote interface. That's because the container can derive it from the signature of the AdaptedHome's create() method. If the bean exposed a local home interface, it would use the @LocalHome annotation instead. The other important annotation in the class is @Init. The EJB 2.x view always defines a create method, so you must define a method on the bean class to handle the create operation. The @Init annotation tells the EJB container which method that is. The method can have any name, but its method parameters must match the create method in the corresponding home interface. Here is the standalone client code for accessing AdaptedBean: try { InitialContext ic = new InitialContext(); Object o = ic.lookup(AdaptedHome.class.getName()); AdaptedHome adaptedHome = (AdaptedHome) PortableRemoteObject.narrow(o, AdaptedHome.class); AdaptedRemote adapted = adaptedHome.create("duke"); System.out.println("Adapted id = " + adapted.getId()); } catch(Exception e) { ... } Notice that the client code uses the standard EJB 2.x client programming model. It does not need to know that the target bean is implemented with EJB 3.0. Running the Sample Code A sample package accompanies this tip. To install and run the sample: - If you haven't already done so, download the Java EE 5 SDK from the Java EE Downloads Page. Also be sure to have an installed version of the Java Platform Standard Edition (Java SE) 5 SDK. - Download the sample package for the tip and extract its contents. You should now see the newly extracted directory as <sample_install_dir>/ttfeb2007ejbmigration, where <sample_install_dir>is the directory where you installed the sample package. For example, if you extracted the contents to C:\\on a Windows machine, then your newly created directory should be at C:\\ttfeb2007ejbmigration. Below this directory you should see two subdirectories: Migrationand Adapted. - To build and run the EJB 3.0-to-EJB 2.x compatibility example, change to the Migrationdirectory. To build and run the EJB 2.x-to-EJB 3.0 compatibility example, change to the Adapteddirectory. Then set the javaee.homelocation attribute in the build.xmlfile in the selected directory to the directory in which you installed the Java EE 5 application server. - Start the application server by entering the following command: <appserv_install>/bin/asadmin start-domain domain1 where <appsrv_install>is where you installed the Java EE 5 application server. - Enter the command: ant all This builds the sample application then deploys and executes it. You should see the following in the output for the EJB 3.0-to-EJB 2.x compatibility example : runappclient: [exec] Successfully called EJB 3.0 bean You should see the following in the output for the EJB 2.x-to-EJB 3.0 compatibility example: runjavaclient: [java] Adapted id = duke The application is then automatically undeployed and its build resources erased. Summary The EJB 3.0 specification greatly simplifies the session bean API. But it does so with the understanding that there is a large investment in EJB applications built with earlier versions of the specification. For this reason, a goal of EJB 3.0 is to ensure smooth interoperability between new and existing applications. If you are a developer using EJB 3.0, you have a lot flexibility in deciding whether to migrate legacy applications to the new API or to take advantage of those legacy applications from new components. About the Author Ken Saks is the lead architect for the EJB 3.0 container in the Java EE 5 SDK. He has been a member of the Enterprise Java group at Sun Microsystems since 1999. I have a question for Ken regarding the migration to 3.0 apps. Hi Ken, I am working in a Application which has more than 1000 ejbs(transactions) running with ejb 2.0 . We want to migrate the Application to a different environment where it has to run with ejb 3.0 . We can't go and make changes in code for the 1000 transactions and make it compatible for ejb 3.0 . Is there any other option/way that without changing the code (ejb 2.0) we can still run this app with ejb 3.0 specification . Posted by Jeet on March 09, 2009 at 03:24 PM PDT # Hi Jeet, It depends what you mean by "run this app with ejb 3.0". Just like Java SE, every release of Java EE is backward compatible with its previous releases, so at minimum you could just deploy your existing EJB 2.0 (J2EE 1.3) app to a product that supports EJB 3.0 (Java EE 5) If you want new code to call your old beans, that's fine too. Any Java EE 5 component --whether it's an EJB or not -- can call your old beans using the EJB 2.x client view. It's even a bit simpler to do since they can inject the Home/LocalHome references using @EJB instead of a lookup, but that approach is not required. You could also change the implementation of your old beans to start taking advantage of the new EJB 3.0 API. Obviously, that's more work, especially given the number of components in your application. However, the key is that you don't have to do this for the old components to still be callable from completely new code. Let me know if you need more info. --ken Posted by Ken Saks on March 10, 2009 at 02:02 AM PDT # Thanks for the helpful information sharing! Posted by John Neyman on October 16, 2009 at 03:12 PM PDT #
https://blogs.oracle.com/enterprisetechtips/entry/ejb_3_0_compatibility_and
CC-MAIN-2014-15
refinedweb
1,834
57.98
Noah Campbell wrote: > As I understand c14n (and I'm learning volumes as I prepare to > implement a C14NSaver) the namespace is discarded in the > cananocialized form. Sure the output is not xml valid, or namespace > collisions cause a lossy form, but this is okay. The point is not to > have a valid doc but a representation that will be unique on a byte > level. David's already answered this - but just to cover off. Attribute qnames and namespaces are fully included in a canonicalised document, except exclusive C14n, where they will be discarded if they are not actually used. This is because namespaces impact the meaning of a document, and namespace prefixes could potentially be used to define some meaning in the doc (although I truly hope not!). A signature must be made invalid if anything in the document changes that might impact it's meaning. The output of C14n will be a well formed document for a full document or full sub-tree canonicalisation. Where an XPath (or other) transform has selected nodes that together do not provide a well formed document the output will not be well-formed. (There are some fantastic test cases for c14n interoperability that give truly weird outputs :>.) For full document canonicalisation, I cannot easily think of a document where the canonicalised form would not be valid if the input document was valid (maybe exclusive c14n where default namespaces attributes were discuarded?). C14n is really just a strongly defined serialisation routine. Cheers, Berin - --------------------------------------------------------------------- To unsubscribe, e-mail: xmlbeans-dev-unsubscribe@xml.apache.org For additional commands, e-mail: xmlbeans-dev-help@xml.apache.org Apache XMLBeans Project -- URL:
http://mail-archives.apache.org/mod_mbox/xmlbeans-dev/200407.mbox/%3C40E5EC4F.3010004@wingsofhermes.org%3E
CC-MAIN-2016-44
refinedweb
275
54.02
polygon.cut(cutter) throws the following error: Runtime error Traceback (most recent call last): File "<string>", line 12, in <module> File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\arcobjects\arcobjects.py", line 825, in cut return convertArcObjectToPythonObject(self._arc_object.Cut(*gp_fixargs((other,)))) RuntimeError: An internal error has occurred in the geometry system. it is working successfully for other studies i ran this tool with, but fails on this particular one with no clear error message or indication on what to do. Attached is the GDB on which i try to execute the following script import arcpy fields = ['SHAPE@'] for row_bounding_polygon in arcpy.da.SearchCursor("bounding_polygon", fields): feat_bounding_polygon = row_bounding_polygon[0] for row_polylines in arcpy.da.SearchCursor("debug_polylines", fields): feat_polyline = row_polylines[0] cut_feature = feat_bounding_polygon.cut(feat_polyline) Any help from Esri on what is going wrong here would be helpful. thanks! I'm afraid that the cut method does not like the arcs in the boundary of your polygon. Look at the code below: It will print: So a second polygon is created where every point is added (however without the arcs). This will change the polygon and its area. As a result the cut will work and create a featureclass with 6 polygon. For every line the polygon will be split into 2 polygons. I assume that is not what you want. You are probably interested in obtaining 4 polygon, right? In that case you split the polygon and evaluate with part intersects with the next line and so on.
https://community.esri.com/thread/213907-polygoncut-method-throws-runtimeerror-an-internal-error-has-occurred-in-the-geometry-system
CC-MAIN-2018-39
refinedweb
250
57.37
Details - Type: Improvement - Status: Closed - Priority: Minor - Resolution: Fixed - Affects Version/s: 1.1.1 (alpha) - Fix Version/s: 1.3.0 Release - Component/s: None - Labels:None - Environment: Operating System: other Platform: Other Description I just tried applying the prototype[1] JavaScript library to my project and discovered that its mechanism of adding an "extends" function to the base JavaScript object causes the validation routines in Commons Validator to break because they don't know what to do with the "extends" member. Matt Raible reported a similar problem against JSON[2] [1] [2] I know there have been big potential changes to the validator JS for a while; maybe this is a further motivator. Issue Links - is depended upon by VALIDATOR-7 [validator] Collision between Prototype.js and Validator - Closed Activity - All - Work Log - History - Activity - Transitions Laurie posted on the struts user list that the yet-to-be-release 1.4 version of prototype seems to be OK: I created a bug with id 37594 and submitted a patch that solves this issue. If you're interested go to the bug and see patches or completes JS files. Philippe. Created an attachment (id=17015) Correction to JS files of the library starting from version 1.1.4 Here are the correction made on your Javascript: Scope too large for your variables: - oCreditCard, oByte,oDate - Replaced == true by === true, same for == 0 - parse replaced by parse(x, 10) I'am using prototype.js in conjunction with the validator but I am facing the following problem, this library adds a field extends to objects so for (var x in oRequired) will iterate over 4 fields instead of 3 and encounter x = 'extends' and oRequired[x][0] will be undefined breaking the rest. What I did was to add matchValidationVariable () function with the following code that checks that the variable oRequired[x][0] is not undefined and that the name of x matches your variable names ('^a[0-9]*$'): function matchValidationVariable(variable, value) Created an attachment (id=17016) Patch from version 1.1.4 (JS files) Same content a zip files but at patch format. Created an attachment (id=17025) Javascript patch to version 1.2.0 This is the patch to current version in the Subversion and in the Subversion format. Philippe, thanks for the patch - I implemented something slightly different, testing if its an array of length 3. Tried this out with Prototype 1.3.1 and it worked fine. This should be available in the next nightly build to test out (i.e. one dated 9th Jan or later): Closing as FIXED (I'll open a new bug for the namespaced issue). Re-openned and the set to "Resolved Fixed" again to correct "resolution" which was lost in Bugzilla --> JIRA conversion Yes, Prototype is evil. Not only does it add a property to Object, it also adds properties to other fundamental JavaScript types, such as Array. This is very antisocial behaviour for a toolkit, and pretty much hoses any usage of the 'for ... in ...' construct in existing JavaScript code, unless that code was very carefully written to work around exactly that behaviour. Another big issue with Prototype is that it is not namespaced. All of its classes are defined directly within the global JavaScript namespace, and it defines some classes with names that are quite likely to exist in application code (e.g. Form, Field). This has the potential for creating serious havoc, especially in portal / portlet environments. Of course, one of the big issues with the Commons Validator JavaScript code is that it too is not namespaced. ;-( That's something that needs fixing. It's not that hard to fix, but the changes would introduce new rules for people writing custom validators. It's most definitely do-able, though, and needs to be done. Prototype's increasing popularity, ironically, makes it decreasingly likely that the serious deficiencies will be rectified, since that would mean breaking lots of existing code. So I guess for Commons Validator, at least, we'll need to code around those deficiencies. That too can be done - it's just a pain in the butt, adds more code, and shouldn't be necessary. Personally, I'm going to focus my client-side efforts on Dojo[1], a properly written toolkit that doesn't have these kinds of problems, and I wish the folks who want to use Prototype, and its derivatives, the best of luck. [1]
https://issues.apache.org/jira/browse/VALIDATOR-109?focusedCommentId=12410670&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-27
refinedweb
742
60.04
Results 1 to 2 of 2 - Join Date - Mar 2013 - 1 - Thanks - 0 - Thanked 0 Times in 0 Posts error message 26 and do not know why Could someone advise me why I am receiving the above error message... import javax.swing.JOptionPane; import java.util.Scanner; // Needed for the Scanner Class /** This program demonstrates using dialogs * with JOptionPane. * */ /** This program calculates three instances * to obtain BodyMassIndex by passing * arugments to if statements. */ public class BodyMassIndex { public static void main(String[] args) { String inputString; // For reading input double weight; // The user's weight double height; // The user's height bodyMassIndex // The user's body mass index // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the user's weight. inputString = JOptionPane.showInputDialog("What is " + "your weight in pounds? "); weight = keyboard.nextDouble(); // Get the user's height. inputString = JOptionPane.showInputDialog("What is " + "your height in inches? "); height = keyboard.nextDouble(); // Calculate the body mass index. bodyMassIndex = weight * 703 / Math.pow(height, 2.0); // Display the results. { if (bodyMassIndex > 25) System.out.println("You are overweight"); if (bodyMassIndex >= 18.5 && bodyMassIndex <= 25) System.out.println("You are at optimal weight"); if (bodyMassIndex < 18.5) System.out.println("You are underweight"); } System.exit(0); } } - Join Date - Sep 2002 - Location - Saskatoon, Saskatchewan - 17,026 - Thanks - 4 - Thanked 2,668 Times in 2,637 Posts bodyMassIndex isn't declared properly. It needs a datatype and a semi-colon. Also, you are mixing swing and cli here. Once you've been prompted for input in the gui, you'll then need to proceed and enter on the command line. Choose to either use an entire gui application and stick with the swing components, or drop the swing and run it on the command line. Don't mix the two. Also, in the future please wrap your code in [php][/php] or [code][/code] tags to preserve the formatting.PHP Code: header('HTTP/1.1 420 Enhance Your Calm');
http://www.codingforums.com/java-and-jsp/289950-error-message-26-do-not-know-why.html?s=079d06162da9e1f116968d1fd37ebcba
CC-MAIN-2017-22
refinedweb
326
61.02
Content-type: text/html XmClipboardCopy - A clipboard function that copies a data item to temporary storage for later copying to clipboard #include <Xm/Xm.h> #include <Xm/CutPaste.h> int XmClipboardCopy (display, window, item_id, format_name, buffer, length, private_id, data_id) Display * display; Window window; long item_id; char * format_name; XtPointer buffer; unsigned long length; long private_id; long * data_id;(3X).. Specifies the name of the format in which the data item is stored on the clipboard. Format is known as target in the ICCCM. Specifies the buffer from which the clipboard copies the data. Specifies the length of the data being copied to the clipboard. Specifies the private data that the application wants to store with the data item. Specifies an identifying number assigned to the data item that uniquely identifies the data item and the format. This argument is required only for data that is passed by name. The function is successful.. The function failed because XmClipboardStartCopy was not called or because the data item contains too many formats. XmClipboardCopyByName(3X), XmClipboardEndCopy(3X), XmClipboardStartCopy(3X)
http://backdrift.org/man/tru64/man3/XmClipboardCopy.3X.html
CC-MAIN-2017-09
refinedweb
173
50.33
E4/Resources/Meeting/19-Sep-2008 Kick-off Contents - Regrets: Broadcom - James Blackburn Agenda Feel free to edit, but not during the meeting DougS on the platform-core-dev mailing list: I'd like to start by getting introductions from everyone on the call including their background and a high level view of what they'd like to see out of e4 resources. Then I'd like to walk through the E4/Resources/Work Areas page, that Martin O. has prepared and see if there anything people have objection to, or items they'd like to add. Please take a look before the meeting. That'll easily take the hour, so I'd like to discuss how often we want to meet and get an idea of things people would be able to work on in between meetings. Notes Interested Parties and Background - Doug Schaefer: Wanted to enable VS projects in Eclipse, that initial work later carried on by Ken Ryall (Nokia). Idea was a virtual file system similar to EFS. Ran into troubles due to assumptions of clients (external tools) that resources are backed by a physical file system. EclipseCon 2008 discussion picked up by E4 effort. - McQ: For making Eclipse more pervasive, E4 gives us the freedom to take a step back without immediate need for backward compatibility - Serge Beauchamp: Metroworks CodeWarrior background (similar to VS). Need flexible project structure bug 229633. - Martin: It's not decided yet whether E4 will be a vast, big effort -- it will be what we as a community make it. For now, just all items are on the table. All input is valuable! - Ken Ryall: Many customers coming from CodeWarrior having file-list based project structure. Want migration into Eclipse. Interested in working on broader changes, did some work on flexible file system prototype in CDT (virtual file system), encouraged by initial results. Interested in 3.5 shorter-term fixes. Customers want standard, unmodified Platform. Scalability and filtering (very large projects) - Terry Parker & Tom Ball: Very large code bases on Linux, current model falls down in some cases: - Complete refresh of the workspace don't work - HIDDEN attribute doesn't keep resources from being traversed. Want to exclude portions of large underlying file system. IntelliJ can pull the entire codebase in (Eclipse is killed by that) - Aliased paths (symbolic links) - canonical form of paths (better comparator) instead of plain Strings - Sergey Prigogin: Hiding stuff must be done before EFS, before Resource creation - Ken Hussey: Make Resources file system agnostic, more RESTful style of resources. Better Content Types instead of file extensions. Filtering ("what's visible" based on resource sets) - Chris, Doug - For external tools and version control, EFS mapping to physical paths is a problem - Chris Recoskie: Import existing physical project structures into CDT; Remote Resources; - Martin Oberhuber: Bringing large legacy file structures into Eclipse, making it easier for customers to apply Eclipse to their daily work. Physical project nesting, Flexible Projects. Also interested in Architecture but with lower priority. - Michael Scharf:. - DougS: Clearcase remote client has a good workflow. Resource system as a View on something. - John Arthorne: Could be several different application layers. One characteristic of EFS is that it's stateless, whereas one big value-add of the Resource model is that it's adding state (markers, sync info, ...) on top of physical. - DougS: How to attach metadata that gets checked in? (Coming from the Build angle) - Have different types of notifications (on resource layer and application layer) - Boris: Currently, notifications are on workspace basis. Might want multiple workspaces. - Martin: Multi-workspace also interesting to work on multiple versions of same project (name resolution) - McQ: Name resolution inside single workspace would also be interesting. - McQ: Using EFS for arbitrary filesystem-like things is pushing it too far. On a remote workspace, it's likely that Build wouldnever have to occur locally. Distributed is interesting, but don't warp this into EFS. - McQ: Want to give insight in why things are the way they are, but won't be able to invest lots of resources. - Boris Bokowski: Interested in architectural side of things, want to get rid of Singletons - Szymon Brandys: - Eric Frey: Large user of Eclipse, writing individual tools, want to be Ecilpse based. Need flexible resource and project model (projects in same directory) - based on VS - Michael: need to think about what a project is (root dir + meta info) - that's different than the definition of project in other IDE's - Doug: Lots of problems in the past in CDT came from trying to apply Eclipse concepts to non-Eclipse worlds -- e.g. Autobuilder. In reality, CDT build does work differently. Looking at modeling stuff in the resource system that can help. - McQ: One of the big differentiators of Eclipse to other IDEs is Autobuild, the power of Resource Deltas. This needs to be part of the solution. - Doug: Have 2 builders in CDT, one of them based on resource deltas but most people work on external make (which is annoying). Doug wants to fix the architecture such that external builders work better. - McQ: What about Logical Model Support that's in place now? Managing sub-file or super-file resources? - Resources can be adapted to ResourceMapping, which describes related resources. Allows writing all of them to repository in one operation. - Michael: We need to come up with a common terminology and need to agree on a meaning. - Doug: Wants to start talking in terms of work items, and stuff that we want to start prototyping right away. Want more discussion on platform-core-dev mailing list. - Where should prototyping happen? - Boris: Will get the project created soon. Galileo vs E4 - Adding stuff to Galileo already is compelling, but what about the Risk of creating new complications in terms of compatibility for the "Real solution"? - McQ is a big fan of adding features early, if it doesn't conflict with the big picture. - Most participants will want part features implemented early. Work Areas - E4/Resources/Work Areas - the big rocks: - Improved Alias Management - Fix issues with symbolic links / linked resources - multiple nodes pointing to the same content - clarify semantics of aliasing / overlapping - Alias Management: Terry, Sergey (Google), James (Broadcom), Martin (Wind River) - Improved Project Structure - relative/variable-based linked resources, file-list-based projects, multi-workspace, physical/logical project nesting, namespace resolution, perspectives/filtering - Filtering: Sergey, Terry, Tom (Google), Ken (Nokia), Kenn (Embarcadero), Martin, Michael (Wind River) - Refresh/Large Workspace Performance: Terry, Tom (Google), Ken (Nokia) - Flexible Project Structure: Doug (Wind River), Serge (Freescale), Ken (Nokia), Chris (IBM), Eric (NVidia), James (Broadcom) - Physical Project Nesting: Martin (Wind River) - Multiple Workspaces: Boris, McQ (IBM), Martin (Wind River) - Namespace resolution: McQ (IBM) - Multiple Projects in one Dir - Eric (NVidia) - Improved Meta Data - More settings levelling, arbitrary metadata attached to resources with persistence or from file system (with lifecycle ala markers), pluggable project/metadata persistence (interoperability with other IDEs) - Arbitrary Persistable Data on Resources - Doug (Wind River), for Builders - Improved Remote Support - improved handling of latency, errors, caching; support for remote workspaces; physical/logical path translation - Remote, asynchronous - Chris (IBM) - Remote Workspaces - McQ (IBM) - RESTful - Kenn (Embarcadero) - Mapping URI to physical path - Chris (IBM), Doug (Wind River) - Improved Programming Model - more concurrency, more componentization, fewer listeners, listener order and race conditions, no Singletons (See also E4/Pervasive Themes) - Layered Architecture - Michael (Wind River) - Getting rid of Singletons - Boris (IBM) Communication Channels - platform-core-dev mailing list - Anything else? Try to attract more people? What about IRC, Bugzilla, E4 list? Meeting Schedule - Talk on platform-core-dev list - Will discuss this on CDT Summit - Next meeting in 2 weeks Action Items Martin: Start E4/Resources/Definitions of Terms - discuss on platform-core-dev mailing list, put notes together on Wiki Next Meeting - Next E4/Resources/Meeting/3-Oct-2008 (2 weeks after)
http://wiki.eclipse.org/index.php?title=E4/Resources/Meeting/19-Sep-2008_Kick-off&oldid=119658
CC-MAIN-2016-50
refinedweb
1,300
51.89
Opened 7 years ago Closed 7 years ago Last modified 7 years ago #8617 closed defect (invalid) SVN post-commit hook fails Description (last modified by ) I tried to use the SVN post-commit hook, but was unable to make it work. When I enabled logging (commithook.log) I got the following error: ERROR while processing: Unable to get database connection within 0 seconds. (TracError(<babel.support.LazyProxy object at 0x898175c>,)) Attachments (0) Change History (13) comment:1 Changed 7 years ago by -? comment:2 Changed 7 years ago by Meant to include this snippet above import trac.env e = trac.env.Environment('/path/to/your/trac') comment:3 follow-up: 4 Changed 7 years ago by Replying to bobbysmith007: -? 1) The database works, I think? 2) No, nothing more in the log 3) I used the post-commit from TimingAndEstimationSVNPostCommitHook 3a) Using the simplified post-commit-script resulted in this in the logs: [14:01:09] 2011-03-18 in svn post commit : <path/to/repo> : 1634 [14:01:09] TracEnv:</path/to/trac/env> Repo:<path/to/repo> Rev:1634 Auth:fredrik But nothing shows up in Trac. 4) Could execute the two commands in comment:2 without errors comment:4 follow-up: 5 Changed 7 years ago by - I assume you adjusted all the paths appropriately? - Did the trac post commit log have anything interesting in its log (like more instances of ERROR while processing: Unable to get database connection within 0 seconds. (TracError?(<babel.support.LazyProxy? object at 0x898175c>,)) ) - Can you execute /usr/bin/python /var/trac/trac-post-commit.py -p "$TRAC_ENV" -r "$REV" -u "$AUTHOR" -m "$MESSAGE" 2>&1(filling in the appropriate variables?) Does it work at all? - Are you sure that the user these end up running as all have appropriate permissions? - The place where that error would be the only one in the log, is on opening the environment. If the user executing the script didnt have permission tot eh filesystem in that location or something, I could imagine it manifesting in this way. Just shooting in the dark at various troubles I have had in the past and how I debugged them. comment:5 Changed 7 years ago by comment:6 Changed 7 years ago by The new error is different, but seems somewhat related (environment is failing to load correctly). Previously it seemed like connecting to the database was broken, but now it is connecting to the source control repo. self.env = open_environment(project) repos = self.env.get_repository() repos.sync() - Do you correctly have the repository you are trying to post from, setup in trac? (You can see it in the browser) - Is it the "default" repository? - Do you have more than one repo? This version of the script has only been tested against a single "default" repository. If you only have a single trac with a single repo, this post-commit should be fine. The post commit I use is more complex, but does handle multiple repositories. I have not included it because it contains code specific to my environment that is somewhat difficult to disentangle (about building links to gitweb for non trac git repositories and handling differences between git and svn repositories across our various trac instances). I can post that if you think that might meet your needs better, but it will definitely be a more complex setup and will require digging through the code to get it behaving exactly as you desire. comment:7 Changed 7 years ago by I do know it is not the "default" repository, but it is the only one present. comment:8 Changed 7 years ago by Not sure about the "default", as it seems unnecessary to specify that if there is only one. This is a working repository configuration for me. [trac] repository_dir = /var/svn/test-svn repository_type = svn With it I can execute the following in python shell and get a repository object back. import trac.env e = trac.env.Environment('/var/trac/test-svn/') e.get_repository() This is what the post commit is complaining about. Can you execute it and get a repository object? Sorry this has been such a pain to get working. I am sure we will get it eventually though, Russ comment:9 Changed 7 years ago by comment:10 Changed 7 years ago by comment:11 Changed 7 years ago by There is only one reference to sync, so the error 'NoneType' object has no attribute 'sync' must come from that one location, which makes it seem very much like that the error is opening the environment. Perhaps try adding these log messages near where the error messages are occuring, as they might shed light on why this is being problematic. class CommitHook: def __init__(self, project=options.project, author=options.user, rev=options.rev, url=options.url): log ("About to Open Project: %s", project) self.env = open_environment(project) repos = self.env.get_repository() log ("Got ENV : %s - Repo: %s", self.env, repos) repos.sync() ... Sorry this was supposed to be posted last friday :( comment:12 Changed 7 years ago by Found the problem after adding those log messages: triple checked my trac.ini, and found out that repository_dir was empty. Does repository information get stored in different places, since everything else worked before? comment:13 Changed 7 years ago by Trac 12 changed how repositories are setup, allowing multiple repos for a single trac instance. The repository_dir key is no longer the only way to configure a repository in trac, but that had previously been "the way" that this was configured. My guess is that repository configuration dir can also be set as follows and have everything in trac work (other than possibly this post commit (not sure havent tried this alternative config with this post commit)). Perhaps this is how the trac installer installs this by default now; I'm not sure because I use a very custom install process. [repositories] .alias = design # set design to be default design.dir = /var/svn/Design design.url =
https://trac-hacks.org/ticket/8617
CC-MAIN-2018-13
refinedweb
1,004
54.12
Prev Next C Preprocessor directives: - Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing. - Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol. Below is the list of preprocessor directives that C programming language offers. A program in C language involves into different processes. Below diagram will help you to understand all the processes that a C program comes across. There are 4 regions of memory which are created by a compiled C program. They are, - First region – This is the memory region which holds the executable code of the program. - 2nd region – In this memory region, global variables are stored. - 3rd region – stack - 4th region – heap Do you know difference between stack & heap memory in C language? Do you know difference between compilers VS Interpreters in C language? Key points to remember: - Source program is converted into executable code through different processes like precompilation, compilation, assembling and linking. - Local variables uses stack memory. - Dynamic memory allocation functions use the heap memory. Example program for #define, #include preprocessors in C language: - #define – This macro defines constant value and can be any of the basic data types. - #include <file_name> – The source code of the file “file_name” is included in the main C program where “#include <file_name>” is mentioned. C Output: Example program for conditional compilation directives: a) Example program for #ifdef, #else and #endif in C: - “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are included in source file. - Otherwise, “else” clause statements are included in source file for compilation and execution. C Output: b) Example program for #ifndef and #endif in C: - #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause statements are included in source file. - Otherwise, else clause statements are included in source file for compilation and execution. C Output: c) Example program for #if, #else and #endif in C: - “If” clause statement is included in source file if given condition is true. - Otherwise, else clause statement is included in source file for compilation and execution. C Output: Example program for undef in C language: This directive undefines existing macro in the program. C Output: Example program for pragma in C language: Pragma is used to call a function before and after main function in a C program. C
http://fresh2refresh.com/c-programming/c-preprocessor-directives/
CC-MAIN-2017-04
refinedweb
405
55.64
This article aims to introduce the std::vector as well as cover some of the most common vector member functions and how to use them properly. The article will also discuss predicates and function pointers as used in common iterator algorithms such as remove_if() and for_each(). After reading this article, the reader should be able to use the vector container effectively and should find no use for dynamic C-style arrays again. The vector is part of the C++ Standard Template Library (STL); an amalgamation of general-purpose, templatized classes and functions that implement a plethora of common data structures and algorithms. The vector is considered a container class. Like containers in real-life, these containers are objects that are designed to hold other objects. In short, a vector is a dynamic array designed to hold objects of any type, and capable of growing and shrinking as needed. In order to use vector, you need to include the following header file: #include <vector> The vector is part of the std namespace, so you need to qualify the name. This can be accomplished as shown here: using std::vector; vector<int> vInts; or you can fully qualify the name like this: std::vector<int> vInts; I do however suggest that you refrain from declaring global namespaces such as: using namespace std; This pollutes the global namespace and may cause problems in later implementations. As for the interface to the vector container, I have listed the member functions and operators of vector in the tables below. There are several constructors provided for the vector container. Here are some of the most common. vector<Widget> vWidgets; // ------ // | // |- Since vector is a container, its member functions // operate on iterators and the container itself so // it can hold objects of any type. vector<Widget> vWidgets(500); vector<Widget> vWidgets(500, Widget(0)); vector<Widget> vWidgetsFromAnother(vWidgets); The default method of adding elements to a vector is by using push_back(). The push_back() member function is responsible for adding elements to the end of a vector and allocating memory as needed. For example, to add 10 Widgets to a vector<Widget>, you would use the following code: for(int i= 0;i<10; i++) vWidgets.push_back(Widget(i)); Many times it is necessary to know how many elements are in your vector (if there are any at all). Remember, the vector is dynamic, and the number of allocations and push_back()s are usually determined by a user file or some other data source. To test if your vector contains anything at all, you call empty(). To get the number of elements, you call size(). For example, if you wanted to initialize a variable to -1 if your vector, v, is empty or to the number of elements in v if it's not, you would use the following code: int nSize = v.empty() ? -1 : static_cast<int>(v.size()); There are two ways to access objects stored in a vector. vector::at() vector::operator[] The operator[] is supported mainly for compatibility with a legacy C code base. It operates the same way a standard C-style array operator[] works. It is always preferred to use the at() member function, however, as at() is bounds-checked, and will throw an exception if we attempt to access a location beyond the vector limits. However, operator[] could care less and can cause some serious bugs as we will now demonstrate. Consider the following code: vector<int> v; v.reserve(10); for(int i=0; i<7; i++) v.push_back(i); try { int iVal1 = v[7]; // not bounds checked - will not throw int iVal2 = v.at(7); // bounds checked - will throw if out of range } catch(const exception& e) { cout << e.what(); } Now, just because we reserved space for 10 ints doesn't mean they are initialized or even defined. This scenario is best illustrated in the figure below. You can try this code on your own and observe the results or see a similar situation in the demo. The bottom line: use at() whenever you can. Getting things into a vector is fairly easy, but getting them out can be subtly tricky. First of all, the only member functions a vector has, to get rid of elements are erase(), pop_back(), and clear(). Now these are sufficient if you know: which elements you need to remove; if you only need to remove the last element; or if you want to remove all of the elements, respectively. Now before you go off writing some crazy loop to flag which elements you want to erase and brute-force yourself an application-specific implementation, sit back, take a deep breath, and think to yourself: "S...T...L...". Now, this is where we get into some fun stuff. To use remove_if(), you will need to include the following file: #include <algorithm> remove_if() takes 3 parameters: iterator _First: An iterator pointing to the first element in the range on which to operate. iterator _Last: An iterator pointing to the last element in the range on which to operate. predicate _Pred: A predicate to apply to the iterator being evaluated. Predicates are basically pointers to a function or an actual function object that returns a yes/no answer to a user defined evaluation of that object. The function object is required to supply a function call operator, operator()(). In the case of remove_if(), it is often useful to supply a function object derived from unary_function to allow the user to pass data to the predicate for evaluation. For example, consider a scenario in which you want to remove elements from a vector<CString> based on certain matching criteria, i.e. if the string contains a value, starts with a value, ends with a value or is a value. First you would set up a data structure that would hold the relevant data, similar to the following code: #include <functional> enum findmodes { FM_INVALID = 0, FM_IS, FM_STARTSWITH, FM_ENDSWITH, FM_CONTAINS }; typedef struct tagFindStr { UINT iMode; CString szMatchStr; } FindStr; typedef FindStr* LPFINDSTR; You could then proceed to implement the predicate as shown: class FindMatchingString : public std::unary_function<CString, bool> { public: FindMatchingString(const LPFINDSTR lpFS) : m_lpFS(lpFS) {} bool operator()(CString& szStringToCompare) const { bool retVal = false; switch(m_lpFS->iMode) { case FM_IS: { retVal = (szStringToCompare == m_lpFDD->szMatchStr); break; } case FM_STARTSWITH: { retVal = (szStringToCompare.Left(m_lpFDD->szMatchStr.GetLength()) == m_lpFDD->szWindowTitle); break; } case FM_ENDSWITH: { retVal = (szStringToCompare.Right(m_lpFDD->szMatchStr.GetLength()) == m_lpFDD->szMatchStr); break; } case FM_CONTAINS: { retVal = (szStringToCompare.Find(m_lpFDD->szMatchStr) != -1); break; } } return retVal; } private: LPFINDSTR m_lpFS; }; With this implementation, you could effectively remove strings from a vector as shown below: // remove all strings containing the value of // szRemove from vector<CString> vs. FindStr fs; fs.iMode = FM_CONTAINS; fs.szMatchStr = szRemove; vs.erase(std::remove_if(vs.begin(), vs.end(), FindMatchingString(&fs)), vs.end()); You may be wondering why I have a call to erase() when I am calling remove_if() in the above example. The reason for this is quite subtle and not intuitive for people not familiar with iterators or the STL algorithms. Since remove(), remove_if(), and all the remove cousins operate only on a range of iterators, they cannot operate on the container's internals. The call to remove_if() actually shuffles around the elements of the container being operated on. Consider the above example if: szRemove= "o". vs= the diagram shown below. After observing the results, one can see that remove_if() actually returns a forward iterator addressing the new end position of the modified range, one past the final element of the remnant sequence, free of the specified value. The remaining elements may or may not have their original value, to be safe, always assume they are unknown. The call to erase() then is responsible for actually disposing off the "removed" elements. Notice in the above example that we pass the range from the result of remove_if() through vs.end() to erase(). Many times, after lots of data removal or a liberal call to reserve(), you can end up with a vector whose internals are far larger than they need to be. In this case, it is often desirable to "shrink" the vector to fit the size of the data. However, the resize() member function is only capable of increasing the capacity of the vector. The only member capable of changing the size of the internal buffer is clear(), however this has some significant drawbacks like destroying everything in the vector. So how can one solve this problem? Well, let's attempt a first pass. Remember that we can construct a vector from another vector. Let's see what happens. Consider we have a vector, v, with a capacity of 1000. We then make a call to size() and realize we only have 7 elements in the vector. Wow, we're wasting lots of memory! Let's try and make a new vector from our current one. std::vector<CString> vNew(v); cout << vNew.capacity(); It turns out vNew.capacity() returns 7. The new vector only allocates enough space for what it gets from v. Now, I don't want to get rid of v, because I may be using it all over the place. What if I try and swap() the internals of v and vNew? vNew.swap(v); cout << vNew.capacity(); cout << v.capacity(); Interesting: vNew.capacity() is now 1000, and v.capacity() is 7. Sweet, it worked. Yes, it may have worked, but that's not an elegant solution, now is it? How can we make this swap trick have some flair? Do we really need to name our temporary variable? Lets try another approach. Consider this code: std::vector<CString>(v).swap(v); Can you see what we did there? We have created a temporary unnamed variable instead of a named one and did the swap() all in one step. Much more elegant. Now when the temporary variable goes out of scope, it will take its bloated internal buffer with it, and then we're left with a nice trim v. In the sample applications, you can see how to implement the topics discussed here. The console application is a step-by-step illustration of these examples in action, and the MFC application is mainly a demonstration of using STL, algorithms, and predicates with MFC. I hope this article serves as a valuable reference and guideline for developers using the STL vector container. I would also hope that those who were skeptical about using the vector before reading this article are now undaunted and ready to throw away their C-style arrays and try it out. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/stl/std_vector.aspx
crawl-002
refinedweb
1,758
55.44
NAME sem_getvalue - get the value of a semaphore SYNOPSIS #include <semaphore.h> int sem_getvalue(sem_t *sem, int *sval); Link with -lrt or -pthread. DESCRIPTION sem_getvalue() places the current value of the semaphore pointed to sem into the integer pointed to by sval. If one or more processes or threads are blocked waiting to lock the semaphore with sem_wait(3), POSIX.1-2001 permits two possibilities for the value returned in sval: either 0 is returned; or a negative number whose absolute value is the count of the number of processes and threads currently blocked in sem_wait(3). Linux adopts the former behavior. RETURN VALUE sem_getvalue() returns 0 on success; on error, -1 is returned and errno is set to indicate the error. ERRORS EINVAL sem is not a valid semaphore. CONFORMING TO POSIX.1-2001. NOTES The value of the semaphore may already have changed by the time sem_getvalue() returns. SEE ALSO sem_post(3), sem_wait(3), sem_overview(7) COLOPHON This page is part of release 3.21 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/karmic/man3/sem_getvalue.3.html
CC-MAIN-2013-48
refinedweb
187
66.33
Question: I have an application developed in flash, and I need to access some php files. so the php file return some data if the access is came from swf. How can i identify if the request came from flash or not? without passing get/post variables to php. Solution:1 User agent/Referer possibly. Keep in mind that requests can easily be forged Solution:2 I don't think there really is a reliable way of detecting whether Flash made the request. Flash doesn't allow you to set the user-agent, and there are a lot of restrictions on what headers can be set. Take a look at as John Ballinger suggested, you could set your own header using this and look for that header in the PHP page. Solution:3 This is in response to John Ballinger's answer: import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestHeader; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest(""); var header:URLRequestHeader = new URLRequestHeader("custom-header-name", "value"); request.requestHeaders.push(header); try { loader.load(request); } catch (error:Error) { trace("Unable to load requested document."); } You must also make sure to modify your crossdomain.xml to allow http headers as follows: <!DOCTYPE cross-domain-policy SYSTEM ""> <cross-domain-policy> <allow-access-from <allow-http-request-headers-from </cross-domain-policy> Solution:4 You cannot tell that it is coming from flash as flash actually uses the browser to do the request. But in your flash request you could add your own header to the HTTP request (you can do this pretty easily in flash). That way you can see if the request is coming from Flash. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2019/06/tutorial-how-do-i-know-if-request-came.html
CC-MAIN-2021-04
refinedweb
301
50.02
HackerBoxes 0016: Cellular Metal Introduction: HackerBoxes 0016: Cellular Metal CELLULAR METAL: This month, HackerBox Hackers are exploring cellular mobile communication for embedded IoT (Internet of Things) and M2M (Machine-to-Machine) systems. We are also exploring the beauty of working close to the bare metal of a computing machine. This Instructable contains information for working with HackerBoxes #0016. If you would like to receive a box like this right to your mailbox each month, now is the time to subscribe at HackerBoxes.com and join the revolution! Topics and Learning Objectives for this HackerBox: - Compiling and Uploading Code onto an Arduino Board - Connecting a GSM Mobile Radio Module to an Arduino - Communicating on a Global Mobile Cellular Network - Building a Breadboard-Based Arduino from Scratch - Using an Existing Arduino as a DIY In-System-Programmer - Exploring an Online Microcontroller Course - Implementing a Minimal 8-Pin ATtiny Arduino - Dropping Down into Assembly and Machine Languages - Considering Machine Architecture through Assembly Language HackerBoxes is the monthly subscription box service for DIY electronics and computer technology. We are hobbyists, makers, and experimenters. And we are the dreamers of dreams. Step 1: HackerBoxes 0016: Box Contents - HackerBoxes #0016 Collectable Reference Card - Hologram Global IoT/M2M SIM Card - SIM800L 5V GSM Module with Rubber Ducky Antenna - RobotDyn Arduino UNO R3 Microcontroller Board - CP2102 MicroUSB-Serial Module - Solderless Breadboard - 65 Piece Jumper Wire Set for Breadboard - ATmega328P 28-Pin DIP Microcontroller Chip - ATtiny85 8-Pin DIP Microcontroller Chip - Various Discrete Components for Breadboard Arduino - Various Discrete Components for Microcontroller Course - Exclusive Tux "Hack The Planet" Stress Toy - Exclusive Apple Hacker Fan Art Decal Some other things that will be helpful: - Soldering iron and solder - Computer for running development tools: Setting Up the Arduino UNO Arduino Veteran: If you are already up to speed with using an Arduino UNO, already have the Arduino IDE installed, and already have the CH340 USB driver installed, you can skip to the next step. However, you should probably at least plug in your UNO and make sure you can compile and upload an example (such as blink.ino) just to make sure everything is ready to go. Less of a Veteran: Check out Step 12 of the instructions for the HackerBoxes Starter Workshop. There, you will find an overview of the Arduino ecosystem, the RobotDyn UNO in particular, and most importantly details on installing the CH340 USB drivers. Next, proceed to Step 13 of the instructions for the HackerBoxes Starter Workshop. There, you can grab a free copy of the Introduction to Arduino book by Alan Smith, Install the Arduino IDE, wire up your first Arduino circuit, and write your first Arduino program. Optional Extra: Continue on to Step 14 of the instructions for the HackerBoxes Starter Workshop to explore the world of Arduino even further. The components in this HackerBox #0016 happen to include everything needed to work through section 3.2 of the book. This is worth doing if you are new to Arduinos. You may also want to look at section 5.1 to learn about the serial monitor. While it is well beyond the scope of this current Instructable, the components for the remaining chapters list in Step 14 are included in the HackerBoxes Starter Workshop. Step 3: Wire Up the SIM800L Module to the Arduino UNO Of course we've all had times when we would like to have a project communicate over the cellular communications network. Sometimes Wi-Fi is not available or just doesn't have enough range. For example, maybe you want your project to send you a text message when a sensor is triggered. Or perhaps it needs to report data to another system from various mobile locations not serviced by Wi-Fi. The SIM800L module (datasheet) is a great solution. It has a quad-band radio (850/900/1800/1900MHz) supporting 2G Global System for Mobile Communications (GSM) including data packet transport via General Packet Radio Services (GPRS). The SIM800L can be simply wired to an Arduino UNO as shown here. The SIM800L is fairly easy to control using an AT command set or function from an existing library. Examples for both of these options are outlined in this quickstart tutorial. As a first step, you might want to wire the SIM800L to the Arduino without the antenna feed line or the SIM card, just to make sure that you can get a response to an "AT" or an "AT+CFUN?" command. In the next step we will move on to using the SIM card. Reference Links: Step 4: Hologram - the Global IoT SIM Card HackerBoxes is very excited to partner with Hologram to bring you this ready-to-use, global IoT/M2M SIM along with a $5 promotional balance. To mitigate the various challenges in putting your project or product online anywhere, Hologram has built a global SIM and cell network built for IoT and M2M data with simple activation and transparent pricing. The Global Hologram Cellular Network support connectivity in over 100 countries allowing us to connect our IoT devices seamlessly from one country and carrier to another. Follow the links here to activate your SIM. You will see a link to "Apply Promo Code" where you can enter the activation code: HACKERBOX5. The Hologram SIM card is a triple SIM. Be sure to only pop out the microSIM, which is the size used by the SIM800L modules. Hologram has put together a wonderful Cellular IoT Tutorial and library that leverages the components in this HackerBox. Definitely check it out! Step 5: Bare Metal Programming on the "Bare Metal" or "Near the Metal" or "Close to the Metal" is defined by Wikipedia as programming a machine without an operating system, which is a bit of an over-simplification. After the development of programmable computers, which did not require physical changes to run different programs, but prior to the development of operating systems, programs were fed to the computer system directly using machine language by the programmers without any system software support. This bare metal approach bootstrapped the development of operating systems. Modern operating systems evolved through various stages, from quite elementary to the present day complex, highly-sensitive, real-time systems. Today, bare metal work is mostly applicable to embedded systems and firmware, while everyday programs are executed by a runtime system within an operating system. That said, even the Arduino platform that has become almost ubiquitous in the embedded world, uses a bootloader and various libraries to abstract us away from the metal of the AVR microcontroller. It is time to dig deeper. Step 6: DIY Arduino From a Bare AVR Micrcontroller Chip Starting with a stock (completely blank) ATmega328P chip, you can do some amazing things. This the same chip that is used on the Arduino UNO R3 boards. The ATmega328P is a high-performance 8-bit AVR RISC-based microcontroller. It combines 32KB ISP flash memory with read-while-write capabilities, 1024B EEPROM, 2KB SRAM, and 23 general purpose I/O lines. Take a look at the schematic shown here with the components needed from the HackerBox. This video tutorial from PyroElectro shows how to wire up a DIY Arduino on a breadboard from components. Notice that the schematic we are using here has a slight variation from the one in the video. While the video shows use of a battery and a regulator circuit as the power supply, we are simply using the 5V supply from the Serial-USB module. The Serial-USB Module uses the CP2102 bridge chip. If you do not have drivers installed for this chip, they may be found here. Another important difference is that the video tutorial assumes that the ATmega328P chip already has an Arduino bootloaded burned onto it. Since we are starting from a blank chip, we will need to need to program the bootloader onto the ATmega328P chip. We can use the UNO as an In System Programmer (ISP) as shown under the Burning The Bootloader heading on this page. Step 7: Online Course for Microcontrollers From PyroElectro The PyroElectro video in the last step is actually just one part of an entire ten lesson online course covering microcontrollers. You may wish to work through the other lessons as well. You have all of the necessary components in HackerBox #0016 to do these lessons aside from some of the extra "user interface" components used in lesson 8. As an added exercise, see if you can replace these hardware interface elements with a user interface leveraging the serial monitor. Lesson 10, AVR vs Arduino, covers precisely the "bare metal" issue we are addressing here, so we definitely recommend that you at least watch the video for Lesson 10. Much respect for the work done by PyroElectro on these lessons. Step 8: Minimal Arduino With the 8-pin ATtiny85 The ATtiny85 is a great option for running simple Arduino programs. It’s small, cheap, and relatively easy to use. Compared to the ATmega328P (from the Arduino UNO), the ATtiny85 has fewer pins, meaning you can’t connect as many components. It has less flash memory (8KB instead of 32KB), meaning your programs can’t be as big. It has less RAM (512 bytes instead of 2KB), meaning you can’t store as much data. And there’s no hardware serial port or I2C port, so communication can be a little trickier. However, if your project requires only a few simple inputs and/or outputs, you’re probably fine using an ATtiny85. This tutorial from High-Low Tech can show you how its done! Step 9: Assembly Language for AVR Microcontrollers Now that we've used bare AVR micros to build up DIY Breadboard Arduinos, we can go a step further and drop down to writing machine code directly on the chip. This is an advanced topic, but there is no better way to learn the deep details of how processors work. Luckily, there is an entire online book covering the subject of AVR Assembly Programming. Note that you can also embed inline assembly code within a traditional Arduino program when added efficiency or tight execution is called for. Further down the rabbit hole, you might want to explore more of a general or academic view of assembly/machine programming and how it relates to the underlying computer architecture. If so, check out the CMU lectures on Computer Architecture or the lectures and slides for CS24 at Caltech. Step 10: Hack the Planet Thank you for joinging our adventures into mobile cellular IoT/M2M communications and bare metal computing.! My box contained two "220" ceramic caps instead of the "22" indicated in the tut and images. If I use these 220 in place of the 22 is this going to hurt my board or PC? If so is it possible to mail me the 22's I was supposed to receive? My local Radio Shaq doesn't carry 22's so this is mildly inconvenient for me. Those should be 22pF caps which should be correct for the timing crystal. These are the caps that came with my package in place of the 22pF. This confused me as well, apparently 22pf capacitors can be marked either 22, or 220. Those look like 22pF caps to me :) To clarify, youve got the correct parts. ? Hey folks, I noticed lots of ya were having issues with the SIM800 module. I made an Arduino library and tutorial to help everyone out. Enjoy!... I'm not sure what the issue is, I've done both the HackerBox way and jasper_fracture's way, and I can't get it to send an SMS. Every AT comes back as OK and it has good reception and connectivity and all that happy blah blah blah.The power is hooked up externally from my PC, not through the USB port. In the Serial Monitor I get an error after inputting /032 from the jasper tutorial, but I get the SMS Sent! from the HackerBox one. I'm lost, frustrated, annoyed. Yes, I'm putting my personal cell number in the code... Hi Grant - Regarding my tutorial, it sounds like you might have an incorrect setting in the Serial Monitor. Check out the subreddit thread at:... Can't guarantee it's the exact same problem Anand was having, but it sounds similar. Good luck with it. :) I am in the same boat. Everything acts like it should send normally, I get an Error in the same spot as you. So I found some info on getting more than just "Error" put AT+CMEE=1 or 2 for verbose error output with an error code. Then try your sending again. AT+CMEE=1 OK AT+ HELLO > +CMS ERROR: 2172 Allow me to share the burden of frustration my brother! ;) I have been struggling with the same issues where I've finally got to the point where everything appears to be sending correctly from the GPRS module but I could not see anything on the Hologram Dashboard to corroborate that anything was being sent. Yesterday, I noticed that my Hologram card account balance was dropping which led me to the billing section of the Dash. I can see the transactions that prove that I am communicating to Hologram correctly but I am not receiving these text messages. I'm pretty DANG happy that I at least see the transactions but the text message would be nice too. You should verify in the billing details too. It may bring clarity. All the best! Sean I just saw this in the Hologram Community Forum. This might help! Location Tracker was made using SIM800L module. It will be used to fetch nearby cell tower information. Using this data custom opencellid.org web link will be printed on serial monitor. When user visits that web link, current approximate location of SIM800L module will get displayed. Git Repo: I have an issue, and according what I was reading is the power issue, the D2 light just keeps hold for a little, it blinks every 5 seconds, so I guess I'll need a external power supply. thanks to @jasper who made a lot better tutorial that the one here. Well, likes last one, a lot of little issues. Not really exited by this last two boxes, hope next one be better. Hi Martinez - Thank you! You may have a problem with cell reception. Try the AT command: AT+COPS=? It should return something like: +COPS: (2,”T-Mobile USA”,”TMO”,”310260″),,(0-4),(0-2). If you get something like: (0-4),(0,2), I think you might have reception issues. I'm going to try this tonight, thanks for the answer. Quick question, when I activate the hologram I choose region 1, do you think is better option choose region 2? I'm on the United States and both shows in the map. I'm really not sure on the zones. Hologram has a "Live Chat" feature on their website which would probably get you fastest answer. If you're in a rural area like me, reception might be a problem until you get closer to a tower that the SIM800L can work with. Also, if you have a big cap like a 470uF, try putting it across the power rails supplying the SIM800L. That really seemed to help me. Either way, good luck with it - be interested to hear if you get it working. OK this is driving me nutz!!! It's not connecting to the cellular network it seems. I activated the SIM ok. I have everything wired properly. I tripple checked wiring and code. Then I ate a Nutty Bar and checked it again! AT command responds "OK" But - AT+CREG? = 0. I assume that's meaning its not connected. The Hologram Dashboard doesn't show any data either. Was this ever resolved? Having the exact same issue. I got this response from Ryan @ Hologram as the proposed fix. I have been so busy I have not had a chance to try it myself. I hope to give it a whirl within the next few days and will post my results back here. Hi @TimGTech For some reason the SIM800 sent requires a SMS config. This blog post explains the steps Basically run this command: AT+CSMP=17,167,0,16 . The post explains things in more detail. If you could try this, then we can go from there. @benstr Thanks, Ryan I saw that answer on their forums and i tried it with no success. I opened another topic with hologram to see if i can get any success. It is strange I can receive sms fine but I cant send any. Hey Tim, what does `AT+COPS=?` return? Hi Ben AT+COPS=? = +COPS: (2,"T-Mobile USA","TMO","310260"),,(0-4),(0-2) So I guess maybe it is connecting? I am also having a similar problem. COPS=? returns the same result T-Mobile. I set at+cgdcont=1 to the following +CGDCONT: 1,"IP","hologram","0.0.0.0",0,0 +CGDCONT: 2,"IP","","0.0.0.0",0,0 +CGDCONT: 3,"IP","","0.0.0.0",0,0 And if I run at+cgact=1,1 I get an IP +CGDCONT: 1,"IP","hologram","10.155.128.197",0,0 I still cannot send an SMS. I've even tried a program called "AT Command Tester" to make sure I wasn't doing anything wrong and it doesn't work either. When I attempt to send the SMS I don't get an error back either. +CMGS: <NUM> OK Hologram's portal shows my SIM card as live but shows no data having passed through it. I'm at a loss... Sounds like we have the same issue. I posted in the Hologram forum. Any feedback or resolution I get from there I will post back here. Yep, you are connected. The nearest tower must be TMO. No need to set the APN when only sending SMS. The APN is for sending/receiving data to the cloud. Can you open a post in our forums and we can dive deeper into the issue. Thank Ben. I have a post on the Hologram Community forum. Hopefully it will get worked out. I'm hoping to get it working. At least to be able to send SMS messages. Yep, you are connected. The nearest tower must be TMO. Can you open a post in our forums and we can dive deeper into the issue. AT+COPS? = 0 Interesting article. Looks like we have a year to play with the this SIM module in the US. I think only AT&T has sunset their 2G network (it caused a lot of trouble in the SF Bay Area because the bus service hadn't updated to 3G for their real-time tracking). T-Mobile has been reaching out to people cut off by the AT&T sunset, so hopefully they keep it going. Yep, I'm just not getting a connection to the network. Wired up correctly, SIM in correctly, one solid red light, one blinky red light. AT+COPS=? gives me "+COPS: ,(0-4),(0-2)". What am I doing wrong? Setup Complete! AT OK AT+CFUN=1 OK AT+CMGF=1 OK AT+CMGW="+15033294934" ERROR SMS Ready AT+CMGW="+15033294934" ERROR AT+COPS=? +COPS: (1,"T-Mobile USA","TMO","310260"),,(0-4),(0-2) OK Regards, Ken I don't think you need the + in front of the country code. At least I did not. With or without "+", same problem. grtyvr is right...no need for +1 Also instead of "AT+CMGW", try using: AT+CMGS="1AREACODEYOURNUMBER" If you're entering the text in through the Serial Monitor, you're going to need a way to send "Ctrl-Z" to end the text body entry. There's a demo on my site that might help. Good luck with it! :) Really can't figure out what the heck is wrong with not being able to send out an SMS. Attached is an image of my setup. I am not using the board sent with the kit, as I thought that might have been contributing to the issue, but it's not apparently. Running the following code: /* Sketch: GPRS Connect TCP Function: This sketch is used to test seeeduino GPRS's send SMS func.to make it work, you should insert SIM card to Seeeduino GPRS and replace the phoneNumber,enjoy it! ************************************************************************************ note: the following pins has been used and should not be used for other purposes. pin 8 // tx pin pin 7 // rx pin pin 9 // power key pin pin 12 // power status pin ************************************************************************************ created on 2013/12/5, version: 0.1 by lawliet.zou(lawliet.zou@gmail.com) */ #include <gprs.h> #include <SoftwareSerial.h> GPRS gprs; void setup() { Serial.begin(9600); while(!Serial); Serial.println("GPRS - Send SMS Test ..."); gprs.preInit(); delay(1000); while(0 != gprs.init()) { delay(1000); Serial.print("init error\r\n"); } Serial.println("Init success, start to send SMS message..."); gprs.sendSMS("757XXXXXXX","Hello World!"); //define phone number and text } void loop() { //nothing to do } This is the output to the Serial Monitor: GPRSck failed! GPRS - Send SMS Test ... Power check failed! My "Ring" LED on the SIM is light solid (mostly, it "resets" every so often) and the "Net" LED flashes about 1 to 2 times/second. I have NO idea why I cannot get this to work. When I've run other code to issue AT commands, my +COPS returns +COPS: (2,"T-Mobile USA","TMO","310260"),,(0-4),(0-2) so I should be able to send an SMS based on my review of other posts below. P.S. I changed the code for my phone number to the XXX's here, it's correct in the uploaded Sketch. I've modified my code a bit to add a notification via Serial Monitor after a text is "sent" as seen here: Serial.println("Init success, start to send SMS message..."); gprs.sendSMS("1757XXXxxxx","Hello World!"); //define phone number and text Serial.println("Text sent successfully"); Now, I am getting the following output on the Serial Monitor: GPRS - Send SMS Test ... Power check failed! Init success, start to send SMS message... ERROR:CMGF Text sent successfully So, there seems to be some holdup on being able to issue the CMGF command. Without being able to set AT+CMGF=1, a standard SMS can't be sent. Don't understand why it cannot do this. Hi - I just posted a short tutorial on what did to get ours working:... We found that the 800L board was a little finicky.power seemed to be an issue. Powering from a bench power supply at 5V, 2.5A seemed to work a lot better than USB/micro. Also, putting a 470uF capacitor across the 800L power seemed to help stabilize things. hi, can you show us how you fix that with the capacitor? An image would be very helpful. :) Hi, I posted a guide on how to use the SIM800 to send data to a webpage via HTTP GET, and the image for that post shows the 470uF cap on the power rails next to the board: So, a combination of things have made it work. Not sure which was the most responsible. I pulled out a USB module from a previous HB (was used for programming the Arduino Mini's), set it up to deliver 5v, and used it via a USB port on my computer to provide power. Then I used the code @jasper_fracture provided in the link above. Have now successfully sent three texts to my phone. I am investigating Jasper's code to see if maybe there is something there that I missed (I doubt it) just in case. Thanks for the help! Try going back to powering the device from the Arduino. It took at least 20 minutes for the sim to register on the network and for texts to start flowing for me. So I put a bootloader on the atmega238P and made a video about the process. Thanks again to HackerBoxes for some fun parts and good hints as to what direction to move in. If you need more step by step, this video might help you. The instructions for these are not very beginner friendly. Step by step instruction would be far more useful than just saying 'wire this to that' Do I need to provide my own female plugs for the SIM card? I'm confused about what I was supposed to plug them into the Arduino with? nevermind I'm stupid, I've moved into the testing phase at the 'without the sim or antenna' section. Not really sure what to do to test it here, obv some code in the Arduino ide.... Hopefully I can figure this out without causing an hemorrhage. Sorry I'm such a newb! Haven't messed with code since I helped make a game made with lwc, that was over 15yrs ago. Got this for me and my son. Our first box. I have found the link to the code that communicates to the sim800. Now to figure out how to use these test commands.... Going to try FreedomPop with the GSM module. The service is free - it sucks - but it's free. Got the SIM for $5. Where'd on their site did you see the options to sign up for such service? Do I need to find their 2G service for IoT type stuff?
http://www.instructables.com/id/HackerBoxes-0016-Cellular-Metal/
CC-MAIN-2017-39
refinedweb
4,255
73.68
The revolutionary project management tool is here! Plan visually with a single glance and make sure your projects get done. #include <iostream> #include <string> using namespace std; //--------------------------------------------------------------------------- // Global Variables //--------------------------------------------------------------------------- /* This is the correct DECRYPTED password */ string correctNumber("456"); /* String var to hold users guess at password. This variables value will need to be run through the DECRYPT function to see if it matches the value of correctNumber */ string guess; /* This is the encrypted password that will be built and encrypted based upon what the user types in. This will ultimately be compared to the encrypted version of correctNumber */ string userBuiltPassword; //--------------------------------------------------------------------------- // Function Prototypes //--------------------------------------------------------------------------- string encryptString(string strToEncrypt); string decryptString(string strToDecrypt); //--------------------------------------------------------------------------- int main() { cout << "The password has been generated! You need to guess it." << endl; cout << "Enter password: "; cin >> guess; string tempEnc = encryptString(guess); // Get encrypted version of user guess string tempCorr = encryptString(correctNumber); // Get encrypted version of correct if(tempEnc == tempCorr) { cout << "You cracked the code!" << endl; } else { cout << "Incorrect. You lose." << endl; } return 0; } //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- /** * Encrypts a string (using a global constant key) * * Takes a string and returns the encrypted version of the string. * The string is generated using a very simple character substitution * method. * * @param string strToEncrypt String to encrypt * @return string strEnc Encrypted string * */ string encryptString(string strToEncrypt) { string strEnc; return strEnc; } /** * Decrypts a string * * Takes a string and returns the decrypted version of the string. * The string is generated using a very simple character substitution * method. * * @param string strToDecrypt String to decrypt * @return string strDec Decrypted string * */ string decryptString(string strDec) { string decString; return decString; } Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. What did you try ? How far did you get ? Let's assume the correct plain text is 0... this code is not working: Open in new window I know I am close, but new to C++ , so probably not as close as I think! lol The characters in the string are starting at index 0, and ending at index (strToEncrypt.length() - 1). Make sure not to read too much. >> 90 : userBuiltPassword.substr(i That's not really how things work with std::string's. Try something more like this : userBuiltPassword += "2"; which would add "2" to the end of the existing string (given that you start with an empty string). With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you. As expected, this simple problem is proving more difficult than expected. In psuedocode, I want to: 1. encrypt the plain text correct number 0 , which would be: 2 2. and simply compare that to the number entered by the user. I still don't see why my code is not working? And not only that, I need to know how to check for more than one number, which would include arrays, right? And again, in my code, I don't see where I am going wrong. Can you post some working code as proof of concept for your solution? I simply can't get it to work! Ugh... I can't see it either, since you seem to have forgotten to post the new code ;) Open in new window Not working still.. But the real issue is because of what I said earlier : >> (given that you start with an empty string). That was an important pre-condition for the approach to work : userBuiltPassword needs to be empty at the start of the encryptString function. But, since you are using a global variable for it, and call the same function more than once, the second time the function is called, userBuiltPassword is not empty. Why did you use a global variable in the first place ? Why not a local variable ? Open in new window I know there is an easier way, but it appears to work. Can you just double check and offer suggestions? Thanks. (a) you can avoid the use of substr by iterating over the characters of the string (see eg.). (b) instead of using single character string literals, try working with character literals instead (ie. 'a' instead of "a"). Other code will have to be changed too of course when making this switch. (c) you have your substitution alphabet in the encIntArray array at the top. Why not use it ? Take a character from the plaintext string, convert it to its integer value, use it as the index into that array, get the integer value found there, and use it as the encrypted value. (d) you still have quite a few global variables that don't need to be global. As a rule, keep the scope of your variables as small as possible, and only as big as they need to be. (e) in your current code, the user has to enter the encrypted password, not the plaintext password. Is that intentional ? Thank you very much,
https://www.experts-exchange.com/questions/27659316/Simple-Character-Substitution-Encryption.html
CC-MAIN-2018-13
refinedweb
838
73.37
So, I'm a university student and extremely new to this. I have a professor that isn't exactly the best at teaching anything, so all of the learning is done entirely on my own through the text book. The goal is to create a program that has the user enter their first name, last name, and year of birth. It should then give that information back to them, including the age in years, along with their maximum heart rate, and their target heart rate change. The maximum heart rate is determined by 220 - age in years, and the heart rate change is 50-85% of their maximum heart rate. I know the issue can be solved with strings somehow, but I'm having a hard time understanding this concept. Any solutions or general guidance would be greatly appreciated. I'm sure this should be embarrassingly easy to do properly, but this is my attempt at making it work: Code Java: import java.util.Scanner; public class HeartRatesTest { public static void main( String[] args ) { Scanner input = new Scanner(System.in ); String FirstName; String LastName; String BirthYear; int Age; int MaxRate; int LowerRateChange; double HigherRateChange; System.out.print( "Enter first name: " ); FirstName = input.nextLine(); System.out.print( "Enter last name: " ); LastName = input.nextLine(); System.out.print( "Enter year of birth: "); BirthYear = input.nextLine(); Age = 2013 - BirthYear; MaxRate = 220 - Age; LowerRateChange = MaxRate / 2; HigherRateChange = MaxRate * 0.85; System.out.printf( "Hello, %d %d! You are %d years old.\nYour maximum heart rate is %d.\nYour target heart rate change is %d-%d.", FirstName, LastName, Age, MaxRate, LowerRateChange, HigherRateChange); input.close(); } } I get an error in the section where I'm subtracting BirthYear from 2013, and I understand that is because I can't subtract the string from an int. I think. I just don't know how to make that.. not be an issue. I've been working at this for longer than I'd like to admit using the book and the Internet as a guide, but I just can't seem to take it anywhere beyond this.
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/33265-strings%3B-extremely-basic-issue-printingthethread.html
CC-MAIN-2015-22
refinedweb
347
66.03
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to sort report lines in invoices, SO or DO? Hi Sirs, I'm trying to sort lines by a field in reports, but in rml i'm unable to get. Any idea wellcoming, Regards, To sort invoice, you need a srto method in your rml parser... best way is to make a custom report parser... Here is an example parser : class account_invoice(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(account_invoice, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'sort':self._sort}) def _sort(self, theList): #sorting by name ... change to apropriate: sequence, code price... theList.sort(key=lambda x: x.name, reverse=False) return theList Now, in your rml you can instead of: [[ repeatIn(o.sort_print,'l') ]] use : [[ repeatIn(sort(o.invoice_line),'l') ]] for reveserse sort order : [[ repeatIn(sort(o.invoice_line, reverse=True),'l') ]] modifiy sort conditions to your needs... hope it helps... Hi sirs, I undestand that must to create a new app, isn't it? I tell you something. yes, in order to do this you have to write the code somewhere, so best place is custom module... Hi Ivan, Thanks for your fast response, it is attached a DO that I want to sort by the 3rd field in column (rack). It seems like always it is sorted by description. Yes, DO lines (stock.move) are sorted by description by default. If you need to change the sort order, first, if the field is a function field or related field, it need to be stored in database. Then, @Bole has provided a very good example of a way to get it sorted without having to change the model's _order attribute (which will change all sorting order in the whole application for stock.move). The x.name in the _sort method should be replaced with the field that you want to sort with. If you want to change the model's sorting order in the whole application (mind you that stock.move is used for Incoming Shipment lines and Internal Move lines aside from Delivery Order lines), then you inherit the model can specify the _order attribute. Sorry, to complete @Bole's example, the _sort method should accept reverse optional argument and pass it to the sort, i.e. def _sort(self, theList, reverse=False): #sorting by name ... change to apropriate: sequence, code price... theList.sort(key=lambda x: x.name, reverse=reverse) return the First, the lines will be sorted by the model's _order attribute (which defaults to id) when it is browsed (or SELECT-ed). In order to change that, you need to either do a manual search and specify the order_by parameter or sort the records after the being selected. Maybe you can share the result that you needed and what is the result that you are getting so that we can help you further.
https://www.odoo.com/forum/help-1/question/how-to-sort-report-lines-in-invoices-so-or-do-73596
CC-MAIN-2017-09
refinedweb
509
67.45