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
Submitting the form by pressing Enter key in Angular In this tutorial, we are going to learn about how to submit the form by pressing an enter key inside the input field in angular. See this example code. <div> <form (ngSubmit)="handleSubmit($event)""> <input placeholder="Enter message" name="msg" [(ngModel)]="msg" /> <button type="submit">Submit</button> </form> </div> In the above code, we have a form with an input field and submit button and the form can be only submitted by clicking the submit button. Now, let’s see how to submit the above form by pressing an enter key. Using the keyup event The keyup event occurs when a user releases the key (on keyboard).so that by adding this event inside the input field we can submit a form by pressing the enter key. The keyCode for the Enter key is 13. <div> <form (ngSubmit)="handleSubmit($event)" > <input placeholder="Enter message" name="msg" [(ngModel)]="msg" (keyup)="handleKeyUp($event)" /> <button type="submit">Submit</button> </form> </div> import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { msg = ''; handleSubmit(e){ e.preventDefault(); alert(this.msg); } handleKeyUp(e){ if(e.keyCode === 13){ this.handleSubmit(e); } } } In the above code, we have added the keyup event with handleKeyUp() method to the input field. Inside the handleKeyUp() method, we are using if conditional to check if an enter is pressed; then only we are submitting the form, otherwise we are not doing anything. Note: If you have more than one input field in your form then you need to add keyup event to the last input field.
https://reactgo.com/angular-submit-form-enter/
CC-MAIN-2021-17
refinedweb
274
54.12
The advantages of Python as a programming language Python is a general, all-purpose programming language. The language was designed and written with readability in mind. This means that Python Syntax and code was designed to be as simple as possible. Python therefore allows programmers to create applications using fewer lines of code than programming languages like C, for example. Python offers various programming styles including object oriented programming, imperative programming, functional programming and procedural programming. This means that the transition to Python from other programming languages can be quite easy for programmers who are used to programming in one of these styles. Python is often used as a scripting language but there are modules that allow Python programmers to create stand-alone applications too. Python is therefore a very versatile programming language. Because of the simple scripting ideology that Python was based on, Python is actually an ideal language for beginners who are new to programming and coding. Python’s easily readable code means that beginners can create their own applications fairly quickly and easily. Python also has an interactive mode that allows testing of code snippets so beginners can gain confidence in their code as well as testing their code as they go along. Python is also free to download and use, so no initial outlay is required to start obtaining the skills you need to secure a lucrative job as a web developer or programmer. If you are interested in learning to code in Python or if you are a web developer who is looking to increase your coding skills then Python for Beginners offers a great introduction to programming in Python. Modules available for Python Python offers a comprehensive library of modules that can be used in your python programs. Modules are essentially snippets of code that are written to perform certain predefined functions. Modules save you the time of writing your own code snippets. Python allows you to create your own modules too. Some of the most popular modules in Python include data representation modules like the array module, core modules like the various language support modules and file format modules like the htmllib parser that works with the format module to allow for python to render output in html format. This tutorial will be focused on the use of the CSV module. The CSV module allows you to read from CSV files and also allows you to write to them. To understand the tutorial and follow the concepts, it is highly recommended that you have a basic understanding of Python. A course like Python for Rookies will give you the skills you need to understand the basics of Python used in this tutorial. CSV files and working with CSV files CSV is an acronym for Comma Separated Values. The CSV format is a very common data format used by various programs and applications as a format to export or import data. Most spreadsheet and database applications offer export and import facilities for CSV files. CSV files generally store tables of data that contain fields stored within records. Each field in the record is separated by a character within the CSV file and generally new records start on a new line. This is what a CSV file looks like that has been exported from Excel: Although CSV is a very common import/export file format, there is no standard format with regards to the characters used for the separation of the fields. That can make creating code to import and export data from a CSV file tricky to write. But the CSV module available for Python has taken that fact into account and as you will see later, the Python CSV module allows you to use routines that will help you determine the format of the CSV you need to access. How to use the CSV module in Python to open a CSV File Python is an extremely flexible language where it comes to modules. You can write your own modules for your programs or rely on the hundreds of existing modules to create your code. Whether you have written your own module or whether you want to use a predefined module, you need to import the module into your code to use it. To import a module into your code is very simple because of the simplistic Python syntax. To import the CSV module, you merely need to use the “import” syntax at the beginning of your code. For this tutorial we will use the file above and call it tutorial.csv. The CSV module allows you to read data from tutorial.csv, to write data to tutorial.csv, to determine the format of tutorial.csv and to create a dialect for tutorial.csv. To import the CSV module to have access to the functions predefined in the module, you would add the following line to the beginning of your code: How to read data within the CSV file The Python CSV module contains a number of objects that allow you to manipulate or create data within a CSV file. The reader object allows you to open and read the contents of a CSV within Python. The syntax to open and read a CSV file in python is: The reader object is initialized using the csv.reader instruction. The object contains the following parameters: the csvfile parameter, the dialect parameter and the fmtparams. The csvfile tells the object what file to open. The dialect parameter is optional and can be used to specify the format of the CSV file, and the fmtparams can be used to specify specific formatting parameters. Before we can use the Python CSV module to read our file we need to open the file in Python. To open the file we use the Open command. The syntax for the Open command is: The filename is the filename of the file to be opened. The mode refers to how the file will be used once it’s opened. Modes include the read mode, write mode, append mode. To read our file we will open the file in binary read mode or ‘rb’ for now. Here is the simplest version of code to open our tutorial.csv file: The above code imports the module. It then opens the tutorial CSV file and reads the records in the file into an object we created called reader. Then for each row in the reader object, it outputs the data. The reader object has the following public methods associated with the object. The csvreader.next() method reads the next record from the csv file. The csvreader.dialect method is a description of the dialect used by the parser that is read only format. The csvreader.line_num method returns the number of lines in the csv file. Take note that depending on the length of the records, records may span more than one line so the csvreader.line_num may not equal the number of records within the file. Working with data from the CSV file Once you have opened the CSV file and read the data into your object you can work with or manipulate the data within the object. The following code will read the records into our object and then assign row 0 of the data to a header column. We will then use the header columns to output the data in a format that makes sense using the IF statement to assign the header row and the FOR statement to iterate through the records. For more advanced Python programming and tutorials on how to use the IF and FOR statements in Python, The Ultimate Python Programming Tutorial will teach you about the basic data types within Python as well as methods to use; the IF statements and various programming loops available in Python. Here is the code that will open our CSV file, create the headers without our object and read the data within the object. The output of the above code would look like this for each record. (We have displayed the first record only): How to write data to the CSV file Writing to a CSV file is just as simple as reading from a CSV file. The CSV module in Python provides a write object that allows you to write and save data in CSV format. The syntax and parameters for the write object are very similar to the syntax for the read object. The syntax for the write object can be expressed as follows: The writer function of the object is initialized with the csv.writer statement. The csvfile parameter is used to indicate the name of the CSV file that needs to be written into. The dialect parameter is optional but can be used to specify a format for the CSV file output. The fmtparams is also an optional parameter that allows you to specify the format of the data to be written. Here is the code you would need to write our data to a file saved in CSV format, including code comments: # import the module. import csv # open a file for writing. tutorial_out = open(‘tutorial.csv’, ‘wb’) # create the csv writer object. mywriter = csv.writer(csv_out) # create an object called data that holds the records. data = [ (Employee No;Employee Name;Job Desription;Salary), (123453;Jack;CEO;12000), (453124;Jane;Director;25000), (4568354;Sally;Marketing;68000), (684535;Harry;Sales;56000) ] # write the rows. for item in data: mywriter.writerow(item) # always make sure that you close the file. # to ensure the data is saved. tutorial_out.close() The csv writer object has a number of public methods available to it. The csvwriter.writerow(row) method, writes a single row to the object using the default dialect or dialect selected. The csvwriter.writerows(rows) writes all of the rows to the file object using the default or selected dialect. The csvwriter.dialect refers to the dialect or format of the CSV file to be written to. How to use the dialect function within the CSV module As mentioned above, the CSV format is a very popular file format for data storage. There are however no official standards for the CSV file format itself and the characters used to separate the field of the cells can range from commas to semi-colons to tab characters. The dialect method allows you, as a programmer, to specify the format for the CSV file for reading or writing purposes. The dialect class is specified within the reader or writer object. To specify the output format of the CSV file using the tab character as the value that defines the separator between fields, you can set the value of delimiter parameter within the writer object to ‘/t’. # import the module. import csv # open a file for writing. tutorial_out = open(‘tutorial.csv’, ‘wb’) # create the csv writer object. mywriter = csv.writer(csv_out, delimiter=’/t’) The CSV file will look like this: The dialect function in Python includes a standard formatting function for formatting CSV files in Excel format. To output a file in Excel CSV format the parameter must include the dialect=’excel’ parameter. The code would look like this: # import the module. import csv # open a file for writing. tutorial_out = open(‘tutorial.csv’, ‘wb’) # create the csv writer object. mywriter = csv.writer(csv_out, dialect=’excel’) How to use the Sniffer function within the CSV module There are times when you will need to make provision for reading CSV files that are of unknown origin and you may therefore not know the format of the CSV file. The CSV module allows for the determination of the format using the Sniffer class. The Sniffer class provides a way of determining the format of the CSV file. Take a look at the following code: # import the module. import csv # use the sniffer class to determine the format of the CSV file before # reading the contents with open(‘tutorial.csv’, ‘rb’) as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) Python is an extremely powerful language for scripting websites that need to include the manipulation of CSV files. For more advanced courses and tutorials on Python, why not sign up for Web programming with python and start developing your Python skills today?
https://blog.udemy.com/python-csv/
CC-MAIN-2018-09
refinedweb
2,042
61.56
POSSIBLE SOLUTIONS DATE: 5-7/11/2013 CREATED BY: Joaquim Silvestre Useful links: <-actual presentation <-exemple GOALS PLAN 1 Using processing PLAN 2 PLAN 3 Preparing the shape to digital fabrication EXECUTION You can modify the shape created with processing or create a brand new one. Import .obj file or model a shape with the tools provided in blender. Export Save your file as a .blend file for later modification and export it as .obj file Modify the shape click with the right mouse button (RMB) on the object then press Tab keyboard touch . RESULTS The shape should be a mesh and it need to be a closed surface. It can't be a surface. Use the modifier "solidify" to give thickness. EXECUTION We will use the 123D software import .obj file if the surface is close you shouldn't have any problem. Export Export the board ready to cut in format that can be use by the laser cutter. Arrange the slicing First set the scale of your model. There is no architectural scale. You have to manage it by manipulation of the bounding box. RESULTS Assemble the pieces of card board to build your shape and integrate it in your project. SUCCESS? This shape manipulation method can be hard to manage but it provide some advantage that you can't get with usual 3D software SUCCESS? As you see manipulation are easy but not very precise SUCCESS? This process use only free or open software. You can follow it or just use some parts, use only blender and 123D Make or if you have a copy of Rhino or other 3D software that you understand better you can include it in the design process. YES! YES! YES! NO! NO! NO! WHAT NOW? Generative Componnement Catia / digital project / SolidWorks Rhino SUMMARY -Close/open /SDK -don't be afraid to use multiple software -even toy software (there is no shame) or not designated software -hack them to get what you want and not do what you're expected to do with. Blender -Basic command of the software. -Overview of other software and representation system CSG/ BRep/ Mesh -Shape production process : Scripting and Spaghetti programing Processing -Basic of programming -Overview of the IGeo library -Some geometry explanation -Overview of the other available library 123DMake -explore the different assembling method -try to modify your model with the tool provided in 123DMake -use laser cutter. NEW CHALLENGES RESULTS these different shape are made with Processing found a shape type try the different script to explore the shape and find one that fit your needs or inspire you. output get the .obj file Modify variable to parametrize the shape. You can go further and try to understand how the program work. EXECUTION create a geometry by the numbers PROBLEM -Usual software for architect are not ready for digital fabrication, algorithmic design. -complex curvature shape, procedural draw for instance are not so well implemented. -Software ecology evolve, there is no one software that solve everything (and it's good it prevent us to be framed by it, so we still keep the control) Shape production process In edit mod you can directly manipulate the vertex. That's very instinctive but not so convenient for architecture design. You can add modifier or do some cloth simulation -fulfill your design expectation or discover new ideas -Produce and materializing of digital shapes. -Avoid monkey job Suggestion of other software that you can use -Plugins that enable analysis and other manipulation of shape -The software became free recently -Interface concept associating 3D view, graph and code as different representation of the same thing -Very expensive license -comes from aeronautics engineering field kangaroo : dynamic physic simulation Grasshopper : procedural modeling -Originally designated to jewelry, shoes and boat design -that's why it's more precise than usual 3D modeler. -The use of Brep allow rational free form manipulation, you can "describe" the shape as a sequence of geometrical function. (That's why grasshopper is so efficient) -Because it's mainly product design or part design (the boat hull) beware of crash while manipulating big files. For now I've only talked about geometry and construction. You have to found architectural meaning and purpose of this tool. You need to adapt this process to your project production process and your design intention. -Initially, for pixar like animation movies -Long modeling session, learning curve a bit harder than usual but then quicker modeling ability. (lots of shortcuts ) -Since it's open source, lots of script, plugin and utilization far from the initial goal. (game engine, compositing, research) Doing this by hand is boring and time consuming. Especially if I ask some modification during the process. Even if there is a design pattern that you understand intuitively, you have to draw line and surface one by one and do lots of copy and paste. How to teach to the computer the design pattern so it does the boring work origin : design by numbers MIT java programming language 123D make Autodesk software belong to a suit for design set the material size and thickness, the slicing orientation and the number of slice. When slice are in red there is a problem, try to find a configuration that avoid it We can go deeper on some point of the process if you want to get a better understanding. Shape production process No description byTweet Silvestre Joaquimon 27 December 2013 Please log in to add your comment.
https://prezi.com/mis1l30tn_c7/shape-production-process/
CC-MAIN-2016-50
refinedweb
910
59.84
). The port is created using the BIF open_port/2 with {spawn,ExtPrg} as the first argument. The string ExtPrg is the name of the external program, including any command line arguments. The second argument is a list of options, in this case only {packet,2}. This option says that a1). -export([start/1, stop/0, init/1]). -export([foo/1, bar/1]). start(ExtPrg) -> spawn(?MODULE, init, [ExtPrg]). stop() -> complex ! stop. foo(X) -> call_port({foo, X}). bar(Y) -> call_port({bar, Y}). call_port(Msg) -> complex ! {call, self(), Msg}, receive {complex, Result} -> Result end. init(ExtPrg) -> register(complex, self()), process_flag(trap_exit, true), Port = open_port({spawn, ExtPrg}, [{packet, 2}]), loop(Port). loop(Port) -> receive {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {complex, decode(Data)} end, loop(Port); stop -> Port ! {self(), close}, receive {Port, closed} -> exit(normal) end; {'EXIT', Port, Reason} -> exit(port_terminated) end. encode({foo, X}) -> [1, X]; encode({bar, Y}) -> [2, Y]. decode([Int]) -> Int. 4.2 C Program On the C side, it is necessary to write functions for receiving and sending data with two byte length indicators from/to Erlang. By default, the C program should read from standard input (file descriptor 0) and write to standard output (file descriptor 1). Examples of such functions, read_cmd/1 and write_cmd/2, are shown below. /* erl_comm.c */ typedef unsigned char byte; read_cmd(byte *buf) { int len; if (read_exact(buf, 2) != 2) return(-1); len = (buf[0] << 8) | buf[1]; return read_exact(buf, len); } write_cmd(byte *buf, int len) { byte li; li = (len >> 8) & 0xff; write_exact(&li, 1); li = len & 0xff; write_exact(&li, 1); return write_exact(buf, len); } read_exact(byte *buf, int len) { int i, got=0; do { if ((i = read(0, buf+got, len-got)) <= 0) return(i); got += i; } while (got<len); return(len); } write_exact(byte *buf, int len) { int i, wrote = 0; do { if ((i = write(1, buf+wrote, len-wrote)) <= 0) return (i); wrote += i; } while (wrote<len); return (len); } be sent back to Erlang. /* port.c */ typedef unsigned char byte; int main() { int fn, arg, res; byte buf[100]; while (read_cmd(buf) > 0) { fn = buf[0]; arg = buf[1]; if (fn == 1) { res = foo(arg); } else if (fn == 2) { res = bar(arg); } buf[0] = res; write_cmd(buf, 1); } }
http://www.erlang.org/documentation/doc-5.10/doc/tutorial/c_port.html
CC-MAIN-2015-32
refinedweb
376
65.01
This call the SP I then query the table — it’s a lot of data to I need to do it in batches, which works fine. Calling the SP from Python is proving the difficult part. def executeSP(): cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server+';DATABASE='+database+';UID='+username+';PWD=' + password) cnxn.autocommit = True cursor = cnxn.cursor() cursor.execute("SET NOCOUNT ON; exec [schema].[SPName]") cursor.close() del cursor cnxn.close() I set NOCOUNT to on so that python will wait until the SP is complete before returning. But when I run this, the SP isn’t called. The same connection parameters work for querying the table in the same schema. No errors are produced. I’m running out of ideas. Source: Python-3x Questions
https://askpythonquestions.com/2021/06/17/having-trouble-calling-a-stored-procedure-in-sql-server-from-python-pyodbc/
CC-MAIN-2021-31
refinedweb
130
71.31
Concatenate elements in two list using list comprehension How can I get this output with list comprehension in python x = [1,2,3] y = ["a","b","c"] Expected output: ["a1","a2","a3","b1","b2","b3","c1","c2","c3"]." - How does this program print number's digits in reverse? #include <iostream> int main() { int nr; std::cin>>nr; while (nr > 0) { int digit = nr % 10; nr /= 10; std::cout<<digit; } return 0; } Can someone please explain the workflow of this program, basically with the input "32" it outputs "23", that is good, thats my goal, my question is, why does it say "23" instead of just "2", why is the "3" being added in the end if i only said "cout digit". I get that the "3" comes from " nr /= 10", but why is it being outputed near the "2" to farm the answer "23"? - Using a double in C language gives incorrect output I have the following code: #include <stdio.h> int main() { int a = 10, b = 20; double d; int i; /*------- double d -------*/ d = a + b; printf("d = %d\n", d); d = a - b; printf("d = %d\n", d); d = a * b; printf("d = %d\n", d); d = a / b; printf("d = %d\n", d); /*-------- int i ---------*/ i = a + b; printf("i = %d\n", i); i = a - b; printf("i = %d\n", i); i = a * b; printf("i = %d\n", i); i = a / b; printf("i = %d\n", i); } with the output: d = 1793921352 d = 15 d = 7 d = 6 i = 30 i = -10 i = 200 i = 0 It gives the correct output for int i (except for the last one, which should be a .5, hence why I was trying to use type double.) I've never used C before, so I'm just wondering what I'm doing wrong to get this kind of output and why changing the type to a double gives me weird numbers like "1793921352" when I'm just trying to add 10 and 20 together. If anyone could explain this too me that would be a lot of help! Thank you. - Extract same elements chunk from list after instance of a particular element I'm trying to extract the sequential 'NN' elements (including 'NNP') from a list and append to a new list given 'IN' or 'TO' are encountered before 'NN'. How can I do it? I tried the following code. But unable to capture the other similar instances. new = ['JJ', 'NN', 'IN', 'NNP', 'NN', 'MD', 'VB', 'VBN', 'IN', 'NN', 'TO', 'VB', 'NN', 'CC', 'NN', 'TO', 'NNP', 'NN', 'NN', '.'] lst = [] for i,j in enumerate(new): lst1 = [] if j == 'IN': for i in new[i+1:]: if 'NN' in i: lst1.append(i) lst.append(lst1) break lst = [['NNP'], ['NN']] But I want to improve the code to give the below output: [['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN'] Each output chunk has either 'IN' or 'TO' occurred before them. Actually, the above list (new) is underlying parts of speech for this list : [['Additional', 'condition', 'of', 'DeNOx', 'activation', 'shall', 'be', 'introduced', 'in', 'order', 'to', 'provide', 'flexibility', 'and', 'robustness', 'to', 'NSC', 'regeneration', 'management', '.'], ['JJ', 'NN', 'IN', 'NNP', 'NN', 'MD', 'VB', 'VBN', 'IN', 'NN', 'TO', 'VB', 'NN', 'CC', 'NN', 'TO', 'NNP', 'NN', 'NN', '.']]. How can I map the results back to this list so that I will get [['DeNOx', 'activation'], ['order'], ['NSC', 'regeneration', 'management']] - Efficient way to compute the Vandermonde matrix I'm calculating Vandermonde matrixfor a fairly large 1D array. The natural and clean way to do this is using np.vander(). However, I found that this is approx. 2.5x slower than a list comprehension based approach. In [43]: x = np.arange(5000) In [44]: N = 4 In [45]: %timeit np.vander(x, N, increasing=True) 155 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # one of the listed approaches from the documentation In [46]: %timeit np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1) 65.3 µs ± 235 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [47]: np.all(np.vander(x, N, increasing=True) == np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1)) Out[47]: True I'm trying to understand where the bottleneck is and the reason why does the implementation of native np.vander()is ~ 2.5x slower. Efficiency matters for my implementation. So, even faster alternatives are also welcome! - Python list comprehensions that return multiple lists I don't know whether it is anyway possible in Python and that is the reason why I ask it here. I have a Python function that returns a tuple: def my_func(i): return i * 2, 'a' * i This is just a dumb function that given a number k, it returns k * 2as is and another string is the letter 'a' concatenated ktimes. I want now to form two lists, calling the function with i = 0...9, I want to create one list with all the first values and another one with the rest of them. What I do with my current knowledge is: Option 1: Run the same list comprehension two times, that is not very efficient: first_vals = [my_func(i)[0] for i in range(10)] second_vals = [my_func(i)[1] for i in range(10)] Option 2: Avoiding list comprehensions: first_vals = [] second_vals = [] for i in range(10): f, s = my_func(i) first_vals.append(f) second_vals.append(s) Option 3: Use list comprehension to get a list of tuples and then two other list comprehension to copy the values. It is better than Option 1, as here my_func()is only called once for each i: ret = [my_func(i) for i in range(10)] first_vals = [r[0] for r in ret] second_vals = [r[1] for r in ret] Is it possible to somehow use the list comprehension feature in order to return two lists in one command and one iteration, assigning each returned parameter into a different list?
http://codegur.com/48248963/concatenate-elements-in-two-list-using-list-comprehension
CC-MAIN-2018-05
refinedweb
998
65.66
Java NIO is a new package introduced in jdk 7, this provide extensive support for the file and file system management, learn about path and files in java nio, this will help you interact with file systems. Files are a core of every software or program, every programming language gives a support for the file management and handling, Java is no exception. Java has created a new package in its core package library to handle the file operations. Up to jdk 6 the file handling concepts were all in java.io package, these are there up to some limit. But Java developers decided to create extended support for the file management. Java has introduced java.nio package in JDK 7. This is special package dedicated to file operation to separate the file operations from byte and character streams related operations. This package support the file management to the basic level. If you try and explore this you will find that this is more than only the file handling but the support for the various platforms and different file system support has also been provided here. Most of the utility methods here are actually the static methods to ease your work. Path The concept of files start from the Path class. The path is of two types, Relative and Absolute. The Absolute path is the part starting from the root. and Relative is the path relative to any directory up to specified file or directory. As in the example the path from root to the file is a Absolute path /dir1/dir1.1/file - Absolute path but if you try to access the file from current directory and the current directory is dir1 then, dir1/dir1.1/file - Relative path So Java provide an Interface Path and a final class Paths to take care of the paths in your program you can check out this interface on your console using command, javap java.nio.file.Path javap java.nio.file.Paths The symbolic link means the link to a file or directory in different path, this is what we know as short cut link in general terms. After looking into the methods provided in Path and Paths you can move on to the File system. However the general method we are going to use is Paths.get(URI); Files Files are the collection of data encoded on the storage media. There are different type of files and file systems. The file systems are the programs which manages the storage media and space on it. where the files are the elements which are stored on that media. the files have different properties and are identified using the extension which is usually three or four character long. The common file extensions are .txt for text files, .wmv, mp3, .amr for the audio files, .mp4, .flv, .mkv etc for the video files. The extension helps a operating system to identify the file type which helps it to store it in a efficient way. Now Java provide various ways to create and modify a file. Even the java.nio provide inbuilt methods to copy, move or delete the files on the file system. Java provide some enumerated options which comes in handy to specify the operation we want to do with the file, we use these options while opening a file. These options are found in the java.nio.file.StandardOpenOptions most commonly used of these are, WRITE - open file to write new data APPEND - Append new data at the end of file TRUNCATE_EXISTING - this is used when we are writing to a file, its operation is to truncate the data from file and make it empty. CREATE_NEW - create new file, it throws exception if file is already existing, so you should first check the existence of file using exists() method. CREATE - opens a file for writing, if file is not existing, create it and then open it. DELETE_ON_CLOSE - delete the file when we close the file. This is used to create temporary files. these are few main options however there are more you can find them in the StandardOpenOptions class. Now let us look at the simplest way of creating the file. We use the Linux operating system for the programming purpose so the path we are going to use will be /any-directory where in windows you can use C:\some-directory Note: please take care that windows use the back slash for the directory specifier so you must make it like Paths.get("C:\\some-directory"); the extra back slash is used to escape the backslash, because in java language specification the backslash is an escape character. So lets not look at the program for copying a file content into another file. This will give you a basic idea of the file handling methods and practices. For example the IOException is the key exception thrown by any file operation on failing to fulfil any requirement. And you must close the resource handler on completing the task. package IO; import java.nio.file.*; import java.io.*; public class FileOperations { public static void main(String[] args) throws IOException{ try{ Path p = Paths.get("/home/mayank/test.txt"); byte[] b = null; b = Files.readAllBytes(p); Path d = Paths.get("/home/mayank/test1.txt"); Files.write(d, b,StandardOpenOption.APPEND); } catch(IOException ioe){ System.out.println(ioe); } } } this program will take a file placed at /home/mayank/test.txt which contains some text for example, we put hello world in the test file new line in test file in this file, and first of all we create a path for the file using the Path interface. You can test the existence of the path using Files.exists(p); method, this will return true on success and false if the path does not exists. So this program when first time run will create a file test1.txt and will write the bytes read from test.txt which was read using the readAllBytes() method into the new file. But as you see the file test1.txt is opened with the StandardOpenOption.APPEND so when you next time run this file it will append the text at the end of the content in test1.txt. Did you noticed we have not used finally to close any handlers ? yes there is no handlers in this program and please be careful this way of reading and writing is only applicable to the small files. For the files with bigger size you must use the Buffered Stream as we show in the following program. import java.nio.file.*; import java.nio.charset.Charset; import java.io.*; public class FileOperations { public static void main(String[] args) throws IOException { BufferedReader br = null; BufferedWriter bw = null; try { Path p = Paths.get("/home/mayank/test.txt"); br = Files.newBufferedReader(p, Charset.forName("UTF-8")); Path d = Paths.get("/home/mayank/test1.txt"); bw = Files.newBufferedWriter(d, Charset.forName("UTF-8")); String s = null; while ((s = br.readLine()) != null) { bw.write(s); } } catch (IOException ioe) { System.out.println(ioe); } finally { if (br != null) { br.close(); } if (bw != null) { bw.close(); } } } } In this program we have used the buffered reader and writer to operate the streams while leaving the file handling to the new buffered reader and writer in the nio package. Now when you will run this program you will notice that the output in the test1.txt is all in one line, this is because in this program the reader is reading line by line but writer in just writing into the file, if you want the output file similar to the original file you can just change bw.write(s) to bw.write(s+"\n"); this will give you the same result by appending the new line character to each line. Note: As the file input output is better when you go with the character stream rather than the byte stream the nio gives you this flexibility while handling the underline byte stream by itself. We hope you understand the tutorial, however if you want to learn using a video here is an excellent video tutorial for you.
http://www.examsmyantra.com/article/59/java/java-nio-path-and-files-handling-using-java-nio-package
CC-MAIN-2019-09
refinedweb
1,353
65.01
Andrew Morton <akpm@linux-foundation.org> writes:> On Tue, 28 Aug 2007 16:13:18 +0200 Jan Kara <jack@suse.cz> wrote:>>> Hello,>> >> I'm sending rediffed patch implementing sending of quota messages via netlink>> interface (some rationale in patch description). I've already posted it to>> LKML some time ago and there were no objections, so I guess it's fine to put>> it to -mm. Andrew, would you be so kind? Thanks.>> Userspace deamon reading the messages from the kernel and sending them to>> dbus and/or user console is also written (it's part of quota-tools). The>> only remaining problem is there are a few changes needed to libnl needed for>> the userspace daemon. They were basically acked by the maintainer but it>> seems he has not merged the patches yet. So this will take a bit more time.>> >> So it's a new kernel->userspace interface.>> But we have no description of the interface :(>>> +/* Send warning to userspace about user which exceeded quota */>> +static void send_warning(const struct dquot *dquot, const char warntype)>> +{>> + static unsigned long seq;>> + struct sk_buff *skb;>> + void *msg_head;>> + int ret;>> +>> + skb = genlmsg_new(QUOTA_NL_MSG_SIZE, GFP_NOFS);>> + if (!skb) {>> + printk(KERN_ERR>> + "VFS: Not enough memory to send quota warning.\n");>> + return;>> + }>> + msg_head = genlmsg_put(skb, 0, seq++, "a_genl_family, 0,> QUOTA_NL_C_WARNING);>> + if (!msg_head) {>> + printk(KERN_ERR>> + "VFS: Cannot store netlink header in quota warning.\n");>> + goto err_out;>> + }>> + ret = nla_put_u32(skb, QUOTA_NL_A_QTYPE, dquot->dq_type);>> + if (ret)>> + goto attr_err_out;>> + ret = nla_put_u64(skb, QUOTA_NL_A_EXCESS_ID, dquot->dq_id);>> + if (ret)>> + goto attr_err_out;>> + ret = nla_put_u32(skb, QUOTA_NL_A_WARNING, warntype);>> + if (ret)>> + goto attr_err_out;>> + ret = nla_put_u32(skb, QUOTA_NL_A_DEV_MAJOR,>> + MAJOR(dquot->dq_sb->s_dev));>> + if (ret)>> + goto attr_err_out;>> + ret = nla_put_u32(skb, QUOTA_NL_A_DEV_MINOR,>> + MINOR(dquot->dq_sb->s_dev));>> + if (ret)>> + goto attr_err_out;>> + ret = nla_put_u64(skb, QUOTA_NL_A_CAUSED_ID, current->user->uid);>> + if (ret)>> + goto attr_err_out;>> + genlmsg_end(skb, msg_head);>> +>> + ret = genlmsg_multicast(skb, 0, quota_genl_family.id, GFP_NOFS);>> + if (ret < 0 && ret != -ESRCH)>> + printk(KERN_ERR>> + "VFS: Failed to send notification message: %d\n", ret);>> + return;>> +attr_err_out:>> + printk(KERN_ERR "VFS: Failed to compose quota message: %d\n", ret);>> +err_out:>> + kfree_skb(skb);>> +}>> +#endif>> This is it. Normally netlink payloads are represented as a struct. How> come this one is built-by-hand?No netlink fields (unless I'm confused) are represented as a struct,not the entire netlink payload.> It doesn't appear to be versioned. Should it be?Well. If it is using netlink properly each field should have a tag.So it should not need to be versioned, because each field is strictlycontrolled.> Does it have (or need) reserved-set-to-zero space for expansion? Again,> hard to tell..Not if netlink is used properly. Just another nested tag.> I guess it's OK to send a major and minor out of the kernel like this. > What's it for? To represent a filesytem? I wonder if there's a more> modern and useful way of describing the fs. Path to mountpoint or> something?Or perhaps the string the fs was mounted with.> I suspect the namespace virtualisation guys would be interested in a new> interface which is sending current->user->uid up to userspace. uids are> per-namespace now. What are the implications? (cc's added)That we definitely would be. Although the user namespaces is ratherstrongly incomplete at the moment.> Is it worth adding a comment explaining why GFP_NOFS is used here?-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/8/29/26
CC-MAIN-2018-13
refinedweb
578
59.3
On 8/22/11, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: > Steven D'Aprano wrote: >>(Methods are very similar to functions. At the most basic level, we can >>pretend that a method is just a function that comes stuck to something >>else. Don't worry about methods for now.) > > Can someone please explain the difference between methods and functions? > > Thanks, > Ramit At the most basic level, they're the same. If you have a named, stand-alone section of code that (optionally) operates on some argument passed to it, it's called a function. If you have the same exact code, but you group it together into a named unit along with the data it (optionally) operates on, it's called a method. Technically in Python, they're both objects, both callables and can be called in similar ways. The distinction is quite minimal. Here's a few examples: # A function that expects the first argument to be some object it operates on. # This is just like a method, except it hasn't been declared within any class. # Therefore, it's called a function: def setx(foo): foo.x = 1 # The same exact thing again, but declared in a 'Bar' class. Now it's # called a method. Normally the first parameter to every instance method is # named 'self', (A convention you should adhere to.) To make this example # clearer, however, I use the name 'foo' instead just like the last example: class Bar(object): def setx(foo): foo.x = 1 The call itself is a little different: # As a function you must pass the arguments: a = Bar() setx(a) #<-- Explicitly pass the object as an argument. # As a method the first argument is implied: a = Bar() a.setx() #<-- First argument is passed automatically for you. That said, you could also call a method as if it were a function living in the Bar namespace: a = Bar() Bar.setx(a) You can even declare a function within a class that *doesn't* operate on any instance of the class. Just like an ordinary function, you must pass all arguments. This is called a static method and is declared with the '@staticmethod' decorator: class Baz(object): @staticmethod def bonzo(x, y): return x+y You can then call it like this: Baz.bonzo(3, 5) This looks remarably similar to calling a function that exists in some namespace. For example: import random random.randrange(3, 5) So the ultimate difference? Pretty much just where you declare it. If it's in a class it's called a method, outside of a class its called a function. Especially in python - the distinction is small. -Kurt-
https://mail.python.org/pipermail/tutor/2011-August/085141.html
CC-MAIN-2016-36
refinedweb
443
75
Guys could you help explain me the last 2 lines please MenBook mbobject = (MenBook) other does it mean that mbobject is an object of the class Menbook? and what does the Other mean? public boolean moreExpensiveThan(Object other) { If(other == null) return false; else if (getClass() != other.getClass()) return false; else { MenBook mbobject = (MenBook) other; return (sellingPrice() >= mbobject.sellingPrice()); } Please note that OrderedByPrice is an interface You are assigning to variable mobject (of type MenBook) the object other (of type Object), after checking that its type is of the correct one ( getClass() != other.getClass()). You are creating a new MenBook object called mbObject and you assign the object called other to it. The (MenBook) in front of other means you are casting the object called other to a MenBook object.
http://www.dlxedu.com/askdetail/3/f5680e7b8d23351d9c9739b33b76e7f7.html
CC-MAIN-2019-35
refinedweb
130
61.77
In this extensive write-up, I'll cover how all the main pieces came together for the first SaaS I ever launched. From implementing favicon to deploying to a cloud platform, I will share everything I learned. I'll also share extensive code snippets, best practices, lessons, guides, and key resources. I hope something here will be useful to you. Thanks for reading. ❤️ Table of Contents - Introduction - Finding Ideas - The Stack - Repo - Client - Design - Server - User Authentication System - Tenancy - Domain Name - Deployment - Hosting Your SPA - <script> and <link in your index.html. Then when a user requests your app in a browser, the 'index.html' is fetched and parsed. When it sees <script> and <link>,: Once I understood the basics, I started referring to this resource for more advanced configuration. <script. Well, there is this method, but how about ordering among my <link>too? -: <% if (htmlWebpackPlugin.options.mode === 'production') { %> <script defer</script> <script defer</script> <link rel="stylesheet" href="<%= htmlWebpackPlugin.files.css.filter(e => /app/.test(e))[0] %>" /> <% } %> Note: We only do this when building for production; we let webpack-dev-serverinjects for us during local development. We apply the deferattribute on our <script>so that browser will fetch them while parsing our HTML, and only execute the JS once the HTML has been parsed. source Inlining CSS and JS If you managed to separate your critical CSS or you have a tiny JS script, you might want to consider inlining them in <style> and <script>. 'Inlining' means placing corresponding raw content in HTML. This saves network trips, although not being able to cache them is a concern worth factoring in. Let's inline the runtime.js generated by Webpack as suggested here. Back in the index.html above, add this snippet: <!-- more <link> and <script> --> <script> <%= compilation.assets[htmlWebpackPlugin.files.js.filter(e => /runtime/.test(e))[0].substr(htmlWebpackPlugin.files.publicPath.length)].source() %> </script> The key was the compilation.assets[<ASSET_FILE_NAME>].source(): - compilation: the webpack compilation object. This can be used, for example, to get the contents of processed assets and inline them directly in the page, through compilation.assets[...].source()(see the inline template example). (source) You can use this method to inline your critical CSS too: <style> <%= compilation.assets[htmlwebpackplugin.files.css.filter(e => /app/.test(e)) [0].substr(htmlWebpackPlugin.files.publicPath.length) ].source() %> </style> For non-critical CSS, you can consider 'preload' them. Preload non-critical CSS In short: <link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'" /> But let's see how to do this with Webpack. So I have my non-critical CSS contained in a CSS file, which I specify as its own entry point in Webpack: // webpack.config.js module.exports = { entry: { app: "index.js", components: path.resolve(__dirname, "../src/css/components.scss"), }, }; Finally, I inject it above my critical CSS: <!-- Preloading non-critical CSS --> <link rel="stylesheet" href="<%= htmlWebpackPlugin.files.css.filter(e => /components/.test(e))[0] %>" media="print" onload="this.media='all'" /> <!-- Inlined critical CSS --> <style> <%= compilation.assets[htmlwebpackplugin.files.css.filter(e => /app/.test(e)) [0].substr(htmlWebpackPlugin.files.publicPath.length) ].source() %> </style> Let's measure if, after all this, we have actually done anything good. Measuring the Sametable's signup page: BEFORE AFTER Looks like we have improved almost all of the important user-centric metrics (not sure about the First Input Delay..)! ? Here is a good video tutorial about measuring web performance in the Chrome Dev tool. Code splitting Rather than lump all your app's components, routes, and third-party libraries into a single .js file, you should split and load them on-demand based on a user's action at runtime. This will dramatically reduce the bundle size of your SPA and reduces initial Javascript processing costs. This improves metrics like 'First interactive time' and 'First meaningful paint'. Code splitting is done with the 'dynamic imports': // Editor.jsx // LAZY-LOAD A GIGANTIC THIRD-PARTY LIBRARY componentDidMount() { const { default: MarkdownIt } = await import( /* webpackChunkName: "markdown-it" */ "markdown-it" ); new MarkdownIt({ html: true }).render(/* stuff */); } // OR LAZY-LOAD A COMPONENT BASED ON USER ACTION checkout = () => { const { default: CheckoutModal } = await import( /* webpackChunkName: "checkoutModal" */ "../routes/CheckoutModal" ); } Another use case for code splitting is to conditionally load polyfill for a Web API in a browser that doesn't support it. This spares others that do support it from paying the cost of the polyfill. For example, if IntersectionObserver isn't supported, we will polyfill it with the 'intersection-observer' library: // InfiniteScroll.jsx componentDidMount() { (window.IntersectionObserver ? Promise.resolve() : import("intersection-observer")).then(() => { this.io = new window.IntersectionObserver((entries) => { entries.forEach((entry) => { // do stuff }); }, { threshold: 0.5 }); this.io.observe(/* DOM element */); }); } Guide Differential Serving You have probably configured your Webpack to build your app targeting both modern and legacy browsers like IE11, while serving every user with the same payload. This forces those users who are on modern browsers to pay the cost (parse/compile/execute) of unnecessary polyfills and extraneous transformed codes that are meant to support users on legacy browsers. 'Differential serving' will serve, on one hand, much leaner code to users on modern browsers. And on the other hand, it'll serve properly polyfilled and transformed code to support users on legacy browsers such as IE11. Although this approach makes for an even more complex build setup and doesn't come without a few caveats, the benefits gained (you can find in the resources below) certainly outweigh the costs. That is unless the majority of your user base is on IE11. In that case, you can probably skip this. But even so, this approach is future-proof as legacy browsers are being phased out. Repo Resources - — A very good overview of different approaches to differential serving. Sametable is on the 'Option-1'. - — This Webpack plugin passes the manifest(i.e. assets' reference) of your modern & legacy scripts to 'html-webpack-plugin' so you can access them in your 'index.html'. - — I learned here about structuring my babel config with its 'babel.config.js' method. - — I learned a lot here about structuring my Webpack configs. Fonts Font files can be costly. Take my favorite font Inter for example: If I used 3 of its font styles, the total size could get up to 300KB, exacerbating the FOUT and FOIT situations, particularly in low-end devices. To meet my font needs in my projects, I usually just go with the 'system fonts' that come with the machines: body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; } code { font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New"; } But if you must use custom web fonts, consider doing it right: - You should host them yourself. - 'Font-subsetting' to dramatically reduce the size of the font file. - Go through this checklist. Icons Icons in Sametable are SVG. There are different ways that you can do it: - Copy and paste the markup of an SVG icon wherever you need it. The downside is it will bloat the HTML and incur parsing costs particularly on mobile. - Request for your SVG icons over the network: <img src="./tick.svg" />. Unless an SVG is huge (> 5KB), making a request for every one of them seems a bit much. - Make an icon reusable in the form of a React component. The downside is it unnecessarily introduces Javascript and its associated costs. Instead, the solution I opted for my icons was 'SVG sprites' which is closer to the nature of SVG itself ( <use> and <symbol>). Let's see how. Say there are many places that will use two of our SVG icons. In your index.html: <body> <svg xmlns="" style="display: none;"> <symbol id="pin-it" viewBox="0 0 96 96"> <title>Give it a title</title> <desc>Give it a description for accessibility</desc> <path d="M67.7 40.3c-.3 2.7-2" /> </symbol> <symbol id="unpin-it" viewBox="0 0 96 96"> <title>Un-pin this entity</title> <desc>Click to un-pin this entity</desc> <path d="M67.7 40.3c-.3 2.7-2" /> </symbol> </svg> </body> - Hide the parent SVG element style="display: none". - Give each SVG symbol an unique id <symbol id="unique-id". - Make sure to define the viewBox(usually already provided), but skip the widthand height. - Give it titleand descfor accessibility. - And of course, the pathdata of an icon. And finally, here is how you can use them in your components: // example.jsx render() { <svg xmlns="" xmlnsXlink="" width="24" height="24" > <use xlinkHref="#pin-it" /> </svg> } - Define the widthand heightas desired. - Specify the idof the <symbol>: <use xlinkHref="#pin-it" />. Lazy load SVG sprites Rather than having your SVG symbols in the index.html, you can put them in a .svg file which is loaded only when needed: <svg xmlns=""> <symbol id="header-1" viewBox="0 0 26 24"> <title>Header 1</title> <desc>Toggle a h1 header</desc> <text x="0" y="20" font-H1</text> </symbol> <symbol id="header-2" viewBox="0 0 26 24"> <title>Header 2</title> <desc>Toggle a h2 header</desc> <text x="0" y="20" font-H2</text> </symbol> </svg> Put that file in client/src/assets: - client - src - assets - svg-sprites.svg Finally, to use one of the symbols in the file: // Editor.js import svgSprites from "../../assets/svg-sprites.svg"; /* component stuff */ render() { return ( <button type="button"> <svg xmlns="" xmlnsXlink="" width="24" height="24" > <use xlinkHref={`${svgSprites}#header-1`} /> </svg> </button> ) } And a browser will, during runtime, fetch the .svg file if it hasn't already. And there you have it! No more plastering those lengthy path data all over the place. Sources of icons - - - (has a nice list of sources) References Favicon If I hadn't disabled the inject option of 'html-webpack-plugin', I would have used a plugin called 'favicons-webpack-plugin' that automatically generates all types of favicons (beware - it's a lot!), and injects them in my index.html: // webpack.config.js plugins: [ new HtmlWebpackPlugin(), // 'inject' is true by default // must come after html-webpack-plugin new FaviconsWebpackPlugin({ logo: path.resolve(__dirname, "../src/assets/logo.svg"), prefix: "icons-[hash]/", persistentCache: true, inject: true, favicons: { appName: "Sametable", appDescription: "Manage your tasks in spreadsheets", developerName: "Kheoh Yee Wei", developerURL: "", // prevent retrieving from the nearest package.json theme_color: "#fcbdaa", // specify the vendors that you want favicon for icons: { coast: false, yandex: false, }, }, }), ]; But since I have disabled the auto-injection, here is how I handle my favicon: Go to - Provide your logo in SVG format. - Select the 'Version/Refresh' option to enable cache-busting your favicon asset in your users' browser. - Complete the instructions at the end. You can store your favicons in any folder in your project. Use 'copy-webpack-plugin' to copy all your favicon assets generated from Step-1, from the folder where you store them (in my case, src/assets/favicon) to Webpack's output's path (default behaviour), so that they will be accessible from the root (i.e.). // webpack.config.js const CopyWebpackPlugin = require("copy-webpack-plugin"); plugins: [new CopyWebpackPlugin([{ from: "src/assets/favicon" }])]; And that's it! API Calls A client needs to communicate with a server to perform 'CRUD' operations - Create, Read, Update, and Delete: Here is my hopefully easy to understand api.js: API WRAPPER import { route } from "preact-router"; function checkStatus(response) { const responseCode = response.status; if (responseCode >= 200 && responseCode < 300) { return response; } // handle user not authorized scenario if (responseCode === 401) { response .json() .then((json) => route(`/signin${json.refererUri ? `?dest=${json.refererUri}` : ""}`) ); return; } // pass along error response to the 'catch' block of your await/async try & catch block return response.json().then((json) => { return Promise.reject({ status: responseCode, ok: false, statusText: response.statusText, body: json, }); }); } function handleError(error) { error.response = { status: 0, statusText: "Cannot connect. Please make sure you are connected to internet.", }; throw error; } function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } return response.json(); } function request(url, options) { return fetch(url, options) .catch(handleError) // handle network issues .then(checkStatus) .then(parseJSON) .catch((e) => { throw e; }); } export function api(endPoint, userOptions = {}) { const url = process.env.API_BASE_URL + endPoint; // to pass along our auth cookie to server userOptions.credentials = "include"; const defaultHeaders = { "Content-Type": "application/json", Accept: "application/json", }; if (userOptions.body instanceof File) { const formData = new FormData(); formData.append("file", userOptions.body); userOptions.body = formData; // let browser set content-type to multipart/etc. delete defaultHeaders["Content-Type"]; } if (userOptions.body instanceof FormData) { // let browser set content-type to multipart delete defaultHeaders["Content-Type"]; } const options = { ...userOptions, headers: { ...defaultHeaders, ...userOptions.headers, }, }; return request(url, options); } There is almost nothing new to learn to start using this API module if you have used the native fetch before. Usage // Home.jsx import { api } from "../lib/api"; async componentDidMount() { try { // POST-ing data const response = await api( '/projects/save/121212121', { method: 'PUT', body: JSON.stringify(dataObject) } ) // or GET-ting data const { myWorkspaces } = await api('/users/home'); } catch (err) { // handle Promise.reject passed from api.js } } But if you prefer to use a library to handle your HTTP calls, I'd recommend 'redaxios'. It not only shares an API with the popular axios, but it's much more lightweight. Test Production Build Locally I always build my client app locally to test and measure in my browser before I deploy to the cloud. I have an npm script ( npm run test-build) in the package.json of the 'client' folder that will build and serve on a local web server. This way I can play with it in my browser at: "scripts": { "test-build": "cross-env NODE_ENV=production TEST_RUN=true node_modules/.bin/webpack && npm run serve", "serve": "ws --spa index.html --directory dist --port 5000 --hostname localhost" } The app is served using a tool called 'local-web-server'. It's so far the only one I find works perfectly for a SPA. Security Consider adding the CSP security headers. To add headers in firebase: Sample of CSP headers in your firebase.json: { "source": "**", "headers": [ { "key": "Strict-Transport-Security", "value": "max-age=63072000; includeSubdomains; preload" }, { "key": "Content-Security-Policy", "value": "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'" }, { "key": "X-Content-Type-Options", "value": "nosniff" }, { "key": "X-Frame-Options", "value": "DENY" }, { "key": "X-XSS-Protection", "value": "1; mode=block" }, { "key": "Referrer-Policy", "value": "same-origin" } ] } If you use Stripe, make sure you add their CSP directives too: Finally, make sure you get an A here and pat yourself on the back! Design Before I start to code anything up, I wanted to have a mental reel of how I would want to on-board a new user to my app. Then I would sketch on a notebook of what it might look like doing it, and re-iterate the sketches while playing and rehashing the reel in my head. For my very first 'sprint', I would primarily build a 'UI/UX framework' upon which I would add pieces over time. However, it's important to remember that every decision you make during this process should be one that's open-ended and easy to undo. This way a 'small'— but careful—decision won't spell doom when you get carried away with any over-confident and romantic convictions. Not sure if that made any sense, but let's explore a few concepts that helped structure my design to be coherent in practise. Modular Scale Your design will make more sense to your users when it flows according to a 'modular scale'. That scale should specify a scale of spaces or sizes that each increment with a certain ratio. One way to create a scale is with CSS 'Custom Properties'(credits to view-source every-layout.dev): :root { --ratio: 1.414; --s-3: calc(var(--s0) / var(--ratio) / var(--ratio) / var(--ratio)); --s-2: calc(var(--s0) / var(--ratio) / var(--ratio)); --s-1: calc(var(--s0) / var(--ratio)); --s0: 1rem; --s1: calc(var(--s0) * var(--ratio)); --s2: calc(var(--s0) * var(--ratio) * var(--ratio)); --s3: calc(var(--s0) * var(--ratio) * var(--ratio) * var(--ratio)); } If you don't know what scale to use, just pick a scale that fits closest to your design and stick to it. Then create a bunch of utility classes, each associated with a scale, in a file call spacing.scss. I will use them to space my UI elements across a project: .mb-1 { margin-bottom: var(--s1); } .mb-2 { margin-bottom: var(--s2); } .mr-1 { margin-right: var(--s1); } .mr--1 { margin-right: var(--s-1); } Notice that I try to define the spacing only in the right and bottom direction as suggested here. In my experience, it's better to not bake in any spacing definitions in your UI components: DON'T // Button.scss .btn { margin: 10px; // a default spacing; annoying to have in most cases font-style: normal; border: 0; background-color: transparent; } // Button.jsx import s from './Button.scss'; export function Button({children, ...props}) { return ( <button class={s.btn} {...props}>{children}</button> ) } // Usage <Button /> DO // Button.scss .btn { font-style: normal; border: 0; background-color: transparent; } // Button.jsx import s from './Button.scss'; export function Button({children, className, ...props}) { return ( <button class={`${s.btn} ${className}`} {...props}>{children}</button> ) } // Usage // Pass your spacing utility classes when building your pages <Button className="mr-1 pb-1">Sign Up</Button> Colors There are many color palette tools out there. But the one from Material is the one I always go to for my colors simply because they are laid out in all their glory! ? Then I will define them as CSS Custom Properties again: :root { --black-100: #0b0c0c; --black-80: #424242; --black-60: #555759; --black-50: #626a6e; font-size: 105%; color: var(--black-100); } CSS Reset The purpose of a 'CSS reset' is to remove the default styling of common browsers. There are quite a few of those out there. Beware that some can get quite opinionated and potentially give you more headaches than they're worth. Here is a popular one: Here is mine: *, *::before, *::after { box-sizing: border-box; overflow-wrap: break-word; margin: 0; padding: 0; border: 0 solid; font-family: inherit; color: inherit; } /* Set core body defaults */ body { scroll-behavior: smooth; text-rendering: optimizeLegibility; } /* Make images easier to work with */ img { max-width: 100%; } /* Inherit fonts for inputs and buttons */ button, input, textarea, select { color: inherit; font: inherit; } You could also consider using postcss-normalize that generates one according to your targeted browsers. A Styling Practice I always try to style at the tag-level first before bringing out the big gun if necessary, in my case, 'CSS Modules', for encapsulating styles per component: - src - routes - SignIn - SignIn.js - SignIn.scss The Furthermore, I don't use the CSS libraries popular in the React ecosystem such as 'styled-components' and 'emotion'. I try to use pure HTML and CSS whenever I can, and only let Preact handle the DOM and state updates for me. For example, for the <input/> element: // index.scss label { display: block; color: var(--black-100); font-weight: 600; } input { width: 100%; font-weight: 400; font-style: normal; border: 2px solid var(--black-100); box-shadow: none; outline: none; appearance: none; } input:focus { box-shadow: inset 0 0 0 2px; outline: 3px solid #fd0; outline-offset: 0; } Then using it in a JSX file with its vanilla tag: // SignIn.js render() { return ( <div class="form-control"> <label htmlFor="email"> Email <strong> <abbr title="This field is required">*</abbr> </strong> </label> <input required value={this.email} </div> ) } Layout I use CSS Flexbox for layout works in Sametable. I didn't need any CSS frameworks. Learn CSS Flexbox from its first principles to do more with less code. Plus, in many cases, the result will already be responsive thanks to the layout algorithms, saving those @media queries. Let's see how to build a common layout in Flexbox with a minimal amount of CSS: See the Pen Sidebar/Content layout on CodePen. Resources Server - server - server.js - package.json - .env The server is run on NodeJS(ExpressJS framework) to serve all my API endpoints. // Example endpoint: router.put("/save/:taskId", (req, res, next) => {}); The server.js contains the familiar codes to start a Nodejs server. File Structure I'm grateful for this digestible guide about project structure, which allowed me to hunker down and quickly build out my API. Npm Script(Server) In the package.json inside the 'server' folder, there is a npm script that will start your server for you: "scripts": { "dev": "nodemon -r dotenv/config server.js", "start": "node server.js" } The devscript 'preload' dotenv as suggested here. And that's it— You will have access to the env variables defined in the .envfile from the process.envobject. The startscript is used to start our Nodejs server in production. In my case, GCP will run this script to bootup my Nodejs. Database I use Postgresql as my database. Then I use the 'node-postgres'(a.k.a pg) library to connect my Nodejs to the database. Once that's done, I can do CRUD operations between my API endpoints and the database. Setup For local development: Download Postgresql here. Get the latest version. Leave everything as it is. Remember the password you set. Then, - Open 'pgAdmin'. It's a browser application. - Create a database for you app: Define a set of environment variables in the .envfile: DB_HOST='localhost' DB_USER=postgres DB_NAME=<YOUR_CUSTOM_DATABASE_NAME_HERE> DB_PASSWORD=<YOUR_MASTER_PASSWORD> DB_PORT=5432 Then we will connect a new client through a connection pool to our Postgresql database from our Nodejs. I do it in server/db/index.js: const { Pool } = require("pg"); const pool = new Pool({ user: process.env.DB_USER, host: process.env.DB_HOST, port: process.env.DB_PORT, database: process.env.DB_NAME, password: process.env.DB_PASSWORD, }); // TRANSACTION // const tx = async (callback, errCallback) => { const client = await pool.connect(); try { await client.query("BEGIN"); await callback(client); await client.query("COMMIT"); } catch (err) { console.log(("DB ERROR:", err)); await client.query("ROLLBACK"); errCallback && errCallback(err); } finally { client.release(); } }; // the pool will emit an error on behalf of any idle clients // it contains if a backend error or network partition happens pool.on("error", (err) => { process.exit(-1); }); pool.on("connect", () => { console.log("❤️ Connected to the Database ❤️"); }); module.exports = { query: (text, params, callback) => pool.query(text, params, callback), tx, pool, }; - I will use the txfunction in an API if I have to call many queries that depend on each other. - If I'm making a single query, I will use the queryfunction. And that's it! Now you have a database to work with for your local development ? Usage I will confess: I hand-crafted all the queries for Sametable. In my opinion, SQL itself is already a declarative language that needs no further abstraction—it's easy to read, understand, and write. It can be maintainable if you separated well your API endpoints. If you knew you were building a facebook-scale app, perhaps it would be wise to use an ORM. But I'm just a everyday normal guy building a very narrow-scoped SaaS all by myself. So I needed to avoid overhead and complexity while considering factors such as ease of onboarding, performance, ease of reiteration, and the potential lifespan of the knowledge. This reminds me of being urged to learn vanilla JavaScript before jumping on the bandwagon of a popular front-end framework. Because you just might realize: That's all you need for what you have set out to accomplish to reach your 1000th customer. To be fair, though, when I decided to go down this path, I'd had modest experiences in writing MySQL. So if you know nothing about SQL and you are anxious to ship it, then you might want to consider a library like knex.js. Example // server/routes/projects.js const express = require("express"); const asyncHandler = require("express-async-handler"); const db = require("../db"); const router = express.Router(); module.exports = router; // [POST] api/projects/create router.post( "/create", express.json(), asyncHandler(async (req, res, next) => { const { title, project_id } = req.body; db.tx(async (client) => { const { rows, } = await client.query( `INSERT INTO tasks (title) VALUES ($1) RETURNING mask_id(task_id) as masked_task_id, task_id`, [title] ); res.json({ id: rows[0].masked_task_id }); }, next); }) ); - The express-async-handleris mainly used to handle the async errors in my route handlers. It won't be needed anymore when Express 5 drops. - Import the dbmodule to use the txmethod. Pass your hand-crafted SQL queries and parameters. That's it! Creating table schemas Before you can start querying a database, you need to create tables. Each table contains information about an entity. But we don't just lump all information about an entity in the same table. We need to organize the information in a way that promotes query performance and data maintainability. And what has helped me in that exercise is a concept called denormalization. As mentioned, we don't want to store everything about an entity in the same table. For example, say, we have a users table storing fullname, password and But problem arises when we are also storing the ids of all the projects assigned to a particular user in a separate column in the same table. Instead, I will break them up into separate tables: Create the userstable. Notice that it's not storing any data related to 'projects': CREATE TABLE users( user_id BIGSERIAL PRIMARY KEY, fullname TEXT NOT NULL, pwd TEXT NOT NULL, email TEXT UNIQUE NOT NULL, ); Create a projectstable to store data solely about a project's details: CREATE TABLE projects( project_id BIGSERIAL PRIMARY KEY, title TEXT, content TEXT, due_date TIMESTAMPTZ, status SMALLINT, created_on TIMESTAMPTZ NOT NULL DEFAULT now() ); Create a 'bridge' table about projects' ownerships by associating the ID of an user with the ID of a project that she owns: CREATE TABLE project_ownerships( project_id BIGINT REFERENCES projects ON DELETE CASCADE, user_id BIGINT REFERENCES users ON DELETE CASCADE, PRIMARY KEY (project_id, user_id), CONSTRAINT project_user_unique UNIQUE (user_id, project_id) ); Finally, to get all the projects that are assigned to a particular user, we will do what relational database do best: join. I will put all my schemas in a .sql file at my project's root #: CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE TABLE users( user_id BIGSERIAL PRIMARY KEY, fullname TEXT NOT NULL, pwd TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_on TIMESTAMPTZ NOT NULL DEFAULT now() ); Then, I will copy, paste, and run them in pgAdmin: No doubt there are more advanced ways of doing this, so it's up to you if you want to explore what you like. Dropping a database Deleting an entire database to start with a new set of schemas was something I had to do very often at the beginning. The trick is: Well, you copy, paste, and run the command below in the database's query editor in pgAdmin: DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; COMMENT ON SCHEMA public IS 'standard public schema'; Crafting SQL queries I write my SQL queries in pgAdmin to get the data I want out of an API endpoint. To give a sense of direction to doing that in pgAdmin: Common Table Expressions(CTEs) I stumbled upon a pattern called CTEs when I was exploring how I was going to get the data I wanted from disparate tables and structure them as I wished, without doing lots of separate database queries and for-loops. The way CTE works is simple enough, even though it looks daunting: You write your queries. Each query is given an alias name ( q, q1, q3). And a next query can access any previous query's results by their alias name ( q1.workspace_id): WITH q AS (SELECT * FROM projects_tasks WHERE task_id=$1) , q1 AS (SELECT wp.workspace_id, wp.project_id, q.task_id FROM workspaces_projects wp, q WHERE wp.project_id = q.project_id) , q3 AS (SELECT q1.workspace_id AS workspace_id, wp.name AS workspace_title, mask_id(q1.project_id) AS project_id, p.title AS project_title, mask_id(t.task_id) AS task_id, t.title, t.content, t.due_date, t.priority, t.status) SELECT * FROM q3; Almost all the queries in Sametable are written this way. Redis Redis is a NoSQL database that stores data in memory. In Sametable, I used Redis for two purposes: - Store a user's session data and basic info from the userstable—name, email, and a flag that indicates the user is a subscriber or not—once they have logged in. - Cache the results of some of my Postgresql's queries to avoid having to query the database if the cache is still fresh. Installation I'm on a Windows 10 machine with Windows Subsystem Linux (WSL) installed. This was the only guide I followed to install Redis on my machine: Follow the guide to install WSL if you don't have it already. Then I will start my local Redis server in WSL bash: - Press Win + R. - Type bashand enter. - In the terminal, run sudo service redis-server start Now install the redis npm package: cd server npm i redis Make sure to install it in the server's package.json, hence the cd server. Then I create a file named redis.js under server/db: // server/db/redis.js const redis = require("redis"); const { promisify } = require("util"); const redisClient = redis.createClient( NODE_ENV === "production" ? { host: process.env.REDISHOST, no_ready_check: true, auth_pass: process.env.REDIS_PASSWORD, } : {} ); redisClient.on("error", (err) => console.error("ERR:REDIS:", err)); const redisGetAsync = promisify(redisClient.get).bind(redisClient); const redisSetExAsync = promisify(redisClient.setex).bind(redisClient); const redisDelAsync = promisify(redisClient.del).bind(redisClient); // 1 day expiry const REDIS_EXPIRATION = 7 * 86400; // seconds module.exports = { redisGetAsync, redisSetExAsync, redisDelAsync, REDIS_EXPIRATION, redisClient, }; By default, node-rediswill connect to localhostat port 6379. But that might not be the case in production if you host your Redis in a VM. So I provide this object if it's in production mode: { host: process.env.REDISHOST, no_ready_check: true, auth_pass: process.env.REDIS_PASSWORD, } - I promisfy the Redis methods that I will use to make them async to avoid blocking NodeJS's single-thread. And now you have the Redis for your local development! Error handling & Logging Error handling Error handling in Nodejs has a paradigm which we will explore in 3 different contexts. To set the stage, we need two things in place first: An npm package called http-errors that will give us a standard error data structure to work with especially in client-side. npm install http-errors We create a custom error handler at the global level to capture all propagated errors from the routes or the catchblocks via next(err): // app.js const express = require("express"); const app = express(); const createError = require("http-errors"); // our central custom error handler // NOTE: DON"T REMOVE THE 'next' even though eslint complains it's not being used!!! app.use(function (err, req, res, next) { // errors wrapped by http-errors will have 'status' property defined. Otherwise, it's a generic unexpected error const error = err.status ? err : createError(500, "Something went wrong. Notified dev."); res.status(error.status).json(error); }); As you will see, the general pattern of error handling in Nodejs revolves around the 'middleware' chain and the nextparameter: Calls to next() and next(err) indicate that the current handler is complete and in what state. next(err) will skip all remaining handlers in the chain except for those that are set up to handle errors . . . source Note that although this is a common pattern of handling error in Express, you might want to consider an alternative way that's, however, more complicated. Handle input validation errors It's a good practise to validate a user's inputs both in the client and server-side. At the server-side, I use a library called 'express-validator' to do the job. If any input is invalid, I will handle it by responding with an HTTP code and an error message to inform the user about it. For example, when an email provided by a user is invalid, we will exit early by creating an error object with the 'http-errors' library, and then pass it to the next function: const { body, validationResult } = require("express-validator"); router.post( "/login", upload.none(), [body("email", "Invalid email format").isEmail()], asyncHandler(async (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { return next(createError(422, errors.mapped())); } res.json({}); }) ); The following response will be sent to the client: { "message": "Unprocessable Entity", "email": { "value": "hello@mail.com232", "msg": "Invalid email format", "param": "email", "location": "body" } } Then it's up to you what you want to do with it. For example, you can access the email.msg property to display the error message below the email input field. Handle errors from business logic Let's say we have a situation where a user entered an email that didn't exist in the database. In that case, we need to tell the user to try again: router.post( "/login", upload.none(), asyncHandler(async (req, res, next) => { const { email, password } = req.body; const { rowCount } = await db.query( `SELECT * FROM users WHERE email=($1)`, [email] ); if (rowCount === 0) { // issue an error with generic message return next( createError(422, "Please enter a correct email and password") ); } res.json({}); }) ); Remember, any error object passed to 'next'( next(err)) will be captured by the custom error handler that we have set above. Handle unexpected errors from database I pass the route handler's next to my db's transaction wrapper function to handle any unexpected erorrs. router.post( "/invite", async (req, res, next) => { db.tx(async (client) => { const { rows, rowCount, } = await client.query( `SELECT mask_id(user_id) AS user_id, status FROM users WHERE users.email=$1`, [email] ); }, next) ) Logging When an error occurs, it's a common practice to 1) Log it to a system for records, and 2) Automatically notify you about it. There are many tools out there in this area. But I ended up with two of them: - Sentry for storing details (e.g. stack traces) of my errors, and displaying them on their web-based dashboard. - pino to enable logging in my Nodejs. Why Sentry? Well, it was recommended by lots of devs and small startups. It offers 5000 errors you can send per month for free. For perspective, if you are operating a small side project and careful about it, I would say that'd last you until you can afford a more luxurious vendor or plan. Another option worth exploring is honeybadger.io with more generous free-tier but without a pino transport. Why Pino- Why not the official SDK provided by Sentry? Because Pino has 'low overhead', whereas, Sentry SDK, although it gives you a more complete picture of an error, seemed to have a complex memory issue that I couldn't see myself being able to circumvent. With that, here is how the logging system is hooked up in Sametable: // server/lib/logger.js // install missing packages const pino = require("pino"); const { createWriteStream } = require("pino-sentry"); const expressPino = require("express-pino-logger"); const options = { name: "sametable", level: "error" }; // SENTRY_DSN is provided by Sentry. Store it as env var in the .env file. const stream = createWriteStream({ dsn: process.env.SENTRY_DSN }); const logger = pino(options, stream); const expressLogger = expressPino({ logger }); module.exports = { expressLogger, // use it like app.use(expressLogger) -> req.log.info('haha) logger, }; Rather than attaching the logger( expressLogger) as a middleware at the top of the chain( app.use(expressLogger)), I use the logger object only where I want to log an error. For example, the custom global error handler uses the logger object: app.use(function (err, req, res, next) { const error = err.status ? err : createError(500, "Something went wrong. Notified dev."); if (isProduction) { // LOG THIS ERROR IN MY SENTRY DASHBOARD logger.error(error); } else { console.log("Custom error handler:", error); } res.status(error.status).json(error); }); That's it! And don't forget to enable email notification in your Sentry dashboard to get an alert when your Sentry receives an error! ❤️ Permalink for URL Sharing We have seen URLs consist of cryptic alphanumeric string such as those on Youtube:. This URL points to a specific video, which can be shared with someone by sharing the URL. The key component in the URL representing the video is the unique ID at the end: upyjlOLBv5o. We see this kind of ID in other sites too: vimeo.com/259411563 and subscription's ID in Stripe sub_aH2s332nm04. As far as I know, there are three ways to achieve this outcome: Generate the ID when inserting data in your database. The generated ID will be the ID in your idcolumn rather than the auto-increment ones: Then you will expose these IDs in public-facing URLs:. Given this URL to your backend, you can retrieve the respective resource from the database: router.get("/task/:taskId", (req, res, next) => { const { taskId } = req.params; // SELECT * FROM tasks WHERE id=<taskId> }); The downsides to this method that I know of: - The IDs might be sensitive information to be exposed publicly like that. - These IDs are detrimental to the performance of indexing and 'joining' on your tables. You keep auto-incrementing your IDs in your tables, but you will represent them by generating their alphanumeric counterpart during database operations: SELECT hash_encode(123, 'this is my salt', 10); -- Result: 4xpAYDx0mQ SELECT hash_decode('4xpAYDx0mQ', 'this is my salt', 10); -- Result: 123 I had trouble integrating this library on my Windows machine. So I went with the next option. Similar to the second option above but different approach. This will generate numeric ID: User Authentication System A user authentication system can get very complicated if you need to support things like SSO and third-party OAuth providers. That's why we have third-party tools such as Auth0, Okta, and PassportJS to abstract that out for us. But those tools cost: vendor lock-in, more Javascript payload, and cognitive overhead. I would argue that if you are starting out and just need some kind of authentication system so you can move on to other parts of your app, and at the same time, overwhelmed by all the dated tutorials that deal with stuff you don't use, well, chances are all you need is the good old way of doing authentication: Session cookie with email and password! And we are not talking about 'JWT' either! None of that. Guide Here is a guide I ended up writing. Follow it and you got yourself a user authentication system! Currently, in Sametable, the only emails it sends are of 'transactional' type like sending a reset password email when users reset their password. There are two ways to send emails in Nodejs: Roll your own with Nodemailer. I wouldn't go down this path because although sending one email might seem a trivial task, doing it 'at scale' is hard; every email must be sent successfully; and they must not end up in a user's spam folder; and other things I'm not aware of. Choose one of the email service providers. Many email services offer a free-tier plan offering a limited number of emails you can send per month/day for free. When I started exploring this space for Sametable in October 2019, Mailgun stood out to be a no-brainer—It offers 10,000 emails for free per month! But, sadly, as I was researching for this section write-up, I learned that it no longer offers that. Despite that, though, I would still stick to Mailgun, on their pay-as-you-go plan: 1000 emails sent will cost you 80 cents. If you would rather not pay a cent for whatever reason, here are two options for you that I could find: But do go down this path while being aware there's no guarantee that these free-tier plans will stay that way forever as was the case with Mailgun. Implementation Wrapper file // server/lib/email.js // Run 'npm install mailgun-js' in your 'server' folder const mailgun = require("mailgun-js"); const DOMAIN = "mail.sametable.app"; const mg = mailgun({ apiKey: process.env.MAILGUN_API_KEY, domain: DOMAIN, }); function send(data) { mg.messages().send(data, function (error) { if (!error) return; console.log("Email send error:", error); }); } module.exports = { send, }; Usage const mailer = require("../lib/email"); // Simplified for only email-related stuff router.post( "/resetPassword", upload.none(), (req, res, next) => { const { email } = req.body; const data = { from: "Sametable <feedback@sametable.app>", to: email, subject: "Reset your password", text: `Click this link to reset your password:`, }; mailer.send(data); res.json({}); }) ); Each type of email you send could have its own email template whose content can be varied with dynamic values you can provide. Tool mjml is the tool I use to build my email templates. Sure, there are many drag-and-drop email builders out there that don't intimidate with the sight of 'codes'. But if you know just basic React/HTML/CSS, mjml would give you great usability and maximum flexibility. It's easy to get started. Like the email builders, you compose a template with a bunch of reusable components, and you customize them by providing values to their props. Here are the places where I would write my templates: Example template <mjml> <mj-head> <mj-attributes> <mj-class <mj-class </mj-attributes> </mj-head> <mj-body> <mj-section> <mj-column> <mj-image </mj-column> </mj-section> <mj-section> <mj-column> <mj-text{{assigner_name}} assigned a project to you</mj-text > <mj-spacer <mj-text{{project_title}}</mj-text > <mj-spacer <mj-buttonView the project</mj-button > </mj-column> </mj-section> <mj-spacer <mj-section <mj-column> <mj-text Problems or questions? Feel free to reply to this email. </mj-text> <mj-text Made with ❤️ by <a href="">@kheohyeewei</a> </mj-text> </mj-column> </mj-section> </mj-body> </mjml> Result Notice the placeholder names that are wrapped in double curly brackets such as {{project_title}}. They will be replaced with their corresponding value by, in my case, Mailgun, before being sent out. Integration with Mailgun First, generate HTML from your mjml templates. You are able to do that with the VSCode extension or the web-based editor: Then create a new template on your Mailgun dashboard: Send an email with Mailgun in Nodejs Inside a route: const data = { from: "Sametable <feedback@sametable.app>", to: email, subject: `Hello`, template: "invite_project", // the template's name you gave when you created it in mailgun "v:invite_link": inviteLink, "v:assigner_name": fullname, "v:project_title": title, }; mailer.send(data); Notice that, to associate a value with a placeholder name in a template: "v:project_title":'Project Mario'. How to get one of those hi@example.com It's an email address people use to contact you about your SaaS, rather than with a lola887@hotmail.com. There are three options on my radar: - If you are on Mailgun, follow this guide. However, the new pay-as-you-go tier has excluded the feature( Inbound Email Routing) that makes this possible. So perhaps the next option; - If I ever get kicked out of my '10,000' free-tier in Mailgun, I would give this a shot - If all else failed, pay for 'Gmail on G Suite'. Tenancy When an organization, say, Acme Inc., signs up on your SaaS, it's considered a 'tenant' — They 'occupy' a spot on your service. While I'd heard of the 'multi-tenancy' term being associated with a SaaS before, I never had the slightest idea about implementing it. I always thought that it'd involve some cryptic computer-sciency maneuvering that I couldn't possibly have figured it all out by myself. Fortunately, there is an easy way to do 'multi-tenancy': Single database; all clients share the same tables; each client has a tenant_id; queries the database as per an API request by WHERE tenant_id = $ID. So don't worry—If you know basic SQL (again indicating the importance of mastering the basics in anything you do!), you should have a clear picture on the steps required to implement this. Here are three instrumental resources about 'multi-tenancy' I bookmarked before: - - - Domain name Sametable.app domain and all its DNS records are hosted in NameCheap. I was on hover before(it still hosts my personal website's domain). But I hit a limitation there when I tried to enter my Mailgun's DKIM value. Namecheap also has more competitive prices in my experience. At which stage in your SaaS development should you get a domain name? Well, I would say not until when the lack of a DNS registrar is blocking your development. In my case, I deferred it until I had to integrate Mailgun which requires creating a bunch of DNS records in a domain. How to get one of those app.example.com You know those URLs that has a app in front of it like app.example.io? Yea, that's a 'custom domain' with the 'app' as its 'subdomain'. And it all started with having a domain name. So go ahead and get one in Namecheap or whatever. Then, in my case with Firebase, just follow this tutorial and you will be fine. Deployment Ugh. This was a stage where I struggled for the longest time ?. It was one hell of a journey where I found myself doubling down on a cloud platform but end up bailing out as I found out their downsides to optimize for developer experience, costs, quota, and performance(latency). The journey started with me jumping head-first(bad idea) into Digital Ocean since I saw it recommended a lot in the IndieHackers forum. And sure enough, I managed to get my Nodejs up and running in a VM by following closely the tutorials. Then I found out that the DO Space wasn't exactly AWS S3—It can't host my SPA. Although I could have hosted it in my droplet and hook up a third-party CDN like CloudFlare to the droplet, it seemed to me unnecessarily convoluted compared to the S3+Cloudfront setup. I was also using a DO's Managed Database(Postgresql) because I didn't want to manage my DB and tweak in the *.config files myself. That costs a fixed $15/month. Then I learned about AWS Lightsail which is a mirror image of DO, but to my surprise, with more competitive quota at a given price point: VM at $5/month Managed database at $15/month So I started betting on Lightsail instead. But, the $15/month for a managed database in Lightsail got to me at one point. I didn't want to have to pay that money when I wasn't even sure that I would ever have any paying customers. At this point, I supposed that I had to get my hands dirty to optimize for the cost factor. So I started looking into wiring AWS EC2, RDS, etc. But there were just too many of AWS-specific things I had to pick up, and the AWS doc wasn't exactly helping either—It's one rabbit hole after another just to do one thing because I just needed something to host my SPA and Nodejs for goodness sake! Then I checked back in IndieHacker for a sanity check, and came across render.com. It seemed perfect! It's one of those tools that are on a mission 'so you can focus on building your app'. The tutorials were short and got you up and running in no time. And here is the 'but'—It was expensive: Comparison of Lightsail and Render at their lowest price point And that's just for hosting my Nodejs! So what now?! Do I just say f*** it and do whatever it takes to 'ship it'? But I held my ground. I revisited AWS again. I still believed AWS was the answer because everyone else is singing its song. I must be missing something! This time I considered their higher-level tools like AWS AppSync and Amplify. But I couldn't overlook the fact that both of them force me to completely work by their standards and library. So at this point, I'd had it with AWS, and turned to another...platform: Google Cloud Platform(GCP). Sametable's Nodejs, Redis, and Postgresql are hosted on GCP. The thing that drew me to GCP was its documentation—It's much more linear; code snippets everywhere for your specific language; step-by-step guides about the common things you would do for a web app. Plus, it's serverless! Which means your cost is proportional to your usage. Deploy Nodejs The GAE 'standard environment' hosts my Nodejs. Cost GAE's standard environment has free quota unlike the 'flexible environment'. Beyond that, you will pay only if somebody is using your SaaS ?. Guide This was the only guide I relied on. It was my north star. It covers Nodejs, Postgresql, Redis, file storage, and more: Start with the 'Quick Start' tutorial because it will set you up with the gcloud cli which you are going to need when following the rest of the guides, where you will find commands you can run to follow along. If you aren't comfortable with the CLI environment, the guides will provide alternative steps to achieve the same thing on the GCP dashboard. I love it. I noticed that while going through the GCP doc, I never had to open more than 4 tabs in my browser. It was the complete opposite with AWS doc—My browser would be packed with it. Deploy Postgresql Guide Just follow it and you will be fine. Cost An instance of Cloud SQL runs a full virtual machine. And once a VM has been provisioned, it won't automatically turn itself off when, for example, it has not seen any usage for 15 minutes. So you will be billed for every hour an instance is running for an entire month unless it'd been manually stopped. The primary factor that will affect your cost here, particularly in the early days, is the grade of the machine type. The default machine type for a Cloud SQL is a db-n1-standard-1, and the 'cheapest' one you can get is a db-f1-micro: The other two cost factors are storage and network egress. But they are charged monthly, so they probably won't have as big of an impact on the bill of your nascent SaaS. If you find the price tags to be too hefty to your liking, keep in mind that they are a managed database. You are paying for all the times and anxiety saved from doing devops on your database. For me, it's worth it. Setup schemas in production database Now that I have got a database deployed for production, it's time to dress it up with all my schemas from the .sql file. To do that, I need to connect to the database from pgAdmin: - - There you will find a table with a list of options for connecting from an external application. I went with the first one: Public IP address with SSL. Follow all the guides in the 'More information' column and you will have all the information needed to create a server in your pgAdmin. You will be fine. If not, email me and I will provide assistance. Deploy Redis If you were following the main guide about Nodejs, you can't miss this guide about setting up your Redis in MemoryStore. But I figured it would be more cost-effective to host my Redis in a Google Compute Engine(GCE) which has, unlike MemoryStore, free quota in certain aspects. (See this for comparison of free quota across different cloud platforms) Guide Serverless VPC Access enables you to connect from your App Engine app directly to your VPC network, allowing access to Compute Engine VM instances, Memorystore instances, and any other resources with an internal IP address. In your app.yamlfile: vpc_access_connector: name: "<YOURS_HERE>" env_variables: REDIS_PASSWORD: "<PASSWORD_YOU_SET_IN_A_GUIDE_ABOVE>" REDISHOST: "<INTERNAL_IP_OF_YOUR_VM>" REDISPORT: "6379" # default port when install redis Internal IP of a GCE Finally, in lib/redis.js: const redis = require("redis"); const redisClient = redis.createClient( NODE_ENV === "production" ? { host: process.env.REDISHOST, port: process.env.REDISPORT, // default to 6379 if wasn't set no_ready_check: true, auth_pass: process.env.REDIS_PASSWORD, } : {} // just use the default: localhost and ports ); module.exports = { redisClient, }; File Storage Cloud Storage is what you need for your users to upload their files such as images which they will need to retrieve and possibly display later. Cost There is a free tier for Cloud Storage too. Guide Deploy New Changes in Back-end I have a npm script in the root's package.json to publish new changes in my back-end to GCP: "scripts": { "deploy-server": "gcloud app deploy ./server/app.yaml" } Then run it in a terminal at your project's root: npm run deploy-server Hosting Your SPA When I was still on Lightsail, my SPA was hosted on S3+Cloudfront because I assumed it's better to keep them under the same platform for better latency. Then I found GCP. As a beat refugee from AWS landing in GCP, I first explored the 'Cloud Storage' to host my SPA, and turns out it wasn't ideal for SPA. It's rather convoluted. So you can skip that. Then I tried hosting my SPA in Firebase. Easily done in minutes even when it was my first time there. I love it. Another option you can consider is Netlify which is super easy to get started too. Deploy New Changes in Front-end Similarly to deploying back-end changes, I have another npm script in the root's package.json to publish new changes in my front-end to Firebase: "scripts": { "deploy-client": "npm run build-client && firebase deploy", "build-client": "npm run test && cd client && npm i && npm run build", "test": "npm run lint", "lint": "npm run lint:js && npm run lint:css", "lint:js": "eslint 'client/src/**/*.js' --fix", "lint:css": "stylelint '**/*.{scss,css}' '!client/dist/**/*'" } "Whoa hold on, where all that stuff come from??" They are a chain of scripts that each runs sequentially upon triggered by the deploy-client script. The && character is what glues them together. Let's hold each other's hands and walk through it from start to finish: - First, we do npm run deploy-client, - which runs build-clientfirst, - which runs testfirst, (see, we are just following where a script and its &&lead us, which is why firebase deploywon't run just yet) - which runs lint, - which brings us to lint:jsfirst, and next, lint:css, - then back to cd client, followed by npm iand npm run build, - and finally, it's firebase deploy's turn to run. Tip: If the changes you made are full-stack, you could have a script that deploys 'client' and 'server' together: "scripts": { "deploy-all": "npm run deploy-server && npm run deploy-client", } Rich-text Editor Building the rich-text editor in Sametable was the second most challenging thing for me. I realized that I could have had it easy with those drop-in editors such as CKEditor and TinyMCE, but I wanted to be able to craft the writing experience in the editor, and nothing can do that better than ProseMirror. Sure, I had other options too, which I decided against for several reasons: - Quilljs - Draftjs - They are tightly coupled with React. - With the overhead of virtual DOM, they won't perform as well as Prosemirror. - trix - Based on Web Component. I had issues integrating it in Preact. - It wasn't flexible to build a customized editing experience. Prosemirror is undoubtedly an impeccable library. But learning it was not for the faint of heart as far as I'm concerned. I failed to build any encompassing mental models of it even after I'd read the guide several times. The only way I could make progress from there was by cross-referencing existing code examples and the manual, and trial-and-error from there. And if I exhausted that too, then I would ask in the forum and it's always answered. I wouldn't bother with StackOverflow unless maybe for the popular Quilljs. These were the places I went scrounging for code samples: - The official examples - Search the forum - 'Fork' prosemirror-example-setup - An editor called tiptap that's based on Prosemirror but built for Vuejs. The codebase actually has very few bits of Vuejs. So you can find lots of helpful Prosemirror-specific snippets there(thanks guys!). In keeping with the spirit of this learning journey, I have extracted the rich-text editor of Sametable in a CodeSandBox: ? (Note: Prosemirror is framework-agnostic; the CodeSandBox demo only uses 'create-react-app' for bundling ES6 modules.) CORS To stop your browser from complaining about CORS issues, it's all about getting your backend to send those Access-Control-Allow-* headers back per request. (Apologies for oversimplification is in order) But, correct me if I'm wrong, there's no way to configure CORS in GAE itself. So I had to do it with the cors npm package: const express = require("express"); const app = express(); const cors = require("cors"); const ALLOWED_ORIGINS = [ "", "", // your SPA's domain ]; app.use( cors({ credentials: true, // include Access-Control-Allow-Credentials: true. remember set xhr.withCredentials = true; origin(origin, callback) { // allow requests with no origin // (like mobile apps or curl requests) if (!origin) return callback(null, true); if (ALLOWED_ORIGINS.indexOf(origin) === -1) { const msg = "The CORS policy for this site does not " + "allow access from the specified Origin."; return callback(new Error(msg), false); } return callback(null, true); }, }) ); Payment & Subscription A SaaS usually allows users to pay and subscribe to access the paid features you have designated. To enable that possibility in Sametable, I use Stripe to handle both the payment and subscription flows. Guide There are two ways to implement them: - Very hands-on that's great for customizing your UI. Webhook The last key component I needed for this piece was a 'webhook' which is basically just a typical endpoint in your Nodejs that can be called by a third-party such as Stripe. I created a webhook that will be called when a payment has been charged successfully to signify in the user record that corresponds to the payee as a PRO user in Sametable from there onwards: router.post( "/webhook/payment_success", bodyParser.raw({ type: "application/json" }), asyncHandler(async (req, res, next) => { const sig = req.headers["stripe-signature"]; let event; try { event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret); } catch (err) { return res.status(400).send(`Webhook Error: ${err.message}`); } // Handle the checkout.session.completed event if (event.type === "checkout.session.completed") { // 'session' doc: const session = event.data.object; // here you can query your database to, for example, // update a particular user/tenant's record // Return a res to acknowledge receipt of the event res.json({ received: true }); } else { res.status(400); } }) ); Reference Here is a code snippet of a webhook: Guide Landing page Building I use Eleventy to build the landing page of Sametable. I wouldn't recommend Gatsby or Nextjs. They are overkill for this job. I started with one of the starter projects as I was impatient to get my page off the ground. But I struggled working in them. Although Eleventy claims to be a simple SSG, there are actually quite a few concepts to grasp if you are new to static site generators(SSG). Coupled with the tools introduced by the starter kits, things can get complex. So I decided to start from zero and take my time reading the doc from start to finish, slowly building up. Quiet and easy. Guides - Long version - Short version: (the first website I built as my personal site while learning 11ty. It has a homepage and blog posts. Very few concepts introduced here. You could start with this 'starter project') Hosting I use Netlify to host the landing page. There are also surge.sh and Vercel. You will be fine here. T&C makes your SaaS legit. As far as I know, here are your options to come up with them: - Write your own. - Copy and paste others'. Change accordingly. Never easy in my experience. - Lawyer up. - Generate them in getterms.io. Marketing There is no shortage of marketing posts saying it was a bad idea to "Let the product speaks for itself". Well, not unless you were trying to 'hack growth' to win the game. The following is the trajectory of existence I have in mind for Sametable: - Build something that purportedly solves a problem. - Do your SEO. Write the blog posts. Anyone who is affected by the problem that you have solved for will search for it, or know about it by word of mouth. - If it still didn't take off, well, chances are you weren't solving a huge real problem, or enough people have already solved it. In that case, just be grateful for whatever success that comes your way over the long haul. Resources - - Well-being It's easy to sit and get lost in our contemporary work. And we do that by accumulating debts from the future. One of the debts is our personal health. Here is how I try to stay on top of my health debt: - Install Workrave. You can set it to lock your screen after an interval has passed. Most importantly, it can show some exercises that you can perform behind your computer! - Get an adjustable standing desk if you can afford it. I got mine from IKEA. - Do burpees. Stretch those joints. Maintain good posture. Planking helps. - Meditate to stay sane. I'm using Medito. ?? Thanks for reading. Be sure to check out my own SaaS tool Sametable to manage your work in spreadsheets.
https://www.freecodecamp.org/news/how-to-build-your-first-saas/
CC-MAIN-2021-31
refinedweb
10,298
56.76
SYNOPSIS #include <qnewton.h> Inherits sc::Optimize. Public Member Functions QNewtonOpt (const Ref< KeyVal > &) The KeyVal constructor. QNewtonOpt (StateIn &) void save_data_state (StateOut &) Save the base classes (with save_data_state) and the members in the same order that the StateIn CTOR initializes them. void apply_transform (const Ref< NonlinearTransform > &) void init () Initialize the optimizer. int update () Take a step. Protected Attributes double maxabs_gradient double accuracy_ RefSymmSCMatrix ihessian_ Ref< HessianUpdate > update_ Ref< LineOpt > lineopt_ int take_newton_step_ int print_hessian_ int print_x_ int print_gradient_ int linear_ int restrict_ int dynamic_grad_acc_ int force_search_ int restart_ Detailed Description The QNewtonOpt implements a quasi-Newton optimization scheme. Constructor & Destructor Documentation sc::QNewtonOpt::QNewtonOpt (const Ref< KeyVal > &) The KeyVal constructor. The KeyVal constructor reads the following keywords: - update - This gives a HessianUpdate object. The default is to not update the hessian. - hessian - By default, the guess hessian is obtained from the Function object. This keyword specifies an lower triangle array (the second index must be less than or equal to than the first) that replaces the guess hessian. If some of the elements are not given, elements from the guess hessian will be used. - lineopt - This gives a LineOpt object for doing line optimizations in the Newton direction. The default is to skip the line optimizations. - accuracy - The accuracy with which the first gradient will be computed. If this is too large, it may be necessary to evaluate the first gradient point twice. If it is too small, it may take longer to evaluate the first point. The default is 0.0001. - print_x - If true, print the coordinates each iteration. The default is false. - print_gradient - If true, print the gradient each iteration. The default is false. - print_hessian - If true, print the approximate hessian each iteration. The default is false. - restrict - Use step size restriction when not using a line search. The default is true. Member Function Documentation void sc::QNewtonOpt::save_data_state (StateOut &) [virtual] Save the base classes (with save_data_state) and the members in the same order that the StateIn CTOR initializes them. This must be implemented by the derived class if the class has data. Reimplemented from sc::Optimize. int sc::QNewtonOpt::update () [virtual] Take a step. Returns 1 if the optimization has converged, otherwise 0. Implements sc::Optimize. Author Generated automatically by Doxygen for MPQC from the source code.
https://manpages.org/scqnewtonopt/3
CC-MAIN-2022-40
refinedweb
380
51.65
The Microsoft Visual C++ Express edition can be downloaded free of charge. While the Express edition of Visual C++ offers a rich development environment, it lacks the possibilities to develop and compile MFC programs. In this article, I will explain how you still can compile MFC code within Visual C++ Express, which is particularly useful when you have a lot of old MFC code lying around, like I have. To compile MFC code within the Express edition of Visual C++, you first need to perform five steps: Step 1 - First of all, you need to download and install the Visual C++ Express edition, if you have not already done so. Step 2 - Go to the Windows Server 2003 driver development kit (DDK) webpage, download the DDK ISO file, and burn it to a CD. Most of the time, you can just use the CD burning software that comes with your computer for this task, or alternatively, you can use this software, or this. Step 3 - Install the DDK from the CD (execute setup.exe on the CD). It is enough to simply install the default selection (Build Environment, Documentation, Tools for Driver Developers). Step 4 - You have to add a couple of directory paths to tell Visual C++ where the MFC related files can be found. This can be done by selecting in the "Options..." entry in the "Tools" menu, like shown in the image below: Then, in the "Projects and Solutions" entry in the list on the left, select "VC++ Directories". Now, in the "Show directories for" dropdown on the right, select "Include files". Here, you should add (simply click on an empty line) the following paths: whereby you should replace $(DDK_directory) with the directory where you installed the DDK in the previous step, which is "C:\WINDDK\3790.1830" in my case; see the image below: Now, change the "Show directories for" dropdown to "Library files", and add: Again, replace $(DDK_directory) with the path to the DDK on your machine; see the image below: Step 5 - In the last step, you have to edit the file "afxwin.inl", which can be found in the $(DDK_directory)\inc\mfc42 directory. In this file, from line 1033 onwards, change: _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const { return ((HMENU) menu) == m_hMenu; } _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const { return ((HMENU) menu) != m_hMenu; } into: _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const { return ((HMENU) menu) == m_hMenu; } _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const { return ((HMENU) menu) != m_hMenu; } Looking for the differences? Well, "BOOL" has been inserted twice (mind the capitals). BOOL Now, you are all set to compile MFC programs in the Visual C++ Express edition. Download the example program at the top of this article, and try it! Aren't there any issues? Of course, there are! You just installed version 4.2 of MFC, which is the version that was delivered with Visual Studio 6. This means that if you have code that uses MFC features introduced after VS6, it will not compile. Further, you will not be able to run with the MFC debug DLLs, nor will you be able to link statically against MFC. Using dynamic linking in release mode makes everything run fine, though. Finally, the Express edition does not come with the drag and drop MFC resource editor. You can either edit your resource files (these are the files that determine how your windows look like) by hand in text mode, or you can try an external program. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) valdok wrote:P.S. Does it really matter which MFC version to hijack? For instance, I have a VS2008 installed, I could take MFC/Atl headers and libs from there. ...missing identifier: AFX_CRT_ERRORCHECK c:\winddk\7600.16385.1\inc\mfc42\atlconv.h #if defined(USE_MFC6_WITH_ATL7) #include "..\atlmfc\atlconv.h" #define AFX_CRT_ERRORCHECK(expr) \ AtlCrtErrorCheck(expr) #else #include "..\atl30\atlconv.h" #define _ATL_NO_CONVERSIONS #endif #if defined(USE_MFC6_WITH_ATL7) #include "..\atlmfc\atlconv.h" #define AFX_CRT_ERRORCHECK(expr) \ AtlCrtErrorCheck(expr) #else #include "..\atl71\atlconv.h" //#define _ATL_NO_CONVERSIONS #define AFX_CRT_ERRORCHECK(expr) \ AtlCrtErrorCheck(expr) #endif 1>device.obj : error LNK2001: unresolved external symbol __imp_CM_Get_Device_ID_ExW 1>device.obj : error LNK2001: unresolved external symbol __imp_SetupDiGetClassDevsExW CPoint pnt; pnt = CPoint(10,2); generic "_generic MessageBox AfxMessageBox System::String^ str = gcnew System::String("some words"); General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/30439/How-to-compile-MFC-code-in-Visual-C-Express?msg=3341910
CC-MAIN-2015-06
refinedweb
753
55.44
Revision history for Perl module Hook::WrapSub 0.07 2016-02-04 NEILB - Added myself to the AUTHOR section, as suggested by the original author John Porter in RT#111728 - Added a better introductory paragraph to the pod, saying what the module does. - Moved all the pod to the end of the file. 0.06 2016-02-03 NEILB - Added links to Class::Method::Modifiers & Moose::Manual::MethodModifiers in SEE ALSO. Thanks to ETHER. 0.05 2015-11-10 NEILB - Changed github repo URL after changing my github username - Added [MetaJSON] to dist.ini so META.json is included in releases - Tag and push to github when I run "dzil release" 0.04 2014-06-21 - Non-developer release - changes as per 0.03_01 release 0.03_01 2014-06-19 - Switched to Dist::Zilla - Moved test.pl to t/01-basic.t - Added SEE ALSO section, with links to, and descriptions of, similar modules. - Added github repo to pod - Reformatted Changes as per CPAN::Changes::Spec 0.03 2000-02-01 JDPORTER - Fixed bug: sense of wantarray was inverted 0.02 1999-11-03 JDPORTER - First release to CPAN - Added ability to wrap subs in other namespaces. 0.01 1999-10-14 - original version; created by John Porter, via h2xs 1.19
https://metacpan.org/changes/distribution/Hook-WrapSub
CC-MAIN-2021-17
refinedweb
212
69.79
Created on 2017-05-20 21:01 by dalke, last changed 2018-07-08 09:29 by serhiy.storchaka. This issue is now closed. Others have reported issues like #21074 where the peephole compiler generates and discards large strings, and #30293 where it generates multi-MB integers and stores them in the .pyc. This is a different issue. The code: def tuple20(): return ((((((((1,)*20,)*20,)*20,)*20,)*20,)*20,)*20,)*20 takes over four minutes (257 seconds) to compile on my machine. The seemingly larger: def tuple30(): return ((((((((1,)*30,)*30,)*30,)*30,)*30,)*30,)*30,)*30 takes a small fraction of a second to compile, and is equally fast to run. Neither code generates a large data structure. In fact, they only needs about 1K. A sampling profiler of the first case, taken around 30 seconds into the run, shows that nearly all of the CPU time is spent in computing the hash of the highly-nested tuple20, which must visit a very large number of elements even though there are only a small number of unique elements. The call chain is: Py_Main -> PyRun_SimpleFileExFlags -> PyAST_CompileObject -> compiler_body -> compiler_function -> compiler_make_closure -> compiler_add_o -> PyDict_GetItem and then into the tuple hash code. It appears that the peephole optimizer converts the highly-nested tuple20 into a constant value. The compiler then creates the code object with its co_consts. Specifically, compiler_make_closure uses a dictionary to ensure that the elements in co_consts are unique, and mapped to the integer used by LOAD_CONST. It takes about 115 seconds to compute hash(tuple20). I believe the hash is computed twice, once to check if the object is present, and the second to insert it. I suspect most of the other 26 seconds went to computing the intermediate constants in the tuple. Based on the previous issues I highlighted in my first paragraph, I believe this report will be filed under "Doctor, doctor, it hurts when I do this"/"Then don't do it." I see no easy fix, and cannot think of how it would come about in real-world use. I point it out because in reading the various issues related to the peephole optimizer there's a subset of people who propose a look-before-you-leap technical solution of avoiding an optimization where the estimated result is too large. While it does help, it does not avoid all of the negatives of the peephole optimizer, or any AST-based optimizer with similar capabilities. I suspect even most core developers aren't aware of this specific negative. Nice example. The only fix I see is caching the hash in a tuple. This can even help in more cases, when tuples are used as dict keys. But this affect too much code, and can even break a code that mutates a tuple with refcount 1. Caching a tuple's hash value is a nice idea but it would increase the memory consumption of all tuples, which would probably hurt much more in the average case... Unless of course we find a way to cache the hash value in a separate memory area that's reserved on demand. A complex solution is to stop constant folding when there are more than a few levels of tuples. I suspect there aren't that many cases where there are more than 5 levels of tuples and where constant creation can't simply be assigned and used as a module variable. This solution would become even more complex should constant propagation be supported. Another option is to check the value about to be added to co_consts. If it is a container, then check if it would require more than a few levels of hash calls. If so, then simply add it without ensuring uniqueness. This could be implemented because the compiler could be told how to carry out that check for the handful of supported container types. Proposed patch makes const folding more safe by checking arguments before doing expensive calculation that can create large object (multiplication, power and left shift). It fixes examples in this issue, issue21074, issue30293. The limit for repetition is increase from 20 to 256. There are no limits for addition/concatenation and like, since it is hard to create really large objects with these operations. After testing on Python 2, I was surprised to discover that this issue was introduced to the 2.x series quite recently: 2.7.11 doesn't have the issue, while 2.7.13 does. The culprit appears to be this commit:, introduced as part of issue 27942. Yet another proof that performance improvements should *not* be committed to bugfix branches. Please, can someone learn a lesson? New changeset 2e3f5701858d1fc04caedefdd9a8ea43810270d2 by Serhiy Storchaka in branch 'master': bpo-30416: Protect the optimizer during constant folding. (#4860) New changeset b580f4f2bf49fd3b11f2a046911993560c02492a by Serhiy Storchaka in branch '3.6': [3.6] bpo-30416: Protect the optimizer during constant folding. (#4865) PR 4896 fixes this issue in 2.7, but I'm not sure that I want to merge it. The code in 2.7 is more complex because of two integer types. What do you suggest to do with 2.7? Revert the changes that introduced the regression, merge the backported fix, or keep all as is? We should revert the breaking 2.7 changes. On Sun, Mar 25, 2018, at 13:59, Gregory P. Smith wrote: > > Change by Gregory P. Smith <greg@krypto.org>: > > > ---------- > assignee: -> benjamin.peterson > > _______________________________________ > Python tracker <report@bugs.python.org> > <> > _______________________________________ Reverting issue27942 (67edf73183b8bf0127456454747f596428cc28f6) doesn't solve this issue in 2.7. The previous revision has this issue, as well as 2.7.12 and 2.7.11. Even 2.6.9 and 2.5.6 have this issue. We have either merge PR 4896 or decide that this issue is "won't fix" in 2.7. I vote for "won't fix". 2.7 has lived long enough with this issue, AFAIU. And it won't be triggered by regular code. Okay, this issue is fixed in 3.6.
https://bugs.python.org/issue30416
CC-MAIN-2020-16
refinedweb
1,000
66.03
final int basePrice = _quantity * _itemPrice; //...To: private int basePrice(); //...ExtractMethod: From: double getPrice() { final double discountFactor; if (basePrice() > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice() * discountFactor; }To: double getPrice() { final double discountFactor = discountFactor(); return basePrice() * discountFactor; } private double discountFactor() { if (basePrice() > 1000) return 0.95; else return 0.98; }The ability to do the ExtractMethod is claimed as justification for the ReplaceTempWithQuery. But this has just increased the dependencies within the code. The new discountFactor() method now requires internal access to the object, just to get at the basePrice member. I'd say that this design for discountFactor is better: "private final double discountFactor(int basePrice)" (I'm a C++ programmer, I mean a static method), i.e. passing basePrice as a parameter and not giving access to the object. And if you're doing that, a large part of the justification for ReplaceTempWithQuery is gone. I'm all for adding "final" (or "const" in C++) before local variables, but replacing them with queries is just adding a potential slowdown to the code, for no win that's obvious to me. And there's no limit on how big that slowdown could be. As Ward mentions, caching doesn't come for free, it requires invalidation checks, which are, in my experience, considerably time-consuming to implement and error-prone, not to mention the extra space requirements for the cache. When you come to consider adding the caching, you're going to look at your code and see a hundred different places where you could have used a temporary and then you wouldn't have had this problem in the first place. If I were the one who had to add the cache, I'd be cursing, especially if I'd written it with temps before it got refactored. Martin ends this section with "if worse comes to worse, it's very easy to put the temp back", which sounds like an admission that in that situation you've wasted your time (and quite possibly other people's too). I think the worst-case is that you've repeated this refactoring step many times, and it's a real pain to put all of the temps back. In fact, ReplaceQueryWithTemp is the transform that I'd recommend. That gives actual performance gains, clearly indicates to the reader that the value isn't changing, and also indicates the actual local use for the value returned by the query, which the query's name might not do well on a local basis. Well, that's my two-dollars-worth :-) -- AnAspirant. private final double discountFactor(int basePrice)Why should an object pass an internal member into its own method? Given the code above, I'd suggest there's no need for ANY temps at all: double getPrice() { return basePrice() * discountFactor(); } private double discountFactor() { if (basePrice() > 1000) return 0.95; else return 0.98; }The code "dependencies" (as mentioned above) aren't affected, basePrice() is a member of the same object, and there are no inter-object dependencies created. discountFactor() is a separate IDEA from Price and for the sake of design should be separated out. static double discountFactor( int basePrice ) { return (basePrice > 1000)? 0.95 : 0.98; } double SomeClass::getPrice() { const int basePrice = _quantity * _itemPrice; return basePrice * discountFactor( basePrice ); }The prototype "static double discountFactor( int basePrice );" indicates that this is a simple function which maps an int to a double with no objects getting in the way. In contrast, "double SomeClass::discountFactor();" could do anything. Note that I've left basePrice untouched, i.e. I've got the abstraction benefit of ExtractMethod with no help from ReplaceTempWithQuery. [In fact, I might keep discountFactor within the class ("static double SomeClass::discountFactor( int basePrice );") but didn't for clarity.] --AnAspirant This looks like a step backward in terms of object design. The discount factor is a property specific to objects of SomeClass and depends on another instance variable, so it should be an instance method of that class. And once it's an instance method, you definitely don't need the parameter. You can also look at it this way: By requiring the basePrice parameter you are actually exposing an aspect of the method's implementation. If a client wants to know the discount factor, they shouldn't even have to know that the base price is required for the calculation (let alone tell the object its own base price). Otherwise, you may as well change basePrice() to basePrice(itemPrice), and so on. All you are doing is adding more dependency on SomeClass to the client. --AmarSagoo?
http://c2.com/cgi/wiki?ReplaceTempWithQuery
CC-MAIN-2016-22
refinedweb
764
61.87
Hi python worshippers, I’m trying to replace a mat by another one imported from a lib rather than append it, in some case, depending on a mat name test : if newmat.name not in Material.Get() : append else : update the existing one. thus to keep user links and to avoid duplicates. but it does not work so far. the only way I’ve found is to check every object material slots and change the old mat link to the new one. it seems material_works.py works the wame way. what I’d like to do is something like : def oceAppend(path,source,what) : lib = bpy.libraries.load(path+source) # MATS # import/update/rename mats from a lib if what=='mats' : matsList=[] for m in Material.Get() : matsList.append(m.name) for matname in lib.materials : print matname newname=source+'_'+matname if newname not in matsList : mat = lib.materials.link(matname) mat.name=newname mat.fakeUser=True # THE CODE BELOW DOES NOT WORK <b> [B]else :</b> print newname,'exist' mat = Material.Get(newname) # the mat to update with new parameters m = lib.materials.link(matname) print 'update',mat.name,newname,'with',m.name mat = m.__copy__() <b># does not work</b> mat = m <b># does not work</b> mat.name=newname mat.fakeUser=True m.fakeUser=False[/B] I change the name of the imported lib because several mats will share the same name, so I add the library name in it to avoid 001, 002 etc names. ideally it would be great that the api provide a function that would replace an existing mat by an imported one with a renaming option, to avoid huge list of mats with zero users. thanks for your help, littleneo
https://blenderartists.org/t/replace-a-material-directly-from-the-main-material-list/455144
CC-MAIN-2020-50
refinedweb
289
59.5
Swift version: 5.4 Destructuring is the practice of pulling a tuple apart into multiple values in a single assignment. For example, consider a trivial function that accepts names in the format “FirstName LastName” and returns a tuple containing the first and last names separated: func splitName(_ name: String) -> (String, String) { let parts = name.components(separatedBy: " ") return (parts[0], parts[1]) } If you want to call that using destructuring, just use two values for your assignment when calling it, like this: let (first, last) = splitName("Taylor Swift") That creates first and last constants out of the two returned items in the tuple, and you can then use them as normal: print(first) print.
https://www.hackingwithswift.com/example-code/language/what-is-destructuring
CC-MAIN-2021-31
refinedweb
114
53.04
Structure of the PyObjC package Introduction This document gives an overview of the PyObjC for developers (of the package). One of the sections describes how all of it works, and some of the limitations. This document is a incomplete, it should be updated. Methods Classes are scanned for methods when the Python wrapper for a class is created. We then create Python wrappers for those methods. This way users can use the normal Python introspection methods to check which methods are available. There are several occasions when these method tables are rescanned, because classes can grow new methods when categories are loaded into the runtime. Additionally, it is known that some Cocoa frameworks in Mac OS X change their method tables when the first instance is created. Subclassing It is possible to subclass Objective-C classes from Python. These classes end up in a structure containing both a Python type object and an Objective-C class. Instances of these classes also contain both a Python instance and an Objective-C object. The first Python subclass of an Objective-C class introduces a new instance variable in the Objective-C object to store the pointer to the Python half of the cluster. This variable is always referenced by name. The Python half is a subclass of objc_object that already contains a pointer to an Objective-C object. This first subclass also introduces a number of class and instance methods that the PyObjC bridge uses to maintain the illusion of a single object on both sides. Check class-builder.m for details. Directory structure - Doc/ - Documentation - Examples/ - Example scripts and applets. - Lib/ - The pure Python parts of the packages that comprise PyObjC. - Modules/ - Extension modules related to the packages in ‘Lib’. - libffi-src/ - A local copy of libffi, the Foreign Function Interface library used by PyObjC. Reference counts The Objective-C rules for reference counts are pretty easy: A small number of class methods ( alloc, allocWithZone:, copy, ...) transfer object ownership to the caller. For all other objects you have to call retain if you want to keep a reference. This includes all factory methods, such as [NSString stringWithCString:"bla"]! When programming Cocoa in Python, you rarely need to worry about reference counts: the objc module makes this completely transparent to user. This is mostly implemented in [de]pythonify_c_value. Additonal code is needed when calling methods that transfer ownership of their return value (as described above) and when updating a instance variable in an Objective-C object (retain new and release old, in that order). Both are implemented. Strings Python unicode instances are proxied by the OC_PythonUnicode subclass of NSString. This is a proxy, and will maintain the identity of the original unicode instance. NSString instances are represented in Python as a subtype of unicode: objc.pyobjc_unicode. This performs a conversion, because Python’s unicode type is immutable, but it also maintains a reference to the original NSString. NSString and NSMutableString methods are available from the objc.pyobjc_unicode object, though they do not show up via Python’s introspection mechanisms. In order to get the latest Python representation of a NSMutableString, use the return value of its self() method. Python str instances are proxied by the OC_PythonString subclass of NSString. This is a proxy, and will maintain the identity of the original str instance. OC_PythonString will use the default encoding of NSString, so its results might be surprising if you are using non-ASCII text. It is recommended that you use unicode whenever possible. In order to help you determine where you are not using unicode, it is possible to trigger an objc.PyObjCStrBridgeWarning warning whenever a str instance crosses the bridge: import objc objc.setStrBridgeEnabled(False) To promote these to an exception, do the following: import objc import warnings warnings.filterwarnings('error', objc.PyObjCStrBridgeWarning)
http://pythonhosted.org/pyobjc/dev/structure.html
CC-MAIN-2017-13
refinedweb
632
56.76
#include "pxr/pxr.h" #include "pxr/usd/pcp/api.h" #include "pxr/usd/pcp/cache.h" #include "pxr/base/tf/hashset.h" #include <string> #include <vector> Go to the source code of this file. Returns the changes caused in any cache in caches due to namespace editing the object at curPath in this cache to have the path newPath. caches should have all caches, including this cache. If caches includes this cache then the result includes the changes caused at curPath in this cache itself. To keep everything consistent, a namespace edit requires that everything using the namespace edited site to be changed in an appropriate way. For example, if a referenced prim /A is renamed to /B then everything referencing /A must be changed to reference /B instead. There are many other possibilities. One possibility is that there are no opinions at curPath in this cache's layer stack and the site exists due to some ancestor arc. This requires a relocation and only sites using curPath that include the layer with the relocation must be changed in response. To find those sites, relocatesLayer indicates which layer the client will write the relocation to. Clients must perform the changes to correctly perform a namespace edit. All changes must be performed in a change block, otherwise notices could be sent prematurely. This method only works when the affected prim indexes have been computed. In general, this means you must have computed the prim index of everything in any existing cache, otherwise you might miss changes to objects in those caches that use the namespace edited object. Using the above example, if a prim with an uncomputed prim index referenced /A then this method would not report that prim. As a result that prim would continue to reference /A, which no longer exists.
https://www.sidefx.com/docs/hdk/namespace_edits_8h.html
CC-MAIN-2021-10
refinedweb
302
64.61
#include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): popen(), pclose(): pclose() function returns -1 if wait4(2) returns an error, or some other error is detected. In the event of an error, these functions set errno to indicate the cause of the error. If pclose() cannot obtain the child status, errno is set to ECHILD. The 'e' value for type is a Linux extension. Failure to execute the shell is indistinguishable from the shell's failure to execute command, or an immediate exit of the command. The only hint is an exit status of 127.
https://www.commandlinux.com/man-page/man3/popen.3.html
CC-MAIN-2022-21
refinedweb
111
62.17
9843 [details] Test case Hi, I just tested this on a version of Mono build from source, from the current HEAD (bc57fda921d7c35dd7f52f71bdbdff9e831f328e) on Ubuntu. * How to reproduce: Run the code attached with this bug report (and copy/pasted below) * Expected behavior: We can read the DateTime we just wrote (ie: 03/04/1985) * Behavior with .Net: same as the expected one * Actual behavior: The DateTime read is "01/01/0001 12:00 AM" Some more details: * When we remove the FileOptions.Asynchronous flag, it works fine * If we don't write the Guid (ie: if we only write the TimeStamp), it works fine * When we open the file with an hexadecimal editor, it seems the file starts with several 0 bytes, and then we have the expected content (and "01/01/0001 12:00 AM" is the result of DateTime.FromBinary(0), so the issue if likely when we write, not when we read). Regards, Guillaume --- using System; using System.IO; using System.Linq; public class Program { public static void Main(String[] args) { string filename = "myfilename"; File.Delete (filename); using (var file = new FileStream (filename, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.Asynchronous)) using (var writer = new BinaryWriter (file)){ WriteTimeStamp (writer); WriteGuid (writer); writer.Flush (); file.Close (); writer.Close (); } ReadFile (filename); } private static void WriteTimeStamp(BinaryWriter writer){ var timeStamp = new DateTime (1985, 04, 03); writer.Write (timeStamp.ToBinary ()); } private static void WriteGuid(BinaryWriter writer){ var id = new Guid (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); writer.Write (id.ToByteArray ()); } private static void ReadFile(string filename){ using (var inputStream = new FileStream (filename, FileMode.Open)) using (var reader = new BinaryReader (inputStream)) { var timeStamp = DateTime.FromBinary (reader.ReadInt64 ()); Console.WriteLine (timeStamp); } } } Fixed in master Perfect! Thanks!
https://xamarin.github.io/bugzilla-archives/27/27086/bug.html
CC-MAIN-2019-35
refinedweb
288
55.44
Process and thread Before learning Java multithreading, we need to understand the difference between process and thread. Process is a dynamic execution process of a program. It needs to go through a complete process from code loading, code execution to execution. This process is also the process of the process itself from generation, development to final demise. Multi process operating system can run multiple processes (programs) at the same time. Because the CPU has time-sharing mechanism, each process can cycle to obtain its own CPU time slice. Because the CPU executes very fast, all programs seem to run at the same time. Multithreading is an effective means to realize concurrency mechanism. Like threads, processes are a basic unit of concurrency. Threads are smaller execution units than processes. Threads are further divided on the basis of processes. Multithreading means that a process can produce multiple smaller program units during execution. These smaller units are called threads. These threads can exist and run at the same time. A process may contain multiple threads executing at the same time. Implementation mode There are two ways to implement multithreading in Java. One is to inherit the Thread class, and the other is to implement the Runnable interface. Let's introduce the use of these two methods respectively. Because it is relatively simple, directly paste the implementation code. Implement Runnable interface public class RunnableDemo implements Runnable { public static void main(String[] args) { //You can set the thread name directly in the constructor new Thread(new RunnableDemo(), "Thread 1").start(); } @Override public void run() { for (int i = 0; i < 10; i++) { // Gets the current thread name System.out.println(Thread.currentThread().getName() + "=======" + i); } } } Inherit Thread class public class ThreadDemo extends Thread { public static void main(String[] args) { ThreadDemo threadDemo = new ThreadDemo(); threadDemo.setName("thread1"); //Set thread name threadDemo.start(); // Start thread } // Override thread run method @Override public void run() { for (int i = 0; i < 10; i++) { // Gets the current thread name System.out.println(Thread.currentThread().getName() + "=======" + i); } } } Start mode The thread is started through the start() method instead of the run() method! The run method is the execution method in the thread! - start() method to start the Thread, which really realizes multi-threaded operation. At this time, you can continue to execute the following code directly without waiting for the Run method body code to be executed; Start a Thread by calling the start() method of the Thread class. At this time, the Thread is ready and not running. Then, this Thread class calls the method run() to complete its operation. Here, the method run() is called the Thread body, which contains the content of the Thread to be executed. The Run method ends and the Thread terminates. The CPU then schedules other threads. - The run () method is called as a normal method.. Basic principles of multithreading Next, let's understand the basic principle of multithreading. The overall principle is as follows. After we call the start method of the thread, we actually do a lot of things at the bottom. The specific implementation diagram is as follows. It is not necessarily neat, but it can express the general meaning. There are many OS scheduling algorithms, such as first come first service scheduling algorithm (FIFO), shortest priority (i.e. priority scheduling for short jobs), time slice rotation scheduling, etc. This part belongs to the relevant knowledge of the operating system. General process: - Writing ThreadDemo code - Java starts the thread through the start() method - Start method of starting system thread in JVM - Call different execution methods according to the operating system - Thread execution The running state of the thread Generally speaking, in Java, there are six thread states, namely: NEW: in the initial state, the thread is built, but the start method has not been called RUNNABLED: running state. JAVA threads call the ready and running states of the operating system "running" BLOCKED: the BLOCKED state indicates that the thread enters the waiting state, that is, the thread gives up the CPU usage right for some reason. Blocking can also be divided into several cases - Wait blocking: the running thread executes the wait method, and the jvm will put the current thread into the wait queue - Synchronization blocking: when a running thread obtains the synchronization lock of an object, if the synchronization lock is occupied by other thread locks, the jvm will put the current thread into the lock pool - Other blocking: when the running thread executes the Thread.sleep or t.join method, or issues an I/O request, the JVM will set the current thread to the blocking state. When the sleep ends, the join thread terminates, and io processing is completed, the thread resumes WAITING: WAITING state TIME_WAITING: timeout waiting status. It will be returned automatically after timeout TERMINATED: TERMINATED status, indicating that the current thread has completed execution Thread termination How to stop a thread correctly? There are still many things to say about this issue. We know that Thread provides some operation methods of threads, such as stop, suspend, etc. these methods can terminate a Thread or suspend a Thread, but these methods are not recommended. The reason is simple: For example, suppose that there are multiple tasks executing in a thread. At this time, if the stop method is called to forcibly interrupt, it is equivalent to sending an instruction to tell the operating system to end the thread, but the completion of the end action of the operating system does not mean that the task in the thread is completed, It is likely that half of the task execution of the thread is forcibly interrupted, resulting in data problems. This behavior is similar to executing kill -9 in linux system, which is an unsafe operation. So, in addition to this method, what other methods can realize thread termination? To understand this problem, we first need to know when a thread is terminated. When does a thread end execution Let's analyze the following code. After starting a thread through start (), it is essentially the run method of the thread. If the thread is running until the run method is executed, and the instructions in the run method are executed, the thread will be destroyed. public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); } } MyThread myThread1 = new MyThread(); myThread1.start(); Under normal circumstances, this thread does not need human intervention to end. If you want to force the end, you can only use the stop method. In which cases do thread interrupts require external intervention? There is an infinite loop execution in the thread, such as a while(true) loop There are some blocking operations in the thread, such as sleep, wait, join, etc. Thread with loop Suppose the following scenario exists. In the run method, there is a while loop, because the existence of this loop makes the run method unable to run and end. In this case, how to terminate? public class MyThread extends Thread { public void run() { while(true){ System.out.println("MyThread.run()"); } } } MyThread myThread1 = new MyThread(); myThread1.start(); According to our development thinking, the first thing to be solved is that the while(true) loop must have an end condition, and the second is to modify the end condition elsewhere to make the thread aware of the change. Suppose we change while(true) to while(flag). This flag can be externally modified as a shared variable. After modification, the loop conditions cannot be met, so as to exit the loop and end the thread. This logic is actually very simple. In fact, it gives the thread an exit condition. Without this condition, the thread will run all the time. In fact, an interrupt method is provided in Java, which implements thread interrupt operation. Its function is the same as that of the above case. When other threads call the interrupt method of the current thread, it means to say hello to the current thread and tell him that the execution of the thread can be interrupted. When to interrupt depends on the current thread itself. The thread makes corresponding by checking whether the resource is interrupted. You can judge whether it is interrupted by isInterrupted(). public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { //By default, isInterrupted returns false and becomes true through thread.interrupt i++; } System.out.println("Num:" + i); }, "interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); //thread.interrupt(); // Plus and no effects } } This way of identifying bits or interrupting operations can give the thread the opportunity to clean up resources when terminating, rather than arbitrarily stopping the thread. Therefore, this method of terminating the thread is more safe and elegant. Thread interrupt in blocked state In another case, when the thread is blocked, I want to interrupt the thread. What should I do? public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { //By default, isInterrupted returns false and becomes true through thread.interrupt // Cycle state //i++; //Blocking state try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Num:" + i); }, "interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); //thread.interrupt(); // Plus and no effects } } The feedback from this example shows that sleep, wait, join and other operations we usually use in threads will throw an InterruptedException exception. Why the exception is thrown is because it must be able to respond to a response after an interrupt request is initiated by other threads during blocking, This response is reflected through InterruptedException. However, it should be noted here that if we do not handle this exception, we cannot interrupt the thread, because the current exception only responds to the external interrupt command for this thread, and the interrupt state of the thread will be reset. If you need to interrupt, you also need to add the following code in catch: //Blocking state try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); //Interrupt again } Therefore, throwing an InterruptedException exception does not mean that the thread must terminate, but reminds the current thread of an interrupted operation. The next processing depends on the thread itself, such as: - Directly catch exceptions without any processing - Throw the exception out - Stop the current thread and print exception information
https://programmer.group/basic-principles-of-java-multithreading.html
CC-MAIN-2021-49
refinedweb
1,727
55.34
Hi John, > BTW, this message was just posted to one of the java mailists; i didnt > know it and thought it useful info: > > "You can get an OutOfMemory error because you are trying to allocate > more memory than the VM currently has available. Of course, the VM is > not smart enough to garbage collect and then try it again. This is a > very common thing that happens with large single allocations. I use the > following: > > try { > // huge allocation > }catch( OutOfMemoryError e ){ > Runtime.getRuntime().gc(); > Runtime.getRuntime().runFinalization(); > // try huge allocation again > } > > If there really is enough memory, this will work. We have a large > imaging system we have written, and have this code peppered a lot of > places." I asked the SUN JRE group about this and got the following response from a Sun engineer: Yes, this scenario can unfortunately occur with Classic VM. The HotSpot VM and the Solaris Production release VM does not have this problem, so for Java2 SE 1.3 ("JDK1.3") this will no longer be an issue since HotSpot will be the default VM. Classic VM has a "desired free percentage" after a full GC (parameter -Xminf, default 35% or so (-Xminf0.35). If this free percentage is not fulfilled after a full GC, a subsequent allocation failure will throw OutOfMemoryError. The workaround for Classic VM is to set -Xmx high enough or, alternatively, -Xminf low enough so that the amount of live data always stays lower that the "desired free percentage" of the maximum heap size. The following program shows the failure. This test throws OutOfMemoryError on Classic VM but runs fine with e.g. the HotSpot VM. If you set -Xmx higher or -Xminf lower the program also runs fine on Classic VM. // Run this with -Xms64m -Xmx64m public class Test { public static byte array1[] = null; public static byte array2[] = null; public static void main(String args[]) { array1 = new byte[48*1024*1024]; while (true) { array2 = new byte[4*1024*1024]; } } } So this is a bug in the JVM that is fixed in Hotspot and JDK 1.3. Cheers, Bill ---------------------------------------------------------- Bill Hibbard, SSEC, 1225 W. Dayton St., Madison, WI 53706 hibbard@xxxxxxxxxxxxxxxxx 608-263-4427 fax: 608-263-6738 visadarchives:
https://www.unidata.ucar.edu/mailing_lists/archives/visad/2000/msg00068.html
CC-MAIN-2019-39
refinedweb
368
69.82
The RDM Binary Coded Decimal (BCD) data structure. More... #include "rdmbcdtypes.h" The RDM Binary Coded Decimal (BCD) data structure. Definition at line 41 of file rdmbcdtypes.h. Fraction Definition at line 47 of file rdmbcdtypes.h. The exponent in base 10 that the fraction should be adjusted with Definition at line 44 of file rdmbcdtypes.h. For internal use only. Should be set to 0 Definition at line 45 of file rdmbcdtypes.h. The number of decimals after the desimal point Definition at line 43 of file rdmbcdtypes.h. The sign were 1 indicate a positive numbers and -1 a negative numbers Definition at line 46 of file rdmbcdtypes.h.
https://docs.raima.com/rdm/14_1/struct_r_d_m___b_c_d___t.html
CC-MAIN-2019-09
refinedweb
111
51.24
Saxon,. Here is a little sample how to process XML Inclusions in source XML document before XSLT transformation. using System; using Saxon.Api; using Mvp.Xml.XInclude; class Program { static void Main(string[] args) { Processor proc = new Processor(); XdmNode doc = proc.NewDocumentBuilder().Build( new XIncludingReader("d:/test/document.xml")); XsltExecutable xslt = proc.NewXsltCompiler().Compile( new Uri("d:/test/foo.xsl")); XsltTransformer trans = xslt.Load(); trans.InitialContextNode = doc; Serializer ser = new Serializer(); ser.SetOutputStream(Console.OpenStandardOutput()); trans.Run(ser); } } TrackBack URL: Signs on the Sand: Saxon, NET and XInclude Saxon, famous XSLT 2.0 and XQuery processor, supports XInclude since version 8.9. But in Java version only! When I first heard about it I thought "I have good XInclude implementation for .NET... Thanks,Oleg,this requirement is critical for caching purpose. Andrey, BaseURI property should give you base URI (document where element came from) and IXmlLineInfo should give you original line/position. Is there any means to trace source of particular node(file name) in XIncludingReader? Thanks. Oleg, this is fantastic! Thank you! This page contains a single entry by Oleg Tkachenko published on July 10, 2007 11:01 PM. Mvp.Xml Library version 2.3 released was the previous entry in this blog. Producing XHTML using XSLT in .NET is the next entry in this blog. Find recent content on the main index or look in the archives to find all content.
http://www.tkachenko.com/blog/archives/000711.html
crawl-002
refinedweb
233
54.18
Edited by Nancy Michell MSDN Magazine January 2003 View Complete Post My memory in task manager reaches about 900,000K and I don't know why it does this. Definately slows everything down, especially when I rebuild my tableAdapters, takes about 30 seconds sometimes to rebuild the project. MSDN Magazine June 2004 Other than faking memory pressure to get sql to release memory, is there any other way to quickly release memory? My issue is I do large imports every few nights. This spikes my memory, but once the import is complete, I no longer need immediate access to that table, so I can release the memory. However there's no way for sql server to do that apparently other than having the os pressure it to release it by temporarily running another memory consuming process. I know what you'll say, if the os doesn't need it, why release it? Because I have multiple virtual machines working with a set memory pool size. If I have one box taking up 16gb of my pool, the other machines will suffer, and that one machine will have no idea that it needs to release the memory, even if it is not actively using it. i'm having some problems running exe from an embedded resource in memory public class Searcher { public static void RunSearch(string path, string text) { //Get the current assembly Assembly assembly = Assembly.GetExecutingAssembly(); //Get the resource stream Stream resourceStream = assembly.GetManifestResourceStream("App.Utils.Search.exe"); //Verify the internal exe exists if (resourceStream == null) return; //Read the raw bytes of the resource byte[] resourcesBuffer = new byte[resourceStream.Length]; resourceStream.Read What are the options for handling file uploads to reduce the memory footprint? Is there a way to upload in chunks? Is there a way to stream upload directly to disk instead of loading entire file in server memory? Following this thread: Any plans on releasing the source code for WebMatrix itself? How about those Helpers code? I tried reflecting into WebMatrix.exe but was unable. I'm interested on how you integrated the WPF Ribbon & the Office-style sidebar.
http://www.dotnetspark.com/links/3018-web-qa--releasing-memory-jscript-bulkload.aspx
CC-MAIN-2017-43
refinedweb
352
54.52
Show Show is an alternative to the Java toString method. It is defined by a single function show: def show(a: A): String You might be wondering why you would want to use this, considering toString already serves the same purpose and case classes already provide sensible implementations for toString. The difference, is that toString is defined on Any(Java’s Object) and can therefore be called on anything, not just case classes. Most often, this is unwanted behaviour, as the standard implementation of toString on non case classes is mostly gibberish. Consider the following example: (new {}).toString // res0: String = $anon$1@68313dec The fact that this code compiles is a design flaw of the Java API. We want to make things like this impossible, by offering the toString equivalent as a type class, instead of the root of the class hierarchy. In short, Show allows us to only have String-conversions defined for the data types we actually want. To make things easier, cats defines a few helper functions to make creating Show instances easier. /** creates an instance of Show using the provided function */ def show[A](f: A => String): Show[A] /** creates an instance of Show using object toString */ def fromToString[A]: Show[A] These can be used like this: import cats.Show // import cats.Show case class Person(name: String, age: Int) // defined class Person implicit val showPerson: Show[Person] = Show.show(person => person.name) // showPerson: cats.Show[Person] = cats.Show$$anon$1@62764423 case class Department(id: Int, name: String) // defined class Department implicit val showDep: Show[Department] = Show.fromToString // showDep: cats.Show[Department] = cats.Show$$anon$2@3c7163e7 This still may not seem useful to you, because case classes already automatically implement toString, while show would have to be implemented manually for each case class. Thankfully with the help of a small library called kittensa lot of type class instances including Show can be derived automatically! Cats also offers Show syntax to make working with it easier. This includes the show method which can be called on anything with a Show instance in scope: import cats.implicits._ // import cats.implicits._ val john = Person("John", 31) // john: Person = Person(John,31) john.show // res1: String = John It also includes a String interpolator, which works just like the standard s"..." interpolator, but uses Show instead of toString: val engineering = Department(2, "Engineering") // engineering: Department = Department(2,Engineering) show"$john works at $engineering" // res2: String = John works at Department(2,Engineering)
https://typelevel.org/cats/typeclasses/show.html
CC-MAIN-2018-17
refinedweb
415
55.24
23 December 2009 17:41 [Source: ICIS news] (adds paragraphs 7-16) TORONTO (ICIS news)--Chemical shipments on US railroads rose 13.9% last week from the same time last year, marking their ninth increase this year and the sixth in a row, an industry association said on Wednesday. Chemical railcar loadings for the week ended on 19 December were 26,404, up 3,216 car loads from 23,188 in the same week last year, according to data released by the Association of American Railroads (AAR). The increase for the week comes after a 14.8% year-over-year increase in the previous week ended on 12 0.1% year-over-year decline in overall weekly railcar shipments for the 19 commodity categories tracked by the ?xml:namespace> Year-to-date to 19 December, The AAR also provided comparable chemical railcar shipment data for Canadian chemical rail traffic for the week ended on 19 December rose 4.2% to 12,923 from 12,401 in the same week last year. For the year-to-date period, Canadian shipments were down 18.8% to 596,515 from 734,614 shipments in the same period in 2008. Mexican weekly chemical rail traffic rose 20.8% to 1,011 from 837 in the same week a year earlier. For the year-to-date period, Mexican shipments were up 23.3% to 55,377 from 44,926 in the same period last year. For all of For the year-to-date period, overall North American chemical railcar traffic was down 12.5% to 1,969,977 from 2,250,810 in the year-earlier period. Overall, the From the same week last year, total US weekly railcar traffic for the 19 carload commodity categories fell 0.1% to 271,819 and was down 16.5% to 13.4m
http://www.icis.com/Articles/2009/12/23/9321777/us-weekly-chemical-railcar-traffic-rises-13.9.html
CC-MAIN-2014-52
refinedweb
305
65.93
A degenerate zero-tetrahedron saturated block that corresponds to attaching a Mobius band to a single annulus boundary. More... #include <subcomplex/nsatblocktypes.h> A degenerate zero-tetrahedron saturated block that corresponds to attaching a Mobius band to a single annulus boundary. This is a degenerate case of the layered solid torus (see the class NSatLST), where instead of joining a solid torus to an annulus boundary we join a Mobius band. The Mobius band can be thought of as a zero-tetrahedron solid torus with two boundary triangles, which in fact are opposite sides of the same triangle. By attaching a zero-tetrahedron Mobius band to an annulus boundary, we are effectively joining the two triangles of the annulus together. The meridinal disc of this zero-tetrahedron solid torus meets the three edges of the annulus in 1, 1 and 2 places, so it is in fact a degenerate (1,1,2) layered solid torus. Note that the weight 2 edge is the boundary edge of the Mobius strip. Constructs a clone of the given block structure. Adjusts the given Seifert fibred space to insert the contents of this saturated block. In particular, the space should be adjusted as though an ordinary solid torus (base orbifold a disc, no twists or exceptional fibres) had been replaced by this block. This description does not make sense for blocks with twisted boundary; the twisted case is discussed below. If the argument reflect is true, it should be assumed that this saturated block is being reflected before being inserted into the larger Seifert fibred space. That is, any twists or exceptional fibres should be negated before being added. Regarding the signs of exceptional fibres: Consider a saturated block containing a solid torus whose meridinal curve runs p times horizontally around the boundary in order through annuli 0,1,... and follows the fibres q times from bottom to top (as depicted in the diagram in the NSatBlock class notes). Then this saturated block adds a positive (p, q) fibre to the underlying Seifert fibred space. If the ring of saturated annuli bounding this block is twisted then the situation becomes more complex. It can be proven that such a block must contain a twisted reflector boundary in the base orbifold (use Z_2 homology with fibre-reversing paths to show that the base orbifold must contain another twisted boundary component, and then recall that real boundaries are not allowed inside blocks). In this twisted boundary case, it should be assumed that the twisted reflector boundary is already stored in the given Seifert fibred space. This routine should make any further changes that are required (there may well be none). That is, the space should be adjusted as though a trivial Seifert fibred space over the annulus with one twisted reflector boundary (and one twisted puncture corresponding to the block boundary) had been replaced by this block. In particular, this routine should not add the reflector boundary itself. Implements regina::NSatBlock. Returns a newly created clone of this saturated block structure. A clone of the correct subclass of NSatBlock will be returned. For this reason, each subclass of NSatBlock must implement this routine. Implements regina::NSatBlock. Determines whether the given annulus is a boundary annulus for a block of this type (Mobius band). This routine is a specific case of NSatBlock::isBlock(); see that routine for further details. nullif none was found. Describes how the Mobius band is attached to the boundary annulus. The class notes discuss the weight two edge of the Mobius band (or equivalently the boundary edge of the Mobius band). The return value of this routine indicates which edge of the boundary annulus this weight two edge is joined to. In the NSatAnnulus class notes, the three edges of the annulus are denoted vertical, horizontal and boundary, and the vertices of each triangle are given markings 0, 1 and 2. The return value of this routine takes the value 0, 1 or 2 as follows: Writes an abbreviated name or symbol for this block to the given output stream. This name should reflect the particular block type, but need not provide thorough details. The output should be no more than a handful of characters long, and no newline should be written. In TeX mode, no leading or trailing dollar signs should be written. Implements regina::NSatBlock. Writes this object in short text format to the given output stream. The output should be human-readable, should fit on a single line, and should not end with a newline. Implements regina::ShareableObject.
http://regina.sourceforge.net/engine-docs/classregina_1_1NSatMobius.html
CC-MAIN-2014-10
refinedweb
758
51.68
I'm having trouble to store Lists in the storage and then loading it after a new start of my app. Here is what I've done: At every start of the app I do this, to check if Data has already been written to the storage, if not, I return a new List. public List loadSavedFormationList(){ String[] temp = Storage.getInstance().listEntries(); for(String s: temp){ if(s.equals("Formations") == true){ return (LinkedList<SongList>)Storage.getInstance().readObject("Formations"); } } return new LinkedList<SongList>(); } When the user has entered a FormationList in my App, I do this to save it to the storage: Storage.getInstance().writeObject("Formations", formationList); Now, when I restart the App, I am getting a java.io.EOFException + java.lang.NullpointerException. It seems that he tries to read my Formations List from the storage, but it is empty, but why? On the first start of the App, the Storage should be empty. Does the Simulator also save the stuff I entered into the App at another time? Thank you for any advice. Codename One stores ArrayList not LinkedList and will convert that implicitly. I'm guessing the data wasn't written which is why you got the exception, you need to look at the console when writing and make sure all elements are externalizable.
http://m.dlxedu.com/m/askdetail/3/ba01f7d5345fa923ae4afd6468965949.html
CC-MAIN-2019-18
refinedweb
215
64.91
Problem in Python We really only need to iterate from 10 to 99 for the numberator and from the numerator to 99 for the denominator, since we require that the fraction be less than one. Also, we can ignore any denominators that have zeros (since the only other possible integer to match in the numerator is nonzero). We form a list from the numerator and denominator, check for redundancy, remove the redundancies when found, then cross multiply to find if the fractions are equivalent to their redundant-removed siblings. import time import fractions start = time.time() p = fractions.Fraction(1,1) for a in range(10, 100, 1): for b in range(a+1, 100, 1): if b % 10 == 0 or a == b: continue La, Lb = [a/10, a%10], [b/10, b%10] if any(i in Lb for i in La) and not all(i in Lb for i in La): if La[0] in Lb: x = La[0] else: x = La[1] La.remove(x) Lb.remove(x) if a*Lb[0] == b*La[0]: p *= fractions.Fraction(La[0],Lb[0]) elapsed = time.time() - start print "result %s found in %s seconds" % (p, elapsed) We’ve used Python’s fractions module to make things a bit easier. When executed, we get the following. result 1/100 found in 0.00531482696533 seconds
http://code.jasonbhill.com/2013/10/
CC-MAIN-2017-13
refinedweb
225
62.38
HOUSTON (ICIS)--Here is Friday's midday ?xml:namespace> CRUDE: Jul WTI: $104.35/bbl, up 61 cents; Jul Brent: $110.49/bbl, up 13 cents NYMEX WTI crude futures rose on pre-weekend buying in response to some upbeat housing and manufacturing data. A stronger dollar helped cap the rally. WTI topped out at $104.46/bbl before retreating. RBOB: Jun $3.0168/gal, up 1.10 cents/gal Reformulated blendstock for oxygen blending (RBOB) gasoline futures pushed higher during morning trading on pre-weekend buying ahead of the long holiday weekend. NATURAL GAS: Jun $4.391/MMBtu, up 3.2 cents The front month contract on the NYMEX natural gas futures market climbed through Friday morning, reversing the declines seen over the previous two days on the bullish demand outlook caused by weather forecasts predicting above average temperatures across most of the US through to early June. ETHANE: steady at 28.50 cents/gal Ethane spot prices held steady as natural gas futures made slight gains in early trading on Friday. AROMATICS: benzene tighter at $4.39-4.41/gal Prompt benzene spot prices were discussed at $4.39-4.41/gal FOB (free on board) and DDP (duty, delivered paid) on Friday morning, sources said. The morning range was tighter compared with $4.35-4.40/gal FOB the previous afternoon. OLEFINS: ethylene tighter at 54.00-54.75 cents/lb, RGP offered at 58 cents/lb US May ethylene bid/offer levels tightened to 54.00-54.75 cents/lb from 53.50-56.25 cents/lb the previous day. US May refinery-grade propylene (RGP) was heard offered at 58.00 cents/lb against no fresh bids, compared with the previous reported trade at 57.75 cents/lb. For more pricing intelligence please visit
http://www.icis.com/resources/news/2014/05/23/9784193/noon-snapshot-americas-markets-summary/
CC-MAIN-2016-22
refinedweb
299
70.6
Creative. [image: cover-image] 6 Editing Text Lesson Overview In this lesson, you’ll learn how to do the following: Sync fonts from Typekit. Handle a missing font. Enter and import text. Find and change text and formatting. Check the spelling in a document. Edit a spelling dictionary. Automatically correct misspelled words. Use the Story Editor. Move text by dragging and dropping. Track changes. [image: images] This lesson will take about] InDesign offers many of the text-editing features you find in dedicated word-processing software, including the ability to search and replace text and formatting, check spelling, automatically correct spelling as you type, and track changes as you edit. Getting started In this lesson, you will perform editoria; l tasks commonly expected of a graphic designer. These include importing a new story and using the editorial features in InDesign to search and replace text and formatting, check spelling, enter and track text changes, and more. .) Open the 06_Start.indd file in the Lesson06 folder, located inside the Lessons folder within the InDesignCIB folder on your hard disk. [image: images] Note: If the Goudy Old Style and Urbana Light fonts happen to be active on your system, this alert will not display. You can review the steps on replacing a missing font and then move on to the next section. When the Missing Fonts alert displays, click Sync Fonts. Click Close when font syncing is complete. (If necessary, click “Turn Typekit On” in the upper-right corner.) [image: images] The Adobe Typekit online service will locate, download, and activate the missing Urbana Light font. The Goudy Old Style font is not available through Adobe Typekit and will remain missing for now. You will fix the problem of the missing Goudy Old Style font in the next section by replacing it with a font installed on your system. To ensure that the panels and menu commands match those used in this lesson, choose Window > Workspace > [Advanced], and then choose Window > Workspace > Reset Advanced. [image: images] Tip: In general, it is not necessary to display images at full resolution when working with text. If you are working on a slower computer, you can leave the display at Typical Display or even gray out the images with Fast Display. If necessary, choose View > Display Performance > High Quality Display to display the document at a higher resolution. Choose File > Save As, rename the file 06_Text.indd, and save it in the Lesson06 folder. If you want to see what the finished document looks like, open the 06_End.indd file in the same folder. You can leave this document open to act as a guide as you work. [image: images] [image: images] Note: For higher contrast in the printed manual, the screen captures in this book show the Medium Light interface. Interface elements such as panels and dialog boxes may be darker on your screen. When you’re ready to resume working on the lesson document, 06_Text.indd, display it by clicking its tab in the upper-left corner of the document window. Finding and changing a missing font When you opened the document in the previous exercise, the Goudy Old Style font may have been listed as missing. If this font is active on your computer, you did not receive an alert message, but you can still follow the steps for future reference. You will now search for text formatted with the Goudy Old Style font and replace it with the Minion Pro Regular font. Choose View > Screen Mode > Normal so you can see layout aids such as guides. Notice that once you leave Preview mode, the word “city” on the right-facing page is highlighted in pink. This indicates a missing font. Choose Type > Find Font. The Find Font dialog box lists the fonts used in the document. An alert icon ([image: images]) appears next to any missing fonts. Select Goudy Old Style in the Fonts In Document list. For the Replace With option at the bottom of the dialog box, choose Minion Pro from the Font Family menu. [image: images] Tip: If you select Redefine Style When Changing All in the Find Font dialog box, any character styles or paragraph styles that specify the missing font will be updated to include the Replace With font as well. This can be handy for quickly updating documents and templates—as long as you’re sure the font change is appropriate. Choose Regular from the Font Style menu. [image: images] [image: images] Tip: To display more information about a missing font (such as character count, page where it is used, and font type), click More Info in the Find Font dialog box. Click Change All. Click Done to close the dialog box and see the replaced font in the document. Choose File > Save. Adding missing fonts For most projects, you need to add the missing font to your system instead of substituting a different font. This maintains the original design and the way the text fits and flows. You can do this in the following ways: If you have the font, activate it on your system. If you do not have the font, you can purchase it. If you are a Creative Cloud member, you can see whether the font is available for use through Adobe’s Typekit font library (click Sync Fonts in the Find Font dialog box). Once you have the font, you can use font management software to activate it. You can also add the font to your InDesign Fonts folder or a Document Fonts folder in the folder containing the InDesign document. For more information on acquiring and using fonts, see Chapter 6, “Fonts,” in Real World Print Production with Adobe Creative Cloud, by Claudia McCue (Peachpit, 2014). Entering and importing text You can enter text directly into your InDesign documents, or you can import text prepared in other applications, such as word-processing software. To type text, you need to use the Type tool and select a text frame or text path. Options for importing text include dragging files from the desktop, “loading” the cursor with one or more text files to import, or importing text into a selected text frame. Entering text While graphic designers are not generally responsible for the text in all their layouts, they are often asked to enter edits from a marked-up hard copy or Adobe PDF. In this exercise, you will use the Type tool to revise the headline. [image: images] Note: If you cannot see the frame edges, be sure that the screen mode is set to Normal (View > Screen Mode > Normal). Choose View > Extras > Show Frame Edges. The text frames are outlined in gold so you can see them. Locate the text frame on the left-facing page under the images containing the headline “Urban Renewal.” Using the Type tool ([image: images]), click in the text frame next to “Urban Renewal.” Type a space and the words with Respect. [image: images] Choose File > Save. Importing text When working with a template for a project such as a magazine, designers generally import article text into existing text frames. In this exercise, you will import a Microsoft Word file and apply body-copy formatting to it. Using the Type tool ([image: images]), click in the first column of the text frame on the right-facing page. [image: images] [image: images] Tip: In the Place dialog box, you can Shift-click to select multiple text files. When you do this, the cursor is “loaded” with those files. You can then click in text frames or on the page to import the text from each file. This works well with content such as long captions that are saved in different text files. Choose File > Place. In the Place dialog box, make sure Show Import Options is not selected. Navigate to and select the Feature_February2018.docx file in the Lesson06 folder, located inside the Lessons folder within the InDesignCIB folder on your hard disk. Click Open. If the Missing Fonts dialog box displays, click Close to dismiss it. You will apply a different font through a paragraph style. The text flows from column to column, filling the three columns. Choose Edit > Select All to select all the text in the story. Click the Paragraph Styles panel icon at the right to display the panel. Click the Body Paragraph style to apply it to the selected paragraphs. If a plus sign displays next to Body Paragraph, click Clear Overrides ([image: images]) at the bottom of the Paragraph Styles panel. [image: images] Note: Now that you have changed the formatting, the story may no longer fit. In the lower-right corner of the text frame on the right-facing page, a red plus sign (+) will indicate overset text (additional text). Later, you will use the Story Editor to resolve this. Click in the first body paragraph starting with “We rush past.” Click the First Body Paragraph Style in the Paragraph Styles panel to apply a style that includes a drop cap. [image: images] Choose Edit > Deselect All to deselect the text. Choose View > Extras > Hide Frame Edges. Choose File > Save. Finding and changing text and formatting Like most popular word-processing software, InDesign lets you search and replace text and formatting. Often, while graphic designers are working on layouts, the copy is still being revised. When editors request global changes, Find/Change helps ensure accurate and consistent changes. Finding and changing text For this article, the fact checker discovered that the tour guide’s name is not spelled as “Alexis”—it’s “Alexes.” You will change all instances of her name in the document. Using the Type tool ([image: images]), click at the beginning of the story before “We rush past” (on the right-facing page in the far left column). Choose Edit > Find/Change. Click the menu in the Query field to see the built-in Find/Change options. Click each tab across the top to view other options: Text, GREP, Glyph, and Object. Click the Text tab for a simple search and replace of text. [image: images] Tip: You can toggle the search direction by pressing Ctrl+Alt+ Enter (Windows) or Command+Option+ Return (macOS). Click Forward for the search Direction. Type Alexis in the Find What box. Press Tab to navigate to the Change To box. Type Alexes. Using the Search menu in the Find/Change dialog box, you can choose to search All Documents, Document, Story, To Beginning Of Story, To End Of Story, or Selection (when text is selected). Select Story from the Search menu, which defines the scope of the search. [image: images] When using the Find/Change dialog box, it’s always a good idea to test your settings. Find one instance of the search criterion, replace it, and review the text before you make global changes. (Alternatively, you may opt to look at each instance with Find as you make the changes so you can see how each change affects surrounding copy and line breaks.) [image: images] Tip: When the Find/Change dialog box is open, you can still click in the text and make edits with the Type tool. The Find/Change dialog box remains open so you can resume your search after editing the text. Click Find Next. When the first instance of “Alexis” is highlighted, click Change. Click Find Next, and then click Change All. When the alert indicates that two additional replacements were made, click OK. [image: images] Leave the Find/Change dialog box open for the next exercise. Finding and changing formatting The editors request one more global edit to this article; this one concerns formatting rather than spelling. The city’s HUB bike program prefers to see its name in small caps rather than lowercase. [image: images] Tip: For acronyms and abbreviations, designers often prefer to use Small Caps style (abbreviated versions of capital letters) rather than All Caps style (all capital letters). The small caps are generally the same height as lowercase characters, and they blend into body copy better. Type hub in the Find What box. Press Tab to select the text in the Change To field and press Backspace or Delete. Point at each icon in the row below the Search menu to view its tool tip and see how it affects the Find/Change operation. For example, clicking the Whole Word icon ([image: images]) ensures that instances of the Find What text within another word will not be found or changed. Do not change any of the settings. If necessary, click the More Options button to display formatting options for the found text. In the Change Format section at the bottom of the dialog box, click the Specify Attributes To Change icon ([image: images]). On the left side of the Change Format Settings dialog box, select Basic Character Formats. [image: images] Tip: If you are unhappy with the results of Find/Change, you can choose Edit > Undo to undo the last “change” operation, whether it was Change, Change All, or Find/Change. In the main part of the Change Format Settings dialog box, choose Small Caps from the Case menu. [image: images] Leave the other options blank, and then click OK to return to the Find/Change dialog box. Notice the alert icon ([image: images]) that appears above the Change To box. This icon indicates that InDesign will change text to the specified formatting. [image: images] Test your settings by clicking Find Next and then clicking Change. Once you confirm that “hub” changes to “hub,” click Change All. When the alert indicates that two changes were made, click OK. Click Done to close the Find/Change dialog box. Choose File > Save. Checking spelling [image: images] Tip: Be sure to discuss with your client or editor whether you should be the one checking spelling in InDesign. Many editors strongly prefer to check spelling themselves. InDesign has features for checking spelling similar to the options in word-processing programs. You can check the spelling in selected text, an entire story, all the stories in a document, or all the stories in several open documents at once. To customize which words are flagged as possible misspellings, you can add words to your document’s dictionary. In addition, you can have InDesign flag possible spelling issues and correct spelling as you type. The Check Spelling dialog box provides the following buttons to handle the words shown in the Not In Dictionary field (otherwise known as suspect words): Skip: Click Skip when you are confident of the spelling of the current suspect word but would like to review any other instances of the spelling in context. Change: Click Change to change the spelling of the current instance of the suspect word to the spelling in the Change To field. Ignore All: Click Ignore All when you are confident that the spelling of the suspect word is appropriate for use througout the selection, story, or document. Change All: Click Change All when you are confident that changing the spelling of the suspect word is appropriate for the entire selection, story, or document. Checking spelling in the document [image: images] Note: Depending on the InDesign preferences set for Dictionary and Spelling, or whether you’ve added words to a custom dictionary, different words may be flagged. Simply experiment with the various Check Spelling options to get familiar with them. Before a document is ready for print or electronic distribution, it’s a good idea to check spelling. In this case, we suspect the newly imported story may be a little sloppy, so you will check the spelling now. If necessary, choose View > Fit Spread In Window to view both pages of the document. Using the Type tool ([image: images]), click before the first word of the article you’ve been working on: “We.” Choose Edit > Spelling > Check Spelling. Using the Search menu in the Check Spelling dialog box, you can choose to check All Documents, Document, Story, To End Of Story, or Selection. Select Story from the Search menu at the bottom of the dialog. The spell check starts automatically. InDesign highlights various words that do not match the spelling dictionary. [image: images] Handle the flagged words as follows: Meridien’s, Alexes, nonprofits: Click Ignore All. renaisance: Select “renaissance” in the Suggested Corrections list and click Change. Nehru: Click Ignore All. recieve: Type receive in the Change To field and click Change. pomme, Grayson, Meridien: Click Ignore All. Click Done. Choose File > Save. Adding words to a document-specific dictionary With InDesign, you can add words to your user dictionary or to a document-specific dictionary. If you work with multiple clients who may have different spelling preferences, for example, it is better to add words to a document-specific dictionary. In this case, you will add “Meridien” to the document’s dictionary. [image: images] Tip: If a word is not specific to one language—such as a person’s name—you can choose All Languages to add the word to every language’s spelling dictionary. Choose Edit > Spelling > User Dictionary to display the User Dictionary dialog box. [image: images] Select 06_Text.indd from the Target menu. Type Meridien in the Word box. Select Case Sensitive to add only “Meridien” to the dictionary. This ensures that a lowercase use of “meridien” is still flagged when you check spelling. Click Add. Type Meridien’s in the Word box. Make sure Case Sensitive is still selected, and then click Add. Click Done, and then choose File > Save. Checking spelling dynamically It’s not necessary for you to wait until a document is finished before checking the spelling. Enabling dynamic spelling allows you to see misspelled words in text. To see how this works: Choose Edit > Preferences > Spelling (Windows) or InDesign CC > Preferences > Spelling (macOS) to display Spelling preferences. In the Find section, select the possible errors you want highlighted. Select Enable Dynamic Spelling. In the Underline Color section, use the menus to customize how possible errors are signified. You can customize what the Check Spelling dialog box flags as possible errors: Misspelled Words, Repeated Words, Uncapitalized Words, and Uncapitalized Sentences. For example, if you’re working on a directory with hundreds of names, you might want to select Uncapitalized Words but not Misspelled Words. [image: images] Click OK to close the Preferences dialog box and return to your document. Words that may be misspelled (according to the default user dictionary) are now underlined. Right-click (Windows) or Control-click (macOS) a word flagged by dynamic spelling to display a contextual menu from which you can select an option to change the spelling. Automatically correcting misspelled words Autocorrect takes the concept of dynamically checking spelling to the next level. With Autocorrect activated, InDesign automatically corrects misspelled words as you type them. Changes are made based on an internal list of commonly misspelled words. You can add other commonly misspelled words, including words in other languages, to this list if you like. Choose Edit > Preferences > Autocorrect (Windows) or InDesign CC > Preferences > Autocorrect (macOS) to display Autocorrect preferences. Select the Enable Autocorrect option. By default, the list of commonly misspelled words is for English: USA. Change the language to French and note the commonly misspelled words in that language. Try other languages, if you’d like. Change the language back to English: USA before proceeding. The editors have realized that the name of their city, “Meridien,” is frequently typed as “Meredien,” with an “e” in the middle rather than an “i.” You will prevent this mistake by adding the misspelling and correct spelling to the Autocorrect list. Click Add. In the Add To Autocorrect List dialog box, type Meredien in the Misspelled Word box and Meridien in the Correction box. [image: images] Click OK to add the word, and then click OK again to close the Preferences dialog box. [image: images] Tip: Words are autocorrected as soon as you finish a word, as indicated by typing a space, period, comma, or forward slash. Using the Type tool ([image: images]), type the word Meredien followed by a space anywhere in the text. Notice that Autocorrect changes the spelling from “Meredien” to “Meridien,” and then choose Edit > Undo until the word you added is deleted. Choose File > Save. Editing text by dragging and dropping To quickly cut and paste words in your document, InDesign allows you to drag and drop text within the same story, between frames, and between documents. You’ll now use drag and drop to move text from one paragraph to another in the magazine layout. Choose Edit > Preferences > Type (Windows) or InDesign CC > Preferences > Type (macOS) to display Type preferences. In the Drag And Drop Text Editing section, select Enable In Layout View. This option lets you drag and drop text in Layout view in addition to the Story Editor. Click OK. [image: images] [image: images] Tip: When you drag and drop text, by default InDesign automatically adds and deletes spaces before and after words as necessary. If you need to turn off this feature, deselect Adjust Spacing Automatically When Cutting And Pasting Words in Type preferences. Locate the subhead below the “Urban Renewal with Respect” headline. Adjust the zoom level as necessary so you can read the subhead text. Using the Type tool ([image: images]), double-click in the word “ECLECTIC” to select it. Position the I-bar pointer over the selected word until the pointer changes to the drag and drop icon ([image: images]). [image: images] [image: images] Tip: If you want to copy a selected word instead of moving it, hold down the Alt (Windows) or Option (macOS) key after you start dragging. Drag the word to its correct location before “URBANISM.” [image: images] Choose File > Save. Using the Story Editor If you need to enter many text edits, rewrite a story, or cut a story, you can isolate the text with the Story Editor. The Story Editor window works as follows: Text displays without formatting—with the exception of the styles bold, italic, and bold italic. Any graphics and other nontext elements are omitted to make editing easier. The column to the left of the text displays a vertical depth ruler and the name of the paragraph style applied to each paragraph. Dynamic spelling (if enabled) highlights misspelled words, just like in the document window. If the Enable In Story Editor option is selected in Type preferences, you can also drag and drop text in the Story Editor, just as you did in the previous exercise. In Story Editor Display preferences, you can customize the font, size, background color, and more for the Story Editor window. The article on the right-facing page is too long to fit in the text frame. You will delete a sentence in the Story Editor to help it fit. Choose View > Fit Spread In Window. Using the Type tool ([image: images]), click in the first full paragraph in the third column of the article. [image: images] Note: If the Story Editor window goes behind the document window, you can bring it to the front by choosing its name from the bottom of the Window menu. Choose Edit > Edit In Story Editor. Position the Story Editor window next to the far-right column on the spread. Drag the vertical scroll bar in the Story Editor to the end of the story. Note the line that indicates the overset text. In the Story Editor, scroll up to locate and select the following sentence: “The long arcade is a kaleidoscope of nature’s colors—fruits, vegetables, and meats meticulously arranged in bins by their growers and producers.” Be sure to select the final period. [image: images] Press Backspace or Delete. Leave the Story Editor open for the next set of steps. Choose File > Save. Tracking changes For some projects, it’s important to see what changes are made to the text throughout the design and review process. In addition, reviewers may suggest changes that another user can accept or reject. As with a word-processing program, you can track text that is added, deleted, or moved using the Story Editor. In this document, you will edit a few words. When the final edits are made, the text frame should no longer have overset text. Choose Type > Track Changes > Track Changes In Current Story. [image: images] Tip: In Track Changes preferences, you can customize which changes are tracked and how the changes display in the Story Editor. In the Story Editor, scroll up to the second paragraph of the story starting with “One of Meridien’s.” [image: images] Tip: InDesign provides a Notes panel and a Track Changes panel for reviewing and collaborating on documents (Window > Editorial, Type > Notes, and Type > Track Changes). The panel menus provide access to many of the controls. Using the Type tool ([image: images]) in the Story Editor, make the following changes in the second paragraph: [image: images] Change “eight” to “five” Delete “controversial” Insert “more” before “robust social service programs” Notice how the changes are marked in the Story Editor window. With the Story Editor window still open, choose Type > Track Changes, and review the options for accepting and rejecting changes. Once you have reviewed the possibilities, choose Accept All Changes > In This Story. When the alert dialog box displays, click OK. Click the Story Editor window’s close box. If necessary, choose Edit > Spelling > Dynamic Spelling to disable this feature. Choose File > Save. Congratulations. You have finished the lesson. Exploring on your own [image: images] Tip: Companies generally follow a style guide that governs issues such as spacing and punctuation. For example, The Associated Press Stylebook specifies a space on either side of an em dash, while The Chicago Manual of Style does not. Now that you have tried the basic text-editing tools in InDesign, experiment with them more to edit and format this document. Using the Type tool ([image: images]), add subheads to the story and format them with options in the Control panel. If you have additional text files on your system, try dragging them from the desktop to the layout to see how they’re imported. Choose Edit > Undo if you don’t want to keep them in the document. Use the Find/Change dialog box to find all em dashes in the story and replace them with an em dash with a space on either side of it. Click the @ icon next to the Find What box to search for special characters such as em dashes. Edit the story using the Story Editor and Track Changes. See how the different changes are marked, and experiment with accepting and rejecting the changes. Experiment with changing Spelling, Autocorrect, Track Changes, and Story Editor Display preferences. Review questions Which tool lets you edit text? Where are most of the commands for editing text? What is the InDesign search-and-replace feature called? While checking the spelling in a document, InDesign flags words that are not in the dictionary—but they may not actually be misspelled. How can you fix this? If you seem to continually type a word incorrectly, what can you do? Review answers The Type tool allows you to edit text. Most commands for editing text are in the Edit menu and the Type menu. InDesign uses the term Find/Change (Edit menu). Add those words to the document’s or InDesign’s default spelling dictionary for the language or languages of your choice (Edit > Spelling > User Dictionary). Add the word to your Autocorrect preferences. 8 Working with Color Lesson Overview In this lesson, you’ll learn how to do the following: Set up color management. Specify output requirements. Create color swatches. Create color themes and add them to CC Libraries. Apply colors to objects, strokes, and text. Create and apply a tint. Create and apply a gradient swatch. Work with color groups. [image: images] This lesson will take approximately] You can create and apply process and spot color swatches to objects, strokes, and text. Color themes make it easy to achieve color harmony in layouts. For consistent color usage across projects and workgroups, you can add color themes to CC Libraries. Using a preflight profile helps ensure that colors output properly. Getting started In this lesson, you’ll add colors, color themes, tints, and gradients to a flyer for an art show. The flyer consists of CMYK colors and a spot color along with imported CMYK images. (You’ll learn more about CMYK later in this chapter.) Before you get started, however, you will do two things to ensure that the document looks as good in print as it does onscreen: You will review color management settings and use a preflight profile to review the color modes of the imported images. When the flyer is finished, you will organize the colors into a color group. .) Choose File > Open, and open the 08_Start.indd file, in the Lesson08 folder, located inside the Lessons folder in the InDesignCIB folder on your hard disk. If an alert informs you that the document contains links to sources that have been modified, click Update Links. If the Missing Fonts dialog box displays, click Sync Fonts. Click Close when font syncing is complete. To ensure that the panels and menu commands match those used in this lesson, choose Window > Workspace > [Advanced], and then choose Window > Workspace > Reset Advanced. Choose File > Save As, rename the file 08_Color.indd, and save it in the Lesson08 folder. If you want to see what the finished document looks like, open the 08_End.indd file located in the same folder. You can leave this document open to act as a guide as you work. When you’re ready to resume working on the lesson document, click its tab in the upper-left corner of the document window. [image: images] Managing color [image: images] Note: The screen captures in this book show the Medium Light interface. Interface elements such as panels and dialog boxes may be darker on your screen. Color management works to reproduce colors consistently across a range of output devices, such as monitors, tablets, color printers, and offset presses. InDesign gives you easy-to-use color management features that help you achieve good, consistent color without needing to become a color management expert. With color management enabled out of the box, you’ll be able to view colors consistently while ensuring more accurate color from edit to proof to final print or display output. The need for color management [image: images] Tip: You can find additional information about color management in the InDesign Help file, online at adobe.com (search for “color management”) and in DVDs/videos such as Peachpit’s Color Management for Photographers and Designers: Learn by Video. No screen, film, printer, copier, or printing press can produce the full range of color visible to the human eye. Each device has specific capabilities and makes different kinds of compromises in reproducing color images. The unique color-rendering abilities of a specific output device are known collectively as its “gamut.” InDesign and other graphics applications, such as Adobe Photoshop CC and Adobe Illustrator CC, use color numbers to describe the color of each pixel in an image. The color numbers correspond to the color model, such as the RGB values for red, green, and blue, or the CMYK values for cyan, magenta, yellow, and black. Color management is simply a way of translating the color numbers for each pixel from the source (the document or image stored on your computer) to the output device (such as your monitor, laptop, tablet, smartphone, color printer, or high-resolution printing press). Because each source and output device has its own specific gamut (or range) of colors it is capable of reproducing, the aim of the color translation is color accuracy across devices. Creating a viewing environment for color managementscreen, so keep shades closed or work in a windowless room. To eliminate the blue-green cast from fluorescent lighting, you can install D50 (5000° Kelvin) lighting. You can also view printed documents using a D50 light box. View your document in a room with neutral-colored walls and ceiling. A room’s color can affect the perception of both monitor color and printed color. Neutral gray is the best color for a viewing room. The color of your clothing reflecting off your monitor may affect the appearance of colors on typical light bulbs used in homes, or view an office furniture catalog under the fluorescent lighting used in offices. Always make final color judgments under the lighting conditions specified by the legal requirements for contract proofs in your country. —From InDesign Help Displaying images at full resolution [image: images] Tip: You can specify Display Performance defaults in the Preferences dialog box, and you can change the display of an individual object using the Object > Display Performance In a color management workflow, even using default color settings, you should display images at high quality for the best possible color representation that your monitor is capable of showing. When you use lower-resolution image displays, graphics are displayed more quickly, but the colors are less precise. To see the difference in one of your documents, experiment with the options in the View > Display Performance menu. Fast Display (ideal for quick text editing because images do not display) Typical Display (the default) High Quality Display (displays raster and vector graphics at high resolution) For this lesson, choose View > Display Performance > High Quality Display. Specifying color settings in InDesign [image: images] Tip: According to Adobe, “For most color-managed workflows, it is best to use a preset color setting that has been tested by Adobe Systems. Changing specific options is recommended only if you are knowledgeable about color management and very confident about the changes you make.” For consistent color in InDesign, you can specify a color settings file (CSF) with preset color management policies and default profiles. The default setting is North America General Purpose 2, which is the best option for beginners. In this section, we review some of the preset color settings in Adobe InDesign that you can use to help achieve consistent color in your projects. However, you will not change any color settings. Choose Edit > Color Settings. These settings apply to the InDesign application rather than to individual documents. Click the various options in the Color Settings dialog box to see what is available. Point at the Working Spaces title to see a description of this feature in the Description box at the bottom of the dialog box. Point at various other features to see their descriptions. [image: images] Click Cancel to close the Color Settings dialog box without making changes. Proofing colors onscreen When you proof colors onscreen, also known as “soft proofing,” InDesign attempts to display colors according to specific output conditions. The accuracy of the simulation depends on various factors, including the lighting conditions of the room and whether your monitor is calibrated. To experiment with soft proofing, do the following: Choose Window > Arrange > New Window for 08_Color.indd to open a second window for your lesson document. If necessary, click the 08_Color.indd:2 window to activate it. Choose View > Proof Colors. You can see a soft proof of the colors according to the current settings under View > Proof Setup. [image: images] Tip: SWOP stands for Specifications for Web Offset Publications. The current setting is Document CMYK - U.S. Web Coated SWOP V2, which reflects the typical output method for print documents in the United States. To customize the soft proof, choose View > Proof Setup > Custom. In the Customize Proof Condition dialog box, click the Device To Simulate menu and review the available presses, desktop printers, and output devices such as monitors. Scroll down in the menu and select Dot Gain 20% from the Device To Simulate menu, and click OK. Grayscale profiles such as Dot Gain 20% let you preview how a document will print in black and white. Notice that the InDesign document’s title bar shows which device is being simulated, such as (Dot Gain 20%) or (Document CMYK). Try different soft proofing options. When you’re finished reviewing the various soft proofing options, click 08_Color.indd:2’s close box to close the second window. Resize and reposition the 08_Color.indd window as necessary. About monitor calibration of display intensity), gamma (the brightness of the midtone values), and white point (the color and intensity of the brightest white the monitor can reproduce).. For details, see “Calibrate and profile your monitor” in InDesign Help. —Condensed from InDesign Help Defining printing requirements [image: images] Tip: Your commercial printer may provide a preflight profile with all the necessary specifications for output. You can import the profile and use it to check your work against these criteria. Whether you are working on a document for delivery in a print or digital format, it’s a good idea to know the output requirements before you start working. For example, for a print document, meet with your printer and discuss your document’s design and use of color. Because printers understand the capabilities of their equipment, they may suggest ways for you to save time and money, increase quality, and avoid potentially costly printing or color problems. The flyer used in this lesson was designed to be printed by a commercial printer using CMYK colors. (Color modes are described in more detail later in this lesson.) To confirm that your document matches the printing requirements, you can check it against a preflight profile, which contains a set of rules regarding the document’s size, fonts, colors, images, bleeds, and more. The Preflight panel can alert you to anything in the document that does not follow the rules set in the profile. In this exercise, you will import a preflight profile, select it in the Preflight panel, and resolve an issue with the document. First, you will load a preflight profile provided by the printer. Choose Window > Output > Preflight. Choose Define Profiles from the Preflight panel menu button ([image: images]). [image: images] In the Preflight Profiles dialog box, click the Preflight Profile Menu button ([image: images]) below the list of preflight profiles at left. Choose Load Profile. [image: images] Select the Flyer Profile.idpp file, in the Lesson08 folder, located inside the Lessons folder within the InDesignCIB folder on your hard disk. Click Open. With the Flyer Profile selected, look through the settings specified for the output of this ad. Click the arrows next to the other categories to see all the options you can include in a preflight profile. [image: images] Checked options are those that InDesign will flag as incorrect. For example, under Color > Color Spaces And Modes Not Allowed, RGB is selected. As a result, all uses of RGB colors will be reported as errors. Click OK to close the Preflight Profiles dialog box. Selecting a preflight profile Now, you will select the Flyer Profile and review any errors that it flags. From the Profile menu in the Preflight panel, choose Flyer Profile. Notice that the profile detects one issue with the colors that currently exist in the document. To view the error, click the triangle next to COLOR (1). [image: images] Tip: The lower-left corner of the document window displays the number of preflight errors in a document (provided that On is selected in the upper-left corner of the Preflight panel). If you start to see a lot of errors, open the Preflight panel to see more information. Click the triangle next to Color Space Not Allowed (1). Double-click Text Frame to select the frame that is triggering the error. [image: images] If necessary, click the triangle next to Info below to see details on the problem. Leave this panel open for the next exercise. Because this document is destined for CMYK printing, colors in the RGB color mode are not allowed. The fill color of the text frame is in the RGB color model. Converting a color mode for a swatch Now, you will resolve the preflight error by converting the color mode of the swatch applied to the text frame. [image: images] Tip: When you package a document for final output (File > Package), InDesign may flag issues with color models. You will change the color mode in the same way as shown here. Choose Window > Color > Swatches to display the Swatches panel. In the list of colors in the Swatches panel, double-click the sage color swatch (R=133 G=155 B=112) to open the Swatch Options dialog box. Select CMYK from the Color Mode menu, and then click OK. [image: images] Notice that the error no longer displays in the Preflight panel. Close the Preflight panel, and choose File > Save. Creating colors For maximum design flexibility, InDesign provides a variety of methods for creating colors. Once you create colors and color swatches, you can apply them to objects, strokes, and text in the layout. For consistent color usage, you can share colors among documents and users. [image: images] Note: As you work through the lesson, you can move panels around and change the zoom level to a setting that works best for you. For more information, see “Working with panels” and “Changing the magnification of a document” in Lesson 1. Create colors on-the-fly using the Color panel. Create named color swatches for repeated and consistent usage with the Swatches panel. Select a color from an image using the Eyedropper tool. Use the Color Theme tool to choose among color themes generated from images or objects. Create and select themes from the Adobe Color Theme panel. Use the CC Libraries feature to share colors with Photoshop and Illustrator, with other members of your workgroup, and with other documents. You can define colors in a variety of color modes, including RGB, CMYK, and “spot color” modes such as PANTONE. The difference between spot and process (CMYK) colors is discussed in detail later in this exercise. This flyer will be printed by a commercial printer using CMYK color, which requires four separate plates for printing—one each for cyan, magenta, yellow, and black. However, the CMYK color mode has a limited range of colors, which is where spot colors are useful. Spot colors are used to add colors beyond the range of CMYK (for example, metallic and pastel inks) and to ensure consistent color (for example, for use in company logos). [image: images] Tip: Many corporate identities, including logos, specify a PANTONE color. When working on projects for clients, it’s a good idea to ask about any PANTONE colors and fonts required to reproduce their corporate identity. In this exercise, you will use the Swatches panel to create a PANTONE color for a logo. You will then use the Eyedropper tool, Color panel, and Swatches panel to create a CMYK color swatch for the flyer’s background color. Finally, you will use the Color Theme tool to create a set of complementary colors from one of the mosaic images in the document. The selected color theme is added to the Swatches panel and to your CC Library. Creating a PANTONE color swatch In this flyer, the ART logo in the lower-right corner calls for a PANTONE spot color ink. You’ll now add a spot color from a color library. In a real-world scenario, you would need to notify the printer that you plan to use a PANTONE spot color. Using the Selection tool ([image: images]), click the pasteboard surrounding the page to make sure nothing is selected. If necessary, choose Window > Color > Swatches to display the Swatches panel. Choose New Color Swatch from the Swatches panel menu button ([image: images]). In the New Color Swatch dialog box, choose Spot from the Color Type menu. Select PANTONE+ Solid Coated from the Color Mode menu. In the PANTONE C box, type 265 to automatically scroll the list of Pantone swatches to the color you want for this project, which is PANTONE 265 C. [image: images] Tip: CC Libraries allow you to share assets, such as colors, among documents and users. You will learn about CC Libraries in Lesson 10, “Importing and Modifying Graphics.” Deselect Add To CC Library in the lower-left corner. [image: images] [image: images] Tip: When selecting PANTONE colors for print, it’s a good idea to select them from a printed PANTONE color guide, available from. Click OK. The spot color is added to your Swatches panel. The icon ([image: images]) to the right of the color name in the Swatches panel indicates that it is a spot color. New colors added to the Swatches panel are stored with the document in which they are created. [image: images] Choose File > Save. You’ll apply the newly added spot color to the “ART” text later in this lesson. Creating CMYK color swatches [image: images] Tip: Using the Swatches panel to name colors makes it easy to apply, edit, and update colors for objects in a document. Although you can also use the Color panel to apply colors to objects, there is no quick way to update these colors, which are considered “unnamed colors.” Instead, if you want to change an unnamed color on multiple objects, you need to change each one individually. To create a CMYK color swatch from scratch, you need an understanding of color mixing and color values. Alternatively, you can experiment with defining colors in the Colors panel and add a color as a color swatch. You can also use the Eyedropper tool to “pick up” a color from an image. In this exercise, you will use the Eyedropper tool to get a head start on creating a CMYK color swatch. Then, you will create two additional colors by simply entering color values. Choose Window > Color > Color to display the Color panel. On the Color panel, click the Fill box ([image: images]) in the upper-left corner. [image: images] Click the Color Theme tool ([image: images]) toward the bottom of the Tools panel. Hold the mouse button down to view the pop-out menu, and then select the Eyedropper tool ([image: images]). Click the Eyedropper tool on the word “Choose” in the lower-left corner of the page as shown. [image: images] The color picked up from the image displays in the Color panel. The color values may differ depending on precisely where you clicked. To create the intended color, fine-tune the values as necessary: [image: images] Cyan: 0 Magenta: 73 Yellow: 95 Black: 0 Choose Add To Swatches from the Color panel menu button ([image: images]). A color swatch is added to the bottom of the list in the Swatches panel. It is automatically selected. Click the New Swatch icon ([image: images]) at the bottom of the Swatches panel. This makes a copy of any selected swatch. Double-click the new swatch added to the bottom of the Swatches panel. This opens the Swatch Options dialog box so you can edit the swatch. [image: images] Make sure the Color Type is Process and the Color Mode is CMYK. Adjust the color by typing values in the following fields; you can tab from field to field. [image: images] Tip: When you know the color definition, as with the PANTONE color, it’s easiest to use the Swatches panel and create a swatch. When you’re trying to match a color in an image, it can work better to use the Eyedropper tool and Color panel. Cyan: 95 Magenta: 85 Yellow: 40 Black: 30 Click OK to close the Swatch Options dialog box. Press Alt (Windows) or Option (macOS) while you click the New Swatch icon ([image: images]) at the bottom of the Swatches panel. This creates a new swatch and automatically opens the New Color Swatch dialog box. [image: images] Tip: If you want to give a color a recognizable name, such as Aqua or Forest Green, deselect Name With Color Value in the Swatch Options dialog box. You can then enter a name in the Swatch Name field. [image: images] If necessary, select Name With Color Value. Make sure that Color Type is set to Process and Color Mode is set to CMYK. Enter the following values in the fields, tabbing between fields: Cyan: 35 Magenta: 90 Yellow: 95 Black: 0 Click OK to update the color, and then choose File > Save. You have now created a spot color swatch and three process (CMYK) color swatches. Later, you will create color themes from an image. In the next exercise, you will apply colors to objects on the page. About spot and process colors A spot color is a special premixed ink used instead of, or in addition to, CMYK process inks. Each spot color requires its own printing plate on a printing press, so use spot colors when few colors are specified and color accuracy is critical. Spot color inks can accurately reproduce colors outside the gamut of process colors. However, the exact appearance of the printed spot color is determined by the combination of the ink as mixed by the commercial printer and the paper it’s printed on, not by color values you specify or by color management., those color values are converted to CMYK when you print color separations. These conversions differ based on your colormanagement settings and document profile. Don’t specify a process color based on how it looks on your monitor, unless you are sure you have set up a color-management system properly and you understand its limitations for previewing color. Avoid using process colors in documents intended for onscreen viewing because CMYK has a smaller color gamut than that of a typical screen.. Each spot color you create generates an additional spot-color plate for the press. In general, commercial printers produce either two-color (using black and one spot color) or four-color CMYK work, with the possibility of adding one or more spot colors. Using spot colors typically increases printing costs. It is a good idea to consult with your printer before using spot colors in a document. —Condensed from InDesign Help Applying colors Once you create color swatches, you can apply them to objects, text, and more. The Swatches panel, Control panel, and CC Libraries panel offer the primary tools for applying colors. There are three general steps to applying a color: Select the text or object. Select the stroke or fill option, depending on what you want to change. Select a swatch. You use the Stroke/Fill box ([image: images]) to specify whether you want to apply color to a selection’s stroke (outline) or fill (background). You can find the Stroke/Fill box on the Tools panel, the Swatches panel, the Color panel, and the Control panel. Whenever you apply colors, keep an eye on this box, as it’s easy to apply color to the wrong part of an object. InDesign provides many other options for applying colors, including dragging swatches onto objects, copying color from an object with the Eyedropper tool, and specifying colors in styles. As you work with InDesign, you will discover which methods work best for you. In this exercise, you will apply color swatches to strokes, fills, and text using various panels and techniques. Applying fill colors to objects In this task, you will apply fill colors to various objects on the page by using the Swatches panel, dragging a swatch, and using the Eyedropper tool. [image: images] Tip: Clicking the small arrow on the Fill/Stroke box ([image: images]) swaps the stroke and fill colors of a selected object. If necessary, choose Window > Color > Swatches to display the Swatches panel. Leave this panel open until you reach the end of this lesson. Choose View > Screen Mode > Normal to see the frame edges. Using the Selection tool ([image: images]), click anywhere in the margin of the page (outside the margin guides) to select the large background frame. [image: images] Click in the margins of the page to select the large text frame as shown above. Click the Fill box ([image: images]) on the Swatches panel. Click the orange color you created from the word “choose”: C=0 M=73 Y=95 K=0. [image: images] Using the Selection tool, select the text frame at left containing the words “Experience the Evolution.” With the Fill box still selected, click the blue color swatch named C=65 M=40 Y=0 K=0. [image: images] Click the pasteboard to make sure nothing is selected on the page. In the Swatches panel, click the burgundy color swatch: C=35 M=90 Y=95 K=0. Drag the swatch to the text frame centered at the bottom of the page containing the words “beautiful mosaics.” [image: images] Click the pasteboard so no objects are selected. The lower portion of the page should look something like this: [image: images] Choose File > Save. Applying colors to strokes The Stroke panel (Window > Stroke) lets you apply a border to lines, frames, and text. Here, you will apply color to an existing line and a graphics frame stroke using options on the Control panel. Using the Selection tool ([image: images]), click the horizontal line below the words “Art Show.” Click the Stroke menu on the Control panel. [image: images] Note: If you apply color to the wrong object or the wrong part of an object, you can always choose Edit > Undo and try again. Scroll down and select the burgundy color: C=35 M=90 Y=95 K=0. [image: images] Using the Selection tool, click the graphics frame containing the mosaic with the word “Trust.” Be sure to click outside the content grabber to select the frame. Click the Stroke box ([image: images]) on the Swatches panel. Scroll down to click the dark blue color swatch named C=95 Y=85 M=40 K=0. [image: images] Choose File > Save. Applying colors to text [image: images] Tip: [Paper] is a special color that simulates the color of the paper on which you’re printing. You will now select text with the Type tool and apply a fill color to it using the Swatches panel and the Control panel. To create reverse type, which is lighter text on a dark background, you will apply InDesign’s [Paper] color to text in one frame. Using the Type tool ([image: images]), click in the text frame starting with “Experience the Evolution.” Drag to select all the text. On the Swatches panel, notice that the Fill box has changed to indicate that text is selected: ([image: images]). With the Fill box still selected, click the dark blue color swatch named C=95 Y=85 M=40 K=0. Using the Type tool, click in the frame at right containing the words “First Fridays.” Press Ctrl+A (Windows) or Command+A (macOS) to select all the text in the paragraph. With the Fill box still selected in the Swatches panel, click the burgundy color: C=35 M=90 Y=95 K=0. Click the pasteboard to deselect the text, which should look something like this: [image: images] Using the Type tool, click in the text frame centered at the bottom of the page containing the words “beautiful mosaics.” Choose Edit > Select All to select all the text. With the Fill box still selected, click the [Paper] color on the Swatches panel. Click the pasteboard to deselect the text and see the results. [image: images] Using the Type tool, click in the text frame containing the word “Art” in the lower-right corner. Double-click in the word to select it. With the Fill box still selected, click the PANTONE 265 C swatch. With the word “Art” still selected, choose Window > Stroke. Type 1 pt in the Weight field, and press Enter or Return. [image: images] With the Stroke box ([image: images]) selected on the Swatches panel, click [Black]. Choose Edit > Deselect All, and then choose File > Save. [image: images] Working with tint swatches A tint swatch is a screened (lighter) version of a color that you can apply quickly and consistently. The tint swatch is available on the Swatches panel and in other color menus, such as in the Control panel. You can share tint swatches with other documents through the Load Swatches command on the Swatches panel menu. You will now create a light-green tint swatch and apply it to the yellow text frame. Creating a tint swatch You create a tint swatch from an existing color swatch. [image: images] Tip: Tints are helpful because InDesign maintains the relationship between a tint and its parent color. So if you change the parent color swatch to a different color, the tint swatch becomes a lighter version of the new color. Choose View > Fit Page In Window to center the page in the document window. Using the Selection tool ([image: images]), click the pasteboard surrounding the page to make sure nothing is selected. Select the yellow color swatch named C=5 M=4 Y=40 K=0. Click the Fill box ([image: images]). Choose New Tint Swatch from the Swatches panel menu ([image: images]). In the New Tint Swatch dialog box, the Tint option at the bottom is the only option you can modify. Type 65 in the Tint box, and then click OK. The new tint swatch appears at the bottom of the list of swatches. The top of the Swatches panel displays information about the selected swatch, with a Fill/Stroke box showing that the 65% tint is currently the selected fill color and a Tint box showing that the color is 65% of the original color. [image: images] Applying a tint swatch You will apply the tint swatch as a fill color. Using the Selection tool ([image: images]), click the text frame at right containing the words “First Fridays.” Click the Fill box ([image: images]) on the Swatches panel. Click the new tint you just created in the Swatches panel. Its tint swatch name will be C=5 M=4 Y=40 K=0 65%. Notice how the color changes. [image: images] Choose File > Save. Working with gradients [image: images] Tip: It’s a good idea to test gradients on the intended output device, whether it’s a tablet, inkjet printer, or press. [image: images] A gradient is a graduated blend between two or more colors or between tints of the same color. You can create either a linear or a radial gradient. In this exercise, you will create a linear gradient swatch with the Swatches panel, apply it to several objects, and adjust the gradients with the Gradient Swatch tool. Creating a gradient swatch In the New Gradient Swatch dialog box, gradients are defined by a series of color stops in the gradient ramp. A stop is the point at which each color is at full intensity between the transitions; it is identified by a square below the gradient ramp. Every InDesign gradient has at least two color stops. By editing the color of each stop and adding additional color stops, you can create custom gradients. Choose Edit > Deselect All to make sure no objects are selected. Choose New Gradient Swatch from the Swatches panel menu ([image: images]). For Swatch Name, type Blue/White. Leave the Type menu set to Linear. Click the left stop marker ([image: images]) on the Gradient Ramp. [image: images] Tip: To create a gradient that uses a tint of a color, first create a tint swatch in the Swatches panel. From the Stop Color menu, select Swatches, and then scroll down the list and select the blue color swatch named C=65 M=40 Y=0 K=0. Notice that the left side of the gradient ramp is now blue. With the left stop marker still selected, type 5 in the Location field. Click the right stop marker ([image: images]), and make sure the Stop Color is set to [Paper]. Type 70 in the Location field. The gradient ramp shows a color blend between blue and white. [image: images] Click OK. The new gradient swatch appears at the bottom of the list in the Swatches panel. Choose File > Save. Applying a gradient swatch Now you’ll replace the fill in one of the text frames with the gradient. Using the Selection tool ([image: images]), click the text frame at left containing the words “Experience the Evolution.” Click the Fill box ([image: images]) on the Swatches panel. Click the new gradient you just created in the Swatches panel: Blue/White. [image: images] Choose File > Save. Adjusting the direction of the gradient blend [image: images] Tip: When using the Gradient Swatch tool, the farther away you start from the outer edges of the object, the more gradual the gradient blend will be. Once you have filled an object with a gradient, you can modify the gradient by using the Gradient Swatch tool to “repaint” the gradient along an imaginary line that you draw. This tool lets you change the direction of a gradient and change its beginning point and end point. You’ll now change the direction of the gradient. Make sure the “Experience the Evolution” text frame is still selected, and then press G on the keyboard to select the Gradient Swatch tool ([image: images]) in the Tools panel. [image: images] Tip: To constrain gradient angles to horizontal, vertical, or 45-degree angles, press the Shift key while dragging with the Gradient tool. To create a more gradual gradient effect, position the cursor slightly outside the left edge of the selected text frame, and drag to the right as shown. When you release the mouse button, you’ll notice that the transition between blue and white is more gradual than it was before you dragged the Gradient Swatch tool. [image: images] To create a sharper gradient, drag a short horizontal line in the center of the text frame using the Gradient Swatch tool. Continue to experiment with the Gradient Swatch tool so that you understand how it works. [image: images] When you are finished experimenting, drag from the top to the bottom of the text frame to form a gradient from top to bottom. That’s how you’ll leave the gradient for the “Experience the Evolution” text frame. [image: images] Press V on the keyboard to switch to the Selection tool ([image: images]), and then click the pasteboard to make sure no objects are selected. Choose File > Save. Working with color groups If a document contains many color swatches intended for specific purposes (such as chapter openers or divider pages), you can group the swatches in the Swatches panel. You can then easily share the color group with other documents and with other designers working on the campaign. Adding colors to a color group You will organize the colors in this document into a new color group. To create a new color group, choose New Color Group from the Swatches panel menu ([image: images]). In the Edit Color Group dialog box, type Art Show Campaign. Cl
https://el.b-ok.org/book/3410281/9aa9cc
CC-MAIN-2020-16
refinedweb
10,500
63.7
import Sweden Our Leeki has been spayed on 02/26/2014 and will unfortunately never be able to give us a litter … But just like all our other dogs we love her VERY much and can not miss her anymore. Leeki is a sweetheart, a very cheerful, enthusiastic girl with a lot of passion to work who gives us lots of love and joy. With her ever-wobbling tail and her waterfall of kisses, she immediately conquers everyone’s heart. We are therefore very happy that she is part of our family. She has already conquered our hearts forever. Leeki has a lot of passion to work. She loves to go hunting and is one of Stefaan’s regular picking up dogs. We hope that our “princess of kisses” will be part of our “Flat Passion’s” family for many years to come. Thank you Ragnhild for having entrusted Leeki to us
https://flatpassions.be/en/hond/almanza-bellini/
CC-MAIN-2021-39
refinedweb
152
71.95
I'm attempting to set up DFS Standalone replication for the static content of a group of 2008 r2 web servers, without getting the Domain Controller involved. I've created a namespace on one computer A pointed at empty shares on computers A and B. When I try to replicate this folder through the DFS Management Server Manager snap-in, I get the error "computerA\namespace\share: The replication group cannot be created. There are insufficient permissions to create the replication group". From what I can gather, this action is trying to make changes on the DC. Is what I am trying to do even possible? I tried using the command line utils but they've proven more cryptic than anything. A standalone DFS namespace cannot participate in DFS-R (If it is not a member of an AD domain). Clarification: DFS can utilize two methods to replicate data: If the server you are setting up the namespace on, and the target servers are members of an AD domain then, Yes you can use DFS replication. If you do not have Domain Admin rights you will need to be delegated permissions to create replication groups: Detailed delegation Grant permissions to create a replication group This action is one of the two delegation actions that are available in DFS Management. To manually perform this action in Active Directory Users and Computers, follow these steps: Or alternatively you could ask to be set to control all Replication groups: Control of all replication groups To grant a user control of all existing and future replication groups in a domain, follow these steps: Steps were taking from KB911604 No, sorry. DFS-R is integrated into the domain architecture. It is not planned and supposed to work outside. I suggest instead of trying what you do, you actually use the hosting as suggested by MS best practices for hosters. By posting your answer, you agree to the privacy policy and terms of service. asked 3 years ago viewed 3303 times active
http://serverfault.com/questions/253205/dfs-standalone-replication
CC-MAIN-2014-35
refinedweb
336
59.13
The System.Reflection.Emit namespace allows developers to emit types at runtime. Part of the interest in writing books like this one is to try to understand what motivated Microsoft developers when they defined and implemented these capabilities. Sometimes it is obvious or guessable, and other times I have to ask and am fortunate enough to get answers from those in the know. You are likely to use some of these new capabilities as the implementers intended, and more than likely many of you will contrive new uses for them. Reflection seems to be a replacement for COM Automation. The Emit namespace seems to be intended for code generators, perhaps for tools like Rational Rose that reverse-engineer UML models to generate code. The Reflection.Emit namespace supports generating types at runtime using Builder classes. These Builder classeslike AssemblyBuilder and MethodBuilderwork by emitting IL (Intermediate Language) code. General information about classes capable of emitting code to the ILGenerator can be found by searching the help documentation topic ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemReflectionEmit.htm in Visual Studio .NET. There are many excellent examples of .NET code defined in the Visual Basic QuickStarts and Other Samples help topics. If you search the QuickStarts topics, you will find several solutions demonstrating various aspects of Visual Basic .NET programming. The example in Listing 6.6 is loosely based on the ReflectionEmitVB.vbproj example installed in the Microsoft.Net\FrameworkSDK folder when you installed the .NET Framework. 1: Option Strict On 2: Option Explicit On 3: 4: Imports System.Threading 5: Imports System.Reflection 6: Imports System.Reflection.Emit 7: 8: Public Class Form1 9: Inherits System.Windows.Forms.Form 10: 11: [ Windows Form Designer generated code ] 12: 13: Private Sub Button1_Click(ByVal sender As System.Object, _ 14: ByVal e As System.EventArgs) Handles Button1.Click 15: 16: DynamicType.Test() 17: End Sub 18: 19: End Class 20: 21: 22: Public Class DynamicType 23: 24: Public Shared Sub Test() 25: Dim AClass As Type = _ 26: CreateType(Thread.GetDomain, AssemblyBuilderAccess.Run) 27: 28: Dim Obj As Object = _ 29: Activator.CreateInstance(AClass, _ 30: New Object() {"It's a brave new world!"}) 31: ' Reuse Obj reference here! 32: Obj = AClass.InvokeMember("Text", _ 33: BindingFlags.GetField, Nothing, Obj, Nothing) 34: 35: MsgBox(Obj) 36: End Sub 37: 38: Public Shared Function CreateType(ByVal Domain As AppDomain, _ 39: ByVal Access As AssemblyBuilderAccess) As Type 40: 41: Dim AName As New AssemblyName() 42: AName.Name = "EmitAssembly" 43: Dim AnAssembly As AssemblyBuilder = _ 44: Domain.DefineDynamicAssembly(AName, Access) 45: 46: Dim AModule As ModuleBuilder 47: AModule = AnAssembly.DefineDynamicModule("EmitModule") 48: 49: Dim AClass As TypeBuilder = _ 50: AModule.DefineType("AClass", TypeAttributes.Public) 51: 52: Dim AField As FieldBuilder = _ 53: AClass.DefineField("Text", GetType(String), _ 54: FieldAttributes.Public) 55: 56: Dim Args As Type() = {GetType(String)} 57: Dim Constructor As ConstructorBuilder = _ 58: AClass.DefineConstructor(MethodAttributes.Public, _ 59: CallingConventions.Standard, Args) 60: 61: Dim IL As ILGenerator = Constructor.GetILGenerator 62: IL.Emit(OpCodes.Ldarg_0) 63: Dim Super As ConstructorInfo = _ 64: GetType(Object).GetConstructor(Type.EmptyTypes) 65: IL.Emit(OpCodes.Call, Super) 66: IL.Emit(OpCodes.Ldarg_0) 67: IL.Emit(OpCodes.Ldarg_1) 68: IL.Emit(OpCodes.Stfld, AField) 69: IL.Emit(OpCodes.Ret) 70: 71: Return AClass.CreateType 72: 73: End Function 74: 75: End Class The shared method Test is called, which starts the process of creating the dynamic type. CreateType returns a Type object. Activator.CreateInstance is used directly to create an instance of the new type on line 28. (We used the Activator object implicitly in Listing 6.3 when Type.CreateInstance was called.) The Obj reference is reused on line 32 when we call AClass.InvokeMember to get the value of the field named Text. After lines 3233 Obj refers to the String member Text. Clearly this is not an efficient way to write code in general, but is a powerful way to create types on the fly. The CreateType method may seem a bit confusing to less experienced developers. After you have read the first 10 chapters or so of this book, the code itself should be comprehensible. Clearly, emitting IL is an advanced subject. In summary, CreateType uses builder classes to create the various pieces of code. An AssemblyName and AssemblyBuilder are created first to create an assembly. On lines 46 and 47 a Module is created, using the ModuleBuilder class, and added to the assembly. Lines 49 and 50 define a single statement that creates the new class type. The statements on lines 52 to 54 add a single public, string field to the type. (Thus far, these are all steps that a programmer would perform manually by creating a project and defining a class in that assembly.) The ConstructorBuilder is used to define a parameterized constructor for our new type; the new constructor takes a single string argument. Lines 61 through 69 use an ILGenerator object to emit the IL code. Line 71 returns the new type. Lines 65 through 69 represent generic, low-level code in IL that will be converted to machine-specific code by the JITter. These five strange -looking statements using OpCodes represent the IL form of code that defines a constructor. Line 65 calls the base constructor. Lines 66 and 67 manage arguments passed to the constructor, including the hidden reference to self, Me and the string parameter. Line 68 initializes the field, and line 69 emits the equivalent of the Ret instruction. Basically, the code is the IL version of statements you might write: MyBase.New and Text = Value. Emitting code using reflection is one of those subjects that will probably be explored in its own book, after the dust from absorbing the core changes to Visual Basic .NET.
https://flylib.com/books/en/1.488.1.82/1/
CC-MAIN-2020-24
refinedweb
963
51.65
version.py saves you from having to hard-code the version number of your project by getting it from git tags (directly or indirectly). To use the script, simply copy it into your project and call get_version() in your setup.py file: from version import get_version setup( ... version=get_version(), ... ) By default the tags that are considered to be version numbers are those that start with a digit. If you use a prefix, for example a v, modify the PREFIX constant in version.py accordingly. You need to distribute the version.py file in your sdist packages by adding the following line in the MANIFEST.in file: include version.py For the script to work within git archives (for example those automatically generated by GitHub for each tag) you need to add the following line to the .gitattributes file: version.py export-subst Note: if you don't care about git archives, or you're looking for a solution that works with Mercurial, then you can use setuptools_scm instead. Compatibility: python 3.x and 2.7 Licence: CC0 Public Domain Dedication
https://recordnotfound.com/version-py-Changaco-75
CC-MAIN-2018-47
refinedweb
180
59.4
In the first part of the tutorial series we got a glimpse of MVC. In this part we’ll focus on the practical implementation of MVC Pattern. I don’t need to explain about theory of MVC as we have already covered this in the previous article. We stick our agenda as follows: System.Component.DataAnnotation Step 1: Open Visual Studio 2010/2013 (I am using 2010). Go to File=> New=> Project and select ASP.NET MVC3 Web Application, as shown below: traditional ASP.NET web application. We get Models, Views Controllers, and a Shared folder in the Views folder. The folders hold their respective MVC players model-view-controllers. The shared folder in Views contains the _Layout.cshtml, which can be used as the master page for the views we create. We see the global.asax file that contains a default routing table, that defines the route to be followed when the request comes. It says that when the request comes to the Home controller, the Index action of that Home Controller has to be called. Actions are the methods defined in Controllers (that can be called defining a route). The Action methods can also contain parameters in the above mentioned figure. It says that the Home controller has an Action Index which contains an optional parameter ID. When we run our application we get something as shown below: It says that the resource which we are looking for cannot be found. The request by default follows the default route as mentioned in global.asax, I.E. go to the controller Home and invoke method Index. Since we don’t have any of these yet, the browser shows this error. Never mind, let's make the browser happy. Step 1: Create a My Controller by right clicking on Controllers folder and add a controller named My. Add the controller with empty read/write actions, and: RegisterRout can see that we have Actions but they return a View, so we need to create Views for them. But before this we’ll create a Model named User for our Views. Right click on the Model folder add a class named User. Add following the properties to the User class: Now our model is created and we can create Views bound to this particular model. Step 3: have to take overhead to maintain it. Now we have controller as well as Views, so if we run the application we get. i.e. Index Action of our My controller is Fired that returned Index View. Our MVC application is ready, but rather than displaying dummy data I run the application talking to a database so that we can cover a broader aspect of the application. Step 1: Create a database, script is given in the attachment, just execute it over SQL Server 2005/2008. Step 2: Add new Item to the solution, and select LINQ to SQL class, call it MyDB.dbml. Our Solution looks like: Step 3: Open Server explorer of Visual Studio, Open a connection, by providing Server name and existing database name in Server Explorer Open Connection window. Click OK. Our solution looks like: Step 4: Drag the User table to DBML designer window, we get the table in class diagram format in designer window. When we open MyDB.designer.cs, we get the MyDBDataContext class. This class holds the database User table information in the form of Class and Properties. For every column of the table, properties are created in the class, and we can use these properties to get/set values from/in database. MyDBDataContext We now have a database, a context class to talk to the database and an MVC application to perform CRUD operations in database using the context class. When we run the application, we get an empty list, I.E. we don’t have records in database. Now that we can perform the update and delete by ourselves,. I wanted to take this topic as there is much confusion regarding these three players. MVC provides us ViewData, ViewBag and TempData for passing data from controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData performs additional roles. Let's get key points on these three players: ViewData ViewBag TempData I have written sample test code in the same application which we are following from the beginning, Following are roles and similarities between ViewData and ViewBag: Differences between ViewData and ViewBag (taken from a blog): ViewDataDictionary TempData is a dictionary derived from the TempDataDictionary class and stored in short lives session. It is a string key and object value. TempDataDictionary It keep the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain data when we move from one controller to another controller or from one action to other action. In other words, when we redirect Tempdata helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when we are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally it is used to store only one time messages like error messages, validation messages. Tempdata I added a TempData in Edit Action as: [HttpPost] public ActionResult Edit(int? id, User userDetails) { TempData["TempData Name"] = "Akhil"; ….. And when View redirected to Index Action. I.E. I get the TempData value across Actions. We can have many methods for implementing validation in our Web Application Client Side, Server Side etc… But MVC provides us a feature with which we can annotate our Model for validation by writing just one/two line of code. the System.ComponentModel.DataAnnotations; Namespace, when using Model Validation. This is the namespace that holds classes used for validation. System.ComponentModel.DataAnnotations; Now we know what MVC is, how to Implement it, its advantages, CRUD operations in MVC. Upcoming parts of the tutorial will be focusing on more advanced topics like EntityFramework, Repository Pattern, Unit Of Work Pattern. Code First Approach.
http://www.codeproject.com/Articles/620197/Learning-MVC-Part-Creating-MVC-Application-and-P
CC-MAIN-2014-52
refinedweb
1,027
64.91
I got a little problem , I need to store two new CSV file in my project. I had create two new class Fish and Dog,i had put some new methods and inheritance another class call pet into it, read those csv files in my FileIO,made a arraylist for them in a class control the model ApplicationModel, also i had give the right methods to the main methods and my viewer. There's no error in my project but it can't read my fish and dog csv file. I have this code for my pet : And new methods for my dog ( ignore fish for now)And new methods for my dog ( ignore fish for now)Code:public abstract class Pet { private String Shop; private String Type; private double Price; private String dateAcquired; private String notes; Everything works fine , but my fish and dog tab pages is still emptyEverything works fine , but my fish and dog tab pages is still emptyCode:public class Dog extends Pet { private String Size; private boolean neutered; public Dog(String csvString) { String[] attributes = csvString.split(","); this.setShop(attributes[0]); this.setType(attributes[1]); this.setPrice(Integer.parseInt(attributes[2])); this.setDateAcquired(attributes[3]); this.setNotes(attributes[4]); this.setSize(attributes[5]); this.setNeutered(attributes[6]); } //getter setter methods for new stuffs @Override public String toString() { return this.getShop() + "\t" + this.getType() + "\t" +this.getPrice() + "\t" + this.getDateAcquired() +"\t" +this.getNotes()+this.getSize()+"\t"+ this.getNeuteredAsString()+"\n"; } with no reason, no error, can someone please give me any tips?
http://forums.devshed.com/java-help-9/inheritance-937406.html
CC-MAIN-2014-10
refinedweb
254
58.52
C++ <deque> - size() Function The C++ deque::size function is used to find out the total number of elements in the deque. It returns the total number of elements held in the deque, and it is not necessarily equal to its storage capacity. Syntax size_type size() const; size_type size() const noexcept; Parameters No parameter is required. Return Value Number of elements present in the deque. Time Complexity Constant i.e, Θ(1). Example: In the example below, the deque::size function is used find out the total number of elements in a deque called MyDeque. #include <iostream> #include <deque> using namespace std; int main (){ deque<int> MyDeque{10, 20, 30, 40, 50}; cout<<"Deque size is: "<<MyDeque.size()<<"\n"; cout<<"Three elements are added in the Deque.\n"; MyDeque.push_back(60); MyDeque.push_back(70); MyDeque.push_back(80); cout<<"Now, Deque size is: "<<MyDeque.size()<<"\n"; return 0; } The output of the above code will be: Deque size is: 5 Three elements are added in the Deque. Now, Deque size is: 8 ❮ C++ <deque> Library
https://www.alphacodingskills.com/cpp/notes/cpp-deque-size.php
CC-MAIN-2021-43
refinedweb
174
57.27
Introduction I recently wrote a simple event handling module for a group project. I found it to be quite a useful tool, and I'm writing this article so that hopefully others may find it useful as well. Our group project was implemented by five programmers, each writing a different component of the game. The need for event handling arose when different components each needed to know about certain types of input (mainly keyboard and mouse events), but didn't need to know about the underlying lower-level implementation. For example, components needed to know when a key corresponding to a certain action was pressed (such as the “jump” key), but didn't want to know which actual key was pressed. From that arose this simple event dispatching and handling system. The goals for this system where three-fold: - A simple system to use and setup - Relatively quick (we don't want to send events about everything) - Object-oriented (given that it had to fit in with the rest of the project) Events The first thing we will need is an Event structure to hold information about events to be sent around: struct Event { int Type; int arg1, arg2; }; The Event structure is fairly straightforward. The Type variable will indicate what type of event the structure refers to. The two arg variables are simply arguments to be passed along with the structure. When this system was first being designed, the only events to be passed around were mouse movement events (needing an x and y coordinates as arguments), and key press events (needing the key being pressed as an argument). A possible improvement here is to pass around a pointer to an Event class instead of a structure. The Event class could then contain any amount of information, and derived classes could be created for different types of events. I choose a simpler option, mainly because the scope of our project didn't require such a complex solution. The Event.Type variable is used by event handlers to identify the event. I choose to define the type of events in an enumeration structure. Here is a simplified version of the structure used in our project to illustrate its function: }; IEventHandler The next thing we need is an interface for event handlers. I defined a simple IEventHandler interface: class IEventHandler { public: virtual void EventHandler(const Event &e) = 0; }; Every class that wants to listen to events needs to inherent from IEventHandler, and needs to implement the EventHandler virtual function. A typical implementation of this method will have a switch statement (switching on the Event.Type variable), and will have a case statement for any events the class wants to handle. Here's a short example: void Foo::EventHandler(const Event &e) { switch (e.Type) { case E_NEWGAMEEASY: // handle creating a new easy game. break; case E_MOUSELEFTBUTTONPRESS: // handle mouse button being pressed break; default: break; } } Event Dispatcher We now need an EventDispatcher class. I implemented it as a singleton class. Explaining how to implement a singleton class and how it works is beyond the scope of this article. It suffices to say that there will only ever exist one instance of the class, and to obtain a pointer to that instance, one has to call EventDispatcher::Get(). For reference, the code implementing the singleton class is included along with the rest of the code at the end of the article. For our EventDispatcher class, we only need to declare two public functions (ignoring the singleton implementation part): class EventDispatcher { public: void RegisterHandler(IEventHandler *device); // Sends the event to all the devices registered to listen void SendEvent(int eventType, int arg1 = 0, int arg2 = 0); private: IEventHandler *_deviceList; }; These two functions are again fairly straightforward. RegisterHandler is called to add a new object (device) as a listener. SendEvent is the method used to dispatch events. The two arguments to the event are zero by default. The list of registered devices will be stored as a simple singly-linked list, so we need a IEventHandler pointer. This pointer will be initialized to null by EventDispatcher's constructor (not shown here). Now we'll go over the definitions of the two functions specified above: void EventDispatcher::RegisterHandler(IEventHandler *device) { device->SetNextHandler(_deviceList); _deviceList = device; } This method just adds the device to the device list (the device is added to the front of the list, but we are not concerned with the order of the devices in the list, since every device is sent every event. The user has to make sure that _deviceList is originally set to null in EventDispatcher's constructor. void EventDispatcher::SendEvent(int eventType, int arg1, int arg2) { Event e; e.Type = eventType; e.arg1 = arg1; e.arg2 = arg2; IEventHandler * curDevice = _deviceList; for (; curDevice; curDevice = curDevice->GetNextHandler()) { assert(curDevice != curDevice->GetNextHandler()); curDevice->EventHandler(e); } } This method creates a new event and dispatches to every device registered with the dispatcher. At this point, the reader should have noticed the use of two methods (GetNextHandler and SetNextHandler) belonging to the IEventHandler class, which I haven't discussed. Well, it's time to further develop the IEventHandler interface. Revising the IEventHandler interface As it stands, the interface is still fairly simple. We now need to add certain functionality to handle creating the linked list, as well as a couple extra useful methods. Here is the final full code for the IEventHandler interface: class IEventHandler { public: virtual void EventHandler(const Event &e) = 0; // Mutator and selector IEventHandler * GetNextHandler(void) {return _nextHandler;} void SetNextHandler(IEventHandler *next) {_nextHandler = next;} IEventHandler() : _nextHandler(0) { EventDispatcher::Get()->RegisterHandler(this); } protected: void SendEvent(int eventType, int arg1 = 0, int arg2 = 0) { EventDispatcher::Get()->SendEvent(eventType, arg1, arg2); } private: IEventHandler *_nextHandler; }; I've added a pointer to the next handler (_nextHandler), as well as mutator and selector methods for this variable. As noted above, these two methods are used by the EventDispatcher to update, and cycle through the list of devices. Using a linked list allows for the list to vary in size without worrying about dynamically allocating memory, or knowing beforehand how many devices will listen for events. (Early versions of this system used these less elegant methods). I've also added a constructor for this interface. A class which implements the IEventHandler interface will automatically call IEventHandler's constructor when its own constructor is invoked. In this manner, one does not have to remember to register an object as a listener as IEventHandler's constructor does so automatically. A class listening to events doesn't need to know how the event dispatching is implemented, nor does it have to rely on a third party to register it with the dispatcher. The last method (SendEvent) is used to further abstract the EventDispatcher. Any class implementing this interface doesn't need to know anything about the dispatcher. It just calls its own SendEvent method when it needs to generate an event. Putting It All Together Now, I'll illustrate the usage of this system with a relatively short example. Assuming we have two classes A and B defined as follows: #include "IEventHandler.h" class A : public IEventHandler { public: void EventHandler(const Event &e) { switch (e.Type) { case E_NEWGAMEEASY: cout << "Class A handling E_NEWGAMEEASY event" << endl; SendEvent(E_INCREMENTSCORE); break; case E_PAUSEGAME: cout << "Class A handling E_PAUSEGAME event" << endl; break; } } }; class B : public IEventHandler { public: void EventHandler(const Event &e) { switch (e.Type) { case E_INCREMENTSCORE: cout << "Class B handling E_INCREMENTSCORE event" << endl; break; case E_PAUSEGAME: cout << "Class B handling E_PAUSEGAME event" << endl; break; } } }; We compile and execute the following piece of code: #include using namespace std; #include "EventDispatcher.h" void main () { A a1; B b1; cout << "Main fct sending E_NEWGAMEEASY event" << endl; EventDispatcher::Get()->SendEvent(E_NEWGAMEEASY); cout << "Main fct sending E_PAUSEGAME event" << endl; EventDispatcher::Get()->SendEvent(E_PAUSEGAME); char c; cout << "Press any key followed by [Enter] to exit" << endl; cin >> c; exit(0); } The output of the program will be: Main fct sending E_NEWGAMEEASY event Class A handling E_NEWGAMEEASY event Class A sending a E_INCREMENTSCORE event Class B handling E_INCREMENTSCORE event Main fct sending E_PAUSEGAME event Class B handling E_PAUSEGAME event Class A handling E_PAUSEGAME event Conclusion Now we have a simple Event Handling/Dispatching system. There are certain performance issues to consider when using this system. Spending too much time in the EventHandler methods basically slows down the overall event dispatching. One solution is to spawn off a thread for each event handler, but as the number of events and event handling objects increase, the overhead for creating and deleting threads will become significant. The best solution is to use the event handler to set flags or store important variables (such as mouse coordinates), and make use of that during the update/render loop. The use for this type of system is fairly obvious. Aside from handling mouse and keyboard events (and abstracting those events), general events can be created and shared across the program. Sound events can be generated for specific situations (such as a collision, or a menu selection). Different components of a game might need to be informed when a new game is created or when the game play is paused. The biggest advantage of this system, in my opinion, is that it allows a higher level of abstraction between modules. I've included all c++ header and source code I've mentioned in this article, and you're free to use it in any program you want. Any questions or comments, please email me.
http://www.gamedev.net/page/resources/_/technical/game-programming/simple-event-handling-r2141
CC-MAIN-2014-35
refinedweb
1,573
58.52
Lens extensibility for Windows Phone 8 [ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ] In Windows Phone 8, you can create a camera app called a lens. A lens opens from the built-in camera app and launches right into a viewfinder experience to help the user capture the moment. All lenses must register for a lens extension to appear in the lens picker. It’s the responsibility of your app to ensure that it opens to a viewfinder experience when it is launched from the lens picker. You also need to create new icons to use specifically for the lens picker. This topic describes how to incorporate lens extensibility into your app. For info about designing a lens app, see Lens design guidelines for Windows Phone. Step 1: Prepare icons for the lens picker The lens picker requires icons that are a different resolution than the app icon. Your app must provide three icons in the Assets folder, one for each of the three phone resolutions. For more info about these icons, see Lens design guidelines for Windows Phone. Step 2: Register for a lens extension To integrate with the lens experience, register for the Camera_Capture_App extension. This extension declares to the operating system that your app can display a viewfinder when it is launched from the lens picker. It also is used by the Windows Phone Store to identify lenses and display them in the lens picker. Extensions are specified in the WMAppManifest.xml file. Just after the Tokens element, inside the Extensions element, the lens extension is specified with the following Extension element. <Extension ExtensionName="Camera_Capture_App" ConsumerID="{5B04B775-356B-4AA0-AAF8-6491FFEA5631}" TaskID="_default" /> The Windows Phone Manifest Designer does not support extensions; use the XML (Text) Editor to edit them. For more info, see How to modify the app manifest file for Windows Phone 8. Step 3: Handle a launch from the lens picker It’s the responsibility of your app to ensure that it opens to a viewfinder experience when launched from the lens picker. When a user taps your app in the lens picker, a deep link URI is used to take the user to your app. You can either let the URI launch your default page (MainPage.xaml, for example) or use a URI mapper to launch a different page. This step describes both cases. Launch your app to the default page If you have only one page in your app and that page displays a viewfinder, no URI mapping is required. Your app launches to the page that is specified in the DefaultTask element of the app manifest file. Note that when you create a new Windows Phone app, MainPage.xaml is specified as the launch page by default. Launch your app to a different page If your default launch page doesn’t provide a viewfinder, use URI mapping to take the user to a page in your app that does have a viewfinder. To map a launch from the lens picker to a specific page in your app, we recommend that you create your own URI mapper class based on the UriMapperBase class (in the System.Windows.Navigation namespace). In the URI mapper class, override the MapUri(Uri) method to map incoming URIs to pages in your app. For example, the following code looks for a URI that contains the string ViewfinderLaunch. If the URI mapper finds the string, it takes the user to a page that displays a viewfinder named viewfinderExperience.xaml. If it doesn’t find that string, it returns the incoming URI in its original state. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace LensExample {; } } } After you create a URI mapper class for your app, assign it to the frame of the app in the App.xaml.cs file. The following example shows how you can do this. // Assign the lens example URI-mapper class to the application frame. RootFrame.UriMapper = new LensExampleUriMapper(); This code assigns the LensExampleUriMapper class to the UriMapper property of the app frame. Don’t modify any of the existing code in the InitializePhoneApplication method; add only the UriMapper assignment, as shown in the following example.; // Assign the lens example URI-mapper class to the application frame. RootFrame.UriMapper = new LensExampleUriMapper(); // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Ensure we don't initialize again phoneApplicationInitialized = true; } When the app is launched from the lens picker, it assigns the URI mapper during initialization. Before launching any pages, the app calls the MapUri method of the URI mapper to determine which page to launch. The URI that the URI mapper returns is the page that the app launches. See Also Other Resources Photo extensibility for Windows Phone 8 Capturing photos for Windows Phone 8 Additional requirements for specific app types for Windows Phone Lens design guidelines for Windows Phone How to create a base camera app for Windows Phone 8 Advanced photo capture for Windows Phone 8
https://docs.microsoft.com/en-us/previous-versions/windows/apps/jj662936(v=vs.105)
CC-MAIN-2018-17
refinedweb
844
55.13
The logic of my program works. I am having a hard time asking the user "do you want to do another? yes or no." and user would type yes or no, for the scanner class to read as a string. If the user types yes the program will start over if the user says no the program will say " Thanks for playing." I got it to print " Do you want to do another? yes or no" and used a scanner class. However the scanner class is not working. Can anyone help me... THanks in advance. Code Java: import java.util.Scanner; public class test4 { public static void main (String[] args) { Scanner scan = new Scanner (System.in); int userNum, total, addNum = 0, totalNum; String play = "yes"; while ( play == "yes" && play != "no") { System.out.println("Enter a number that is 3 or higher."); userNum = scan.nextInt(); if (userNum >= 3) { for(int count = 3; count<userNum; count +=2) { addNum = addNum + count; } System.out.println("The sum of the ODD integers from 3 to " + userNum + " is " + addNum); System.out.println(" "); System.out.println ("Do you want to do another? yes or no"); play = scan.nextLine( ); } if(userNum < 3) { System.out.println("Error: The value must be greater than two"); System.out.println(" "); } } while (play == "no") { System.out.println("Thanks Good Bye."); } } }
http://www.javaprogrammingforums.com/%20loops-control-statements/11729-loop-help-printingthethread.html
CC-MAIN-2015-22
refinedweb
217
71.1
0.15 2016-09-09 - Fixed command namespace pushing to be limited. 0.14 2016-08-30 - Fixed META_MERGE in Makefile. 0.13 2016-04-01 - Added dependency of Digest::JHash, as there seem to be broken builds of CHI out there (dependencies in CHI are correkt; cpantesters). 0.12 2015-11-14 - Removed smartmatch in tests. - Made dependencies more concrete. 0.11 2015-01-16 - Improve error handling in commands. 0.10 2015-01-16 - Improve documentation regarding precedence of configuration. - Improve config check. - Improve license information in M::P::CHI::chi. - Update year. 0.09 2014-04-20 - Bugfix test suite. 0.08 2014-04-17 - Logging now defaults to application log. - Update requirements. - Added commands. 0.07 2014-04-01 - Update year. - Documentation tweaks on CHI. - Fixed License issue (now coherent Artistic License 2.0; max). 0.06 2013-03-08 - Update year. - Update description. - Documentation tweaks. - Namespaces parameter now set by default (the opposite was deprecated in 0.04). - Improve test suite. - Warn regarding non-unique cache handles. 0.05 2012-12-07 - Fix for never started IOLoops. - Removed IOLoop dependency (reneeb). 0.04 2012-11-26 - Introduced 'namespaces' parameter. 0.03 2012-11-26 - Fixed typo in synopsis (borisdaeppen). 0.02 2012-11-19 - Small improvements on the documentation. 0.01 2012-10-31 - Separation from Sojolicious package. - Initial submission to GitHub. - Initial submission to CPAN.
https://metacpan.org/changes/distribution/Mojolicious-Plugin-CHI
CC-MAIN-2017-30
refinedweb
231
56.01
C plus plus:Modern C plus plus:Vectors Modern C++ : Going Beyond "C with Classes" - Preface - std::vector - RAII - Containers - Iterators - Algorithms - Functors - Binders - Storing Functors - References - Glossary - Appendices Introduction std::vector is perhaps the most widely known and used template ( except maybe for std::string ) in the STL-inspired part of the Standard C++ Library, and for good reason: It's basically an easy-to-use, safe, and fast dynamic array. Easy To Use std::vector includes most of the member functions you'd expect, and with intuitive names. #include <iostream> #include <vector> #include <stdexcept> int main() { // declare a new vector of ints std::vector<int> v; // std::vector keeps track of its size for you // initially there's nothing in it std::cout << "v contains " << v.size() << " elements" << std::endl; // this line does what you'd expect v.resize( 4 ); // we resized to 4, so now size is 4 std::cout << "v contains " << v.size() << " elements" << std::endl; // and you can specify what you want to fill the new elements with, if you want v.resize( 8, 42 ); // only the four new elements are 42 -- resize doesn't change existing elements // thanks to an overloaded operator[], you can use it just like an array for ( std::vector<int>::size_type i = 0; i < v.size(); ++i ) { std::cout << i << "th element is " << v[i] << '\n'; } std::cout << std::flush; // for speed, operator[] doesn't check bounds // for that, use the at member function which can throw try { v.at( 85693 ) = 68; } catch ( std::out_of_range &e ) { std::cerr << "Index out of range: " << e.what() << std::endl; } // std::vectors are very good at adding to the end, // so there's a special function that guarantees // it'll be done in amortized constant time v.push_back( 127 ); // inserting is obviously not as fast, but one line is sure // more convenient that moving and reallocating everything yourself v.insert( v.begin()+1, 2 ); // insert a two before v[1] // you can erase single elements v.erase( v.begin()+2 ); // erase v[2] // or whole ranges v.erase( v.begin()+3, v.end()-2 ); // erase the middle, // leaving only the first 3 and // the last 2 for ( std::vector<int>::size_type i = 0; i < v.size(); ++i ) { std::cout << i << "th element is " << v[i] << '\n'; } std::cout << std::flush; } You end up with the following output: v contains 0 elements v contains 4 elements 0th element is 0 1th element is 0 2th element is 0 3th element is 0 4th element is 42 5th element is 42 6th element is 42 7th element is 42 Index out of range: vector::_M_range_check 0th element is 0 1th element is 2 2th element is 0 3th element is 42 4th element is 127 For a full list of what std::vector can do, check out Roguewave's std::vector documentation. Safe & Fast Much of the time, people new to the Standard C++ Library don't want to use it because they think it's slow and end up using their own solution instead. ( A fairly common form of NIH Syndrome. ) There are a whole bunch of counterarguments for this. - std::vector works and is complete. A custom solution needs to be debugged. - std::vector is written by people that know the compiler very well and often includes optimization tricks that of which most people would never have thought. - std::vector is standard, so many people are already familiar with it. It's also consistant with the rest of the Standard C++ Library. - std::vector is safe. There are well-defined exception-safety guarantees for all of its member functions. If it holds elements that act like they're supposed to, which mostly means obvious things like no exceptions from destructors and copies are equivalent, then there is never a case where an exception can put a std::vector into an unusable state. To illustrate these, I wrote up a fairly simple example. Both of these programs do basically the same thing: add numbers to a dynamic array, one at a time. The first uses a fairly basic append_to_array that you could reasonably expect to find in a custom solution. It works by allocating a new, larger array; copying the elements over; and copying the new element to the end. #include <new> #include <iostream> void append_to_array(long *&array, long &array_size, long what) { long *newarray = new long[array_size+1]; for ( long i = 0; i < array_size; ++i ) newarray[i] = array[i]; newarray[array_size] = what; delete[] array; array = newarray; ++array_size; } int main() { long *v = 0; long v_size = 0; for ( long i = 0; i < 0x10000; ++i ) { append_to_array( v, v_size, i ); } std::cout << "Array size: " << v_size << std::endl; } This second version uses std::vector's push_back member function. #include <vector> #include <iostream> int main() { std::vector<long> v; for ( long i = 0; i < 0x1000000; ++i ) { v.push_back(i); } std::cout << "Vector size: " << v.size() << std::endl; } The second version is easier to read and the author got it right on the first try. For the first one, he initially forgot to pass array_size by reference, forgot to delete the old array, and forgot to initialise v and v_size to 0. Also, append_to_array is only fine for non-throwing types -- it's untemplated it because it'll leak memory if a copy assignment fails. The most effective point, however, is the speed one: $ time ./dynarray_new Array size: 65536 real 0m25.149s user 0m16.129s sys 0m7.784s $ time ./dynarray_vector Vector size: 16777216 real 0m0.421s user 0m0.288s sys 0m0.128s The std::vector version builds its array 256 times larger, and yet is roughly 60 times faster. ( If you're wondering how it manages this, look in the next section. ) More Nice Things One fact of life in C++ is that, unfortunately, you can't always use C++ libraries. Most libraries have a C interface, which might make you think that you can't use std::vector -- it's a templated class in a namespace and C has neither templates, classes, nor namespaces. Luckily, the elements in a std::vector are guaranteed to be stored contiguously in memory. In other words, given std::vector<T> v; and std::vector<T>::size_type i, then it's guaranteed that for all i < v.size(), &v[i] == &v[0]+i. If you're confused by the math-talk, the important things about that is that you can treat the address of the first element of your array like a pointer to the first element of a normal array: #include <iostream> #include <vector> #include <cstring> int main() { std::vector<char> v(256, '\0'); std::strncpy( &v[0], "Hello World!", v.size()-1 ); std::cout << &v[0] << std::endl; } This trick is extremely useful for storing the pixels in an image, for example, since you can then pass it to something like glTexImage2D. Of course, please prefer std::string to std::vector<char>, this is just a nice example since it gives readable output. This trick is, however, still useful because unlike std::string's c_str() member function, you are allowed to write to the std::vector through the pointer. In Closing If you remember nothing else from this series, remember std::vector. You can use it in almost any program and it'll make your code shorter, easier to understand, and quite possibly faster. What's Next Having a class that can clean up after itself automatically turns out to be an idiom with much wider applicability than just memory. RAII can be used to handle all resources in a safe, consistent manner.
http://content.gpwiki.org/index.php/C_plus_plus:Modern_C_plus_plus:Vectors
CC-MAIN-2014-52
refinedweb
1,259
60.45
Sometimes, people want to compute a discrete Fourier transform (DFT) where only a subset of the outputs are needed, and/or conversely where only a subset of the inputs are non-zero. Fast algorithms to compute this are, in general, known as "pruned" FFTs. Unfortunately, the performance gains in general from pruned FFTs are quite modest. If you have a transform of size N where only K outputs are desired, the complexity is in general O(N log K), vs. O(N log N) for the full FFT, thus saving only a small additive factor in the log. (Similarly for K nonzero inputs.) This is discussed in more detail by the references at the end. In principle, the arithmetic count can be reduced (however slightly) whenever K < N, simply by discarding (pruning) unused operations from an ordinary FFT. Turning these arithmetic gains into actual performance improvements is much more difficult, however. The problem is that optimizing an FFT requires a lot of effort, and is not just a matter of minimizing arithmetic cost on modern computers. By implementing a pruned FFT, you are gaining a small factor in the log, but you are sacrificing a significant part of the effort that went into optimizing full FFTs (even if you use an optimized FFT as a subroutine), and the latter can easily outweigh the former. Because of this, I would not recommend bothering to consider a pruned 1d FFT unless you want 1% of the outputs or fewer (and/or if 1% or fewer of your inputs are nonzero). The most common case where people seem to want a pruned FFT is for zero-padded convolutions, where roughly 50% of your inputs are zero (to get a linear convolution from an FFT-based cyclic convolution). Here, a pruned FFT is hardly worth thinking about, at least in one dimension. In higher dimensions, matters change (e.g. for a 3d zero-padded array about 1/8 of your inputs are non-zero, and one can fairly easily save a factor of two or so simply by skipping 1d sub-transforms that are zero). Another possibility, of course, is to simply use the naive DFT formula or the Goertzel algorithm, both of which have O(N K) complexity. These methods have the added advantage of only requiring O(K) storage if the N inputs are computed or read on the fly (a huge advantage in some applications). However, they are also generally less accurate than FFT-based methods when implemented in finite-precision floating-point arithmetic — the naive formula and Goertzel's algorithm have error bounds that grow as O(N3/2) and O(N5/2), respectively, compared to O(log N) for the FFT. The minimum K at which a pruned FFT becomes faster will depend upon the context, but we have observed benefits below from a pruned FFT (compared to Goertzel) for K as small as 10 with N of 105 (where Goertzel is orders of magnitude less accurate). FFTW does not currently implement any general pruned FFT algorithm. However, in principle one can easily implement a pruned FFT algorithm on top of FFTW, and we describe the simplest such case below. Another case that we experimented with once in the past is 3d FFTs with sparse inputs/outputs; you can see some sample code that we wrote for that at. An important special case where one can easily achieve O(N log K) complexity is where one wishes to compute only the first K outputs of a DFT, where K divides N. In this case, one simply computes N/K FFTs of size K, with stride N/K in the data, and then combines the output by summing with appropriate phase ("twiddle") factors. Essentially, you are performing "by hand" a single radix-K decimation-in-frequency Cooley-Tukey step, where you only compute one size-K block of the output. (The dual problem is where only the first K inputs are non-zero, in which case you essentially just reverse these steps.) More generally, if you want an arbitrary subset of K outputs, you would compute N/K FFTs of size K as below, and then each output is one output of a DFT of size N/K, premultiplied by twiddle factors. This general case is not implemented below, however. In principle, to gain maximum possible arithmetic savings, you should notice when you are computing more than one output of a given size-N/K DFT, and use a pruned FFT recursively, but this is much more complicated to implement and the practical gains are doubtful in general. More simply, you would just compute each output using the naive DFT formula with O(N/K) operations for each of the K outputs in the last step. (In the special case, below, where you want the first K outputs of the DFT, you are computing only the 0th output of each size-N/K DFT, and no additional pruning is possible.) Note: the code below will often only yield substantial gains over the normal FFTW if K is much smaller than N (ideally by a factor of 100 or more, depending on your machine/compiler). Below is an outline of code to do this with FFTW3's complex FFT, operating out of place. Here, for simplicity, we assume that C99's complex.h header is available so that we can use complex arithmetic in C. #include <math.h> #include <complex.h> #include <fftw3.h> { int i, j; const double TWOPI = 6.2831853071795864769252867665590057683943388; fftw_complex in[N], out[N], twids[(K-1)*(N/K-1)]; fftw_plan plan; /* plan N/K FFTs of size K */ plan = fftw_plan_many_dft(1, &K, N/K, in, NULL, N/K, 1, out, NULL, 1, K, FFTW_FORWARD, *only* first K outputs, in out[], to values for full size-N DFT: */ for (j = 1; j < N/K; ++j) { out[0] += out[j*K]; for (i = 1; i < K; ++i) out[i] += out[i + j*K] * twids[(j-1)*(K-1) + (i-1)]; } fftw_destroy_plan(plan); } Notice that, while the inputs are transformed with stride N/K, the outputs have stride 1, so that each size-K sub-transform is stored as a contiguous length-K chunk in out. This is convenient because it allows us to overwrite the first size-K chunk, in-place, with the desired output (and is essentially what FFTW normally does internally for radix-K DIF). Other data arrangements could be devised, of course. Of course, further optimizations are possible. You may want to plan with FFTW_MEASURE instead of FFTW_ESTIMATE if you are computing many FFTs. You probably also want to allocate the input/output arrays with fftw_malloc to ensure correct alignment and to avoid limitations on the stack size. Many games can be played with how the twiddle factors are computed (e.g. they can be stored in the order that they are used to improve locality). We should also comment on the floating-point accuracy. For K = 1, the above algorithm is exactly the naive DFT, with the same floating-point accuracy. In general, then, for K much smaller than N, the accuracy of this code is worse than that of the full FFT, and approaches (from below) the error of the naive DFT formula. The accuracy could be improved by a number of techniques, quite possibly with negligible computational cost (e.g. by cascade summation), albeit with more code. Now, if you really have complex data, then you probably want the K lowest positive and negative frequency amplitudes, where the negative frequencies are located at N-k (for k=1..K-1) because of aliasing. This can be accomplished by replacing the final loop above with: /* set *only* first K outputs and the last K-1 outputs, in out[], to values for full size-N DFT: */ out[0] += out[N - K]; for (i = 1; i < K; ++i) { fftw_complex o0 = out[i], oN = out[(N - K) + i]; out[i] = o0 + oN * twids[(N/K-2)*(K-1) + (i-1)]; out[(N - K) + i] = o0 + oN * conj(twids[(N/K-2)*(K-1) + (K-i-1)]); } for (j = 1; j < N/K - 1; ++j) { out[0] += out[j*K]; for (i = 1; i < K; ++i) out[i] += out[i + j*K] * twids[(j-1)*(K-1) + (i-1)]; for (i = 1; i < K; ++i) out[(N-K) + i] += out[i + j*K] * conj(twids[(j-1)*(K-1) + (K-i-1)]); } This code is a little more complicated, but the basic idea is the same. The only difference from before is that we generate two size-K blocks (minus one point) of the Cooley-Tukey output instead of one. (Here, the first loop is separated so that we can continue to operate in-place on out[].) An even more common case is where you have real inputs, and you want only the first K amplitudes of the DFT output. (Here, because of the conjugate symmetry, there is no need to distinguish positive and negative frequencies.) #include <math.h> #include <complex.h> #include <fftw3.h> { int i, j; const double TWOPI = 6.2831853071795864769252867665590057683943388; double in[N], out1[N]; fftw_complex out[K], twids[(K-1)*(N/K-1)]; fftw_r2r_kind kind = FFTW_R2HC; fftw_plan plan; /* plan N/K FFTs of size K */ plan = fftw_plan_many_r2r(1, &K, N/K, in, NULL, N/K, 1, out1, NULL, 1, K, &kind, K elements of out[] to first K outputs of full size-N DFT: */ out[0] = out1[0]; for (i = 1; i+i < K; ++i) { double o1 = out1[i], o2 = out1[K-i]; out[i] = o1 + I*o2; out[K-i] = o1 - I*o2; } if (i+i == K) /* Nyquist element */ out[i] = out1[i]; for (j = 1; j < N/K; ++j) { out[0] += out1[j*K]; for (i = 1; i+i < K; ++i) { double o1 = out1[i + j*K], o2 = out1[K-i + j*K]; out[i] += (o1 + I*o2) * twids[(j-1)*(K-1) + (i-1)]; out[K-i] += (o1 - I*o2) * twids[(j-1)*(K-1) + (K-i-1)]; } if (i+i == K) /* Nyquist element */ out[i] += out1[i + j*K] * twids[(j-1)*(K-1) + (i-1)]; } fftw_destroy_plan(plan); } This is essentially the same as the very first case above, except that it takes into account that the sub-FFTs were of real data and so have conjugate-symmetry ("halfcomplex") output. In this case, it is more difficult to compute the final output in the same array as the sub-FFT outputs, so we instead store the result in a separate complex array out[K], while using an auxiliary real array out1[N] for the outputs of the sub-FFTs. Again, in realistic code you would probably allocate the arrays with fftw_malloc instead of on the stack. Various optimizations and other variations are possible, as before. The above code does not exploit SIMD instructions, even for the FFTW sub-transforms, because it uses FFTW's r2r interface. To exploit SIMD for the sub-tranasforms, you should change it to the r2c interface (which involves a different output format).
http://www.fftw.org/pruned.html
CC-MAIN-2014-52
refinedweb
1,837
55.68
Lesson 13 - Structures in the C language C and C++ The C language Basics Structures in the C language In the previous lesson, Functions in the C language, we learned how to declare custom functions in the C language. In today's tutorial, we'll learn to use another important feature of the C language which is structures. Since we're only going to create a simple program, we won't use custom functions today. Just remember if it was just a little bit longer, we really would need to split it into separate functions. Storing complex items Consider that we want to store data for a single user. He/she has a name, an age, and lives on a certain street. Using our current knowledge, we'd create multiple variables: int main(int argc, char** argv) { char name[] = "John Smith"; int age = 33; char street[] = "Skew street 5"; return (EXIT_SUCCESS); } However, we usually don't store a single user in a program. As we already know, we use arrays to store multiple items of the same type. However, since the user contains values of 3 different types, we'd have to create 3 different arrays. One for names, the second one for ages, and the third one for streets. Let's create several arrays which are 10 elements long (for storing a maximum of ten users). We'll demonstrate their functionality by storing 2 users and printing them to the console using a for loop. #include <stdio.h> #include <string.h> int main(void) { char names[10][51]; int ages[10]; char streets[10][51]; strcpy(names[0], "John Smith"); ages[0] = 33; strcpy(streets[0], "Skew street 5"); strcpy(names[1], "Jack Brown"); ages[1] = 28; strcpy(streets[1], "Sunnyvale 8"); int i; for (i = 0; i < 2; i++) { printf("The user at the index %d\n", i); printf("Name: %s\n", names[i]); printf("Age: %d\n", ages[i]); printf("Street: %s\n\n", streets[i]); } return 0; } The result: Console application The user at the index 0 Name: John Smith Age: 33 Street: Skew street 5 The user at the index 1 Name: Jack Brown Age: 28 Street: Sunnyvale 8 The program looks pretty impressive considering our skills at this point. Once we learn to store data to files, we could program e.g. a phone book like this. Despite all that, the code above isn't ideal. Let's take note of several things here. The definition of the names and streets arrays is interesting. Since we need to have a char array (name) in every item of the names array, we have to create a variable which is technically an array of arrays. Therefore, there are two pairs of brackets. In the first brackets, we have specified the number of items of the outer array, i.e. the number of names. In the second pair of brackets, we have the number of characters in each name. In our case it's 50 characters (+1 for \0). As we already know, we can't assign string constants in the C language in any different way other than during the initialization. This is why we have to use the strcpy() function which copies a string into an existing variable. Printing using a loop should be clear, we're simply working with indexes < 2 since we don't have any more people at the moment. Structures To avoid declaring so many confusing arrays, the C language allows us to declare a structure. Simply put, it's a data type which is represented by a single variable, but contains multiple values (it's sometimes called a record type). It may remind you of an array, but it's items don't have to all be of the same type and they're not accessed by numbers. Instead, they're accused by their names. The best decision we could currently make is to create a USER structure in order to store users. Add the following definition somewhere into the global scope above the main() function: typedef struct { char name[51]; int age; char street[51]; } USER; Although there are multiple ways to declare structures, as it often happens in the C language, we'll stick strictly with this one. We'll define structures as new data types using the typedef keyword which will help us with declaring variables of that type (USER) later on. Then the struct keyword follows. We declare items for the structure in the curly brackets block as ordinary variables. We name structures with UPPERCASE_LETTERS and end the whole declaration with a semicolon. Now, let's rewrite the main() function to the following form: #include <stdio.h> #include <string.h> typedef struct { char name[51]; int age; char street[51]; } USER; int main(int argc, char** argv) { USER users[10]; strcpy(users[0].name, "John Smith"); users[0].age = 33; strcpy(users[0].street, "Skew street 5"); strcpy(users[1].name, "Jack Brown"); users[1].age = 28; strcpy(users[1].street, "Sunnyvale 8"); int i; for (i = 0; i < 2; i++) { printf("The user at the index %d\n", i); printf("Name: %s\n", users[i].name); printf("Age: %d\n", users[i].age); printf("Street: %s\n\n", users[i].street); } return 0; } The whole application is way more readable now. It simply contains a single array of the USER type instead of 3 arrays as before. We use the . (dot) operator to access structure items. If we used structures dynamically (which we can't quite yet), we would use the arrow operator ( ->). We'll explain all of this further along in the course. Alternative structure definitions Just for completeness' sake, let's go over other ways to create structures. Mainly, to enable you all to read programs by other programmers. If we created a structure without the typedef keyword, we'd name it as a lowercase_name: struct user { char name[51]; int age; char street[51]; }; We'd have to provide the struct keyword for declaring variables of this type from then on: struct user users[10]; Sometimes, a structure is even defined directly with a variable: struct { char name[51]; int age; char street[51]; } users[10]; Consider this last example as a rather deterrent code. Just because it's a little bit shorter doesn't always mean it's clearer. Furthermore, we can't use this sort of structure at multiple places in our program. Note: Of course, we don't have to use structures all as arrays. They're an ordinary data type just like int. However, they increase readability, so be sure to use it everywhere where you need to store multiple values which are related to each other. Note: Aside from structures, we can also declare so-called unions in the C language. Unions look the same as structures but variables of the union type can only have one of their items (values) initialized. Meaning that each user could only have either a name, an age, or a street address. This doesn't make much sense with users, however, it may sometimes happen that we need to store items and each item is a bit different. However, unions didn't become very popular because it gets troublesome to determine which of the values is initialized (therefore, they're often wrapped in structures). All in all, we won't deal with unions here. We'll get back to structures once more throughout our courses. The source code for today's application is available for download below the article. At this point, you have now finished the introductory course into the C language. Congratulations, you're now aware of most of its constructs! Of course, we'll continue, there are more exercises for you to practice, and then your journey shall continue in the Dynamic memory management in the C language course. There, you'll learn how to allocate memory dynamically, and no longer be limited by the lengths of static arrays. Since these matters are a bit complicated, the whole basics course avoided said constructs so you could try different, simpler C constructs while you get warmed up. I look forward to seeing you all soon. There, we'll create real-world applications! No one has commented yet - be the first!
https://www.ict.social/cplusplus/c-language/basics/structures-in-the-c-language
CC-MAIN-2017-30
refinedweb
1,381
72.26
With the shipment of the AudioWorklet feature in Chrome 64, it’s probably reasonable to say 2018 was a good year for the Web Audio API. Nearly a year later after its release, there are still relatively few examples outside of the resources at Google Chrome Labs and dsp.audio for developers to draw from. These serve as great introductions to the interface, but with relatively few user-created examples to learn from, we’re left to our own devices when figuring out how to implement it out in the wild. The reality is, the task of getting AudioWorklets to play nice with React and other UI frameworks isn’t as straightforward as it might seem. The aim of this article is to show programmers already familiar with the Web Audio API how they can connect AudioWorklets to a React interface. For more info on the AudioWorklet specification, see the links at the very bottom of this article. Background As a conservatory-trained musician entering the world of software engineering and DSP via computational musicology, I was (and still am) giddy at the prospect of creating web interfaces with a dedicated audio rendering thread. In short, upon hearing the news, I was ready to blast off! I fired up create-react-app, copied some examples from Chrome Labs, and ran yarn start only to receive the following error: Failed to compile. ./src/worklet/worklet-node.js Line 2: 'AudioWorkletNode' is not defined no-undef Is my version of Chrome outdated? It’s not? Why is AudioWorkletNode undefined? Thankfully Dan Abramov was quick to relieve my confusion on StackOverflow (thanks, Dan!): Create React App is configured to enforce that you access browser APIs like this with a window.qualifier. This way it's clear you're using a global and didn't forget to import something (which is very common). This should work: class MyWorkletNode extends window.AudioWorkletNode { (In the future releases, ESLint will be aware of this global by default, and you will be able to remove window.) Ok, no big deal! We should be good now, right? Not quite. Trying to load my AudioWorklet processor using context.audioWorklet.addModule() threw the vaguest, most damning error no developer would ever want to come across: DOMException: The user aborted a request. Back to StackOverflow I went. John Weisz at AudioNodes pointed out that this error may be a bug in the Chromium module loader: …it parses the worklet/processor.jsfile by removing whitespace, which in turn causes it to have JavaScript syntax errors everywhere, which then finally causes this generic non-explanatory error message to show up. He went on to suggest serving the module with specified headers Content-Type: application/javascript. I didn’t know where or how to specify AudioWorklet content headers, so I took a long break from AudioWorklets with the hopes that more examples would pop up over time. 7 Months Later: An Unexpectedly Simple Solution Serve your AudioWorklet processors from the public folder. Just do it. I was fiddling around and discovered that the addModule('path/to/your/module') method points there by default. No imports, no requires, no {process.env.PUBLIC_URL}/my-worklet-processor needed. With all that behind us, it would be a great exercise to port the four audio processing demos from Google Chrome Labs to React: the Bypasser, One Pole Filter, Noise Generator, and BitCrusher. If you’re impatient and want to dig into the entire codebase immediately, the link to the GitHub repo is listed at the very bottom. Simply clone it, install dependencies with yarn install, and run the app with yarn start . In the following walkthrough, we’ll create a dead simple UI over create-react-app boilerplate code. We’ll work with Ant Design components and gain familiarity with AudioWorklets by making slight modifications to each processor to accept data via the messagePort to toggle it on or off. The user will be able to choose between the four audio processing demos from a drop-down menu. We’ll stick a button next to the drop-down which will toggle the current node on and off. That’s it! If you want to see the demo in action, click the link to the left (it’s above if you’re viewing on mobile). Below is a broad overview of the project we are going to create. Directories and files we are adding to create-react-app boilerplate are bolded and italicized with neighboring descriptions. | — README.md | — package.json | — public | | — favicon.ico | | — index.html | | — manifest.json | ` — worklet /*Contains AudioWorkletProcessors*/ | | — bit-crusher-processor.js | | — bypass-processor.js | | — noise-generator.js | ` — one-pole-processor.js | — src | | — App.css | | — App.js /* Main UI */ | | — App.test.js | | — Demos.js /*Functions that interface with the processors*/ | | — index.css | | — index.js | | — logo.svg | — serviceWorker.js | — yarn.lock The Barebones UI Step 1: create-react-app react-audio-worklet Step 2: Install dependencies. In this case, we’re just using one package for the UI, so go ahead and run the command yarn add antd. Make sure to import 'antd/dist/antd.css' into index.js. Step 3: Bring in the necessary components to create a drop-down menu and set up the initial state: Module Selection/Loading and Audio Toggling Step 1: Keeping separation of concerns in mind, let’s include callbacks to trigger the audio demos from a separate file called Demos.js: Step 2: Create AudioWorklet processers in public/worklet: Note: Like the demos, these are practically the Chrome Team’s code verbatim with the slight modification of binding the port’s onMessage function to the AudioWorkletProcessor for better readability. Step 3: Now we’ll create methods in App.js to handle the selection/loading of processor modules, as well as toggling playback of the currently selected module: Before we forget, let’s import Demos.js into the main app. Your final App.js should now read as follows: Now go ahead and run yarn start and listen to those demos. Hear that? That’s the sweet sound of Web Audio processing on its own dedicated rendering thread! Conclusion I hope this article has clarified how to avoid some common hiccups that many may encounter when trying to integrate AudioWorklets into React. I also hope it has helped in gaining familiarity in using the Worklet API itself. The Chrome WebAudio team has introduced powerful technology to the web platform with AudioWorklets — and with WebAssembly on the rise, the future of DSP on the web is looking bright. Links The AudioWorklet Interface About the Author Nathan Bloomfield is a conservatory-trained musician who collided with the world of software engineering and DSP via computational musicology. LinkedIn | Instagram | Twitter | bloom510.art
https://hackernoon.com/implementing-audioworklets-with-react-8a80a470474?source=rss----3a8144eabfe3---4
CC-MAIN-2019-35
refinedweb
1,116
54.83
Parsing command line options in JDK 5.0 style: args4j Parsing, but I didn't quite like any of those. I felt that I can write a better one by taking advantanges of JDK 5.0 features. That eventually became args4j. With args4j, you first write a Java class that represents all the options that you are going to define. I call this class an option bean (although it doesn't have to be a Java Bean), and it can look like this:. - Login or register to post comments - Printer-friendly version - kohsuke's blog - 35936 reads Hi, is there any way for using multiple beans in CmdLine ... by timofey - 2013-05-20 13:33 Hi, is there any way for using multiple beans in CmdLine parser ? I have set of tools that share different option subsets with each other. so I want something like this: 4 beans (each for own option set), tool 1 uses options from beans 1 and 2, tool 2 uses beans 2 and 3, tool 3 uses beans 1,3,4, etc. But I do not want to copy-paste option definition and getters from one tool to another. Instead I'd like to have something new CmdLineParser(Object[] beans), or new CmdLineParser(Collection<?> beans) or aggregate needed beans into a tool specific one: class Tool3Bean { Bean1 bean1; Bean3 bean3; Bean4 bean4; } new CmdLineParser(new Tool3Bean()) Im diggin out a corpse with this but i think you would like ... by StudyBudy - 2012-05-08 04:09 Im diggin out a corpse with this but i think you would like to know that im "forced" to use your this tool by my Professor on a German University! How to validate arguments by kajkandler - 2010-10-06 07:19I have a command lien syntax that includes commands, which I interpret as arguments. How can I define such a thing. If I annotate a property as Arguments(), I can't validate for valid arguments. If I annotate a setter method for the arguments, I get an error no OptionHandler set for List, the arguments format. What is the thing to do here? Is there a user list/discussion forum? by kajkandler - 2010-10-06 07:16Hi, I'm using this lib and I have some questions. Is t there a user mailing list or a forum that discussed the lib? Or is this the place to ask questions? How to exclude -D args from being handled by tiburblium - 2010-09-21 10:53Greetings, Is there an elegant way to exclude specific options from being handled? For example: public class StartupOptions { @Option(name="-a", usage="Option A") private boolean optionA; @Option(name="-df",usage="Option DF") private boolean optionDF; } startupOptions = new StartupOptions(); CmdLineParser parser = new CmdLineParser(startupOptions); parser.parseArgument(args);I want to ignore some params such as: -Dcom.sun.management.jmxremote.port=1099 or -Dcom.sun.management.jmxremote.authenticate=false etc... Is there a good way to handle this in the startupOptions class? Thanks alive? by karenin - 2010-03-16 03:56Is the project still active? I need some additional functionality but as I can see in the issue tracker there are some other unanswered issues too. Does it make sense to send additional patches or rather I should fork the project? I still use args4j in many by kohsuke - 2010-03-16 10:06 I still use args4j in many of my projects. If you have patches, send them in!
https://weblogs.java.net/blog/kohsuke/archive/2005/05/parsing_command.html
CC-MAIN-2014-15
refinedweb
573
72.56
I get many dm's from dev's asking me how to get started with web3, hear such questions on twitter spaces and see the conversations on discord. It looks like so many developers are interested in the space. If you are one of them, you're at the right place! In this post, I'll first try to explain the basics of web3 applications to provide an outline and then guide you through creating your dApp frontend with React. Please note: In this article, we will be referring to dApp's on the Ethereum blockchain. A dApp is just like any software application- any website or phone app. The difference is that the backend code runs on a decentralized network such as a peer to peer network or a blockchain. So an application on Ethereum is a dApp. Since the backend code(smart contracts) of a dApp is on a decentralized network, the dApp is free from control and can not be modified/removed by a centralized source. Developers and creators can trust the underlying infrastructure without worrying about being terminated or censored. Once a smart contract is deployed to the Ethereum network, no one can change it. Therefore, users can trust how it will work since even the person deploying the contract can't change it. All the smart contracts on Ethereum are public and accessible; it's an open-source ecosystem. This open-source nature allows for composability, so this means that you can re-use parts of the codes from others. You can look at all the smart contracts from Etherscan; here is an example smart contract. A dApp only implies that the backend code(smart contract) is on a decentralized network. It's important to note that not all of the components of the application have to be decentralized. For example, the application developers decide where the frontend is hosted and where app data is stored. The decentralized world advocates for making the entire technology stack decentralized and is building it right now! Today the most popular categories for dApp's are gaming, financial services and digital goods. Here are some popular dApp's on the Ethereum blockchain: There are probably more categories that we have not even discovered yet. With most dApp's your cryptocurrency wallet is your first sign in. (Yay! No more username and passwords or connecting with other social media accounts.) You basically need a cryptocurrency wallet and ETH-which is the native currency for the Ethereum blockchain. The wallet enables you to connect to the network and create a transaction, and you need the ETH to pay for the transaction. A dApp consists of a backend (smart contract) and a frontend user interface in the most basic form. The frontend is the client-side, and the backend is the server-side of the application. The backend of the dApp is the smart contract. Smart contracts are self-executing computer programs stored inside the blockchain, on Ethereum they are all open and accessible. You can look at them from Etherscan; here is an example of a smart contract. Another important note on smart contracts is that no one can change it once a smart contract is changed. Solidity is one of the most popular smart contract languages for Ethereum. The frontend of the dApp can be written in any language that can talk to the backend. The frontend can then be hosted on a centralized service or a decentralized service. In short, dApps are applications with a backend on a decentralized platform and a frontend that connects to it. To use a dApp, you need a cryptocurrency wallet and some cryptocurrency. In this project we will be creating a react project and connecting to our crypto wallet which is our interface to the blockchain. Please note: This project is only for the frontend of the application. When we want to add the backend piece we will need an Ethereum development environment. Hardhat and Truffle are popular Ethereum development environments. Additionally, to deploy the application to the network we would need to use a blockchain developer platform such as Alchemy or Infura . Create a project folder and setup a react app npx create-react-app edas-dapp cd edas-dapp npm start Install the ethers.js libary with npm: npm install ethers with yarn: yarn add ethers The following code creates a button that the user can click which will prompt the user to connect to Metamask wallet. I have added the comments to explain what's going on. Add the following code to App.js. const App = () => { //state variable to store user's public wallet const [currentAccount, setCurrentAccount] = useState(""); // check wallet connection when the page loads const checkIfWalletIsConnected = async () => { // access to window.ethereum const {ethereum} = window; //check if user has metamask if(!ethereum) { alert("Make sure you have metamask"); return; } //get the wallet account const accounts = await ethereum.request({method: 'eth_accounts'}); //get the first account if(accounts.length !== 0){ const account = accounts[0]; console.log("Found account:", account); //set the account as a state setCurrentAccount(account); } else{ console.log("No account"); } } // connect to wallet const connectWallet = async () => { try { // get the wallet const {ethereum} = window; // there is no wallet extension if(!ethereum) { alert("Opps, looks like there is no wallet!"); return; } const currentNetwork = ethereum.networkVersion; console.log("Current network", currentNetwork); // request access to account const accounts = await ethereum.request({ method: "eth_requestAccounts"}); //set the account in the state setCurrentAccount(accounts[0]); } catch( error){ console.log(error); } } //run function checkIfWalletIsConnected when the page loads useEffect(()=> { checkIfWalletIsConnected(); }, []); //connect to wallet const walletNotConnected = () => ( <button onClick={connectWallet} Connect to Wallet </button> ); //wallet connected const walletConnected = () => ( <div> <p>Connected to the wallet</p> </div> ); return ( <div className="App"> <div style={{display: 'flex', justifyContent:'center', height: '50px'}}> {currentAccount === "" ? walletNotConnected() : walletConnected()} <br /> </div> </div> ); }; export default App; Now the following code will connect to the latest active network. So if the user was on the Ethereum Mainnet it will connect to Ethereum, if the user was on the Rinkeby Test Network it will connect to that. However, in many cases we need to the user to connect to a certain network. You can check to see which network the user is connected to and prompt the user with a message to change the network they are on. Modify connectWallet in App.js as below. const connectWallet = async () => { try { const {ethereum} = window; if(!ethereum) { alert("Opps, looks like there is no wallet!"); return; } const currentNetwork = ethereum.networkVersion; console.log("Current network", currentNetwork); //check which network the wallet is connected on if(currentNetwork != 4){ // prompt user with a message to switch to network 4 which is the rinkeby network on metamask alert("Opps, only works on Rinkeby! Please change your //network :)"); return; }; const accounts = await ethereum.request({ method: "eth_requestAccounts"}); setCurrentAccount(accounts[0]); } catch( error){ console.log(error); } } A better way to do this is to directly prompt the user with the request to switch the network. Instead of asking the user to change the network they are connected on. Change the if statement with the following lines. // request to switch the network const tx = await ethereum.request({method: 'wallet_switchEthereumChain', params:[{chainId: '0x4'}]}).catch() if (tx) { console.log(tx) } By default Chain 4 is already defined in Metamask. You can also prompt the user to add a new network which is not already defined. Here is how you can add the Avalanche network. Add the following piece of code just before requesting access to the account. // define avax network values const avax_mainnet = [{ chainId: '0xA86A', chainName: 'Avalanche Mainnet C-Chain', nativeCurrency: { name: 'Avalanche', symbol: 'AVAX', decimals: 18 }, rpcUrls: [''], blockExplorerUrls: [''] }] // request to add the new network const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:avax_mainnet}).catch() if (tx) { console.log(tx) } 🎉 There you go; that's how you can use a crypto wallet in your app! The next step would be to connect to the smart contract and do some cool stuff such as mint you nft, swap tokens etc. Overall, it's good to know some js and html to put together a well-tailored frontend for your application. If you have any questions, do drop them below or reach out to me on Twitter!
https://eda.hashnode.dev/intro-to-dapps-create-your-dapp-frontend-withreact
CC-MAIN-2021-49
refinedweb
1,361
56.66
Brute-force scan for rectangular cuts Project description ahoi (A Horrible Optimisation Instrument) This module contains a few python functions to run Brute-force scans for rectangular cut optimization. Installation To install ahoi run python3 -m pip install [--user] ahoi Use --user if not in a virtual environment or conda environment. It's recommended to use python3, but currently python2 is also supported. Example The basic functionality uses a masks_list which is a list of lists or a list of 2D numpy arrays that represent pass flags for selection criteria. For example, the following represents pass flags for the criteria >0, >0.1, >0.2, ..., >0.9 for 5 random uniform variables in 10000 events: import numpy as np np.random.seed(42) x = np.random.rand(10000, 5) masks_list = [[x[:,i] > v for v in np.linspace(0, 0.9, 10)] for i in range(x.shape[1])] To count all matching combinations for all criteria on each variable run import ahoi counts = ahoi.scan(masks_list) The entry [0, 1, 2, 3, 4] of counts will contain the number of matching events where the first column of x is >0, the second one >0.1, the third one >0.2 etc. >>> counts[0, 1, 2, 3, 4] 3032 >>> np.count_nonzero((x[:,0] > 0) & (x[:,1] > 0.1) & (x[:,2] > 0.2) & (x[:,3] > 0.3) & (x[:,4] > 0.4)) 3032 You can also pass weights weights = np.random.normal(loc=1, size=len(x)) counts, sumw, sumw2 = ahoi.scan(masks_list, weights=weights) The arrays sumw and sumw2 will contain the sum of weights and sum of squares of weights for matching combinations. The sum of squares of weights can be used to estimate the statistical uncertainty on the sum of weights ($ \sigma = \sqrt{\sum w_i^2}$). >>> sumw[0, 1, 2, 3, 4] 3094.2191136427627 >>> np.dot( ... (x[:,0] > 0) & (x[:,1] > 0.1) & (x[:,2] > 0.2) & (x[:,3] > 0.3) & (x[:,4] > 0.4), ... weights ... ) 3094.219113642755 >>> np.sqrt(sumw2[0, 1, 2, 3, 4]) 78.5528532026876 >>> np.sqrt( ... np.dot( ... (x[:,0] > 0) & (x[:,1] > 0.1) & (x[:,2] > 0.2) & (x[:,3] > 0.3) & (x[:,4] > 0.4), ... weights ** 2 ... ) ... ) 78.55285320268761 Tutorial/Notebook Have a look at the examples for a tutorial that explains how to use this for solving a classification problem. Tests/Coverage Run the tests and coverage report inside the project directory with python3 -m pytest --cov=ahoi --doctest-modules coverage html Project details 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/ahoi/
CC-MAIN-2021-25
refinedweb
433
69.38
>>:What will he be doing at DropBox? (Score:5, Informative) AFAIK he was working on the Python part of Google App Engine, in particular the NDB [google.com] API. He has also developed Mondrian, a code review tool that was partially open sourced as Rietveld. [google.com] (Not a Google employee, so just going by public knowledge here) Big Question? (Score:5, Insightful) Re:Big Question? (Score:5, Insightful) Only when you already have it. Which, to be fair, he likely does. Re: (Score:2, Funny) As is my wife. Re: (Score:2) Money is severely over-rated as a driver. As is my wife. Just drive with your other hand, then. Re:Big Question? (Score:4, Insightful) He's a hacker. Maybe he wants to work for a technology company instead of an advertising company. FUD, and more FUD (Score:5, Insightful) Best I'm aware, Python was important for Google long before Guido got hired by Google. He was the cherry on the pie, if anything. As such, it means absolutely nothing for Google, bar that they lost someone who they may have wanted to keep in-house. Re:He Was Fired... (Score:4, Insightful) I work for Google. Let me just say that you're full of shit. First of all, python is just as much in use now as before. Secondly, it will continue to be so. Secondly - fired? Nope. Re: (Score:2) Google replacing Python with Go in large parts of the company. Do you have documentation for that? (I am really interested, because that would be an interesting event). But I don't think Python ever had an important job at Google. I can't even name any of their important projects which are done in Python. Re: (Score:2) ALL old google stuff was done in python. ... You seem pretty bad informed. it means they all get to upgrade to python 3.xxx (Score:2, Funny) and break every script they have Gut reaction? (Score:4, Informative) In my case, was that Google are moving away from Python. Also see the last answer here:- [stackoverflow.com] Perhaps there are some anonymous Googlers out there that are brave enough to comment? Re: (Score:3) AFAIK, nobody ousted Guido from the company, and he was just looking for something new. At Google, Python is popular for all kinds "operations" scripts, eg. scripts that help start up production jobs, or interact with version control systems. For production systems (ie. user-facing systems), it is not popular, since its performance sucks, and python programs are fragile. More complex programs have tons of dependencies, and other teams change dependencies from under you all the time. With a dynamic language l Google Drive and Linux as a motive? (Score:2) There could be more to this story, given the interest from the Linux community. There is an on-going discussion, or rather expression of frustration with Google, going on in the Google groups regarding Google Drive and the lack of support for Linux See here: [google.com] Could that be the reason behind the departure? foolish (Score:3) So... file sharing companies like dropbox are getting litigated out of business and shut down by the feds left and right... and yes, I see pirated shit on dropbox accounts all the time... but Google is poised to be one of the most powerful companies and history... that just seems foolish. Of course, he might know something we don't... Re: (Score:2) Re: (Score:2) You're not getting it. They are going to get shut down by the feds any day now. Here's an email I just got from them today: That's got "Future MegaUpload" written all over it. Re: (Score:3) Re: (Score:2) I thought it was more ironic that Google has just introduced Drive this year, their own Dropbox replacement. End of Google App Engine? (Score:3) I realize it's only speculation, but that's all we get with Google products. One minute it's a product, the next it's EOL. Or perhaps App Engine stays but the Python support gets phased out in favor of Java. Google products do sometimes lose features over time - the thread on why Google Docs took away table cell merging is a funny read if you get software freedom. Re: (Score:3) AppEngine originally seemed like Java was the first class language and Python was the second class one, then that switched around with Python getting more love and the Java support stagnating. Now they both seem neglected in favour of Go. It wouldn't surprise me if AppEngine becomes Go only at some stage Re: (Score:2) What does it mean? (Score:3) For the language, not much, as no matter where Guido ends up python is still his baby. And even if he got hit by a bus or something the language will continue on without him. What does it mean to Guido? Well only he can answer that but i would imagine he was ready for a change in scenery. I dont think he is in it for the money anymore and doesn't have to work unless he wants to. What does it mean to Google, not much there either, they used it before he got there, and im sure will use it after hes gone.: (Score:2) Re:Python VS PHP (Score:5, Informative) Re:Python VS PHP (Score:5, Informative) Quite right. And don't forget about LAN sync. Dropbox clearly is technically more advanced than Skydrive. The only handicap I see with Dropbox is the lack of some sort of permission system when you share folders. Or at least a read-only setting. Re: (Score:2) Dropbox clearly is technically more advanced than Skydrive. I think I would agree that Dropbox is more technically advanced; however, I would say that Skydrive (for good or ill) is also more ingrained into the Microsoft technology stack. Office 2013, SharePoint 2013, and (I think) Windows 8 have the ability to use it. In Office I think it is the default now which will probably trip a few people when they go to browse for their file and mistakenly saved it on Skydrive instead of their local box. Re: (Score:3) SkyDrive, like SharePoint is just another attempt at Microsoft lock-in. Personally I prefer it when people create suites of products that I *want* to use, not that I *have* to use. The Apple ecosystem is the same. Re: (Score:2) Re: (Score:2) dropbox on windows = a magic folder that just works. not much to be business oriented about it. only problem with it is that it's just not that much free unless you whore ref codes etc. being able to make web links is certainly a plus. the only complaint I have is that shared folders(with others, like a company group) count against your drive space. that sucks bigtime. Re: (Score:2) Yes I know, the fine print says don't use it for anything you wouldn't want to see on the the nightly news, but idiots share commercially sensitive information with it anyway. Re: (Score:2) Perhaps this guy will make it less of a joke. Last I heard you still couldn't revoke Dropbox access from someone you've given it to in the past, even though it gives you the illusion of doing so with a password change page. While that's not as bad as the legendary, but fixed, fuckups in the past of letting people get your stuff without any authentication other than your username, or the even more comical fuckup based on Re:Python VS PHP (Score:5, Funny) I've always loved PHP - it gives flexibity and I just love coding using it. But I know many people love Python too. What's more elegant and nicer in Python than PHP? I've always like skydrive a lot more than dropbox due to it's more lax restrictions. Nothing to do with the programming language whatsoever. I too prefer to skydive rather than program in PHP. Personal preference, I suppose... Re:Python VS PHP (Score:5, Funny) Is that with or without a parachute? Because falling out of an airplane to a grizzy death doesn't sound so bad after you've been programming PHP all day.:Python VS PHP (Score:5, Informative) One word for all you whiny kids today: MFC. Jesus H. I'd rather pull out my teeth. With pliers. Re: (Score:2, Funny) ARRGGH!!! &$ )!$!@$ !@ !!&*(!#@!!!!!!!!! I had forgotten all about MFC, until you had to go bring it up again. I'm sure my lack of memory was due to some form of self-defense by my subconscious. Some things are best left behind, that humanity can move on to enlightenment without having to admit our barbaric past. DAMN YOU! What is wrong with you man? Do you play Justin Bieber recordings in public too? Re:Python VS PHP (Score:5, Funny) ARRGGH!!! &$ )!$!@$ !@ !!&*(!#@!!!!!!!!! Now while writing an entire sharepoint replacement in one line of perl is impressive, it doesn't really constitute a specific argument against MFC. Re: (Score:2) In my day, we used C and sometimes assembler.... no, on second thought, you win. Re: (Score:2) I still write my CGI in C, like everything else. C++? Why? Also: What's a "PHP" or a "VB"? And, isn't COM the same as EXE except for the 64k limit? Re:Python VS PHP (Score:4, Informative) Also: What's a "PHP" or a "VB"? A security exploit. Re: (Score:2) Is that with or without a parachute? Because falling out of an airplane to a grizzy death doesn't sound so bad after you've been programming PHP all day. I take it that you are not a C# programmer? Or maybe you a a Java guy who lost your mind years ago? Not a fractal of bad design (Score:5, Informative) What's more elegant and nicer in Python than PHP? Python isn't a fractal of bad design [veekun.com]. Re: (Score:3, Informative) Every point in that write up has been rebutted. Linking to that over and over doesn't make any of it true. [devshed.com] [ircmaxell.com] from collections import Counter as bag (Score:2) When you say a "bag", how big a bag are you talking? Might it be this bag [wikipedia.org] implemented in Python as collections.Counter [python.org]? Only two warts (Score:2) In defense of PHP, Python and Ruby suck in their own ways too -- plain and simple. Maybe not as much [... See] "Python: teaching kids and biting bits don't mix" by yosefk If the hex() change and the division operator are the only "warts" in Python, then it at least has PHP beat. One of the warts that yosefk complains about (int / int = float) is there just as much in PHP, and unlike Python, PHP doesn't even have a floor division operator. As to the example motivating that article: I deal with binary files in Python, such as tools to manipulate NES programs and data, and the first thing I do 90 percent of the time when loading a binary file is put it in an array.array('B'). Re: (Score:3) How does this Slashdot ecode bug affect Python? (Score:3) Most people working with C-derived languages use some form of block indentation, and large shops usually have coding standards that insist you stick to it rigorously. This means most people already have the tooling in place to enforce indentation Anyway, my point is that code in languages that use braces for blocks can be sent through lossy channels that collapse whitespace and then reconstructed using an automated tool that applies these coding standards you mention [gnu.org]. Inexact division (Score:2) One of the warts that yosefk complains about (int / int = float) That's not a wart. That's how it's supposed to be. How it's supposed to be is int / int = fraction. Doing int / int = float is inexact. Re: (Score:2) In the case of Python, since it's on topic, try recent versions of Python's hex() function for instance. Assume it works like it does for other languages, [...] Why would you assume that? Re:Not a fractal of bad design (Score:5, Funny) In defense of PHP, Python and Ruby suck in their own ways too... That's like saying "In defense of a knife to the eye, cheesecake and ice cream have their own drawbacks." I'm glad some one else will say what I've always said, PHP is a three-headed Satan baby. When the seventh seal was broken and the seventh trumpet sounded, PHP leaped out of the womb and ate its mother, the whore of Babylon. Re: (Score:3, Insightful) I'm glad some one else will say what I've always said, PHP is a three-headed Satan baby. When the seventh seal was broken and the seventh trumpet sounded, PHP leaped out of the womb and ate its mother, the whore of Babylon. Thanks for that awesome metaphor! Every single time that delightfully deep and correct analysis of PHP's shortcomings is mentioned someone who doesn't know anything about language design chimes in with this ridiculous, "Yes but no language is perfect!" line. As if "every well-designed language consists of an intersection of compromises between incompatible ideals" is in any way an answer to, "PHP is fractal of bad design." I'm not totally sure why anyone thinks "no language meets some impossible standard I'v Encourages programmers to misunderstand it (Score:2) the other half falls down to misunderstanding PHP. How about "PHP is bad because it all but encourages programmers to misunderstand it in a way that leads to security breaches?" Re: (Score:2) Way to go proving the author's point. The article is nuanced and clear. Your screed is content free and laughable. Re: (Score:2) In defense of PHP... Your "defense" of PHP is that you know nothing about language design, so you can't see what the problem is? Re: (Score:2) I've been using Ruby for a decade and yet to find much suck. I love working with the language. Where should I be looking, pray tell? Re:Python VS PHP (Score:4, Insightful) I'm a big python fan. It encourages elegant and readable code and has a good library and community. The lack of static typing hurts a bit in now having good static checking ("compiler errors") and IDE autocomplete, but it also means that you can scrap tehe 90% of code that java forces you to write to declare and then work around interfaces and abstraction layers :-) I haven't written PHP the last 10 years, so I can't really compare to state of the art, but I felt that PHP encourages sloppy programming and lack of separation of concerns by sticking a lot of business logic in the presentation layer. But that be more about the language being used by a lot of people without formal programming training than about the language itself. Re:Python VS PHP (Score:4, Insightful) Dude, I disagree with this statement. Why? Because the choice of where to place business logic lies entirely on the coder. It isn't an attribute you'll find tied to a system just because it employs a particular a language, in this case PHP as you say. The same can be said about Microsoft's Visual Basic as used on its JET DB engine found in MS Access. Re: (Score:2) The lack of static typing hurts a bit The understatement of the year. You know a language got a feature wrong when it comprises an inordinate proportion of the compiler error/bugs found. In Pascal it was the missing semicolon, though in that case the compiler caught it. In C it is the change in meaning of = to assignment and == to comparison (though not _that_ common of an error). In Python, more than half of the bugs are either an improper use of a variable or the wrong amount of white space after refactor Re: (Score:2) In Python, more than half of the bugs are either an improper use of a variable or the wrong amount of white space after refactoring some nested code. I think the white space is mainly a red herring, but you are right that it is annoying to copy-paste code or refactor and have to remember how many spaces to shift a block to the right. In that regard curly braces and select-all + reindent does work easier. About static typing (I assume that you mean static vs dynamic and not strong vs weak typing?): I think I disagree. I've not looked at how perl did it, so my experience mainly comes from java. But in java you are spending so much time mucking around with i Re: (Score:2) I think the white space is mainly a red herring, I used to be a big fan of white spaces and for small projects it is easy to keep in your head the nesting level at which code should be, but when you are editing someone else's code in a 1000 KLOC project it is much more difficult to remember where it should be. As I said it is an inordinately common source of bugs. But in java you are spending so much time mucking around with interfaces, casting etc. that it becomes a big mess quite soon, That a consequence of improper polymorphism, not static typing. Again once you get past 100 KLOC it gets very hard to keep types and names straight. You need the compiler/interpreter to flag you Re: eve Re:Python VS PHP (Score:4, Informative) You know, I've gotten used to anti-language screeds being the frustration of the ignorant and lazy compounded with childish exaggerations and intemperance even I boggle at. But .... wow. Just wow. NULL < -1 && NULL == 0? "0133" == "133" because of implicit string-to-numeric conversions, but 0133 != 133? And the ? : implementation just leaves those examples in the dust. Re: (Score:2) If you would kindly put forth what you think "design" should provide Consistent naming conventions for functions in the standard library, for one thing. Some way to protect names of functions defined in a program from colliding with names of functions added to newer versions of the language, for another. Re:Python VS PHP (Score:5, Informative) I've professionally programmed in both Python and PHP. There's no reasonable competition - Python wins hands down. A few of the advantages of Python over PHP: filtered = [x for x in unfiltered where x.foo=="bar"] In PHP the same thing looks like: $filtered = array_filter($unfiltered, function($x) { return $x->foo == "bar"; }); Web hosting providers slow to offer new PHP (Score:3) $filtered = array_filter($unfiltered, function($x) { return $x->foo == "bar"; }); Which looks a little like how Python would look without list comprehensions: The worse part is that lambdas, such as your function($x) { return $x->foo == "bar"; }, are a fairly recent addition to PHP (5.3 series IIRC). This wouldn't be so bad, seeing as PHP 5.3 is three years old, except that shared web hosts have tended not to make it easy to run multiple PHP versions side by side for different applications or even to migrate a whole site to a n Re: (Score:3) PHP gets widespread hosting support for exactly one reason: mod_php. This is why it's impossible to run two PHPs at once, and why hosters are slow to upgrade. Compare the number of companies willing to install an apache module and just forget it (often to their peril) to the number of companies willing to babysit a million RAM-chewing django, rails, and java servlets for all their customers, and that's why. Someone should resurrect mod_python. It hasn't moved in over 2 years now. Re: (Score:2) PHP gets widespread hosting support for exactly one reason: mod_php. This is why it's impossible to run two PHPs at once, and why hosters are slow to upgrade. For one thing, two Apaches in two virtual machines can run two PHPs. For another, even if you don't run your app servers in virtual machines, you can still mount customer files on a file server and switch the user from the app server that handles 5.2 to the app server that handles 5.4. Compare the number of companies willing to install an apache module and just forget it (often to their peril) to the number of companies willing to babysit a million RAM-chewing django, rails, and java servlets for all their customers, and that's why. Which is part of why after this discussion [slashdot.org] I moved my own site from Go Daddy to WebFaction [webfaction.com]. It has Rails, Django, and other common frameworks as one-click installs alongside a more "typical" configuration with CGI and PHP, if Re: (Score:2) Re: (Score:2) Did you know that Apache will execute compiled C binaries and that you can simply read and write from STDIN & STDOUT to do CGI? Also, same with C++. Also, there's plenty of libs for parsing parameters and JSON and SQL DBI, etc. Bonus, no scripts to "compile" no need for mod_php or mod_perl to speed up scripts by pre-compiling (I did that when I built the program) and the server can run as many bins as I can make. They pretty much all still support this because that's how we used to do CGI back whe Re: (Score:2) Wait, you think testing C and C++ against possible exploits is easier than using an interpreted language like Python or Perl? I wouldn't go back to writing my CGI with C unless there was a no-lawsuits clause. Web hosting providers charge extra for C CGI (Score:2) Did you know that Apache will execute compiled C binaries and that you can simply read and write from STDIN & STDOUT to do CGI? I was aware of that, in an environment that gives the user at least as much control as a VPS. But did you know that some providers' cheapest plans do not support C CGI, only PHP? This restriction is part of why I left Go Daddy shared hosting for WebFaction shared hosting [webfaction.com]. Do the same on my mobile & tablets too -- Just run full-on Linux. Use compiled "apps" to get's tons more battery life than when it had Android on it. Which brand of phone and tablet do you use, and where can I try them in a store in the United States? And how much more battery life do your tablets get than the eight hours that I get out of a Nexus 7? Re: (Score:2) I still use Zope when I want to write Python for the web. Its not perfect, but its one of the best options. Write your own module using the interfaces given and voila. Re: (Score:2) Which looks a little like how Python would look without list comprehensions: True, but my brain just auto-converted that to a car analogy: "You know, if I take off one of the wheels off this fancy sports car, it doesn't drive too good" :) Re: (Score:2) Python list comprehension method: filtered = [x for x in unfiltered where x.foo=="bar"] Or you could just use Python's filter() which is conceptually the same as PHP's version: filtered = filter(lambda x: x.foo == 'bar', unfiltered) Python has better syntax than PHP, but this is one of the weaker examples. Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:3, Interesting) Python use within Google has been on the decline for years now. It's not exactly a secret that they discourage using it for new projects. Re:Pay Decrease? (Score:4, Interesting) That's funny, because I just interviewed with Google last week for an SRE role, and they specifically wanted someone with hardcore Python and Java development experience, at the filesystem and kernel level. They're moving -everything- into those two language engines. Re: (Score:2) That's funny, because I just interviewed with Google last week for an SRE role, and they specifically wanted someone with hardcore Python and Java development experience, at the filesystem and kernel level. They're moving -everything- into those two language engines. Java? Why? Re: (Score:3, Insightful) True. SRE doesn't tend to write the consumer facing services. We tend to write the stuff that keeps stuff running. And as you bloody well know, it's mostly written in Python and various DSL's. Signed, Someone who actually works in SRE at Google. Re: (Score:2) Money isn't everything to everyone. If you were being paid $500.00 per hour to shovel out a barn, wouldn't you take a job that offered something more fun like programing with python even if it paid $490.00 per hour? Re:Pay Decrease? (Score:5, Insightful) Actually, I'd take shoveling out a barn at 500/hr. It would get me exercise and a chance to be alone with my thoughts, which would let me do fun things like programming with python for things I want to program, instead of what someone else wants programmed. Re: (Score:2) 500$/hr?! Fuck the shovel, I'll use the hands Re: (Score:2) Money isn't everything to everyone. If you were being paid $500.00 per hour to shovel out a barn, wouldn't you take a job that offered something more fun like programing with python even if it paid $490.00 per hour? Depends on the job. Which one do I take to wade through the least amount of bullshit? I'm burnt out enough that I might try the barn for a year just for the variety. Re: (Score:2) You could rebuild it, but the huge shit barn "sort of works", whereas your new barn won't work till it's mostly complete. I'd be happy to shovel shit from a barn for USD500/hour if I only had to do a very few hours a week Re: (Score:2) I am not sure shoveling out barns is the best career move if you are looking to avoid bullshit. I don't have tons of experience in agriculture but I suspect quite a lot bullshit is produced in barns. Perhaps not as much as out in grazing fields but a substantial amount. Re: (Score:2) No one can really answer that except for Guido and/or dropbox. I think my favorite job I've ever had paid the least. If I was comfortable enough finacially, I'd go back to it. Re: (Score:2) isn't youtube built in python? Re: (Score:2) Google has almost 40'000 employees now. You underestimate them. Their PR is good tho. What does their employee count (or PR) have to do with their commitment to Python or appreciation for employees? A company's employee count or PR firm isn't connected to how good of an employer they are. Otherwise everyone at McDonalds or Walmart would be loving their jobs. Re: (Score:2) Please, God, cannot somebody please take that stupid abomination of a language Python out in back and shoot it in the head until dead. I have never used a less friendly piece of Monkey Pus than the "language" Python. A fan og PHP, are you? It shows! Re: (Score:2) Re: (Score:2) That, is what matters in the end. By your own logic, languages like C shouldn't have existed at all. Re: (Score:3) 2. Calling a language construct, that captures... nothing, a *closure* is an insult to computer science. def f(a): return lambda x: x+a g = f(10) print g(4) >>> 14 That captured something. Maybe not what you want, but it did capture something. Re: (Score:3) CPython is the reference implementation. It's as much about being clear about how things work as it is about performance. You can literally drop down into standard library and interpreter code with zero understanding of it, and figure out what's going on right away. If you want perf, there's always PyPy, Jython etc. Re: (Score:2) Why is this downvoted? If it's plain wrong, a reply clarifying that would have been better than a downvote!
http://developers.slashdot.org/story/12/12/07/2242237/python-creator-guido-van-rossum-leaves-google-for-dropbox
CC-MAIN-2014-52
refinedweb
4,787
72.26
I'm having a weird problem and I hope someone can help me. I was trying to compile a program with string earlier and I got errors while compiling. That's fine. But now, all of the programs I try to compile give me the same error that has nothing to do with the code. For example: Code : public class New { public static void main(String[] args) { System.out.println("Hello"); } } gives me the following error: .\String.java:11: incompatible types found : java.lang.String required: String String username = scanner.nextLine(); ^ .\String.java:17: incompatible types found : java.lang.String required: String String password = scanner.nextLine(); ^ 2 errors And this happens with everything I do. Sorry, but I'm completely new to this. **I use javac
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/1110-strange-compiling-error-printingthethread.html
CC-MAIN-2017-47
refinedweb
126
70.7
One of the strongest side of QlikView is the build-in powerful ETL layer that allows you to import data from various sources. Sooner or later QlikView developer have to load some old huge unique and extremely valuable ascii file that sometimes contains a few odd line feed (LF or \n) or carriage return (CR or \r) symbols. As a result strings are divided into subsequent rows. You just can’t load it as delimited file directly into QlikView. The power of ‘transform step’ can’t help here too. Nevertheless QlikView can easily handle it with a few tricks. I decide to write a detailed guide as there are pitfalls that must be explained carefully.
https://community.qlik.com/docs/DOC-4716
CC-MAIN-2017-39
refinedweb
115
72.16
Vim’s simplicity makes it possible to start working with it easily and quickly. The minimalistic interface allows users to concentrate on the main task of writing. Understanding the main concepts behind the program also helps users learn and make use of its deeper functionalities. The power behind Vim allows users to accomplish certain tasks better, faster, and much more easily. Its powerful functionality allows users to put in minimum effort while getting maximum efficiency, giving them the capability to solve simple and complex problems. Vim is actively used by programmers. Its functionality, usability, and flexibility make it a great choice for those who write a lot of code. Increasing Efficiency Lighting A basic option in Vim is syntax lighting which allows users to “see” the code more easily. This change contributes to faster code reading and writing. If you edit a file in Python, launch :set filetype=python and Vim will add colors. To view the list of available languages, open the catalogue $VIMRUNTIME/syntax/. Indents A programmer’s code usually uses indentation. Vim can help programmers write code with the correct indentation. For example, if you made an indent to a certain point and want the following lines of code to be written using the same indent, use :set autoindent. If you start a new operator's block, use :set smartindent to create the following lines with one more indent level. Moves There are many ways to move within code. With Vim, files can be opened by placing the cursor on the file’s name in the code and pressing gf. By placing the cursor on a variable’s name and pressing gd, Vim will move you to a local definition of the variable’s name. Gd does the same for global contents, searching from the beginning of a file. Easy Writing Omni completion “Omni completion” was added to Vim 7 and is one of the most useful functions of the program. This allows users to automatically finish text according to the current context. For example, if the long name of a variable is used, you can set a key-combination for autocompletion and Vim will do the rest. Vim solves this task with the help of ftplugins. Here is an example with a simple program in Python: def hello(): print 'hello world' def hey_body(): print 'what’s up?' After entering this program, create a new line in this file, type he and press ctrl-x ctrl-o. You will be shown variants for autocompletion. Vim automatically uses the first variant for autocompletion and allows users to choose the next or previous option with the help of ctrl-n and ctrl-p, respectively. Use of fragments Code fragments are small pieces of code which, as a rule, are constantly repeating. Users may use plugins to help insert fragments in the code, as many good programmers do. Let’s use plugin SnippetsEmu as an example. 1. Open a new file, e.g. test.py. 2. Press keys d, e, f and then <tab>. 3. SnippetsEmu creates a function structure. def <{fname}>(<{args}>): """ <{}> <{args}> """ <{pass}> <{}> Note: If all you can see is def<tab> , it’s probably that the fragments plugin is not loaded. Enter :runtime! ftplugin/python_snippets.vim. 4. Now the cursor will be placed at the function name, i.e. fname. 5. Type a function name, e.g. test. 6. Press <tab> and the cursor will automatically move to arguments. Press 7. Now enter a comment, e.g. No. 8. Press <tab> again and enter Hello World. 9. Press <tab>. 10. The program is ready! You should now see the following: def test(): """ Just say Hi """ print 'Hello World' The best thing about this is that SnippetsEmu creates a standard format which must be followed and nothing will be “forgotten”. Advice and Recommendations to Make Your Work Easier 1.Work with several files If you are a software developer or somebody who uses Vim as a main editor, there is a high chance that you need to work with several files simultaneously. Instead of opening different files in different cover tabs, you can open several files in one tab, sending their names as arguments in Vim commands. For example: vim file1 file2 file3 The first file ( file1 in the example) is a current file and is read out in the buffer. Within the editor, use commands :next or :n to pass over to the next file and :prev or :p to go back to the previous one. To quickly switch to the first or the last file, use :bfand :bl commands, respectively. To open and start editing another file, use :e with the filename as an argument (use the full procedure in case the file is absent from the current catalogue). 2.Autocomplete Want to save time and increase accuracy? Use abbreviations. They will come in handy when writing long or complex words, especially if they are repeated several times within a file. The Vim command for contractions is :ab. For example: :ab asap as soon as possibleEvery time asapis used, it will automatically be substituted by the words ‘as soon as possible’. 3.Split windows In some cases, you’ll want to copy a part of code or text from one file to another. Although this process is simple when working with editors with graphic interface, it becomes a bit tiresome and laborious with the command line editor. Fortunately, Vim minimizes the time and effort needed for this. You can open one of two files and then split the Vim window in order to open another file with the help of :split command and the filename as an argument, e.g. :split test.py. It should be pointed out that the command will split the window horizontally. If you want to split it vertically, use command :vsplit. As soon as both files open, copy material from one file to another and press ctrl+w to switch the activity to another file. 4.Preserving indents Most experienced programmers work in Vim using default indents. Although this is meant to save time, it causes problems when you insert code with an indent of its own. You can use pastetoggle to solve this problem. Add this line set pastetoggle=<F3> to a vimrc file and press F3 in insert mode just before inserting the code. This will preserve the original indentation. Note that you can substitute F3 with any other key if this one is already used for another functionality. Conclusion Text editing, in general, and code editing, in particular, require additional time and effort to be invested into a project. By learning new commands and making a habit of using them, the task of editing can be streamlined and made so much easier because of programs like Vim. This introductory article was devoted to familiarizing users with Vim, its basics, and its capabilities. We hope it is a useful guide for beginners who want to understand what Vim is. Future posts will look at a more advanced specifics and more complicated aspects of this editor.
https://steelkiwi.com/blog/vim-tutorial-beginners-part-1/
CC-MAIN-2019-35
refinedweb
1,176
63.39
Template Constraints Templates are normally overloaded and matched based on the template arguments being matched to the template parameters. The template parameters can specify specializations, so that the template argument must match particular type patterns. Similarly, template value arguments can be constrained to match particular types. But this has its limitations. Many times there are arbitrarily more complex criteria for what should be accepted by the template. This can be used to: - more finely discriminate about which template gets instantiated for given arguments - provides better self-documentation about what characteristics template parameters must have - can provide better diagnostics when arguments don't match, rather than an obscure error message based on the irrelevant (to the user) internal details of the template implementation Constraints address this by simply providing an expression that must evaluate at compile time to true after the arguments are matched to the parameters. If it is true, then that template is a valid match for the arguments, if not, then it is not and is passed over during overload matching. The constraint expression follows the template declaration and the if keyword: template Foo(int N) if (N & 1) { ... } which constrains the template Foo to match only if its argument is an odd integer. Arbitrarily complex criteria can be used, as long as it can be computed at compile time. For example, here's a template that only accepts prime numbers: bool isPrime(int n) { if (n == 2) return true; if (n < 1 || (n & 1) == 0) return false; if (n > 3) { for (auto i = 3; i * i <= n; i += 2) { if ((n % i) == 0) return false; } } return true; } template Foo(int N) if (isPrime(N)) { ... } Foo!(5) // ok, 5 is prime Foo!(6) // no match for Foo Type constraints can be complex, too. For example, a template Bar that will accept any floating point type using the traditional type specializations: template Bar(T:float) { ... } template Bar(T:double) { ... } template Bar(T:real) { ... } and the template implementation body must be duplicated three times. But with constraints, this can be specified with one template: template Bar(T) if (is(T == float) || is(T == double) || is(T == real)) { ... } This can be simplified by using the isFloatingPoint template in library module std.traits: import std.traits; template Bar(T) if (isFloatingPoint!(T)) { ... } Characteristics of types can be tested, such as if a type can be added: // Returns true if instances of type T can be added template isAddable(T) { // Works by attempting to add two instances of type T const isAddable = __traits(compiles, (T t) { return t + t; }); } int Foo(T)(T t) if (isAddable!(T)) { return 3; } struct S { void opAdd(S s) { } // an addable struct type } void main() { Foo(4); // succeeds S s; Foo(s); // succeeds Foo("a"); // fails to match } Since any expression that can be computed at compile time is allowed as a constraint, constraints can be composed: int Foo(T)(T t) if (isAddable!(T) && isMultipliable!(T)) { return 3; } A more complex constraint can specify a list of operations that must be doable with the type, such as isStack which specifies the constraints that a stack type must have: template isStack(T) { const isStack = __traits(compiles, (T t) { T.value_type v = top(t); push(t, v); pop(t); if (empty(t)) { } }); } template Foo(T) if (isStack!(T)) { ... } and constraints can deal with multiple parameters: template Foo(T, int N) if (isAddable!(T) && isprime(N)) { ... } Overloading based on Constraints Given a list of overloaded templates with the same name, constraints act as a yes/no filter to determine the list of candidates for a match. Overloading based on constraints can thus be achieved by setting up constraint expressions that are mutually exclusive. For example, overloading template Foo so that one takes odd integers and the other even: template Foo(int N) if (N & 1) { ... } // A template Foo(int N) if (!(N & 1)) { ... } // B ... Foo!(3) // instantiates A Foo!(64) // instantiates B Constraints are not involved with determining which template is more specialized than another. void foo(T, int N)() if (N & 1) { ... } // A void foo(T : int, int N)() if (N > 3) { ... } // B ... foo!(int, 7)(); // picks B, more specialized foo!(int, 1)(); // picks A, as it fails B's constraint foo!("a", 7)(); // picks A foo!("a", 4)(); // error, no match References - Concepts (Revision 1) by Douglas Gregor and Bjarne Stroustrup
https://docarchives.dlang.io/v2.071.0/concepts.html
CC-MAIN-2019-18
refinedweb
724
61.26
The cbrt() function of the cmath library allows you to take the cubic root of any number. Cubic root is a math function that finds x by following the equation below. For a given y we can find x by taking . The cbrt() function in cmath takes a number of any type in the argument and returns its cubic root. The returned value can be a float, double, long double or int. Let’s see different examples of how the cbrt() function can be used below. #include <iostream> #include <cmath> using namespace std; int main() { // input output both of same type double x0, y0 = 589.6; x0 = cbrt(y0); cout << "Cubic root of " << y0 << " is : " << x0 << endl; //input output both of different type double x1; float y1 = 512; x1 = cbrt(y1); cout << "Cubic root of " << y1 << " is : " << x1 << endl; // output as an integer // notice that the output will discard any decimal places int x2; long double y2 = 56972.3; x2 = cbrt(y2); cout << "Cubic root of " << y2 << " is : " << x2 << endl; return 0; } RELATED TAGS View all Courses
https://www.educative.io/answers/how-to-use-cbrt-in-cpp
CC-MAIN-2022-33
refinedweb
177
69.11
Difference between revisions of "Taking a screenshot" Revision as of 17:07, 19 February 2010 import gimp You also can take screenshots with gimp (File -> Acquire -> Screenshot ...). xwd xwd is part of the xorg-apps package. Take a screenshot of the root window: xwd -root -out screenshot.xwd scrot Scrot, available in the "extra" repository, provides for taking screenshots from the CLI, and offers features such as a user-definable time delay. Unless instructed otherwise, it saves the file in the directory bash was at when the command was launched. scrot -t 20 -d 5 saves a dated .PNG file, along with a thumbnail (20% of original) for Web posting. It provides a five second delay before capturing, in this instance. KDE If you use KDE, you might want to use ksnapshot, which can also be activated using <Prt Scr>. GNOME You can press <Prt Scr> or Apps->Accessories->Take Screenshot. Virtual console Install a framebuffer and use Template:Package Official to take a screen shot. Another option is to use Template:Package Official, but that tends to corrupt the image by inverting colors.
https://wiki.archlinux.org/index.php?title=Taking_a_Screenshot&diff=97468&oldid=93542
CC-MAIN-2016-40
refinedweb
184
65.01
Creating an Adventure Game in the Terminal with ncurses How to use curses functions to read the keyboard and manipulate the screen. My previous article introduced the ncurses library and provided a simple program that demonstrated a few curses functions to put text on the screen. In this follow-up article, I illustrate how to use a few other curses functions. An Adventure When I was growing up, my family had an Apple II computer. It was on this machine that my brother and I taught ourselves how to write programs in AppleSoft BASIC. After writing a few math puzzles, I moved on to creating games. Having grown up in the 1980s, I already was a fan of the Dungeons and Dragons tabletop games, where you role-played as a fighter or wizard on some quest to defeat monsters and plunder loot in strange lands. So it shouldn't be surprising that I also created a rudimentary adventure game. The AppleSoft BASIC programming environment supported a neat feature: in standard resolution graphics mode (GR mode), you could probe the color of a particular pixel on the screen. This allowed a shortcut to create an adventure game. Rather than create and update an in-memory map that was transferred to the screen periodically, I could rely on GR mode to maintain the map for me, and my program could query the screen as the player's character moved around the screen. Using this method, I let the computer do most of the hard work. Thus, my top-down adventure game used blocky GR mode graphics to represent my game map. My adventure game used a simple map that represented a large field with a mountain range running down the middle and a large lake on the upper-left side. I might crudely draw this map for a tabletop gaming campaign to include a narrow path through the mountains, allowing the player to pass to the far side. Figure 1. A simple Tabletop Game Map with a Lake and Mountains You can draw this map in cursesusing characters to represent grass, mountains and water. Next, I describe how to do just that using curses functions and how to create and play a similar adventure game in the Linux terminal. Constructing the Program In my last article, I mentioned that most curses programs start with the same set of instructions to determine the terminal type and set up the curses environment: initscr(); cbreak(); noecho(); For this program, I add another statement: keypad(stdscr, TRUE); The TRUE flag allows curses to read the keypad and function keys from the user's terminal. If you want to use the up, down, left and right arrow keys in your program, you need to use keypad(stdscr, TRUE) here. Having done that, you now can start drawing to the terminal screen. The curses functions include several ways to draw text on the screen. In my previous article, I demonstrated the addch() and addstr() functions and their associated mvaddch() and mvaddstr() counterparts that first moved to a specific location on the screen before adding text. To create the adventure game map on the terminal, you can use another set of functions: vline() and hline(), and their partner functions mvvline() and mvhline(). These mv functions accept screen coordinates, a character to draw and how many times to repeat that character. For example, mvhline(1, 2, '-', 20) will draw a line of 20 dashes starting at line 1, column 2. To draw the map to the terminal screen programmatically, let's define this draw_map() function: #define GRASS ' ' #define EMPTY '.' #define WATER '~' #define MOUNTAIN '^' #define PLAYER '*' drawing this map, note the use of mvvline() and mvhline() to fill large chunks of characters on the screen. I created the fields of grass by drawing horizontal lines ( mvhline) of characters starting at column 0, for the entire height and width of the screen. I added the mountains on top of that by drawing vertical lines ( mvvline), starting at row 0, and a mountain path by drawing a single horizontal line ( mvhline). And, I created the lake by drawing a series of short horizontal lines ( mvhline). It may seem inefficient to draw overlapping rectangles in this way, but remember that curses doesn't actually update the screen until I call the refresh() function later. Having drawn the map, all that remains to create the game is to enter a loop where the program waits for the user to press one of the up, down, left or right direction keys and then moves a player icon appropriately. If the space the player wants to move into is unoccupied, it allows the player to go there. You can use curses as a shortcut. Rather than having to instantiate a version of the map in the program and replicate this map to the screen, you can let the screen keep track of everything for you. The inch() function, and associated mvinch() function, allow you to probe the contents of the screen. This allows you to query curses to find out whether the space the player wants to move into is already filled with water or blocked by mountains. To do this, you'll need a helper function that you'll use later: int is_move_okay(int y, int x) { int testch; /* return true if the space is okay to move into */ testch = mvinch(y, x); return ((testch == GRASS) || (testch == EMPTY)); } As you can see, this function probes the location at column y, row x and returns true if the space is suitably unoccupied, or false if not. That makes it really easy to write a navigation loop: get a key from the keyboard and move the user's character around depending on the up, down, left and right arrow keys. Here's a simplified version of that loop: do { ch = getch(); /* test inputted key and determine direction */ switch (ch) { case KEY_UP: if ((y > 0) && is_move_okay(y - 1, x)) { y = y - 1; } break; case KEY_DOWN: if ((y < LINES - 1) && is_move_okay(y + 1, x)) { y = y + 1; } break; case KEY_LEFT: if ((x > 0) && is_move_okay(y, x - 1)) { x = x - 1; } break; case KEY_RIGHT if ((x < COLS - 1) && is_move_okay(y, x + 1)) { x = x + 1; } break; } } while (1); To use this in a game, you'll need to add some code inside the loop to allow other keys (for example, the traditional WASD movement keys), provide a method for the user to quit the game and move the player's character around the screen. Here's the program in full: /* quest.c */ #include <curses.h> #include <stdlib.h> #define GRASS ' ' #define EMPTY '.' #define WATER '~' #define MOUNTAIN '^' #define PLAYER '*' int is_move_okay(int y, int x); void draw_map(void); int main(void) { int y, x; int ch; /* initialize curses */ initscr(); keypad(stdscr, TRUE); cbreak(); noecho(); clear(); /* initialize the quest map */ draw_map(); /* start player at lower-left */ y = LINES - 1; x = 0; do { /* by default, you get a blinking cursor - use it to indicate player */ mvaddch(y, x, PLAYER); move(y, x); refresh(); ch = getch(); /* test inputted key and determine direction */ switch (ch) { case KEY_UP: case 'w': case 'W': if ((y > 0) && is_move_okay(y - 1, x)) { mvaddch(y, x, EMPTY); y = y - 1; } break; case KEY_DOWN: case 's': case 'S': if ((y < LINES - 1) && is_move_okay(y + 1, x)) { mvaddch(y, x, EMPTY); y = y + 1; } break; case KEY_LEFT: case 'a': case 'A': if ((x > 0) && is_move_okay(y, x - 1)) { mvaddch(y, x, EMPTY); x = x - 1; } break; case KEY_RIGHT: case 'd': case 'D': if ((x < COLS - 1) && is_move_okay(y, x + 1)) { mvaddch(y, x, EMPTY); x = x + 1; } break; } } while ((ch != 'q') && (ch != 'Q')); endwin(); exit(0); } int is_move_okay(int y, int x) { int testch; /* return true if the space is okay to move into */ testch = mvinch(y, x); return ((testch == GRASS) || (testch == EMPTY)); } the full program listing, you can see the complete arrangement of curses functions to create the game: 1) Initialize the curses environment. 2) Draw the map. 3) Initialize the player coordinates (lower-left). 4) Loop: - Draw the player's character. - Get a key from the keyboard. - Adjust the player's coordinates up, down, left or right, accordingly. - Repeat. 5) When done, close the curses environment and exit. Let's Play When you run the game, the player's character starts in the lower-left corner. As the player moves around the play area, the program creates a "trail" of dots. This helps show where the player has been before, so the player can avoid crossing the path unnecessarily. Figure 2. The player starts the game in the lower-left corner. Figure 3. The player can move around the play area, such as around the lake and through the mountain pass. To create a complete adventure game on top of this, you might add random encounters with various monsters as the player navigates his or her character around the play area. You also could include special items the player could discover or loot after defeating enemies, which would enhance the player's abilities further. But to start, this is a good program for demonstrating how to use the curses functions to read the keyboard and manipulate the screen. Next Steps This program is a simple example of how to use the curses functions to update and read the screen and keyboard. You can do so much more with curses, depending on what you need your program to do. In a follow up article, I plan to show how to update this sample program to use colors. In the meantime, if you are interested in learning more about curses, I encourage you to read Pradeep Padala's NCURSES Programming HOWTO at the Linux Documentation Project.
https://www.linuxjournal.com/content/creating-adventure-game-terminal-ncurses
CC-MAIN-2018-34
refinedweb
1,613
63.73
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. ntobjx: NT objects About This. Kurzer Hinweis: deutsche Version Dieses Programm gibt es jetzt auch auf Deutsch. Entsprechend der Einstellungen eures Benutzerkontos wird das Programm ggf. schon direkt auf Deutsch gestartet. Ansonsten könnt ihr F11 oder das "View"-Menü zum Umschalten benutzen. Viel Spaß! Die deutsche Dokumentation findet sich hier. Das Fälertoifelchen Defekte könnt ihr mir gern auch auf Deutsch melden. Call to action: translations Hey there. Yes, you. Want to see this program in your native language? Feel confident enough to translate any existing translation into your native tongue? If so, please send a pull request with the translated .rc file or alternately file a ticket here to get in touch. Download A code-signed version of the utility can be found in the download section. Please be sure to verify the signature using either signtool or sigcheck from live.sysinternals.com (both from Microsoft). There is also a PGP-signed .7z archive. The signature is detached and carries the file extension .asc. These archives contain the debug symbols (.pdb) alongside the executables. The name contains the revision number and the short changeset ID, so I don't need to remove old builds all the time due to name clashes. State of affairs and compatibility The utility already duplicates the functionality of WinObj and surpasses it. It allows you to export a text or XML representation (both using Unicode) of the object manager namespace. The utility should work on Windows 2000 and newer. Windows NT 4.0 and older are explicitly unsupported (although the source can probably be adapted to run on those). Build your own I still prefer Visual Studio 2005 and therefore the projects and solution which I committed to the repository are of that format. However, the premake4.lua should allow you to generate projects and solution for a newer Visual Studio at will. Potential caveat: you may need to use my own premake4 flavor, as I have not tested the premake4.lua against the stock version. However, you can find pointers to that end at the top of premake4.lua. I noticed that newer versions of the Windows SDK contain a more complete winternl.h file, such that some of the typedef declarations in ntnative.h may be duplicates and the compiler may choke. If you find any such cases, please file a ticket to point them out to me. More details on how to build can be found in the project Wiki. Creating the solutions Using the correct premake4 flavor the creation of the solutions and projects is as easy as: premake4 vs2005 For example to create all solutions and projects for VS 2005 through VS 2017 in parallel: for %i in (vs2005 vs2008 vs2010 vs2012 vs2013 vs2015 vs2017) do @premake4 %i And don't worry, the names of the solutions and projects contain the version of Visual Studio and therefore won't clash. Personally I currently use VS 2005 to build release versions, but VS 2017 to develop the utility. Command line version If you are merely interested in listing the objects, you can pass the parameter --cmdline to your invocation of premake4 and it will generate an extra project named ntobjx_c inside the solution. This project also is a nice show case for just the stuff provided in objmgr.hpp, so if you want to play with that or understand it, you needn't sift through lots of GUI related code. Don't look any further than said command line tool. Defects Some people call them "bugs", but "bug" misses the distinction between cause (the defect), propagation of the defective program state and symptom (the defective behavior exhibited). I prefer the terminology as proposed by Andreas Zeller in his book Why Programs Fail (2nd ed.). Therefore I call them defects. Now, if you find one of those, please report them here. Feel free to use German, English or - if absolutely necessary - Russian to describe the erratic behavior. Please make sure to provide some way to contact you for more feedback. One easy way is to log into Bitbucket and file a ticket as logged on user..
https://bitbucket.org/assarbad/ntobjx
CC-MAIN-2018-34
refinedweb
707
66.23
"DefaultValidationEventHandler: unexpected element" error on unmarshalling Hi! I used JAXB 2.1.1 with IMS LD schema files to generate jaxb classes. Parsing xml files, conforming to IMS LD schema, I've came across a problem which made me stuck. The symptom is: DefaultValidationEventHandler: [ERROR]: unexpected element (uri:"", local:"title"). Expected elements are <{}title>,<{}prerequisites>,<{}learning-objectives>,<{}method>,<{}components>,<{}metadata> in xml file: Introduction to the Dutch language Learner ..... However, IMS LD schema implies all elements are described there, and are in the same namespace, which is xmlns:imsld="", though declaration seems to be a little bit different: - for <{}title> for <{imsld=""}learning-design> Suppose this bug has something in common with this one... What should I do to original schema files or whatever to make it work without changing element namespace to xmlns="" (which really solves the problem, but only for this particular title element of course)? Sorry, Kohsuke I got confused by versions: I've made classes using Jaxb 2.1.1 command line, but then used JDK 6 built-in version to unmarshal file. I've generated classes with JDK 6 built-in version and now got everything working all right. Thank you for reply! Anton Well, actually using 2.1.1 CLI for generation and running the result on JDK6 should have been just fine, provided that you put "-target 2.0" to indicate that your runtime is 2.0, not 2.1. And even if you forgot to do that, you still shouldn't have seen this unexpected element. I still think there's something wrong here. Can you file an issue in and attach the schema so that we can take a look? I'm assuming that you've checked package-info.java. Also, if you haven't read yet, please consider trying that.
https://www.java.net/node/662092
CC-MAIN-2015-32
refinedweb
300
58.48
I always love doing the fix-it Fridays at I ♥ Faces. This week is no exception and we had an extremely cute picture to work with! Here is the original: I love her expression in this picture! Here is my "fix": and what I did: Lightroom (I've recently downloaded the free beta version of the new Lightroom to see if I like it and would consider buying it. This was a great opportunity to experiment with it to see if I like using it over photoshop to "fix" a face that is overly bright on one side and a bit shadowy on the other. I was impressed with what Lightroom could accomplish even with my "newbie" skills): import picture recover 100 fill light 39 blacks 1 clarity +26 vibrance +26 tone curve: highlights-42; lights -36; dark +6; shadows +21 export ran the exported picture through noiseware (portrait mode). photoshop 7: - eyes: duplicated the layer and did a slight curve adjustment up in the middle just to brighten them a bit; added a bit more contrast; unsharp mask (amount 50; radius 1; threshold 0); made that layer into a mask and masked in only the colored parts of the eye. duplicated that eye layer and changed the mode to soft light. reduced opacities on both the eye layers until it was how I liked it and merged the 3 layers together. - used an action from called "Sweet Skye". Amy does really beautiful actions, be sure to check them out! I tweaked the action until the picture was how I liked and flattened the image. - duplicated the picture layer and flipped that layer horizontally. Made that layer into a mask and masked in the background of the flipped layer over the background of the original layer just by the stairs (so that the stairs were hidden). merged the two layers. - brought in this texture: , changed the mode to color burn and masked her out. - brought in the Garden Lights Nr.1 texture that I had downloaded when doing the "In the Fairy Garden" tutorial on I ♥ Faces:; set it on screen mode and masked her mostly out (I left parts of her in at different opacities, just playing with it until I liked it). - flattened the image and did a slight burn at some of the edges frame: - duplicated the picture layer and cut out a section in the middle of that layer, leaving only the outer edge, then by blending options: - added a drop shadow, picking a dark color from the picture as the shadow color and changing the distance to 0, the spread to 0, and the size to 21 ( I left the angle at 30° and left the mode at multiply at 75%) - bevel and emboss - an inner bevel and choose my highlight and shadow colors from the picture - pattern overlay- choose a super fine pattern and set it at multiply at 56% - duplicated the picture layer and brought it to the top and made it into a mask. I masked her in (so she's in front of the frame) and masked in parts of the brighter parts of the background so they were brighter on the frame. - flattened the image finished! If you want to check out some more fixes, be sure to head on over to I ♥ Faces: This is super cute! I love a little sparkle... I love the work you did on the eyes; very natural and not at all over-processed. Wow - it looks like a painting now. Wow - that was some editing! I love the way you have her in front of the frame. I don't get what you did, but I know it looks brilliant! :D Very sweet! Looks like a painting
http://cherylekupschphotography.blogspot.com/2010/02/i-faces-fix-it-friday-43.html
CC-MAIN-2017-39
refinedweb
624
75.95
You need to be logged in to post in the forums. If you do not have an account, please sign up first. 24. August 2011, 10:03:20 Disable HTML5 videoOne thing I really liked about Opera when I first started using it was that I could easily disable all plugins so I wasn't browsing the web with annoying flash adverts and could open multiple youtube tabs without having all the videos play at once. However, I have recently come across a few sites using HTML5 video which plays automatically and very loudly. I've searched around and had a look at the config file and haven't been able to find a way to either disable html5 video or prevent it playing automatically. If in the future more sites are going to start forcing video on us using html5 it would be nice to have a way to turn it off. 24. August 2011, 10:30:19 The reason for the autoplay attribute should be that annoying people won't script their annoying Javascripts and that we can disable it with a simple browser preference. 24. August 2011, 12:10:44 [ Tweedo Monitor - Deluxe Website & Service Monitoring ] 24. August 2011, 12:35:05 If you need any help from me with regards to Opera, please make a comment on any of my blog posts. Support Opera wishes 24. August 2011, 13:03:12 I thought controlling how the video element works was one of the points of HTML5 video. 24. August 2011, 15:11:23 24. August 2011, 18:27:47 video { display: none !important; }. A configuration setting like you get for plugins would be appreciated though. MyOpera Community Optimizations — by fearphage Scribit improved posting tools for the MyOpera Community — by xErath Improve Weeklies Blog — by MisterE & fearphage 24. August 2011, 19:14:41 Originally posted by BtEO: Though I imagine someone less lazy than me could come up with a fairly simple User JavaScript/Extension that would do a better job. As long as User JavaScripts/Extensions require JavaScript to be enabled in the browser they are not an option! At least by far not for standards Opera is claiming. Every morning a lion wakes up. It knows it must outrun the slowest gazelle or it will starve to death. It doesn't matter whether you are a lion or a gazelle: when the sun comes up, you'd better be running. 24. August 2011, 20:38:10 (edited) Originally posted by BtEO:. Just dump it in the user styles directory instead. Make show popup menu, "internal style list" easily accessible through a keyboard shortcut, button or mouse gesture. Turning it on and off is then a piece of cake. Originally posted by BtEO: Though I imagine someone less lazy than me could come up with a fairly simple User JavaScript/Extension that would do a better job. I already did, last year. Well, sort of. To tell you the truth I never imagined we'd still be waiting for control over such issues, so I never actually finished anything. Anyone's free to pick it up; it's not like it's in any way a complicated script. I've got no time this and next week to do anything, plus I'm not actually sufficiently bothered by HTML5 stuff yet. I also wrote another audio/video related script. It demos querySelectorAll for those who don't know what it is, and could conceivably be used to come to a solution quicker. Specifically, just replace the src attribute and source element selectors with ones for autoplay and then get rid of it/set it to false. 22. January 2012, 20:43:16 HTML5 video keeps crashing my computer!! I want to turn it off. One of the founding principles of Opera is to let the user turn off images, javascript, cookies, Flash, Animated images etc all nice and easily in the F12 menu or custom checkboxes on the status bar. It must be done. 5. February 2012, 01:22:25 6. February 2012, 02:41:33 6. February 2012, 22:35:36 Please... BiB 7. February 2012, 05:25:32 (edited) Also, with userjs, you can make play() on the audio/video object do nothing if you want: HTMLMediaElement.prototype.play = function() { }; You an override other methods if needed. You can also cache HTMLMediaElement.prototype.play. Then, you can override it/restore it with a keyboard shortcut. And, there's already the browser.css method mentioned to patch Opera's default stylesheet to hide video/audio elements by defaul. And, there's the user css method to override the page's styles to do the same. But, those methods won't stop the video/audio from playing. I'm not a web developer, so it took me some time to turn burnout426's tantalizing hints into something that works for me (at least for YouTube and embedded YouTube vids on other sites). No doubt I've committed a few howlers that real JS developers will pick up on. Anyway, here's my userjs: (function () { HTMLMediaElement.prototype.playZeMovieYah = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function() { if (!this.hasOwnProperty('okToPlayZeMovie')) this.okToPlayZeMovie = confirm("Play multimedia?"); if (this.okToPlayZeMovie) this.playZeMovieYah(); }; HTMLMediaElement.prototype.load = function() { }; })(); Using the boolean 'okToPlayZeMovie' means that I only get the popup once, not every time I pause and restart the movie. And the override for load() prevents autoloading of something I'm not going to play. It's not quite right yet: if I cancel the popup so as not to play the movie, I still get the annoying circular loading animation looping endlessly. Any ideas on how to stop it? Magic Senna Originally posted by BOYD1981: However, I have recently come across a few sites using HTML5 video which plays automatically and very loudly. +1 for request Still we can have fun with the "SOPA/PIPA thing" Away Nilzer - CHAEL SONNEN (UFC) - SUBTITLED Save the Opera Unite, give us Opera back Originally posted by crapshark: Anyway, here's my userjs: Untested, by I'd do it like this: (function() { var play = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function() { if (confirm("Play multimedia?")) { play.call(this); } }; })(); As for the animation, don't know. You could add an "else" condition and call this.stop() in it to see if it helps. Or, just add this.stop() before the if (confirm()) part to see if helps. But, for youtube, you don't need this. Just install the extendtube extension and make sure autoplay is disabled. Thanks for that ".call(this)" suggestion, burnout426 - it fixes the context problems ('WRONG_THIS_ERR') that induced me to store data in properties-with-funny-names on the HTMLMediaElement itself, which was nasty. I still need the boolean to stop a double pop-up when the page first loads and subsequent ones whenever I restart the video after pausing it. The this.stop() suggestion didn't prevent the load-loop animation, unfortunately. Here's my new userjs that no longer pollutes the HTMLMediaElement namespace and successfully stops the dollarshaveclub video: (function () { var okToPlay; var play = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function() { if (typeof okToPlay === 'undefined') okToPlay = confirm("Play multimedia?"); if (okToPlay) play.call(this); }; HTMLMediaElement.prototype.load = function() { }; })(); as long as html5 videos on yt have this bad performance this is needed unconditionally. Random freezes and crashes, most likely caused by GStreamer component, are driving me mad too. Unfortunately, nobody is going to debug that weird issues thoroughly. Originally posted by Lonely Soul: Just discovered that Opera will forget about its embedded media player if you just remove or rename "gstreamer" folder in Opera's installation directory.Random freezes and crashes, most likely caused by GStreamer component, are driving me mad too. Unfortunately, nobody is going to debug that weird issues thoroughly. But will it fall back properly? Originally posted by Lonely Soul: Fall back to what? I assume he meant: <video src="file.ext"> <object type="application/x-shockwave-flash" data="file.swf"></object> </video> <video> is only supposed to fall back if the video element isn't supported. So, if you yank out Opera's video support, the object nested in it should load instead, but will it? Originally posted by burnout426: I assume he meant: Indeed I did. 16. January 2013, 19:25:17 17. January 2013, 19:40:42 Forums » Opera for Windows/Mac/Linux » Desktop wish-list
http://my.opera.com/community/forums/topic.dml?id=1081282&t=1368901179&page=1
CC-MAIN-2013-20
refinedweb
1,400
57.16
Code. Collaborate. Organize. No Limits. Try it Today. In our previous article we had compared MVC implementation for J2ee and ASP.NET without using frameworks; to view comparison click ASP.NET MVC and J2ee MVC. In today’s world no one implements MVC without help of frameworks. So it’s either ASP.NET or j2ee, framework support is a must. Struts 2 has been the most accepted framework in J2ee while in ASP.NET the ASP.NET MVC template is the king. In this article we will compare these frameworks in terms of how they differ in implementation and their positive and negative points. In this article we will compare both frameworks using 8 agenda points: - Do watch our .Net interview questions and answers video from this link .NET interview questions and answers, you can also catch out J2ee Design pattern videos from this link Java J2ee Design pattern. In case you are not aware of the frameworks you can see the below videos to just get a quick start in both the frameworks Click here to view simple ASP.NET MVC video which displays a hello world. Click here to view simple J2EE struts video to teach struts 2 with the help of an example. Before even I start below is a full comparison sheet which gives an overall view of the comparison. The same we will be discussing in more detail as we proceed in the article. The first thing which caught our eyes is the Microsoft VS IDE which has a nice readymade template from where developers can start. In MVC J2ee framework the core struts framework does not have something inherent as Microsoft MVC has it. Said and done that it does not mean J2EE community is lagging; you can still take help of open source plug-in to get the template from. Below is a simple snapshot of MVC web project template. The only difference it’s not inherent like Microsoft MVC. Conclusion: - Definitely Microsoft wins here in terms of more user friendly interfaces and automation due to the MVC template. In j2ee struts framework we need to hunt for a third party plug which will help us to achieve the same kind automation. In MVC one of the most crucial parts is transferring data from controller to view. Microsoft MVC introduces a new variable called as ‘ViewData’ which will help us to transport data between controller and view as shown in the below code snippet. The below code snippet sets data in the controller. ViewData["CurrentTime"] = DateTime.Now.ToString(); The below code snippet displays data on the view. J2ee Struts framework uses the HTTP request object to pass data from controller to the view. The below code snippet sets a simple date value to the request object using the ‘setAttribute’ function. In ASP.NET MVC we cannot change the request object. request.setAttribute(“CurrentTime”,new Date()); Later we can display the data using ‘getAttribute’. Conclusion: - First thing both the technologies have the facility of passing data, but somehow j2ee Struts framework thought process looks more convincing. At the end of the day view gets a HTTP request, so it’s more logical to pass data using the request objects rather than creating a new variable like view data for the same. Many ASP.NET MVC fans (which includes me) can also argue logically that the request object is created by using the data sent by the end user i.e. from the browser. This data should not be allowed to be changed in between by the web application code. The request object should only be allowed to be modified by the end user using POST and GET. For this I will give equal point to both of them for now. In ASP.NET MVC the template creates a readymade folder structure (they are termed as areas) which gives a developer a clear picture of where to store the model, views and controllers as shown in the below figure. In j2EE struts framework we do not have the clear cut vocabulary for folders as we have in ASP.NET MVC. In J2EE framework the controller and model lies in Java resources folder, while the views are saved in web content folder as show in the below diagram. Said and done you can always manually rename and create different folder structure to have the same logical representation as we have in ASP.NET MVC , only that it’s not automated. As per our knowledge the above logical structure is not possible currently by using any J2EE struts plug-in either. Conclusion: - ASP.NET MVC has a slight advantage in terms of better project management due to readymade logical folder structure, while in J2ee framework we need to create them manually. In ASP.NET MVC you have a nice option where you can create strongly typed view. In other words when you add a view you can select the model with which this view will connect. Later when you go in the view and type model keyword you can get the properties of the object in a strongly typed manner. In java we do not have the concept of strongly typed view. If you want you can set the object in request.getAttribute and then to a type cast to get the object intellisense. Conclusion: - This feature can look very exciting for ASP.NET community but it was bit amusing for my J2ee friends (I think they are right in lot of sense also). The whole purpose of strong typed views in ASP.NET MVC is for better intellisense which we can be achieved by type casting data from view data object as shown in the below figure. The biggest problem here is that developers can start thinking that the model is tied up the view. We understand the intention is not that, but the dialog box just makes a visual intention of doing the same. The end goal of MVC is to separate the model from the view. So concluding it’s a good feature to get maximum from less code but just that it can be confusing for junior developers who are working on MVC. For a small automation I hope we do not end with a logical confusion about MVC fundamental. Equal points again to both. I am not giving an extra point to ASP.NET MVC as view thing is more confusing and can be achieved by typecasting. A good MVC framework will always provide helper classes to create HTML code for views. In ASP.NET MVC we have the helper classes. For instance to create a simple HTML form in ASP.NET MVC you can use the HTML helper class as shown in the below code. In j2ee struts framework we have tag libraries which help us to generate the HTML code as it is done by using ASP.NET MVC html helper classes. Conclusion: - Both the frameworks have HTML helper classes. Let’s not get in to which library is better or else we will lose focus on our main comparison. So even points to both the framework on this discussion. MVC is all about actions and these actions are mapped to URL. As a developer you would love to see your MVC framework have the capability of customizing and configuring the MVC URL with action mapping. Below is a simple table which explains why developers would expect customization and configuration for MVC URL’s. In ASP.NET MVC this is achieved by using the inbuilt routing mechanism. In order to configure routes you can go to the global.asx.cs code and use the routes collection to map the URL structure with the controllers and actions. routes.MapRoute( "HelloWorld", // Route name "Pages/RegisterAction/{1}", // URL with parameters new { controller = "Register", action = "RegisterAction", id = UrlParameter.Optional }); // Parameter defaults In order to configure MVC URL in J2ee struts framework we can use the Struts XML file to the same. The below mapping is more clean than the routing collection of ASP.NET MVC. In J2ee framework we can see the mappings more better as they are mapped directly to page names. Conclusion: - J2ee Struts framework definitely wins in terms of MVC URL configuration and mapping to the controller as its defined using XML file. This thing can be really improved in ASP.NET MVC framework. To change the mapping compiling code is more of a burden. In ASP.NET MVC we have the advantage of doing URL validation using regex (regular expression) before the action hits the controller. For instance below is a simple validation where before the view customer action is called we can check that the input to the action is only numeric value with 2 digits. routes.MapRoute( "View", // Route name "View/ViewCustomer/{id}", // URL with parameters new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id = @"\d{1,2}" } ); Currently J2ee struts framework does not support the same, said and done you can always still do validation after hitting the controller using some custom logic. Conclusion: - This is definitely a plus point for ASP.NET MVC because MVC URL’s can be invoked from any medium, via browser, via URLs etc. So we would like to ensure that appropriate validation is checked much before it hits the controller. MVC URL’s are mapped to action and they can be invoked directly which also means that they are subjected to cross site attacks, sql injection etc. ASP.NET MVC framework has provided security attributes by which we can protect our URL from such attacks. For instance to prevent forgery attacks and cross site scripting attacks we can use the ‘HtmLAntiForgeryToken()’ as shown in the below code snippet. In the actions later you can then check if there was any violation. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int customerid) { } You can also mark the controller by using validate input attribute to avoid CSS. [ValidateInput(true)] public class OurController : Controller Critical functions on which you do not want actions to be invoked you can mark the methods as ‘nonaction’ as shown in the below code snippet. [NonAction] public void DoPasswordChange(string username, string newpassword) { /* Rest of code unchanged */ } In J2ee Struts framework currently we do not have any inherent security function to achieve the same. Some customized code. Conclusion: - This is the biggest win for ASP.NET MVC framework security. Hope that J2ee struts framework in coming times has such kind of inherent security feature which will be a great extra added advantage for the framework. Below is the final conclusion. ASP.NET MVC framework out performs J2ee in 4 things while J2ee has the flexible XML URL customization which is currently not available in ASP.NET MVC. For all the other points both of them remain on the same page. I have tried my level best to put forward both the sides and while doing so I never had in my mind that I am an ASP.NET Microsoft MVP and I should hard sell ASP.NET MVC framework. I have made by best effort to make a true comparison and see which one of them is the best. I do understand how every developer loves his technology, by any chance I have hurted….BIG SORRY. Special thanks to Mr Vishwanathan Narayanan who helped me to give inputs on the J2EE side without which I would not have achieved the same. You can see his Java and j2ee design patterns videos by clicking on Java J2ee Design pattern Member 9649062 wrote:You can also mark the controller by using validate input attribute to avoid CSS. cross site scripting is XSS not CSS.. tecgoblin wrote:The guy compared MVC 2 (instead of 3 which is way better), luisserrano wrote:I would have chosen to compare .Net MVC against Spring MVC, which is really good and also has its own IDE, like .Net has General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/187556/Comparison-of-MVC-implementation-between-J2EE-Stru?fid=1623274&df=10000&mpp=50&noise=5&prof=True&sort=Position&view=None&spc=None&select=3877430&fr=1
CC-MAIN-2014-23
refinedweb
2,009
72.05
- Install the GitLab.com for Jira Cloud application for self-managed instances - Troubleshooting GitLab.com for Jira Cloud GitLab.com for Jira Cloud app You can integrate GitLab.com and Jira Cloud using the GitLab.com for Jira Cloud app in the Atlassian Marketplace. The user configuring GitLab.com for Jira Cloud must have Maintainer permissions in the GitLab.com namespace. This integration method supports smart commits. This method is recommended when using GitLab.com and Jira Cloud because data is synchronized in real-time. The DVCS connector updates data only once per hour. If you are not using both of these environments, use the Jira DVCS Connector method. For a walkthrough of the integration with GitLab.com for Jira Cloud, watch Configure GitLab.com Jira Could Integration using Marketplace App on YouTube. - Go to Jira Settings > Apps > Find new apps, then search for GitLab. Click GitLab.com for Jira Cloud, then click Get it now, or go to the App in the marketplace directly. After installing, click Get started to go to the configurations page. This page is always available under Jira Settings > Apps > Manage apps. If not already signed in to GitLab.com, you must sign in as a user with Maintainer permissions to add namespaces. Select Add namespace to open the list of available namespaces. Identify the namespace you want to link, and select Link. Only Jira site administrators are permitted to add or remove namespaces for an installation. After a namespace is added: - All future commits, branches, and merge requests of all projects under that namespace are synced to Jira. - From GitLab 13.8, past merge request data is synced to Jira. Support for syncing past branch and commit data is planned. Install the GitLab.com for Jira Cloud application for self-managed instances If your GitLab instance is self-managed, you must follow some extra steps to install the GitLab.com for Jira Cloud application. Each Jira Cloud application must be installed from a single location. Jira fetches a manifest file from the location you provide. The manifest file describes the application to the system. To support self-managed GitLab instances with Jira Cloud, you can either: Install the application manually You can configure your Atlassian Cloud instance to allow you to install applications from outside the Marketplace, which allows you to install the application: - Sign in to your Jira instance as a user with administrator permissions. - Place your Jira instance into development mode. - Sign in to your GitLab application as a user with Administrator permissions. - Install the GitLab application from your self-managed GitLab instance, as described in the Atlassian developer guides: In your Jira instance, go to Apps > Manage Apps and click Upload app: - For App descriptor URL, provide full URL to your manifest file, modifying this URL based on your instance configuration: - Click Upload, and Jira fetches the content of your app_descriptorfile and installs it for you. If the upload is successful, Jira displays a modal panel: Installed and ready to go! Click Get started to configure the integration. - Disable development mode on your Jira instance. The GitLab.com for Jira Cloud app now displays under Manage apps. You can also click Get started to open the configuration page rendered from your GitLab instance. Create a Marketplace listing If you prefer to not use development mode on your Jira instance, you can create your own Marketplace listing for your instance, which enables your application to be installed from the Atlassian Marketplace. For full instructions, review the Atlassian guide to creating a marketplace listing. To create a Marketplace listing, you must: - Register as a Marketplace vendor. - List your application, using the application descriptor URL. - Your manifest file is located at: - GitLab recommends you list your application as private, because public applications can be viewed and installed by any user. - Generate test license tokens for your application. Review the official Atlassian documentation for details. Troubleshooting GitLab.com for Jira Cloud The GitLab.com for Jira Cloud app uses an iframe to add namespaces on the settings page. Some browsers block cross-site cookies. This can lead to a message saying that the user needs to log in on GitLab.com even though the user is already logged in. “You need to sign in or sign up before continuing.” In this case, use Firefox or enable cross-site cookies in your browser.
https://docs.gitlab.com/14.0/ee/integration/jira/connect-app.html
CC-MAIN-2021-39
refinedweb
727
50.73
Quota Introduction IMAP can be used to archive all your messages. This may include 15 apache.org high-traffic mailing lists and a complete collection of all fun-ppt/fun-pics/fun-movies mails + attachments, your funny colleagues have sent to you in the last 5 years. ;-) Reaching a few GiB is possible. That is why setting up a quota might be necessary. (If you are the sysadmin, you know that sending a daily message to your users "please clean up your mailbox" is really futile.) Sooner or later your boss will notice that you are deleting old messages underhand... Interfaces see Quota and ImapMailboxRepository General Quota objects are responsible for a list of mailboxes. They are not treated hierarchically but have to be assigned to each mailbox individually. When a mailbox is created or renamed, it has to inherit the quota of its parent. Implementation of quota management could of course be done in a hierarchy way. I came to the conclusion that it makes no sense to have user specific quotas. E.g. user1 has a 100 MB quota for the whole namespace. He is employee in the buying department. Why shouldn't he store an important message into #shared.buying, just because he has exceeded his personal quota? Forcing the buying department to clean up their shared mailbox not to reach a limit of 1 GiB makes sense. Root-Mailbox Quotas are not hierarchy agnostic. One quota-object could be responsible for a selection of mailboxes even across namespaces. But this makes management of quotas very complex. It may even be desirable to allow users to setup their own quotas e.g. for their trash folder. This would also require checking credentials. The approach is to allow setting a root mailbox for a quota. Only this mailbox itself and children are allowed to be added. Users could be restricted in only being allowed to setup quotas with a root mailbox they have the "quota management" right for. quotas bound to a root mailbox are more easy to browse in a management interface. Many-To-Many Because quotas are not hierarchy agnostic, they are not inherited automatically. There are situations where a mailbox may be bound to several quota object. E.g. #mail.user1.Trash has a quota of 10 MB setup by user1. #mail.user1 has a quota of 100 MB setup by his local sysadmin. "#mail" has a quota of 5 GiB and there is a system wide quota of 10 GiB bound to all mailboxes. This means "#mail.user1.Trash" is bound to 4 quota objects. If any of the 4 quotas is exceeded he cannot store a message. Quotas In JDBC In a RDBMS each quota object should hold the current usage. It will need too much time to compute it always on the fly. This means when a message is appended to a mailbox every quota object bound to this mailbox has to be updated. A system-wide quota object has to be update every time a message is appended somewhere Incrementing an integer value should not be so time intensive. Transactions will guarantee a consistent state. This is how I think such a transaction could work: 1. Fetch all quota objects bound to "#mail.user1.Trash" and check if there is enough space to try the transaction 2. Start transaction 3. Store the header 4. Store the message (this may take long) 5. update the quota objects ( No one else is able to update these quota objects anymore) 6. Check if we are in the limit (doing a select now should give us the updated values) 7. Commit if we are in, rollback if we are out The weak point is that if there is a system-wide quota noone else could append a message anywhere between 5 and 7. Do we have to worry about that? Normally this could be done in a few milliseconds. The expensive parts (storing content) are non-blocking. --------------------------------------------------------------------- To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org For additional commands, e-mail: server-dev-help@james.apache.org
http://mail-archives.us.apache.org/mod_mbox/james-server-dev/200607.mbox/%3C1152023281.20399.61.camel@localhost%3E
CC-MAIN-2019-18
refinedweb
683
67.86
Level 1 Level 2 Learn More Likes Total Posts Correct Reply 07-01-2021 I have a requirement that <b> tag should be converted into <strong> after submitting. I was able to achieve this by introducing below node structure as a sibling to rtsPlugins of my text component in apps. <htmlRules jcr: <docType jcr: <typeConfig jcr: @useSemanticMarkup Boolean true </typeConfig> <docType<htmlRules Problem is in our site already we have used RTE for more that 500 odd places and those RTE ,The new change is not getting reflected unless manually editing those RTE components(need to hit twice B icon).Is there anyway to overcome that existing RTE s in pages not getting reflected that change <b> to <strong>. Thanks in advance. Hi, You can try replacing the <b> to <strong> in java while reading value from node property and displaying in htl. This will not replace <b> to <strong> in the jcr node but for in html it will have <strong> instead of <b> for already added rte's. The content is already stored in the repository, so the only way you can fix this is by writing Groovy Script, the below script can help you to fix this Note: the code is not tested and it is self-understanding you can modify it if it does not work for you def search = "<b>"def replace = "<strong>"def path = "/content"def property = 'jcr:description';def query = createSQL2Query(path, search , property)def result = query.execute()result.nodes.each{node ->def description = node.get(property)println descriptionnode.set('jcr:description', description.replaceAll(search ,replace))println node.path}save()def createSQL2Query(path, search, property) {def queryManager = session.workspace.queryManagerdef statement = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([${path}]) and s.[${property}] like '%${search}%'"def query = queryManager.createQuery(statement, "JCR-SQL2")query} Write a groovy script to update existing nodes , It is not possible to change the existing stored content without editing manually or via script.
https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem-6-5-lt-b-gt-to-lt-strong-gt-in-rte/qaq-p/392727
CC-MAIN-2021-31
refinedweb
324
51.07
UIScrollView Tutorial: Getting Started Learn how to use UIScrollViews for paging, zooming, scrolling, and more! Update Note: This tutorial has been updated to Xcode 9.0 and Swift 4 by Owen Brown. The original tutorial was written by Ray Wenderlich. UIScrollView is one of the most versatile and useful controls in iOS. It is the basis for the very popular UITableView and is a great way to present content larger than a single screen. In this UIScrollView tutorial, you’ll create an app that’s very similar to the Photos app and learn all about UIScrollView. You’ll learn: - How to use a UIScrollViewto zoom and view a very large image. - How to keep the UIScrollView‘s content centered while zooming. - How to use UIScrollViewfor vertical scrolling with Auto Layout. - How to keep text input components visible when the keyboard is displayed. - How to use UIPageViewControllerto allow scrolling through multiple pages of content. This tutorial assumes you understand how to use Interface Builder to add objects and connect outlets between your code and storyboard scenes. If you’re not familiar with Interface Builder or Storyboards, work through our Storyboards tutorial before this one. Getting Started UIScrollView tutorial, and then open it in Xcode. Build and run to see what you’re starting with: You can select a photo to see it full sized, but sadly, you can’t see the whole image due to the limited size of the device. What you really want is to fit the image to the device’s screen by default, and zoom to see details just like the Photos app. Can you fix it? Yes you can! Scrolling and Zooming a Large Image To kick off this UIScrollView tutorial, you’ll set up a scroll view that lets the user pan and zoom an image. Open Main.storyboard, and drag a Scroll View from the Object Library onto the Document Outline right below View on the Zoomed Photo View Controller scene. Then, move Image View inside your newly-added Scroll View. Your Document Outline should now look like this: See that red dot? Xcode is complaining that your Auto Layout rules are wrong. To fix them, select Scroll View and tap the pin button at the bottom of the storyboard window. Add four new constraints: top, bottom, leading and trailing. Set each constraint’s constant to 0, and uncheck Constrain to Margins. This should look like this: Now select Image View and add the same four constraints on it too. If you get an Auto Layout warning afterwards, select Zoomed Photo View Controller in the Document Outline and then select Editor\Resolve Auto Layout Issues\Update Frames. If you don’t get a warning, Xcode likely updated the frames automatically for you, so you don’t need to do anything. Build and run. Thanks to the scroll view, you can now see the full-size image by swiping! But what if you want to see the picture scaled to fit the device screen? Or what if you want to zoom in and out? You’ll need to write code for these! Open ZoomedPhotoViewController.swift, and add the following outlets inside the class declaration: @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint! Back in Main.storyboard, set the scrollView outlet to the Scroll View, and set the Scroll View's delegate to Zoomed View Controller. Also, connect the new constraint outlets the appropriate constraints in the Document Outline like this: Back in ZoomedPhotoViewController.swift, add the following to the end of the file: extension ZoomedPhotoViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } } This makes ZoomedPhotoViewController conform to UIScrollViewDelegate and implement viewForZooming(in:). The scroll view calls this method to get which of its subviews to scale whenever its pinched, and here you tell it to scale imageView. Next, add the following inside the class right after viewDidLoad(): fileprivate func updateMinZoomScaleForSize(_ size: CGSize) { let widthScale = size.width / imageView.bounds.width let heightScale = size.height / imageView.bounds.height let minScale = min(widthScale, heightScale) scrollView.minimumZoomScale = minScale scrollView.zoomScale = minScale } This method calculates the zoom scale for the scroll view. A zoom scale of one indicates that the content is displayed at normal size. A zoom scale less than one shows the content zoomed out, and a zoom scale greater than one shows the content zoomed in. To get the minimum zoom scale, you first calculate the required zoom to fit the image view snugly within the scroll view based on its width. You then calculate the same for the height. You take the minimum of the width and height zoom scales, and set this for both minimumZoomScale and zoomScale on the scroll view. Thereby, you’ll initially see the entire image fully zoomed out, and you’ll be able to zoom out to this level too. Since the maximumZoomScale defaults to 1, you don’t need to set it. If you set it to greater than 1, the image may appear blurry when fully zoomed in. If you set it to less than 1, you wouldn’t be able to zoom in to the full image’s resolution. Finally, you also need to update the minimum zoom scale each time the controller updates its subviews. Add the following right before the previous method to do this: override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateMinZoomScaleForSize(view.bounds.size) } Build and run, and you should get the following result: You can now pan and zoom, and the image initially fits on the screen. Awesome! However, there’s still one problem: the image is pinned to the top of the scroll view. It’d sure be nice to have it centered instead, right? Still in ZoomedPhotoViewController.swift, add the following inside the class extension right after viewForZooming(in:) func scrollViewDidZoom(_ scrollView: UIScrollView) { updateConstraintsForSize(view.bounds.size) } fileprivate func updateConstraintsForSize(_ size: CGSize) { let yOffset = max(0, (size.height - imageView.frame.height) / 2) imageViewTopConstraint.constant = yOffset imageViewBottomConstraint.constant = yOffset let xOffset = max(0, (size.width - imageView.frame.width) / 2) imageViewLeadingConstraint.constant = xOffset imageViewTrailingConstraint.constant = xOffset view.layoutIfNeeded() } The scroll view calls scrollViewDidZoom each time the user scrolls. In response, you simply call updateConstraintsForSize(_:) and pass in the view’s bounds size. updateConstraintsForSize(_:) gets around an annoyance with UIScrollView: if the scroll view’s content size is smaller than its bounds, the contents are placed at the top-left rather than the center. You get around this by adjusting the layout constraints for the image view. You first center the image vertically by subtracting the height of imageView from the view‘s height and dividing it in half. This value is used as padding for the top and bottom imageView constraints. Similarly, you calculate an offset for the leading and trailing constraints of imageView based on the width. Give yourself a pat on the back, and build and run your project! Select an image, and if everything went smoothly, you’ll end up with a lovely image that you can zoom and pan. :] Scrolling Vertically Now suppose you want to change PhotoScroll to display the image at the top and add comments below it. Depending on how long the comment is, you may end up with more text than your device can display: Scroll View to the rescue! Note: In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. However, UIScrollView scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the edges within a scroll view actually refer to the edges of its content view. To size the scroll view’s frame with Auto Layout, constraints must either be explicit regarding the width and height of the scroll view, or the edges of the scroll view must be tied to views outside of its own subtree. You can read more in this technical note from Apple. You’ll next learn how to fix the width of a scroll view, which is really its content size width, using Auto Layout. Scroll View and Auto Layout Open Main.storyboard and lay out a new scene: First, add a new View Controller. In the Size Inspector replace Fixed with Freeform for the Simulated Size, and enter a width of 340 and a height of 800. You’ll notice the layout of the controller gets narrower and longer, simulating the behavior of a long vertical content. The simulated size helps you visualize the display in Interface Builder. It has no runtime effect. Uncheck Adjust Scroll View Insets in the Attributes Inspector for your newly created view controller. Add a Scroll View that fills the entire space of the view controller. Add leading and trailing constraints with constant values of 0 to the view controller, and make sure to uncheck Constrain to margin. Add top and bottom constraints from Scroll View to the Top and Bottom Layout guides, respectively. They should also have constants of 0. Add a View as a child of the Scroll View, and resize it to fit the entire space of the Scroll View. Rename its storyboard Label to Container View. Like before, add top, bottom, leading and trailing constraints, with constants of 0 and unchecked Constrain to Margins. To fix the Auto Layout errors, you need to specify the scroll view’s size. Set the width of Container View to match the view controller’s width. Attach an equal-width constraint from the Container View to the View Controller’s main view. For the height of Container View, define a height constraint of 500. Note: Auto Layout rules must comprehensively define a Scroll View’s contentSize. This is the key step in getting a Scroll View to be correctly sized when using Auto Layout. Add an Image View inside Container View. In the Attributes Inspector, specify photo1 for the image; choose Aspect Fit for the mode; and check clips to bounds. Add top, leading, and trailing constraints to Container View like before, and add a height constraint of 300. Add a Label inside Container View below the image view. Specify the label’s text as What name fits me best?, and add a centered horizontal constraint relative to Container View. Add a vertical spacing constraint of 0 with Photo View. Add a Text Field inside of Container View below the new label. Add leading and trailing constraints to Container View with constant values of 8, and no margin. Add a vertical-space constraint of 30 relative to the label. You next need to connect a segue to your new View Controller. To do so, first delete the existing push segue between the Photo Scroll scene and the Zoomed Photo View Controller scene. Don’t worry, all the work you’ve done on Zoomed Photo View Controller will be added back to your app later. In the Photo Scroll scene, from PhotoCell, control-drag to the new View Controller, add a show segue. Make the identifier showPhotoPage. Build and Run. You can see that the layout is correct in vertical orientation. Try rotating to landscape orientation. In landscape, there is not enough vertical room to show all the content, yet the scroll view allows you to properly scroll to see the label and the text field. Unfortunately, since the image in the new view controller is hard-coded, the image you selected in the collection view is not shown. To fix this, you need to pass the image name to the view controller when the segue is executed. Create a new file with the iOS\Source\Cocoa Touch Class template. Name the class PhotoCommentViewController, and set the subclass to UIViewController. Make sure that the language is set to Swift. Click Next and save it with the rest of the project. Replace the contents of PhotoCommentViewController.swift with this code: import UIKit class PhotoCommentViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var nameTextField: UITextField! var photoName: String? override func viewDidLoad() { super.viewDidLoad() if let photoName = photoName { self.imageView.image = UIImage(named: photoName) } } } This adds IBOutlets and sets the image of imageView based on a passed-in photoName. Back in the storyboard, open the Identity Inspector for View Controller, and select PhotoCommentViewController for the Class. Then wire the IBOutlets for the Scroll View, Image View and Text Field. Open CollectionViewController.swift, and replace prepare(segue:sender:) with this: override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UICollectionViewCell, let indexPath = collectionView?.indexPath(for: cell), let photoCommentViewController = segue.destination as? PhotoCommentViewController { photoCommentViewController.photoName = "photo\(indexPath.row + 1)" } } This sets the name of the photo to be shown on PhotoCommentViewController whenever one of the photos is tapped. Build and run. Your view nicely displays the content and when needed allows you to scroll down to see more. You’ll notice two issues with the keyboard: first, when entering text, the keyboard hides the Text Field. Second, there is no way to dismiss the keyboard. Ready to fix the glitches? Managing the Keyboard Unlike UITableViewController, which automatically handles moving content out of the way of the keyboard, you manually have to manage the keyboard when you use a UIScrollView directly. You can do this by making PhotoCommentViewController observe keyboard Notification objects sent by iOS whenever the keyboard will show and hide. Open PhotoCommentViewController.swift, and add the following code at the bottom of viewDidLoad() (ignore the compiler errors for now): NotificationCenter.default.addObserver( self, selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil ) Next, add the following method to stop listening for notifications when the object’s life ends: deinit { NotificationCenter.default.removeObserver(self) } Then add the promised methods from above to the view controller: func adjustInsetForKeyboardShow(_ show: Bool, notification: Notification) { let userInfo = notification.userInfo ?? [:] let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let adjustmentHeight = (keyboardFrame.height + 20) * (show ? 1 : -1) scrollView.contentInset.bottom += adjustmentHeight scrollView.scrollIndicatorInsets.bottom += adjustmentHeight } @objc func keyboardWillShow(_ notification: Notification) { adjustInsetForKeyboardShow(true, notification: notification) } @objc func keyboardWillHide(_ notification: Notification) { adjustInsetForKeyboardShow(false, notification: notification) } adjustInsetForKeyboardShow(_:,notification:) takes the keyboard’s height as delivered in the notification and adds a padding value of 20 to either be subtracted from or added to the scroll views’s contentInset. This way, the UIScrollView will scroll up or down to let the UITextField always be visible on the screen. When the notification is fired, either keyboardWillShow(_:) or keyboardWillHide(_:) will be called. These methods will then call adjustInsetForKeyboardShow(_:,notification:), indicating which direction to move the scroll view. Dismissing the Keyboard To dismiss the keyboard, add this method to PhotoCommentViewController.swift: @IBAction func hideKeyboard(_ sender: AnyObject) { nameTextField.endEditing(true) } This method will resign the first responder status of the text field, which will in turn dismiss the keyboard. Finally, open Main.storyboard, and from Object Library drag a Tap Gesture Recognizer onto the View on the Photo Comment View Controller scene. Then, wire it to the hideKeyboard(_:) IBAction in Photo Comment View Controller. To make it more user friendly, the keyboard should also dismiss when the return key is pressed. Right click on nameTextField and wire Primary Action Triggered to hideKeyboard(_:) also. Build and run. Navigate to the Photo Comment View Controller scene. Tap the text field and then tap somewhere else on the view. The keyboard should properly show and hide itself relative to the other content on the screen. Likewise, tapping the return key does the same. Paging with UIPageViewController In the third section of this UIScrollView tutorial, you’ll create a scroll view that allows paging. This means that the scroll view locks onto a page when you stop dragging. You can see this in action in the App Store app when you view screenshots of an app. Go to Main.storyboard and drag a Page View Controller from the Object Library. Open the Identity Inspector and enter PageViewController for the Storyboard ID. In the Attributes Inspector, the Transition Style is set to Page Curl by default; change it to Scroll and set the Page Spacing to 8. In the Photo Comment View Controller scene’s Identity Inspector, specify a Storyboard ID of PhotoCommentViewController, so that you can refer to it from code. Open PhotoCommentViewController.swift and add this property after the others: var photoIndex: Int! This will reference the index of the photo to show and will be used by the page view controller. Create a new file with the iOS\Source\Cocoa Touch Class template. Name the class ManagePageViewController and set the subclass to UIPageViewController. Open ManagePageViewController.swift and replace the contents of the file with the following: import UIKit class ManagePageViewController: UIPageViewController { var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"] var currentIndex: Int! override func viewDidLoad() { super.viewDidLoad() // 1 if let viewController = viewPhotoCommentController(currentIndex ?? 0) { let viewControllers = [viewController] // 2 setViewControllers( viewControllers, direction: .forward, animated: false, completion: nil ) } } func viewPhotoCommentController(_ index: Int) -> PhotoCommentViewController? { guard let storyboard = storyboard, let page = storyboard.instantiateViewController(withIdentifier: "PhotoCommentViewController") as? PhotoCommentViewController else { return nil } page.photoName = photos[index] page.photoIndex = index return page } } Here’s what this code does: viewPhotoCommentController(_:_)creates an instance of PhotoCommentViewControllerthough the Storyboard. You pass the name of the image as a parameter so that the view displayed matches the image you selected in previous screen. - You setup the UIPageViewControllerby passing it an array that contains the single view controller you just created. You next need to implement UIPageViewControllerDataSource. Add the following class extension to the end of this file: extension ManagePageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, index > 0 { return viewPhotoCommentController(index - 1) } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, (index + 1) < photos.count { return viewPhotoCommentController(index + 1) } return nil } } The UIPageViewControllerDataSource allows you to provide content when the page changes. You provide view controller instances for paging in both the forward and backward directions. In both cases, photoIndex is used to determine which image is currently being displayed. The viewController parameter to both methods indicates the currently displayed view controller, and based on the photoIndex, a new controller is created and returned. You also need to actually set the dataSource. Add the following to the end of viewDidLoad(): dataSource = self There are only a couple things left to do to get your page view running. First, you will fix the flow of the application. Switch back to Main.storyboard and select your newly created Page View Controller scene. In the Identity Inspector, specify ManagePageViewController for its class. Delete the push segue showPhotoPage you created earlier. Then control drag from Photo Cell in Scroll View Controller to Manage Page View Controller Scene and select a Show segue. In the Attributes Inspector for the segue, specify its name as showPhotoPage as before. Open CollectionViewController.swift and change the implementation of prepare(segue:sender:) to the following: override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UICollectionViewCell, let indexPath = collectionView?.indexPath(for: cell), let managePageViewController = segue.destination as? ManagePageViewController { managePageViewController.photos = photos managePageViewController.currentIndex = indexPath.row } } Build and run. You can now scroll side to side to page between different detail views. :] Displaying a Page Control Indicator For the final part of this UIScrollView tutorial, you will add a UIPageControl to your application. Fortunately, UIPageViewController has the ability to automatically provide a UIPageControl. To do so, your UIPageViewController must have a transition style of UIPageViewControllerTransitionStyleScroll, and you must provide implementations of two special methods on UIPageViewControllerDataSource. You previously set the Transition Style- great job!- so all you need to do is add these two methods inside the UIPageViewControllerDataSource extension on ManagePageViewController: func presentationCount(for pageViewController: UIPageViewController) -> Int { return photos.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentIndex ?? 0 } In presentationCount(for:), you specify the number of pages to display in the page view controller. In presentationIndex(for:), you tell the page view controller which page should initially be selected. After you've implemented the required delegate methods, you can add further customization with the UIAppearance API. In AppDelegate.swift, replace application(application: didFinishLaunchingWithOptions:) with this: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let pageControl = UIPageControl.appearance() pageControl.pageIndicatorTintColor = UIColor.lightGray pageControl.currentPageIndicatorTintColor = UIColor.red return true } This will customize the colors of the UIPageControl. Build and run. Putting it all together Almost there! The very last step is to add back the zooming view when tapping an image. Open PhotoCommentViewController.swift, and add the following to the end of the class: @IBAction func openZoomingController(_ sender: AnyObject) { self.performSegue(withIdentifier: "zooming", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let id = segue.identifier, let zoomedPhotoViewController = segue.destination as? ZoomedPhotoViewController, id == "zooming" { zoomedPhotoViewController.photoName = photoName } } In Main.storyboard, add a Show Detail segue from Photo Comment View Controller to Zoomed Photo View Controller. With the new segue selected, open the Identity Inspector and set the Identifier to zooming. Select the Image View in Photo Comment View Controller, open the Attributes Inspector and check User Interaction Enabled. Drag a Tap Gesture Recognizer onto the Image View, and connect it to openZoomingController(_:). Now, when you tap an image in Photo Comment View Controller Scene, you'll be taken to the Zoomed Photo View Controller Scene where you can zoom the photo. Build and run one more time. Yes, you did it! You've created a Photos app clone: a collection view of images you can select and navigate through by swiping, as well as the ability to zoom the photo content. Where to Go From Here? Here is the final PhotoScroll project with all of the code from this UIScrollView tutorial. You’ve delved into many of the interesting things that a scroll view is capable of. If you want to go further, there is an entire video series dedicated to scroll views. Take a look. Now go make some awesome apps, safe in the knowledge that you’ve got mad scroll view skillz! If you run into any problems along the way or want to leave feedback about what you've read here, join the discussion in the comments below. Team Each tutorial at is created by a team of dedicated developers so that it meets our high quality standards. The team members who worked on this tutorial are: - Author Owen L Brown - Tech Editor Joshua Greene - Final Pass Editor Richard Turton - Team Lead Andy Obusek
https://www.raywenderlich.com/159481/uiscrollview-tutorial-getting-started
CC-MAIN-2017-26
refinedweb
3,772
50.02
2 Answers2. There's copy constructor and there's assignment operator. Since A != B, the copy assignment operator will be called. Short answer: operator = from class A, since you're assigning to class A. A=B will not work, since A and B are class types. In which case, operator = for class A will be called. t2 = t1 .x; c = other.c; s = other.s; return *this; } In general, any time you need to write your own custom copy constructor, you also need to write a custom assignment operator In your real code you'd probably use a scoped pointer. Prior to C++11, all assignment was via copy construction and assignment operators. You would copy one instance to another via a constructor and also by an assignment operator. In some cases a constructor will be used instead of an assignment In C++, assignment and copy construction are different because the copy constructor initializes uninitialized memory, whereas assignment starts with an existing initialized object. If your class contains instances of other classes as data members, the copy constructor must first construct these data members before it calls operator= final (C++11) Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members In case of parameterized constructor, you can use following syntax to initialize the fields −. If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use same syntax and separate the fields by comma as follows −. C::C ( double a, double b, double c): X (a), Y (b), Z (c) {. Copy Operator C Constructor Assignment Vs. Filter_none. s Pointer to a null-terminated sequence of characters Declare a copy constructor and assignment operator. A move assignment operator has the following signature: C& C::operator=(C&& other);//C++11 move assignment operator. Hence, expensive operations. By default, C++ will provide a copy constructor and copy assignment operator if one is. If the implicitly-declared default constructor is not defined as deleted, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++11), and it has the same effect as a user-defined constructor with empty body and empty initializer list. That is, it calls the default constructors of the bases and of the non-static. However, if C is initialized by a, c. data and. data points to the same place, which will be deleted twice: once C is destroyed, and once a is destroyed. The copying of constructors is different from the assignment operator. When the value is called, it may cause problems. Of course, as stated in Clause 22, the object is rarely called for. There are two ways to initialize a member variable in a C + + class: Constructor initializes the list and the constructor body assignment. Here's how the two approaches are different. The order in which member variables are initialized is in the . Home > Developer > C++. The difference between the C + + constructor initialization list and the assignment in the constructor __jquery. Last Update. //C++03 copy constructor MemoryPage(const MemoryPage&); //C++03 assignment operator MemoryPage& operator=(const MemoryPage&); }; //C++11 move constructor MemoryPage(MemoryPage&& other): size(0), buf(nullptr) { // pilfer other's resource size=other.size; buf=other.buf; // reset other other.size=0; other.buf=nullptr; } //C++11 move assignment operato Copy constructor + assignment constructor of C + + As mentioned in the high quality C programming guide, there are four default constructors in an empty C + + class Originalersatzteile genau passend für Ihr Constructa Gerät In this post, we will understand the difference between copy constructor and assignment operator in C++. Copy Constructor. It is an overloaded constructor. It initializes the new object with an already existing object data/value. It is used when a new object is created with the help of some existing object. Both these objects would be stored in separate memory locations. If no copy constructor. Rule: If you want a move constructor and move assignment that do moves, you'll need to write them yourself.. The book 'Inside the C++ Object Model' says, constructor has an initialization list, so it is easy to avoid calling A's constructor in B's or C's constructor. But an assignment operator doesn't have a similar list, so the compiler is hard to reduce the times of calling A's assignment operator and it leads to call A's assignment operator twice Constructors save time! Take a look at the last example on this page to really understand why. Constructor Parameters. Constructors can also take parameters, which is used to initialize fields. The following example adds a string modelName parameter to the constructor. Inside the constructor we set model to modelName (model=modelName). When we call the constructor, we pass a parameter to the. A constructor like this one, which takes no arguments, is called a parameterless constructor. However, it is often useful to provide additional constructors. For example, we can add a constructor to the Coords class that allows us to specify the initial values for the data members: // A constructor with two arguments. public Coords(int x, int y) { this.x = x; this.y = y; } This allows Coords.. Overloaded assignment and copy constructor. Copy constructor. This version copies the original object member-by-member, which is the most common approach. Copy constructor. When there are many non-pointer members, it may be more efficient to do a byte-wise copy first and then copy each pointer member individually. Note that the order of operations is important: calling memcpy at the end will. Trong bài này chúng ta sẽ cùng tìm hiểu về Copying Constructor và Assignment Constructor, hãy xem ý nghĩa của chúng là gì và chúng được call khi nào. 1. Assignment Operator Assignment Constructor dùng để thay thế data của một đối tượng đã được khởi tạo bằng data của một đối tượng khác. . Hãy xem ví dụ sa Move constructor: C::C (C&&); Move assignment: C& operator= (C&&);. Copy Operator C Constructor Assignment. There are plenty of good books written on the subject, but I found no clear and concise set of rules on the Internet for those who don't want to understand every nuance of the language—and just want the facts By using the assignment operator operator= together with 1 2 Homework Solutions a reference to the class type as the return type and the. Result Version 2 (class C2) is more efficient—when the constructor handles its assignments, the code is both more readable and faster. C# program that benchmarks constructors . using System; using System.Diagnostics; class C1 { public int A; public int B; public C1 () { } } class C2 { int A; int B; public C2 (int a, int b) { A = a; B = b; } } class Program { const int _max = 1000000; static. Copy Constructor in C: Assignment Operator in C: Definition: An entity that works for the creation of an object and does so by initializing it with the same class object that exists already. An entity used to define a new variable that has a beginning value and helps with properties, events, and indexers. Example : It has the first parameter a reference to its class sort. Operator such as. In the constructor you need to assign a value to each of the member variables: Since year has specific values that are allowed, call the setYear function with the value sent. Set make to the value passed. Set speed to zero. You can do this with a simple assignment statement or you can call the setSpeed function. Accessors Appropriate accessor functions should be created to allow values to be. Copy Assignment And C Operator Disable Constructor . Oct 21, 2005 · Degenerating the constructor/copy ector etc. I had forgotten to overload the = operator for one of the complicated objects Dec 13, 2010 · Assignment operator vs copy constructor. Only when we have externally allocated resources, such as memory Jun 22, 2020 · Note that the. In C++, if we do not write our own, then compiler automatically creates a default constructor, a copy constructor and a assignment operator for every class. Question 2. When a copy constructor may be called? A. When an object of the class is returned by value. B. When an object of the class is passed (to a function) by value as an argument. C. When an object is constructed based on another. integer, a default constructor, and a assignment operator. Before the body of the constructor starts to execute all members of the class have to be initialised (so that they are complete objects when the body of the constructor executes). If you want bar and baz to be objects created with a and b passed to their constructors and do not use an initialisation-list you would have to do something. We laudable zeal for reducing duplicate maintenance, some developers make the mistake of writing their class' copy constructors using the assignment operator instead of the other way around. This results in very subtle program bugs that often seem to appear out of no where. Sometimes the program throws an exception, and sometimes it just works wrong without any obvious reason why it should. If you define copy constructors and copy assignment operators for the class that has the stupid CArray on it, there's no need to molest any of your other classes. Frankly, if you'd avoid using microsoft's piece of shit containers and use something well thought out like std::vector you'd not have to write anything at all. Jul 22 '05 #2. This discussion thread is closed. Start new discussion. The. Copy Constructor (Syntax) classname (const classname.. The struct data type can contain other data types so is used for. T has a user-defined move constructor or move assignment operator (this condition only causes the implicitly-declared, not the defaulted, copy constructor to be deleted). (since C++11) Trivial copy constructor. The copy constructor for class T is trivial if all of the following are true: it is not user-provided (that is, it is implicitly-defined or defaulted) ; T has no virtual member. c# assignments. GitHub Gist: instantly share code, notes, and snippets Copy constructors versus assignment operators are not involved with deep copy versus shallow copy. First, the copy consstructor is to initialize a new object with the data from an existing object. Whether it allocates new memory for m_name is irrelevant. Second, the assignment operator replaces the contents of the this object with the contents of the argument object. Whether the assignment. move constructor;. The copy assignment operator is called whenever selected by overload resolution, e.g. when an object appears on the left side of an assignment expression. [] Implicitly-declared copy assignment operatoIf no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class Windows Dev Center. Windows Dev Center. Windows Dev Cent. Copy C Constructor Operator Overloading Assignment. Let's Best Cv Maker App Ios see if that's right. a class), then the assignment operator should be overloaded for the class. The compiler-generated bitwise copy . overloaded assignment operator c. Its node's copy constructor and assignment operator should copy itself and all its descendents. The assignment operator expects the type of both the left- and right-hand side to be the same for successful assignment Assignment Operator (=) = is an Assignment Operator in C, C++ and other programming languages, It is Binary Operator which operates on two operands. Dec 13, 2010 · The difference between copy constructor and assignment operator is that assignment operator is used to copy the. 今天我们先来聊聊其中的copy constructor、copy-assignment operator的destructor这三个。 copy constructor. copy constructor:一个constructor如果他的第一个参数是对类的引用,且其他的参数都有缺省值(default values)则,这是一个copy constructor。 1,第一个参数必须是引用类型,因为当我们把一个object当做参数传递给一个. class Sample { private: int x; double y; public : Sample(); //Constructor 1 Sample(int); //Constructor 2 Sample(int, int); //Constructor 3 Sample(int, double); //Constructor 4 }; i. Write the definition of the constructor 1 so that the private member variables are initialized to 0. ii. Write the definition of the constructor 2 so that the private member variable x is initialized according to the value of the parameter, and the private member variable y is initialized to 0 I still want the default copy constructor / assignment operator functionality to happen-- ie, just copy over every field of the class. Since a lot of the fields are themselves objects with copy constructors / assignment operators, I can't just memcpy the whole thing. I've tried manually writing out all of the copy instructions. The problem is, whenever anyone adds a field to the class, they need to add the appropriate line to the copy constructor and assignment operator. It's easy to forget. A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. For example, class Wall { public: // create a constructor Wall () { // code } }; Here, the function Wall () is a constructor of the class Wall Copy constructor: C::C (const C&); Copy assignment: C& operator= (const C&); Move constructor: C::C (C&&); Move assignment: C& operator= (C&&) #include <iostream> template <typename T> class list { public: list(); // constructor list(const list &l); // copy constructor list &operator=(const list &l); // assignment operator ~list(); // destructor // Returns number of elements in the list unsigned size(); // Returns true if the list is empty, false otherwise. bool isEmpty() const; // Inserts element to front of list void insertFront(const T &val); // Inserts element to the end of list void insertBack(const T &val); // Returns the. The assignment operator is not 100% exception safe. You should not modify the current object while you have not yet finished making the copy. Node& Node::operator=(const Node& other) { value = other.value; Node * left_orig = left; left = new Node(*other.left); delete left_orig; // You have modified the left side Boost your academic performance by availing our C# assignment help. Learning C sharp can be quite challenging. So, if you're finding it hard to understand the fundamentals of this programming language, then with our c# programming assignment help, you will be able to score better and get your basics right. We know it is not a cakewalk learning these complex languages, but it's not impossible. exception. Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes. The following class have brand, model and year attributes, and a constructor with different parameters. Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc). When we call the constructor (by creating an object of the class), we pass parameters to the constructor, which will set the value of the corresponding attributes. 最基本的形式是:widget & operator= (const widget & )知道为什么要返回引用吗?1. 因为c++设计的目的是要使得自定义类也可以像内置类型那样可以有简单的操作:像operator assignment就是其中之一。比如int a, b,c,你可以像这样赋值 a=b=c;那么对于:widget wa, wb,wc;也应该可以进行这样的操作才是,wa= wb= w oluşturuyor c = a; / / assignment operator call Drivers here Is that assign distressed to change content of Already created object. In case the object does not exists or created on the fly - Copy Constructor Distresse. A very simple subset of C Compiler(Lexical Analyzer, Syntax Analyzer, Semantic Analyzer & Intermediate Code Generator) implemented in C++ using Flex and Yacc-Bison as an assignment of sessional course CSE 310 in undergraduate studies in CSE, BUET . flex cplusplus cpp cse yacc clion c-compiler symbol-table intermediate-representation assembly-8086 compiler-design lexical-analyzer code. Constructor, Copy Constructor, Assignment Operator, Variable. What is Copy Constructor. In programming, sometimes it is necessary to create a separate copy of an object without affecting the original object. Copy constructor is useful in these situations. It allows creating a replication of an existing object of the same class. Refer the below example. Figure 1: Program with copy constructor. The assignment x = y calls the implicitly defined copy assignment operator of B, which calls the user-defined copy assignment operator A::operator=(const A&). The assignment w = z calls the user-defined operator A::operator=(A&). The compiler will not allow the assignment i = j because an operator C::operator=(const C&) has not been defined In class complex_num, fill in the blanks as follows:at LINE-1 to complete the definition of default constructor so that both variables areinitialized to 0 by default,at LINE-2 to complete the definition of constructor,it will assign the r with the double value and i with 0.at LINE-3 to complete the definition of parameterized constructor so that both variablescan be initialized with the values. Copy Constructor und Assignment Operator. Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.? GastXYZ zuletzt editiert von . Hallo ! Wenn ich einen Copy Construktor und einen Assignment Operator selbst definiere, wie kann ich mir dann doppelte Schreibarbeit sparen wenn die Klasse viele Attribute hat die es zu kopieren gilt ? Ich meine wenn ich z.B. ein. Constructor Operator Delete Assignment C Or Copy. Gilgamesh Noahs Ark Essay. Critical Thinking A Concise Guide 2nd Edition. Exemple De Cv D'hotesse De L'air En Anglais. Descriptive Essay At The Market In Summer. Auditor Cv Skills; Boys And Girls Alice Munro Thesis; 2018 Heisman Trophy Presentation Dat Difference C In Assignment Copy Constructor Operator Between And. I have a class with some data and I have to make a Copy Constructor and Assignment Operator, however, si. Mar 08, 2004 · Although it is right that copy constructor is used to create a new object with the existing one and assignment operator deals with two existing objects. Circle C1,C2; C1 = C2; /* Assignment Operator */ Circle. C Write Copy Constructor Copy Assignment Constructor Doubly Linked List Function Definitio Q42288763(C++) Write a copy constructor and copy assignment... | assignmentaccess.co Thus the program for constructor, destructor, copy constructor and assignment operator overloading was executed. Posted by Praveen at 07:01. Email This BlogThis! Share to Twitter Share to Facebook. Labels: 141353-OOP LAB MANUL. 0 comments: Post a comment. Newer Post Older Post Home. Subscribe to: Post Comments (Atom) Search This Blog. Labels. 141351-Digital Lab (2) 141351-DIGITAL SYSTEM LAB (1. Thanks to C++11, the solution becomes magically simple: just delete the copy constructor and assignment operator. Our class will look like this instead: Our class will look like this instead: class Car { public: Car(const Car&) = delete; void operator=(const Car&) = delete; Car(): owner() {} void setOwner(Person *o) { owner = o; } Person *getOwner() const { return owner; } private: Person *owner; } Overview. Every class that has a pointer data member should include the following member functions: . a destructor, a copy constructor, operator= (assignment) The IntList class, defined in the Introduction to C++ Classes notes, includes a pointer to a dynamically allocated array. Here is the declaration of the IntList class again, augmented to include declarations of the class's destructor. Quote:Original post by iMalcStroustrup himself hoped that most implementors would do so, but they mostly did not.Which is strange, because it goes against the language philosophy to do so :)Anyway. Objects are supposed to clean themselves up.Does the Texture *need* to hold its Bitmap *by pointer*?
https://karlekende.com/cprogramming/c_assignment_operatorsjwj41809dgg6.html
CC-MAIN-2021-25
refinedweb
3,241
55.44
C++ is a very difficult programming language. The hard part mainly is to learn in depth, but if you just write strategy logic by C++, it won’t need much deep knowledge, as long as it is not a very complicated strategy. Learning some the basics will be enough. For some people using C++ doesn’t mean it is suitable for everyone to use it. the reason is, programming language is just a tool. In quantitative trading, C++ is not the “must-required”. If you prefer to use the script programming language, such as Python or C++, you can save a lot of time and energy , which can be used for focusing on the strategy design. But among quantitative investment institutions, most of the underlying quantitative trading system software was wrote by C++, because its unique language specificity makes it more efficient and faster than other languages in some aspects, especially in numerical calculations. This also means that C++ is more suitable for financial derivatives and high-frequency trading. So, if you want to use a faster programming language, it must be the the C++. In order to help everyone understand the content of this section more quickly, before introducing the C++ language, let’s look at the strategy that wrote by the C++, so that you have a preliminary understanding of the noun concept in this section. Let’s take the simplest MACD strategy as an example: We all know that the MACD has two curves, namely the fast line and slow line, let’s design a trading logic based on these two lins. When the fast line up cross the slow line, open long position; when the fast line down cross the slow line, open short position. The complete strategy logic are: Long position open: If there is currently no position, and the fast line is greater than the slow line. Short position open: If there is currently no position, and the fast line is less than the slow line. close Long position: If currently holding long position, and the fast line is less than the slow line. close Short position: If current holding short position, and the fast line is greater than the slow line. Using the C++ language to write the above strategy logic, will be like : double position = 0; //Position status parameter, the default position is 0 uint64_t lastSignalTime = 0; // Last signal trigger time bool onTick(string symbol) { // onTick function, inside the function is the strategy logic auto ct = exchange.SetContractType(symbol); // set the trading variety if (ct == false) { // if setting the trading variety is not successful return false; // return false } auto r = exchange.GetRecords(); // get the k line array if (!r.Valid || r.sizeO < 20) { // if get the k line array is not successful or the number of k line is less than 20 return false; // return false } auto signalTime = r[r.size() - 2].Time; // get the previous k line time if (signalTime <= lastSignalTime) { // if the previous k line time is less than or equal to the last trigger signal time return false; // return false } auto macd = TA.MACD(r); // calculate the MACD indicator auto slow = macd[0][macd[0].size() - 2]; // get the previous k line MACD value auto fast = macd[l][macd[l].size() - 2]; // get the previous k line MACD average value string action; // define a string variable action if (fast >= slow && position <= 0) { // if the previous k line macd value is greater than or equal to the previous k line macd average value, and there are no long position holding action = "buy"; // assign buy to the variable action } else if (fast <= slow && position >= 0) { // if the previous k line macd value is less than or equal to the previous k line macd average value, and there are no short position holding action = "sell"; // assign sell to the variable action } if (actton.size() > 0) { // If there are orders for placing order If (position != 0) { // If there are holding position ext::Trade("cover", symbol); // call the C++ trading class library and close all position } position = ext::Trade(action, symbol, 1); // call the C++ trading class library, placing orders according the direction of variable "action", and renew the position status lastSignalTime = signalTime; // reset the time of last trigger signal } return true; // return true } void main() { // program starts from here while (true) { // enter the loop if (exchange.IO("status") == 0) { // if the connection with the exchange is not successful Sleep(1000); // pause for 1 second continue; // skip this loop, continue to the next loop } if (!onTtck("this_week")) { // if the connection is ok, enter the if loop and start to execute the onTick function Sleep(1000); // pause for 1 second } } } The code above is a complete quantitative trading strategy written in C++. It can be apply in the real market and will automatically placing orders. In terms of code size, it is more complicated than other languages. Because the C++ language in mainly for high-frequency strategy development on FMZ Quant platform. Although the coding part is a bit more than before, so many unnecessary trading class libraries have been reduced already, and most of the underlying system level processing is packaged by FMZ Quant platform. For beginners, the design process of the whole strategy remains unchanged: setting the market variety, obtaining K-line data, obtaining position information, calculating trading logic, and placing orders. The identifier is also the name. The variables and function names in C++ are case-sensitive, which means that the variable name test and the variable name Test are two different variables. The first character of the identifier must be a letter, an underscore “_”, and the following characters can also be numbers, as shown in the following: mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Comments include single-line comments and block-level comments. Single-line comments begin with two slashes, beginning with a slash and an asterisk ( /* ), ending with an asterisk and a slash ( */ ), as shown in the following: // this is a single-line comment /* * this is a multiple-line comment * block-level comments * */ In C++, the semicolon is the statement terminator. That is, each statement must end with a semicolon. It indicates the end of a logical entity. For example, here are three different statements: x = y; y = y + 1; add(x, y); A variable is a operational storage area. To define a variable in C++, you must first define the type of the variable. In the development of quantitative trading strategies, we commonly using types are: integer ( int ), float ( double ), string ( string ) and automatic derivation type ( auto ). Integers can be understood as integer numbers; floating point types can be understood as numbers with decimal points; strings are literals, can be English or other language characters. Sometimes when we call an API , but we don’t know if this API will Give us what type of data to return, so using the automatic derivation type ( auto ) will help us automatically determine the data type. As shown below: int numbers = 10; // use int to define a integer variable and assign 10 to this variable double PI = 3.14159; // use double to define a float variable and assign 10 to this variable string name = "FMZ Quant"; // use string to define a string variable and assign "FMZ Quant" to this variable auto bar = exchange.GetRecords(); // use auto to define a variable (automatic derivation type) and assign k line array to this variable An array is a container for storing data. A C++ array can store a fixed-order collection of elements of the same type with a fixed size. So in C++ , to declare an array, you need to specify the type of element and the number of elements. All arrays have an index of 0 as their first element. To get the first data in the array is " [0] ", the second data is " [1] ", and so on, as follows shows: // define a array, array name is balance. there are 5 floating(double) type data inside it double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; double salary = balance[0]; // get the first data in the array, the result is : 1000.0 double salary = balance[1]; // get the second data in the array, the result is : 2.0 A function is a set of statements that execute a task together. The declaration of a function includes: the name of the function, the type of the return, and the parameters. The return type is the data type returned when the function is run when I call this function; the parameter is optional, and the function can also contain no parameters. When the function is called, you can also pass a parameter to the function. Look at the following example: // create a function called "max" // when this function is called, it returns the int type data // this function has 2 parameters, and they both are int type // this function is for passing 2 int type numbers, and return the bigger one int max(int num1, int num2) { int result; // define a int variable result if (num1 > num2) // if the num1 > num2 result = num1; // assign the value of num1 to result else // otherwise result = num2; // assign the value of num2 to result return result; // return the value of result } Using C++ to write quantitative trading strategies, there are three commonly used operators: arithmetic operators, relational operators, logical operators, and assignment operators. The arithmetic operator is the mathematical operation of adding, subtracting, multiplying, and dividing. The relational operator can compare whether the two values are smaller or bigger. The logical operators mainly include: logical AND, logical OR, and logical non. The assignment operator is the variable assignment we talked about earlier. As shown below: int main() { // arithmetic operator int a = 10; int b = 5; a + b; // the result is 15 a - b; // the result is 5 a * b; // the result is 50 a / b; // the result is 2 a % b; // the result is 0 a++; // the result is 11 a--; // the result is 9 // relational operators a == b; // the result is false a != b; // the result is true a >= b; // the result is true a <= b; // the result is false logical operators true && true // the result is true true && false // the result is false false || false // the result is false true || false // the result is true !(true) // the result is false !(false) // the result is true return 0; } If there is a 100*(10-1)/(10+5) expression, which step is the program first calculated? Middle school mathematics tells us: If it is the same level of operation, it is generally calculated from left to right; If there are additions and subtractions, and multiplication and division, first calculate the multiplication and division, then add and subtract; If there are brackets , first calculate the inside of the brackets; If the law of operation is met, the calculation law can be used for the calculation. the same above principle for C++, as shown below: auto num = 100*(10-1)/(10+5); // the value of num is 60 1 > 2 && (2 > 3 || 3 < 5); // the result is : false 1 > 2 && 2 > 3 || 3 < 5; // the result is : true Usually when we writing code, we always need to perform different actions for different decisions. we can use conditional statements in our code to accomplish this task. In C++, we can use the following conditional statements: If statement - Use this statement to execute code only if the specified condition is true If…else statement - execute code if the specified condition is true, the other code executed when the condition is false If…else if…else statement - use this statement to select one of multiple code blocks to execute Switch statement - Use this statement to select one of multiple code blocks to execute This statement executes the code only if the specified condition is true. Please use a lowercase if. Using a capital letter ( IF ) will generate a C++ error! As shown below: // grammar if (condition) { //execute code only if the condition is true } //example if (time<20) { // if current time is less than 20:00 x = "Good day"; // when the time is less that 20:00, assign the "good day" to x } execute code if the specified condition is true, the other code executed when the condition is false, as shown below: //grammar if (condition) { // execute code if the condition is true } else { // the other code executed when the condition is false } //example if (time<20) { // if current time is less than 20:00 x = "Good day"; // when the time is less that 20:00, assign the "good day" to x } else { // otherwise x = "Good evening"; // assign the "Good evening" to x } Use this statement to select one of multiple code blocks to execute switch (condition) { case 1: // code to be executed if condition = 1; break; case 2: // code to be executed if condition = 2; break; default: // code to be executed if condition doesn't match any cases } The For loop can execute N times of code blocks repeatedly, and its execution flow is like this (as shown below): for (int a = 10; a < 20; a++){ // code block } Step 1 : Execute int a = 0 and only execute once. Its purpose is to declare an integer variable and initialize it to 0 to control the for loop. Step 2 : Execute a<20. If it is true, execute the code block of line 2 . Step 3: Execute a++, after execute a++, a becomes 11. Step 4 : Execute a<20 again, and the second, third, and fourth steps will execute repeatedly. Until a<20 is false, if it is false, the code block of line 2 will not executed, and the whole for loop is finished. We all know that the market is constantly changing. If you want to get the latest K-line array, you have to constantly run the same code over and over again. Then use the while loop is the best choice. As long as the specified condition is true, the loop will continue to get the latest k-line array data. void main() { auto ct = exchange.SetContractType(symbol); //set the trading variety while(true) { auto r = exchange.GetRecords(); // constantly getting k-line arrays } } Loops have preconditions. Only when this precondition is " true ", the loop will start doing something repeatedly, until the precondition is " false ", the loop will end. But using the break statement can jump out of the loop immediately during the execution of the loop; # including <iostream> using namespace std; int main() { for(int a = 0; a < 5; a++) { if(a == 2) break; cout << a << endl; } return 0; } // print out : 0, 1 The continue statement also jumps out of the loop, but it doesn’t jump out of the whole loop. Instead, interrupt a loop and continue to the next loop. As shown in the below, when a is equal to 2 , the loop is interrupted, and the next loop is continued until the precondition of the loop is " false " to jump out of the whole loop. # including <iostream> using namespace std; int main() { for(int a = 0; a < 5; a++) { if(a == 2) continue; cout << a << endl; } return 0; } // print out : 0, 1, 3, 4 The return statement terminates the execution of the function and returns the value of the function. The return statement can only appear in the body of the function, and any other place in the code will cause a syntax error! # including <iostream> using namespace std; int add(int num1, int num2) { return num1 + num2; // The add function returns the sum of two parameters } int main() { cout << add(5, 10); // call the add function, and print out the result:50 return 0; } On the FMZ Quant platform, it would be very convenient to write a strategy by C++. The FMZ Quant have a lots of officially built-in standard strategy frameworks and trading class libraries, such as follows: bool onTick() { //onTick function // strategy logic } void main() { // program starts from here while (true) { // enter the loop if (exchange.IO("status") == 0) { // if the exchange connection is not stable sleep(1000); // pause for 1 second continue; // skip this loop, enter the next loop } if (!onTick()) { // if the exchange connection is stable, enter this if statement, start to execute the onTick function sleep(1000);// pause for 1 second } } } As shown the above, this is a standard strategy framework, and these formats are fixed. Use the framework to write a strategy. You only need to write the strategy logic from the second line. Other market acquisition and order processing are handled by the framework and the trading class libraries, you just need focus on strategy development. The above is the content of the C++ language quick start. If you need to write more complex strategy, please refer to the FMZ Quant platform C++ language API documentation, or directly consult the official customer service about the writing service The key to quantitative trading is the trading strategy, not trading tools (programming language). In the next section, let’s write a feasible C++ trading strategy. Still using the simplest technical analysis indicators as an example.
https://www.fmz.com/bbs-topic/3731
CC-MAIN-2019-35
refinedweb
2,843
53.44
MSGGET(2) BSD Programmer's Manual MSGGET(2) msgget - get message queue #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msgget(key_t key, int msgflg);. If a new message queue is created, the data structure associated with it (the msqid_ds structure, see msgctl(2)) is initialized as follows: • msg_perm.cuid and msg_perm.uid are set to the effective UID of the calling process. • msg_perm.gid and msg_perm.cgid are set to the effective GID of the calling process. • msg_perm.mode is set to the lower 9 bits of msgflg. • msg_cbytes, msg_qnum, msg_lspid, msg_lrpid, msg_rtime, and msg_stime are set to 0 • msg_qbytes is set to the system wide maximum value for the number of bytes in a queue (MSGMNB). • msg_ctime is set to the current time. Upon successful completion a positive message queue identifier is re- turned. Otherwise, -1 is returned and the global variable errno is set to indicate the error. [EACCES] A message queue is already associated with key and the caller has no permission to access it. [EEXIST] Both IPC_CREAT and IPC_EXCL are set in msgflg, and a. msgctl(2), msgrcv(2), msgsnd(2), ftok(3) Message queues appeared in the first release of AT&T Unix System V. MirOS BSD #10-current August 17,.
https://www.mirbsd.org/htman/i386/man2/msgget.htm
CC-MAIN-2015-32
refinedweb
212
60.72
Because there are now two versions of the .NET Framework out there (there will be three by 2005), .NET developers should be concerned with making sure their applications use the proper version of the Framework at runtime. Most of the time, Web applications compiled with VS.NET 2002 will run on 1.1-enabled Web servers without having to make any changes at all. Microsoft did an outstanding job ensuring that there were as few code-breaking changes between 1.0 and 1.1 as possible. Web application compatibility There are certain steps you can take, however, to ensure that your application will gracefully use the version of the Framework you want. Simply add Listing A to the Web.config file. Now, as long as your app doesn't try to do anything specific to any one version of the Framework, it will run smoothly. Word of warning If you need to change the bindings to additional assemblies, such as System.Data.dll, copy one of the existing binding redirects and change the assembly name. Although the public key will always be the same for Framework assemblies, be sure to check the version number, because some assemblies are versioned 7.x.xxxx instead of 1.x.xxxx. If you're using VS.NET 2003, the IDE will add this information for you automatically. Right-click on the project title in the Solution Explorer, and then click Properties. In the window that follows, select the Build option, and then click the Compatibility button. A dialog box will appear asking you if you want to support 1.1 only, or both 1.0 and 1.1. If you select the second option, the IDE will add a very long list of <assemblyBinding> tags to your Web.config file. This ensures that your app will try to run no matter what. If you have physical access to the server, you can also use the ASP.NET Version Switcher. This tool reroutes the IIS server mapping for each Web on an individual basis. This is very handy in instances where different apps are compiled against different versions of the .NET Framework running on the same server. The benefit of this method is that you don't have to make any modifications to the application's source files. Windows application compatibility The same procedures for Web applications apply to Windows applications. The only difference is that the settings belong in the ApplicationName.config file instead of the Web.config file. Server control compatibility Currently, there is no graceful way to handle .NET Framework compatibility issues in server controls and other components that don't utilize a configuration file. There are, however, a few workarounds, and a few more are currently in development. In the sections that follow, I will illustrate for you three such solutions, and discuss their pros and cons. Option 1: Dual code bases, dual deliverables While some of you may balk at the idea of maintaining two separate code bases, hear me out before you rush to judgment. Because I sell the source code to many of my components, I use the code as an opportunity to document the ins and outs of working with whatever solution I am attempting to tackle. Take my GenX.NET component for example. This component takes information from any ADO.NET data source, and exports the data into various formats. For my 1.0-compatible version, GenX.NET uses the Oracle ADO.NET Data provider add-on, which is a separate install and resides in the Microsoft.Data.OracleClient namespace. For my 1.1-compatible version, the Oracle provider is built in, and resides in the System.Data.OracleClient namespace. This one difference alone requires me to maintain two separate versions. I used this to my advantage and rewrote parts of the code to use new 1.1-specific features, such as declaring variables within cycle operations. This way, when developers buy the source code along with the product (which accounts for 85 percent of my overall sales), they can see how the code makes the best use of the available feature set. However, there are some pitfalls to this approach. Two code bases require you to be more diligent when bugs come up. It also requires the end user to know which version of the .NET Framework they will be developing against. They must select the right version during the development and deployment process. You can give users the option of downloading only the version they need, or you can include both versions in the same distribution. You can also take advantage of the assembly naming attributes in the AssemblyInfo file to differentiate between the versions. And you could also give the assembly a different physical name to make it easier to tell the difference. Option 2: Single code base, dual deliverables This option comes courtesy of Paul Alexander of Xheo.com. It is possible to maintain a single code base for different versions of the Framework. The secret is to use a Conditional Compilation Constant in your VS.NET 2003 project. You'll still have to maintain two separate project files, but you will have one physical file with all of your code. Start out by creating your solution and project files. You can keep them in the same directories; just make sure they have different names, like YourSolutionName—2002.sln and YourSolutionName—2003.sln. Now, right-click the VS.NET 2003 project and select Properties. Go to Configuration Options | Build, and then enter the information as shown in Figure A. Make sure you only set this in your VS.NET 2003 project. You can use the code below to separate the .NET Framework versions 1.1 and 1.0, like so: #If NET11 Then '..do something specific to .NET 1.1 #Else '..do something specific to .NET 1.0 #End If This is a great solution, but it may not always keep your code files unified. Depending on how you organize your projects in your source code repository, you may still end up needing to have a file for each version. Option 3: Manually reference .NET 1.0 in the IDE The next option requires a little less work, but completely negates the advantages of using VS.NET 2003 and .NET 1.1. In your project, you can manually remove the references to the 1.1 versions of the Framework assemblies (1.0.5000) and replace them with the 1.0 versions (1.0.3705). Your assembly will still be compiled with 1.1, but there is no guarantee that it will work 100 percent of the time. In fact, you will still have issues if the component is used on Windows Server 2003, on which 1.1 is installed by default. I feel that this is the least acceptable option, as do others in the .NET community. It has not been tested in all situations and has the possibility of creating some headaches, but it is an option. This option comes courtesy of Frans Bourma, creator of the LLBLGen Data Access Layer generator component. If you take some time and read Frans’ blog entry and the related posts, you'll see how intense the debate was. Option 4: Dynamically reference Framework assemblies This one requires some actual coding and might make your code just a tad bit more difficult to read (and write), but it is an option nonetheless. Instead of using the IDE to specify your dependencies, you can load them programmatically, based on what version of the .NET Framework is running the application. However, dynamically loading .NET Framework assemblies is a catch-22, because you can't use Reflection to dynamically load the System.dll assembly which contains the System.Reflection namespace. Be consistent I've given you several options for dealing with different versions of the .NET Framework in your applications. You can bet that this system will continue to improve in future versions of the .NET Framework, and that this methodology will continue to evolve. For now, just make sure that, whatever option you choose, you keep it consistent across your entire code base. There is nothing worse than inconsistent code. Further reading For more information on the .NET Framework versions 1.0 and 1.1, check out these links: - GotDotNet: Breaking Changes Between .NET 1.0 and 1.1 - Early & Adopter: What's New in .NET 1.1 & VS.NET 2003 - Early & Adopter: Side-By-Side Framework Execution - Robert McLaws: Upgrade Issues with VS.NET 2003 and .NET 1.1 - Robert McLaws: Ride the Platform Wave: .NET 1.1
http://www.techrepublic.com/article/basic-net-framework-compatibility-issues/
CC-MAIN-2017-13
refinedweb
1,432
68.47
Asp.net web application performance is one of the key factors in online business success. In this post I will try to cover all different asp.net frameworks, including asp.net core website performance improvement tips; so all points may or may not be relevant to your asp.net application depending which framework you are using at your project. Here are 10 simple tips to increase Asp.net Application Performance drastically. Now we have few different framework of Asp.net, most of earlier application were written in AspX with code behind, later we started with Asp.net MVC, then now we have Asp.net Core, so when we talk about improving performance, every framework has some different way of processing request, so keeping that in mind in this article I will cover AspX code behind and Asp.Net MVC, about asp.net core I will publish separately. Here are some ideas on Asp.net website performance improvement. In earlier asp.net framework Viewstate was one of the main reason to slowdown page load and every time the page post occur, but that was the mechanism to hold data between page post back, so if your some page does not have any form or posting data is not necessary, please turn off Viewstate for that page, just by setting EnableViewState = "false" in your page directive, that will not affect any other page of that application, but improve the page loading time significantly. Try, not to write any in-line CSS or any style block on page, put them all in one css file and add the reference, same for JavaScript code, avoid writing any JavaScript code on page, put all JavaScript in separate file and use the reference , this will help reducing the page size to some extent. In page html, don’t use any table tag, use all div, span etc, try to use bootstrap css, you get many ready-to-use css classes, which are responsive by default , this will help page rendering faster. Find out all common data which are being loaded from database when every time page gets loaded, common data means those maser data which remain same, or not going to change very frequently, data like country list, product master etc. you can store them in server side cache object, so instead of pulling them from database, you can fetch them from cache, that will help reducing some time by avoiding unnecessary trip to database server. Server side caching can improve application performance significantly. You must make sure all images are well optimised for webpage, make images as lighter as possible, so that can be loaded faster, probably you need to take help from some Photoshop expert, there are some tool to make good quality and lighter image for web. If you use HTTP compression rightly, page size can be reduced to at least 50 percent, it removed all additional spaces in your rendered html, though there is not ready-to-use tool to compress content , but you can write a filter using ActionFiltterAttribute , here is an example of how to write http compression filter in ASP.NET You can use Page Output Caching, that will help page loading faster, can improve performance drastically, you can set same page caching by parameter also, means depending on parameter different version of same page will be cached in browser, so when user visit the same page, the page will be loaded from cached. Here is an example of how you can implement output caching in asp.net. if your whole page is displaying dynamic content, but some part of your page has static content, you can use partial caching (known as fragment caching), which means only some portion of page will be cached, not the entire page. Asynchronous Methods will not block UI of the Page, also will not wait till one task is completely done, and it will keep loading content asynchronously, thus content loading become much faster, and give end user a good experience of browsing your page. Learn how to make Async page in asp.net mvc Try to use await keyword, instead of Task.Wait or Task.Result. When you use wait, you are actually blocking thread until the task is completed, which works synchronously, but when you use await keyword, it does not block the thread, works asynchronously. // Good Example Task task = GetStudents(); await task; // Bad Example Task task = GetStudents(); task.Wait(); How you fetching data from database that may make huge difference, sometimes even after doing all implementation correctly, application still perform very slow just because of poor data access implementation, though most of Asp.net application uses ORM, LINQ , but here are few simple things may make huge difference. When you are thinking of data access performance optimization, Ado.net can give better performance than Entity Framework. Avoid using application variable if not necessary, even if using then never store any large data or master data in application variable. Use session variable only to keep user specific data for that particular duration, and nullify the session object as soon as user leave the site, using too many session variable for multiple users may slow down application performance, so avoid as much possible. You can minify all your JavaScript and css files using bundling techniques, in BundleConfig file you can add those files in different bundle like example below. bundles.Add(new StyleBundle("~/Content/css") .Include("~/Content/etg_style.css", "~/Content/wtr.css", "~/Content/bootstrap.min.css", "~/Content/bootstrap.css")); Use lazy loading whenever you want to loading collection object, lazy loading is a technique that can really help improving application performance by reducing exaction time, c# lazy class allow us to load data on demand, instead of when the instance is created. Lazy<List<int>> list3Lazy = data.GetList3(); public class data { public static Lazy<List<int>> GetList3() { Lazy<List<int>> list3 = new Lazy<List<int>>(); for (int i = 0; i <= 50; i++) { list3.Value.Add(i); } return list3; } } Learn how to implement lazy loading in C# application development. Optimizing your database objects is equally important, You may also read how to improve SQL Database Performance You may be interested to read following posts:
https://www.webtrainingroom.com/aspnetmvc/performance
CC-MAIN-2021-49
refinedweb
1,031
57.81
QAbstractItemModel for legacy SIL (vtkGraph-based SIL) More... #include <pqSILModel.h> Inherits QAbstractItemModel. QAbstractItemModel for legacy SIL (vtkGraph-based SIL) pqSILModel is QAbstractItemModel implementation for legacy SIL. While not deprecated, this class exists to support readers that use legacy representation for SIL which used a vtkGraph to represent the SIL. It is recommended that newer code uses vtkSubsetInclusionLattice (or subclass) to represent the SIL. In that case, you should use pqSubsetInclusionLatticeTreeModel instead. Definition at line 61 of file pqSILModel.h. Gets the number of rows for a given index. Gets the number of columns for a given index. Gets whether or not the given index has child items. Gets a model index for a given location. Gets the parent for a given index. Gets the data for a given model index. Gets the flags for a given model index. The flags for an item indicate if it is enabled, editable, etc. Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. Returns the QModelIndex for the hierarchy with the given name, if present. If the hierarchy is not present an index referring to an empty tree will be returned. Definition at line 158 of file pqSILModel.h. API to get/set status of a given hierarchy. Returns the model index for a vertex. Returns the vertex id for a vertex with the given name in the SIL. Returns -1 if no such vertex could be found. Used to reset the model based on the sil. Called every time vtkSMSILModel tells us that the check state has changed. We fire the dataChanged() event so that the view updates. Returns if the given vertex id refers to a leaf node. Returns the parent vertex id for the given vertex. It's an error to call this method for the root vertex id i.e. 0. Returns the number of children for the given vertex. Used to initialize the HierarchyVertexIds list with the leaf node ids for each of the hierarchies. Definition at line 226 of file pqSILModel.h. Cache used by makeIndex() to avoid iterating over the edges each time. Definition at line 231 of file pqSILModel.h. Definition at line 233 of file pqSILModel.h. This map keeps a list of vertex ids that refer to the leaves in the hierarchy. Definition at line 239 of file pqSILModel.h. Definition at line 240 of file pqSILModel.h. Definition at line 241 of file pqSILModel.h.
https://kitware.github.io/paraview-docs/latest/cxx/classpqSILModel.html
CC-MAIN-2021-49
refinedweb
412
69.79
1 /* BadURIsStopPageParsingSelfTest2 *3 * Created on Mar 10,.selftest;24 25 import java.io.File ;26 import java.util.ArrayList ;27 import java.util.Arrays ;28 import java.util.Iterator ;29 import java.util.List ;30 31 /**32 * Selftest for figuring problems parsing URIs in a page.33 * 34 * @author stack35 * @see <a 36 *[ 788219 ]37 * URI Syntax Errors stop page parsing.</a>38 * @version $Revision: 1.2.26.1 $, $Date: 2007/01/13 01:31:26 $39 */40 public class BadURIsStopPageParsingSelfTest extends SelfTestCase41 {42 /**43 * Files to find as a list.44 * 45 * We don't find goodtwo.html because it has a BASE that is out46 * of scope.47 */48 private static final List <File > FILES_TO_FIND =49 Arrays.asList(new File []50 {new File ("goodone.html"),51 new File ("goodthree.html"),52 new File ("one.html"),53 new File ("two.html"),54 new File ("three.html")});55 56 public void testFilesFound() {57 List <File > foundFiles = filesFoundInArc();58 ArrayList <File > editedFoundFiles59 = new ArrayList <File >(foundFiles.size());60 for (Iterator i = foundFiles.iterator(); i.hasNext();) {61 File f = (File )i.next();62 if (f.getAbsolutePath().endsWith("polishex.html")) {63 // There is a URI in our list with the above as suffix. Its in64 // the arc as a 404. Remove it. It doesn't exist on disk so it65 // will cause the below testFilesInArc to fail.66 continue;67 }68 editedFoundFiles.add(f);69 }70 testFilesInArc(FILES_TO_FIND, editedFoundFiles);71 }72 }73 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/archive/crawler/selftest/BadURIsStopPageParsingSelfTest.java.htm
CC-MAIN-2017-30
refinedweb
254
64.37
BookVocabularies From W3C Wiki I was wondering how books, booklists, and book reviews should be represented in RDF. Here's what I found: - DublinCore has most of the essentials - ISBN is an official URN namespace. So "urn:isbn:1234567890" refers to a book with that ISBN. - There are problems using these URNs in linked data: - Firstly, they don't resolve to machine-readable data about the book. - Secondly, and I think more importantly, they have no agreed meaning - that is, does urn:isbn:1234567890 represent a book? Or does it represent an ISBN number that belongs to a book? - Hyphens may be included at any point in these URNs which violates the AWWW guideline that "a URI owner should not associate arbitrarily different URIs with the same resource." - Also, RFC 3187 only defines ISBN-10 URNs. Newer 13-digit ISBNs are occasionally used as URNs in the wild, but technically they are outside the scope of the URN namespace registration. - Because of these problems I've created some purl.org URIs for books. e.g. - just plug in an ISBN number and it should work. These use Amazon.com's API to supply RDF/XML data. - Leigh Dodds made a reading list schema at. He also made an XSLT to transform AllConsuming booklists into this RDF format. Here's an example FOAF file with book lists. - A.M. Kuchling created a book review schema - Ideagraph's RDF review vocabulary - FRBR is a bibliographic model of works and editions - Decimalised Database of Concepts is a list of topics that can be used to classify the subject of a book. - RDF Book Vocabulary 0.1 can be used to describe books and the reading of books. - Open Archives Object Reuse and Exchange (OAI-ORE). See also LDOW2009 paper The Library Linked Data XG has also written a report on available metadata element sets in the library domain.
https://www.w3.org/wiki/BookVocabularies
CC-MAIN-2017-22
refinedweb
315
66.33
CodePlexProject Hosting for Open Source Software Just started using Foolproof after finding it while searching for more validators for MVC. As luck would have it, the first validation scenario I needed failed with foolproof on the client side. Server side validation executed correctly, but the client side did not. I was using the RequiredIfTrue and RequiredIfFalse validators, and the problem seems to be how my boolean value in the view model was being rendered in the view. public class EditModel(){ [RequiredIfFalse("IsSystem")]public string Description { get; set; } public bool IsSystem {get;set;} } In my view I was rendering IsSystem as a hidden field, which gets a value of either True or False (capital T/F). Reviewing the javascript code, I noticed that there is a check made for "true" and "false" with a lower case T/F. Adding in some adidtional OR statements to also look for True/False seems to have fixed this for me. I had the problem with both the MVC and Jquery validation, but only looked at the Foolproof JQuery script. I changed lines 11, 12, and 13 to be: else if (value1 === true || value1 === false || value1 === "true" || value1 === "false" || value1 === "True" || value1 === "False") { if (value1 == "false" || value1 == "False") value1 = false; if (value2 == "false" || value2 == "False") value2 = false; value1 = !!value1; value2 = !!value2; } I re-ran the javascript unit tests, and they all passed, so at least I havn't broken anything. I wanted to get some feedback on if this was a good way to fix this, or if I should be looking at trying to adjust how my model (boolean values) are rendered. Salvoz, check out this thread, let me know if this is the same issue and if the referenced change set works for you: I saw that thread before I downloaded, so I started with the latest source as of Monday. Steping thru the javascript code in Firebug I skip over the reference javascript because I'm comparing against a hidden field, not a checkbox. As I mentioned in my first thread I was able to get the desired behvior by adding checks for true/false with a capital T and F. Adam Excellent, works like a charm for me now. I put a .ToLowerCase() on values where needed and it works great. 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.
http://foolproof.codeplex.com/discussions/228726
CC-MAIN-2017-22
refinedweb
416
68.81
The Mersenne Twister (MT) is a pseudorandom number generator (PRNG) developed by Makoto Matsumoto and Takuji Nishimura[1][2] during 1996-1997. MT has the following merits: I present a C# class (RandomMT) that encapsulates the work of the creators. I do not take credit for their work; I am merely presenting an object oriented (OO) version of their code that you can simply drop into your game or application. This work has also been derived from CRandomMT. CRandomMT is a C++ wrapper class for the Mersenne Twister, the original Code Project article can be found here. In that article I not only presented a wrapper class for this marvelous pseudorandom number generator but I also discussed the equidistribution of the MT algorithm as well as its speed increases. I will refer you to those articles for the time being as I do not have access to the latest version of TrueTime. RandomMT CRandomMT TrueTime The inspiration for developing a C# version of this class was two-fold. This thinking resulted in me writing a document that is as much hypothetical as it is factual with respect to game development for the PC in the coming years, those who are interested can find that article here. RandomMT::RandomMT() This is the default CTOR. RandomMT::RandomMT(ULONG seed) A constructor that you provide the seed value. RandomMT::~RandomMT() The DTOR. RandomMT::SeedMT() Used to seed or re-seed the random number generator. ULONG RandomMT::RandomInt() Returns an unsigned long random number. unsigned long int RandomMT::RandomRange(int hi, int lo) Returns an int random number falling in the range specified. int int RandomMT::RollDice(int face, int number_of_dice) Returns an int random number for the number of dice specified and the face of the die. int RandomMT::D#(int die_count) Returns a simulated roll of the number of dice specified for the die (determined by #). These are just wrappers around RollDice() RollDice() int RandomMT::HeadsOrTails() Returns 0 or 1, used to simulate a coin flip. namespace MersenneTwister . . . RandomMT random = new RandomMT(); int rand_3d6 = random.D6(3); // roll 3 six sided die . . . I have held closely to my original C++ implementation as much as possible. The original code used pointer arithmetic which you cannot do in C# and keep the code managed (per MSDN). If someone knows a better approach to this, feel free to let me know. I have updated the code to use the most recent version of the algorithm, MT19937. Here is a brief overview of the MT19937 version of the class. ulong genrand_int32() generates a random number on [0,0xffffffff]-interval long genrand_int31() generates a random number on [0,0x7FFFFFFF]-interval double genrand_real1() generates a random number on [0,1]-real-interval double genrand_real2() double genrand_real3() double genrand_real53() generates a random number on [0,1] with 53 bit resolution int RandomRange(int lo, int hi) returns a random number in the range [hi-lo+1] namespace MersenneTwister . . . MT19937 random = new MT19937(); int rand_d6 = random.RandomRange(1,6); // roll 1 six sided die . . . Again, the demo application is fairly lame. This application allows you to roll six 6 sided die and it keeps track of the total number of times that a number has “hit” – you can roll once or 1000 times. I’ve made use of GDI+ and as I said, I’m learning C# as well as the .NET framework so I may have misused or abused much of GDI+ functionality. The pursuit of the perfect PRNG is an ongoing effort that eludes computer scientists and mathematicians alike. The Mersenne Twister is generally considered to be fast, small and provides equal distribution. C# is an exciting language and I am looking forward to learning and coding with it in the coming future. Thanks go out to Makoto Matsumoto and Takuji Nishimura for creating the algorithm. Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/5147/A-C-Mersenne-Twister-class
CC-MAIN-2017-51
refinedweb
661
62.98
MS Dynamics CRM 3.0... The fortran (77) which actually translates very nicely, i thought is SUBROUTINE tqli(d,e,n,np,z) INTEGER n,np REAL d(np),e(np),z(np,np) CU USES pythag INTEGER i,iter,k,l,m REAL b,c,dd,f,g,p,r,s,pythag do 11 i=2,n e(i-1)=e(i) 11 continue e(n)=0. do 15 l=1,n iter=0 1 do 12 m=l,n-1 dd=abs(d(m))+abs(d(m+1)) if (abs(e(m))+dd.eq.dd) goto 2 12 continue m=n 2 if(m.ne.l)then if(iter.eq.30)pause 'too many iterations in tqli' iter=iter+1 g=(d(l+1)-d(l))/(2.*e(l)) r=pythag(g,1.) g=d(m)-d(l)+e(l)/(g+sign(r,g)) s=1. c=1. p=0. do 14 i=m-1,l,-1 f=s*e(i) b=c*e(i) r=pythag(f,g) e(i+1)=r if(r.eq.0.)then d(i+1)=d(i+1)-p e(m)=0. goto 1 endif s=f/r c=g/r g=d(i+1)-p r=(d(i)-g)*s+2.*c*b p=s*r d(i+1)=g+p g=c*r-b C Omit lines from here ... do 13 k=1,n f=z(k,i+1) z(k,i+1)=s*z(k,i)+c*f z(k,i)=c*z(k,i)-s*f 13 continue C ... to here when finding only eigenvalues. 14 continue d(l)=d(l)-p e(l)=g e(m)=0. goto 1 endif 15 continue return END my matlab is function [d,z] = sceigen_test (d,e,z) %input %d is the diagonal vector of the tridiag matrix %e is the sub and super diagonal of the tridiag matrix %z is the transformation matrix from the tridiag program % output, %d is the eigenvalue vector % z is the eigenvector matrix % d is the eigenvale vector % defining loop size based upon ip vector/matrix size n = size(d,2); %shifting e to the left, so that e(1) is not the zero anymore for i = 2:n e(i-1) = e(i); end e(n)=0; for l = 1:n iter=0; for m = l:n % not to n-1 for reason expained below if m == n break end dd = abs(d(m)) + abs(d(m+1)); if ((abs(e(m))+ dd) == dd) break end end % m = n% this is implemented in the above loop, so the loop goes to n instead of n-1 if m ~= l if iter == 30 error('bloody typical..too many iterations'); end iter = iter+1; g = (d(l+1)-d(l))/(2.0*e(l)); r = pythag(g, 1.0);%it works correctly g = d(m) - d(l) + (e(l) / (g + SIGNO(r, g)));%SIGNO = SIGN... definitely s = 1.0; c = 1.0; p = 0.0; for i = m-1:-1:l f = s*e(i); b = c*e(i); r = pythag(f, g); e(i+1) = r; if r == 0.0 d(i+1)= d(i+1)-p; e(m) = 0.0; break end s = f/r; c = g/r; g = d(i + 1) - p; r = (d(i) - g)*s + 2.0*c*b; p = s*r; d(i + 1) = g + p; g = c * r - b; %eigenvector part now... for k =1:n f = z(k,i+1); z(k,i+1) = s*z(k,i)+ c*f; z(k,i) = c*z(k,i)-s*f; end end if r ~= 0.0 d(l) = d(l) - p; e(l) = g; e(m) = 0.0; end end end The input (example) which is (if anyone will test for themselves) [0.0861,0.0172,0.0466,-0.0186,-0.0384;0.0172,0.0635,-0.0146,-0.0154,0.0399; 0.0466,-0.0146,0.0555,-0.0166,-0.0563;-0.0186,-0.0154,-0.0166,0.0459,-0.000 7;-0.0384,0.0399,-0.0563,-0.0007,0.0704;] which is a covariance matrix, so it is symmetric etc... eigenvalues (ordered hi to low) eig_sort = Columns 1 through 3 0.171639537105982 0 0 0 0.100853395915414 0 0 0 0.037197771768781 0 0 0 0 0 0 Columns 4 through 5 0 0 0 0 0 0 0.011737362737036 0 0 0.000002142655106 I have eigenvectors also, but i want to focus on theeigenvalues for now Tha actual matlab generates eigenvalues (reverse ordered) are: de = 0.000000000000000 0 0 0 0.011739410520354 0 0 0 0.037197816074304 0 0 0 0 0 0 0 0 0 0 0 0 0.100853446274617 0 0 0.171639537313043 They are similar, but there always a constant error... I noticed also, that if I subtract eig_sort(5,5) from itself and add it to eig_sort(4,4), the results become more accurate... But this is probably just indicative of some other problem.... It would be great if someone could see what I was doing wrong and point it out.. Peace, Marwan Here they are again... mine are 0.171639537105982 0.100853395915414 0.037197771768781 0.011737362737036 0.000002142655106 matlab's are (in reverse order to my own) 0.000000000000000 0.011739410520354 0 0.037197816074304 0.100853446274617 0 0.171639537313043 >... > But this is probably just indicative of some other problem.... > It would be great if someone could see what I was doing wrong and > point it out.. What you are doing wrong is converting NR C and Fortran code into matlab code into the first place. Why not use the matlab functionality to do eigenvalue decomposition/analysis (or any other form of linear algebra)? That's one of the things (if not the main one) matlab was built for; and it's arguably more robust than NR routines. Is there a reason you are converting NR codes into matlab?". Since Matlab's original purpose was to remove the need for users to code their own linear algebra algorithms, I wonder why you are not using the built-in functions. If you want Matlab code for some algorithm for pedagogical reasons, the code may already exist on the Matlab file exchange or some other place. anyway hopefully someone might be able to help. For testing of what? The Fortran/C NR code? If so, compare the straight Fortran/C code with the native Matlab results. And what do you mean by "expanded"? Is the final implementation going to be done using matlab, or using the Fortran/C NR codes? If the reason you are using matlab is to test the NR codes (which is a good idea), then curiosity insists I ask again: why are you translating the NR Fortran/C source to matlab? Why not just compare the NR Fortran/C output with the matlab output (using the built-in matlab linear algebra routines) for a canned, typical dataset? For this reason, I wanted code which i test on matlab, without any functions. I can then use this for testing as I write in verilog etc... peace... > For this reason, I wanted code which i test on matlab, without any > functions. I can then use this for testing as I write in verilog > etc... Did you try Dr Reid's advice re: double precision? Matlab computes everything in double precision by default and as he notes your Fortran routine (at least as posted) shows single precision for a floating point variables. Until I had both at the same precision for sure, I'd not be looking for other differences. [1] Except for "code" that was always placed "inline". -- Ivan Reid, School of Engineering & Design, _____________ CMS Collaboration, Brunel University. Ivan.Reid@[brunel.ac.uk|cern.ch] Room 40-1-B12, CERN GSX600F, RG250WD "You Porsche. Me pass!" DoD #484 JKLO#003, 005 WP7# 3000 LC Unit #2368 (tinlc) UKMC#00009 BOTAFOT#16 UKRMMA#7 (Hon) KotPT -- "for stupidity above and beyond the call of duty". I will be coding in verilog. There will not by a host of functions for me to call, so functions like eigenvalues and eigenvectors will need to be coded explicitly. Yes Verilog is being used by me for FPGA programming. Basically, my issue, is when I try to directly translate the TQLI.F OR TQLI.C code to matlab, it just will not work for reason totally beyond me... TRED2.f worked perfectly... which add to the irritation ironically... here is hoping someone who has this done sees this post! peace. I recommend systolic arrays for hardware matrix processing. The usual reason for wanting a hardware implementation is speed, and systolic arrays usually work pretty well for that. Also, they scale with problem size when needed. About how big are your matrices and how fast do you need the results? -- glen
http://www.megasolutions.net/fortran/Fortran-to-matlab-infuriating-problem-77823.aspx
CC-MAIN-2014-49
refinedweb
1,475
75.3
Introduction Various articles I have previously written have described Futures and their use, such as the Futures Advent Calendar. In this article, I want to present a new syntax module that greatly improves the expressive power and neatness of writing Future-based code. This module is Future::AsyncAwait. The new syntax provided by this module is based on two keywords, async and await that between them provide a powerful new ability to write code that uses Future objects. The await keyword causes the containing function to pause while it waits for completion of a future, and the async keyword decorates a function definition to allow this to happen. These keywords encapsulate the idea of suspending some running code that is waiting on a future to complete, and resuming it again at some later time once a result is ready. use Future::AsyncAwait; async sub get_price { my ($product) = @_; my $catalog = await get_catalog(); return $catalog->{$product}->{price}; } This already reads a little neater than how this might look with a ->then chain: sub get_price { my ($product) = @_; return get_catalog()->then(sub { my ($catalog) = @_; return Future->done($catalog->{$product}->{price}); }); } This new syntax makes a much greater impact when we consider code structures like foreach loops: use Future::AsyncAwait; async sub send_message { my ($message) = @_; foreach my $chunk ($message->chunks) { await send_chunk($chunk); } } Previously we'd have had to use Future::Utils::repeat to create the loop: use Future::Utils qw( repeat ); sub send_message { my ($message) = @_; repeat { my ($chunk) = @_; send_chunk($chunk); } foreach => [ $message->chunks ]; } Because the entire function is suspended and resumed again later on, the values of lexical variables are preserved for use later on: use Future::AsyncAwait; async sub echo { my $message = await receive_message(); await delay(0.2); send_message($message); } If instead we were to do this using ->then chaining, we'd find that we either have to hoist a variable out to the main body of the function to store $message, or use a further level of nesting and indentation to make the lexical visible to later code: sub echo { my $message; receive_message()->then(sub { ($message) = @_; delay(0.2); })->then(sub { send_message($message); }); } # or sub echo { receive_message()->then(sub { my ($message) = @_; delay(0.2)->then(sub { send_message($message); }); }); } These final examples are each equivalent to the version using async and await above, yet are both much longer, and more full of the lower-level "machinery" of solving the problem, which obscures the logical flow of what the code is trying to achieve. Comparison With Other Languages This syntax isn't unique to Perl - a number of other languages have introduced very similar features. async function asyncCall() { console.log('calling'); var result = await resolveAfter2Seconds(); console.log(result); } async def main(): print('hello') await asyncio.sleep(1) print('world') public async Task<int> GetDotNetCountAsync() { var html = await _httpClient.GetStringAsync(""); return Regex.Matches(html, @"\.NET").Count; } main() async { var context = querySelector("canvas").context2D; var running = true; // Set false to stop game. while (running) { var time = await window.animationFrame; context.clearRect(0, 0, 500, 500); context.fillRect(time % 450, 20, 50, 50); } } In fact, much like the recognisable shapes of things like if blocks and while loops, it is starting to look like the async/await syntax is turning into a standard language feature across many languages. Current State At the time of writing, this module stands at version 0.22, and has been the result of an intense round of bug-fixing and improvement over the Christmas and New Year break. While it isn't fully production-tested and ready for all uses yet, I have been starting to experiment with using it in a number of less production-critical code paths (such as unit or integration testing, or less widely used CPAN modules) in order to help shake out any further bugs that may arise, and generally evaluate how stable it is becoming. This version already handles a lot of even non-trivial cases, such as in conjunction with the try/catch syntax provided by Syntax::Keyword::Try: use Future::AsyncAwait; use Syntax::Keyword::Try; async sub copy_data { my ($source, $destination) = @_; my @rows = await $source->get_data; my $successful = 0; my $failed = 0; foreach my $row (@rows) { try { await $destination->put_row($row); $successful++; } catch { $log->warnf("Unable to handle row ID %s: %s", $row->{id}, $@); $failed++; } } $log->infof("Copied %d rows successfully, with %d failures", $successful, $failed); } Known Bugs As already mentioned, the module is not yet fully production-ready as it is known to have a few issues, and likely there may be more lurking around as yet unknown. As an outline of the current state of stability, and to suggest the size and criticality of the currently-known issues, here are a few of the main ones: Complex expressions in foreach lose values(RT 128619) I haven't been able to isolate a minimal test case yet for this one, but in essence the bug is that given some code which performs foreach my $value ( (1) x ($len - 1), (0) ) { await ... } the final 0 value gets lost. The loop executes for $len - 1 times with $value set to 1, but misses the final 0 case.The current workaround for this issue is to calculate the full set of values for the loop to iterate on into an array variable, and then foreach over the array: my @values = ( (1) x ($len - 1), (0) ); foreach my $value ( @values ) { await ... } While an easy workaround, the presence of this bug is nonetheless a little worrying, because it demonstrates the possibility for a silent failure. The code doesn't cause an error message or a crash, it simply produces the wrong result without any warning or other indication that anything went wrong. It is, at time of writing, the only bug of this kind known. Every other bug produces an error message, most likely a crash, either at compile or runtime. Fails on threaded perl 5.20 and earlier(RT 124351) The module works on non-threaded builds of perl from version 5.16 onwards, but only on threaded builds 5.22 onwards. Threaded builds of 5.20 or earlier all fail with a wide variety of runtime errors, and are currently marked as not supported. I could look into this if there was sufficient interest, but right now I don't feel it is a good use of time to support these older perl versions, as compared fixing other issues and making other improvements elsewhere. Devel::Cover can't see into async subs(RT 128309) This one is likely to need fixing within Devel::Cover itself rather than Future::AsyncAwait, as it probably comes from the optree scanning logic there getting confused by the custom LEAVEASYNC ops created by this module. By comparison, Devel::NYTprof can see them perfectly fine, so this suggests the issue shouldn't be too hard to fix. Next Directions There are a few missing features or other details that should be addressed at some point soon. Core perl integration Currently, the module operates entirely as a third-party CPAN module, without specific support from the Perl core. While the perl5-porters ("p5p") are aware of and generally encourage this work to continue, there is no specific integration at the code level to directly assist. There are two particular details that I would like to see: - Better core support for parsing and building the optree fragment relating to the signature part of a sub definition. Currently, async sub definitions cannot make use of function signatures, because the parser is not sufficiently fine-grained to allow it. An interface in core Perl to better support this would allow async subs to take signatures, as regular non-async ones can. A mailing list thread has touched on the issue, but so far no detailed plans have emerged. - An eventual plan to migrate parts of the suspend and resume logic out of this module and into core. Or at least, some way to try to make it more future-proof. Currently the implementation is very version-dependent and has to inspect and operate on lots of various inner parts of the Perl interpreter. If core Perl could offer a way to suspend and resume a running CV, it would make Future::AsyncAwait a lot simpler and more stable across versions, and would also pave the way for other CPAN modules to provide other syntax or semantics based around this concept, such as coroutines or generators. local and await Currently, the suspend logic will get upset about any local variable modifications that are in scope at the time it has to suspend the function; for instance async sub x { my $self = shift; local $self->{debug} = 1; await $self->do_work(); # is $self->{debug} restored to 1 here? } This is more than just a limit of the implementation, however as it extends to fundamental questions about what the semantic meaning of such code should be. It is hard to draw parallels from any of the other language the async/await syntax was inspired by, because none of these have a construct similar to Perl's local. Recommendations For Use Earlier, I stated that Future::AsyncAwait is not fully production-ready yet, on account of a few remaining bugs combined with its general lack of production testing at volume. While it probably shouldn't be used in any business-critical areas at the moment, it can certainly help in many other areas. Unit tests and developer-side scripts, or things that run less often and are generally supervised when they are, should be good candidates for early adoption. If these do break it won't be critical to business operation, and should be relatively simple to revert to an older version that doesn't use Future::AsyncAwait while a bugfix is found. The main benefit of beginning adoption is that the syntax provided by this module greatly improves the readability of the surrounding code, to the point that it can itself help reveal other bugs that were underlying in the logic. On this subject, Tom Molesworth writes that: Simple, readable code is going to be a benefit that may outweigh the potential risks of using newer, less-well-tested modules such as this one. This advice is similar to my own personal uses of the module, which are currently limited to a small selection of my CPAN modules that relate to various exotic pieces of hardware. Many of the driver modules related to Device::Chip have begun to use it. A list of modules that use Future::AsyncAwait is maintained by metacpan. I am finding that the overall neatness and expressiveness of using async/await expressions is easy justification against the potential for issues in these areas. As bugs are fixed and the module is found to be increasingly stable and reliable, the boundary can be further pushed back and the module introduced to more places. This article is adapted from one that was originally written in two parts for the Binary.com internal tech blog - part 1, part 2. I would also like to thank The Perl Foundation whose grant has enabled me to continue working on this piece of Perl infrastructure.
https://leonerds-code.blogspot.com/2019/04/awaiting-future.html
CC-MAIN-2020-16
refinedweb
1,862
54.46
to connect to computing resources hosted on Google Cloud Platform via the web. You will learn how to use Cloud Shell and the Cloud SDK gcloud command. This tutorial is adapted ( docker, gcloud, kubectl $ gcloud config set compute/region us-central1 You can pick and choose different zones too. Learn more about zones Inside the helloworld directory, create a file named helloworld.py, and give it the following contents: import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) This Python script: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: helloworld helloworld.py to change Hello, World! to something else e.g. "Hello, Kathy!". import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, Kathy!') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) Reload the tab in the browser in which the app is running. Deploy your Hello World server to the production App Engine environment: $ gcloud app deploy app.yaml After the application is deployed, you can visit it by opening the URL http://<project-id>.appspot.com in your web browser. The full URL for your application is. Optionally, you can instead purchase and use a top-level domain name for your app, or use one that you have already registered. In this step, you set up a simple Python application and ran and deployed your application on App Engine. You learned how to write your first App Engine web application! This work is licensed under a Creative Commons Attribution 2.0 Generic License.
https://codelabs.developers.google.com/codelabs/cloud-app-engine-python/index.html?index=..%2F..%2Fstrata
CC-MAIN-2017-13
refinedweb
271
53.17
Frequently Asked Questions about XSLT The following are frequently asked questions about XSLT. XSLT transformations can be initiated programmatically using any language that supports COM interfaces. Such programming languages include Microsoft JScript, VBScript, Visual Basic, C++, and even Perl. To run XSLT transformations programmatically, you must create two XML DOM objects, one for the XML source document and the other for the XSLT style sheet. Then, you call the transformNode() function on the XML source document with the XSLT style sheet XML DOM object as the argument. The following example in JScript illustrates these points. JScript File (test.js) var '+ ' <xsl:output '+ ' <xsl:template '+ ' <xsl:value-of '+ ' <xsl:text> </xsl:text> '+ ' <xsl:value-of '+ ' </xsl:template> '+ '</xsl:stylesheet>'; var xmldom, xsltdom; try { xmldom = new ActiveXObject("Msxml2.DOMDocument.6.0"); xmldom.validateOnParse = true; xmldom.async = false; xmldom.loadXML(xmlstr); xsltdom = new ActiveXObject("Msxml2.DOMDocument.6.0"); xsltdom.validateOnParse = true; xsltdom.async = false; xsltdom.loadXML(xsltstr); output = xmldom.transformNode(xsltdom); WScript.echo(output); } catch(err) { WScript.echo(err.description); } Try It! Copy and paste the code into a file, and save it as test.js. Type the "test.js" command from a command window. Output The output is "Red apple". No. Use the standard xmlns:xsl="" syntax. If Internet Explorer returns an error when you use this namespace, it is likely that you are using an earlier version of MSXML that does not support XSLT. If you have older XSL files and do not want to convert them to XSLT files, you can still use the namespace declaration xmlns:xsl="". Yes. MSXML is fully compliant with the XSLT specification. For more information, see Supported XSLT Features. Because XSLT is a different technology from XSL. Each new release of MSXML has a Bug List Page that describes known problems, such as coding mistakes or features that are not fully implemented. To find this page, search MSDN. For full conformance disclosure, see Supported XSLT Features. If you find a bug or implementation point that is not clearly documented, please send feedback to the XML documentation team by using the XML Documentation Feedback form. To use this form, click the Feedback icon (the envelope) at the top-right corner of any page of this documentation. Because MSXML is a COM object, you can write VBScript, JScript, or other Windows Script Host (WSH) files to launch MSXML from the command prompt. If you would like to upgrade XSL files so that they are compliant with the XSLT recommendation, you can use the XSL to XSLT 1.1 Converter available from MSDN Downloads at. The reason for this error involves namespaces that ActiveX Data Objects (ADO) 2.6 uses when you use the adPersistXML formatting option with the Save method to persist an ADO recordset as XML. For example, the following line shows the syntax used to persist the current ADO recordset as XML in a Visual Basic application. rs.Save "c:\temp\nwind.xml ", adPersistXML The persisted XML output includes several namespace prefixes: "s", "dt", "rs", and "z". When you use XSLT style sheets to transform ADO-persisted XML, these namespaces must be declared for the transformation to succeed. When using ADO to persist data as XML, you might encounter the following error text when you attempt to apply XSLT to your persisted XML. For example, a style sheet might reference the XSLT namespace URI as follows: This example, though valid as XSLT, produces the undeclared namespace error described above. To fix the problem, style sheets that specify the XSLT namespace URI must also declare any of the ADO namespaces that are used as input. The following example shows how to update the previous style sheet code to declare these namespaces. <xsl:stylesheet xmlns: <xsl:element <xsl:value-of </xsl:element> </xsl:template> </xsl:stylesheet> By adding the ADO namespace declarations above to your style sheet, you can correct the error and permit it to successfully transform ADO-persisted XML. Style sheets that reference the older XSL namespace (like the following sample) do not produce this error. Therefore, these style sheets are not affected and do not require any changes for this issue. No. MSXML versions 6.0 fully implement and support XSL Transformations (XSLT) Version 1.0 (W3C Recommendation 16 November 1999).
https://msdn.microsoft.com/en-us/library/ms757858(v=vs.85).aspx
CC-MAIN-2017-09
refinedweb
707
57.98
.h - Committer: - embeddedartists - Date: - 2015-03-27 - Revision: - 1:2847cc35a84f - Parent: - 0:582739e02e4d File content as of revision 1:2847cc35a84f: #ifndef EWHAL_H #define EWHAL_H #include "mbed.h" #include "DMBoard.h" /** * This is the main class to get Segger's emwin library up-and-running * with the mbed online tools. * * This class handles the porting/integration layer in emwin. */ class EwHAL { public: EwHAL(int numFB = 1, uint32_t extraMem = 1*1024*1024); ~EwHAL(); /** * Returns the address to a memory block which may be used by emwin * to allocate objects. The memory block returned will be given to emwin * by calling GUI_ALLOC_AssignMemory. */ void* getMemoryBlockAddress() { return (void*)_mem; } /** * Returns the size of the memory block returned by * getMemoryBlockAddress(). */ uint32_t getMemoryBlockSize() { return _memSz; } /** * Returns the width of the display. */ uint32_t getDisplayWidth() { return _width; } /** * Returns the height of the display. */ uint32_t getDisplayHeight() { return _height; } /** * Returns the address of the framebuffer (video RAM). This address will * be given to emwin by a call to LCD_SetVRAMAddrEx. */ void* getFrameBufferAddress() { return (void*)_fb; } /** * Returns the size in bytes of the framebuffer (video RAM). */ uint32_t getFrameBufferSize() { return _fbSz; } /** * Returns the number of frame buffers to use, default is 1 meaning * that drawing takes place on the same buffer that is being shown. * Double buffering is 2 and Tripple buffering is 3. No other values * should be used. */ int getNumFrameBuffers() { return _numFB; } /** * Shows frame buffer number id. If getNumFrameBuffers() returns 1 then * this id will always be 0, if getNumFrameBuffers() returns N then this * function will be called with 0..(N-1). */ void showFrameBuffer(int id); /** * Returns the x coordinate of the latest touch event */ int32_t getTouchX() {return _coord.x;} /** * Returns the y coordinate of the latest touch event */ int32_t getTouchY() {return _coord.y;} private: /** * Called when a new touch event is available. Reads the coordinates and * forwards them to emWin */ void handleTouchEvent(); int _numFB; FunctionPointer* _fp; uint32_t _width; uint32_t _height; uint32_t _fb; uint32_t _fbSz; uint32_t _mem; uint32_t _memSz; Display* _display; TouchPanel* _touch; touch_coordinate_t _coord; }; #endif
https://os.mbed.com/teams/Embedded-Artists/code/DMemWin/file/2847cc35a84f/EwHAL.h/
CC-MAIN-2019-47
refinedweb
324
56.86
Hi, I've done a lot of searching and haven't found any good ideas about this. It must be simple. I'm not an experienced C++ programmer and I haven't quite grasped the concepts of data abstraction and classes, so I'm probably still thinking with the old "top-down" paradigm. Admittedly, by getting some code from the "snippets" page and other internet sources, I'm trying to work with functions that I don't thoroughly understand. Here's a description of what I want to do. Loop (in a directory) read file names in the directory into file_name[i] array end of loop Loop through input file_name[] array open each input file read about 250 lines of data into arrays zero out math variables do some math perform some tests if pass all tests? output file_name[i] to a an output file close file end of loop The following came from the snippets page and is used to read all the filenames in the directory. It works. I added the lines to load the file_name[] array which also works. I could probably skip that step and do all my operations within the while(FindNextFile....)loop, but keeping the steps separate is easier for me to keep organized. After I fill the file_names[] array, I want to loop through the files, readAfter I fill the file_names[] array, I want to loop through the files, readCode:// read all the filenames in a directory //************************************************************ WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; char DirSpec[MAX_PATH]; // directory specification cout<<"Path: "; cin.get(DirSpec, MAX_PATH); cout<<"\n"; strncat(DirSpec, "\\*", 3); hFind = FindFirstFile(DirSpec, &FindFileData); if(hFind == INVALID_HANDLE_VALUE) { cout<<"Error: invalid path\n"; } // // Read the files in the directory and assign // the filenames to the file_name[] array int i; string file_name[7000]; //yes, I need to learn how to handle a variable length string array! //number of files could vary but will be around 6500 i = 0; int file_count = 0; while(FindNextFile(hFind, &FindFileData) != 0) { file_name[i] = FindFileData.cFileName; //cout<<FindFileData.cFileName<<"\n"; i++; file_count++; } FindClose(hFind); //output one example cout<<"file 12 is "<<file_name [12]<<"\n\n"; //this works //*********************************************************** lines of data and perform operations. This is the part I haven't figured out. I'm trying to use the following as the basis to loop through the files My test files are consistent with the averaging routine here but this is just a test: I guess my real question is: Is the Infile.open("readfile.txt"....) lineI guess my real question is: Is the Infile.open("readfile.txt"....) lineCode://************************************************************ #include <iostream> #include <fstream> // needed for files using namespace std; int main(void) { fstream InFile; float Num, Total; int Count; // I want to put the following into a loop and somehow replace "readfile.txt" // with file_name[j] InFile.open("readfile.txt", ios::in); if (InFile.fail()) { cout << "Could not open readfile.txt" << endl; exit(1); } Count = 0; Total = 0.0; InFile >> Num; while (! InFile.fail()) { Total = Total + Num; Count++; InFile >> Num; } if (Count > 0) cout << "Average is " << Total / Count << endl; else cout << "No data given" << endl; InFile.close(); return 0; } //*********************************************************** extendable so that it could be used to loop through the file_name[] array? Sort of like the following (this doesn't work, it's just to get the idea of what I'm trying to do): Alternately, does anybody know a good C++ book where you can look up what you are trying to do and find some good examples of how to do it.Alternately, does anybody know a good C++ book where you can look up what you are trying to do and find some good examples of how to do it.Code:For ( j = 1; j <= file_count; j++) { InFile.open(file_name[j], ios::in); //read lines of data //perform operations InFile.close(); } Thanks, Rich
https://cboard.cprogramming.com/cplusplus-programming/126158-how-sequentially-read-all-files-directory.html
CC-MAIN-2018-05
refinedweb
632
61.46
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <net_config.h> U16 http_fread ( FILE* file, /* Pointer to the file to read from. */ U8* buf, /* Pointer to buffer, to store the read data. */ U16 len ); /* Number of bytes to read. */ The http_fread reads len bytes from the file identified by the file stream pointer in the function argument. The argument buf is a pointer to the buffer where the function stores the read data. The http_fread function is in the HTTP_uif.c module. The prototype is defined in net_config.h. note The http_fread function returns the number of bytes read from the file. http_fgets, http_finfo U16 http_fread (void *f, U8 *buf, U16 len) { /* Read 'len' bytes from file to buffer 'buf'. The file will be */ /* closed, when the number of read bytes is less than 'len'. */ return (fread (buf, 1, len,.
http://www.keil.com/support/man/docs/rlarm/rlarm_http_fread.htm
CC-MAIN-2019-43
refinedweb
144
85.18
2645/error-while-copying-the-file-from-local-to-hdfs I am following a hdfs tutorial for learning different hdfs commands. So far I am able to create a directory in hdfs using the command: hdfs dfs -mkdir -p sales/january But, I am getting error while copying the data from local file system to HDFS. I am following all the steps mentioned in the tutorial. Here is the screenshots: Now, I am issuing the following command: hdfs dfs -put january_sales_2017.csv sales/january/january_sale_2017.csv The error that I am getting is: put: `sales/january/january_sale_2017.csv': No such file or directory: `hdfs://localhost:8020/sales/january/january_sale_2017.csv` Please, let me know what I am doing wrong or is there any problem with the hadoop setup. Any help would be appreciated. Well, the reason you are getting such prompt is because you trying to copy the file into a directory that does not exist. In your case, you are trying to push the files january_sales_2017.csv into sales/january/january_sales_2017.csv directory path. Now, you have not created any sub-dir by the name of january_sales_2017.csv inside sales directory and therefore, giving you the error. So, on case you want to copy the files inside sales/january directory, here is the corrected way to do it: hdfs dfs -put january_sales_2017.csv /sales/january There are two possible ways to copy ...READ MORE Please refer to the below code: import org.apache.hadoop.conf.Configuration import ...READ MORE Hey, @Amey, This is probably because of a ...READ MORE Can use pipe from wget to hdfs. You ...READ MORE In your case there is no difference ...READ MORE Firstly you need to understand the concept ...READ MORE put syntax: put <localSrc> <dest> copy syntax: copyFr ...READ MORE hadoop.tmp.dir (A base for other temporary directories) is ...READ MORE The distributed copy command, distcp, is a ...READ MORE Sequence files are binary files containing serialized ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/2645/error-while-copying-the-file-from-local-to-hdfs?show=2646
CC-MAIN-2020-24
refinedweb
335
60.31
The original proposal was well-received but it didn't make provisions to handle str.format(). Here is the revised proposal. Only the last paragraph is new. Raymond Mark Dickinson's decimal test code suggested a good, extensible approach to the problem. Here's the idea in a nutshell: format(value, format_spec='', conventions=None) 'calls value.__format__(format_spec, conventions)' Where conventions is an optional dictionary with formatting control values. Any value object can accept custom controls, but the names for standard ones would be taken from the standards provided by localeconv(): { 'decimal_point': '.', 'grouping': [3, 0], 'negative_sign': '-', 'positive_sign': '', 'thousands_sep': ','} The would let you store several locales using localeconv() and use them at will, thus solving the global variable and threading problems with locale: import locale loc = locale.getlocale() # get current locale locale.setlocale(locale.LC_ALL, 'de_DE') DE = locale.localeconv() locale.setlocale(locale.LC_ALL, 'en_US') US = locale.localeconv() locale.setlocale(locale.LC_ALL, loc) # restore saved locale . . . format(x, '8,.f', DE) format(y, '8,d', US) It also lets you write your own conventions on the fly: DEBUG = dict(thousands_sep='_') # style for debugging EXTERN = dict(thousands_sep=',') # style for external display . . .='-')) . . . 'Nigerian President will forward {0:,d!US} to your account'.format(10000000) format(y, ',d!HY') format(z, ',d!US') My general thought is that I like the mechanism Mark uses to get the parameters into the __format__ function (the conventions dict). I'm just not sure where it needs to be specified in order to get the data into __format__.='-')) I'm not sure you want to use the word "register", as we might want to register other things in the future. Maybe "register_convention"? I realize it's a little long. Also, I don't like the **kwargs functionality here, why not specify it as 2 parameters? str.format.register_convention('HY', dict(thousands_sep='-')) 'Nigerian President will forward {0:,d!US} to your account'.format(10000000) format(y, ',d!HY') format(z, ',d!US') What happens if both a "conventions" parameter and a "!<registered-convention>" specifier are present? An error? Does one win? Are they merged? What happens if you specify a convention that's not registered? I'm not sure I like using the "!<registered-convention>" syntax. I think it means you couldn't have both a "!s" or "!r" and a "!<convention>" in the same format string, unless we allow "!s!HY". OTOH, "!s" and "!r" always yield strings, and I can't see how strings would need a convention, since they don't really do much formatting. But I haven't given that part much thought, and I don't have a counter-proposal. Using "!" also means we should probably require that conventions not be named "s" or "r", and we might want to reserve all single character lower case strings. A larger concern is libraries. If I'm a library author, there's no way I can know what conventions the application has registered. And even if I could inspect them, I'm not sure what I'd do with the knowledge. I either would have to register my own private conventions (like "libraryname.HY"), or we'd need to agree on conventions we're expecting to be available and what they mean. What are your thoughts on what a library author should do? Eric.
https://mail.python.org/archives/list/python-ideas@python.org/thread/DPESM2NXNNTU7YRDJSO6MA3HRLHI3H45/
CC-MAIN-2020-29
refinedweb
548
51.95
Advertisement play sounds its to good for audio programe first time i am seeing fantastic programe.. This tuturial I tried this program and use a different sound file but has the same extension (.wav)but when I pressed on play or stop nothing happened.I try many sound files that has this extension but every time nothing happened.when I download Sound File U About core java This is good souce code please give me more code like this; applet related coading i need for the applet progaramming so give me aright solution Hi Hello to all. new comer Reply to Play Audio in Java Applet I want to know how to play the audio from my system by tha java appletviewer problem in audio i hv tried this code many time bt i cannt b able to run any audio file...plz help me.. thnx Play Audio in Java Applet Play Audio in Java Applet  ... the sound file. This program will show you how to play a audio clip in your java applet viewer or on the browser. For this example we will be creating an applet called No matter what i do, eclipse applet WON'T PLAY SOUND - Java Beginners No matter what i do, eclipse applet WON'T PLAY SOUND OK, so I tried the code in..., even downloaded the sound file. it made a empty applet without any sound applet - Applet : Thanks... in Java Applet.",40,20); } } 2) Call this applet with html code...applet i want a simple code of applet.give me a simple example Applet - Applet in details to visit......., Applet Applet is java program that can be embedded into HTML pages. Java applets how to play audio track in java applat how to play audio track in java applat Sir,i took help of coding in how to play audio track in java applet....nd i found perfect code ..but when i... java.awt.event.*; public class PlayAppletSound extends Applet implements java - Applet java what is applet? Hi Friend, Please visit the following link: Thanks applet - Applet information,visit the following link: Thanks...*; import java.awt.*; public class CreateTextBox extends Applet implements play videos - Java Beginners play videos How to play videos on line.how to embed the video player in the browser.If you can give some basic idea about this i would be thankful to you. Thanks java applet - Applet :// Thanks...java applet I want to close applet window which is open by another button of applet program. plz tell me! Hi Friend, Try
http://roseindia.net/tutorialhelp/allcomments/243
CC-MAIN-2015-48
refinedweb
424
74.69
A few weeks ago I was looking at some of the performance metrics for my site. Specifically, I wanted to see how I was doing on our newest metric, first input delay (FID). My site is just a blog (and doesn’t run much JavaScript), so I expected to see pretty good results. Input delay that’s less than 100 milliseconds is typically perceived as instant by users, so the performance goal we recommend (and the numbers I was hoping to see in my analytics) is FID < 100ms for 99% of page loads. To my surprise, my site’s FID was 254ms at the 99th percentile. And while that’s not terrible, the perfectionist in me just couldn’t let that slide. I had to fix it! To make a long story short, without removing any functionality from my site, I was able to get my FID under 100ms at the 99th percentile. But what I’m sure is more interesting to you readers is: - How I approached diagnosing the problem. - What specific strategies and techniques I used to fix it. To that second point above, while I was trying to solve my issue I stumbled upon a pretty interesting performance strategy that I want to share (it’s the primary reason I’m writing this article). I’m calling the strategy: idle until urgent. My performance problem First input delay (FID) is a metric that measures the time between when a user first interacts with your site (for a blog like mine, that’s most likely them clicking a link) and the time when the browser is able to respond to that interaction (make a request to load the next page). The reason there might be a delay is if the browser’s main thread is busy doing something else (usually executing JavaScript code). So to diagnose a higher-than-expected FID, you should start by creating a performance trace of your site as it’s loading (with CPU and network throttling enabled) and look for individual tasks on the main thread that take a long time to execute. Then once you’ve identified those long tasks, you can try to break them up into smaller tasks. Here’s what I found when doing a performance trace of my site: Notice, when the main script bundle is evaluated, it’s run as a single task that takes 233 milliseconds to complete. Some of this code is webpack boilerplate and babel polyfills, but the majority of it is from my script’s main() entry function, which itself takes 183ms to complete: And it’s not like I’m doing anything ridiculous in my main() function. I’m initializing my UI components and then running my analytics: const main = () => { drawer.init(); contentLoader.init(); breakpoints.init(); alerts.init(); analytics.init(); }; main(); So what’s taking so long to run? Well, if you look at the tails of this flame chart, you won’t see any single functions that are clearly taking up the bulk of the time. Most individual functions are run in less than 1ms, but when you add them all up, it’s taking more than 100ms to run them in a single, synchronous call stack. This is the JavaScript equivalent of death by a thousand cuts. Since the problem is all these functions are being run as part of a single task, the browser has to wait until this task finishes to respond to user interaction. So clearly the solution is to break up this code into multiple tasks, but that’s a lot easier said than done. At first glance, it might seem like the obvious solution is to prioritize each of the components in my main() function (they’re actually already in priority order), initialize the highest priority components right away, and then defer other component initialization to a subsequent task. While this may help some, it’s not a solution that everyone could implement, nor does it scale well to a really large site. Here’s why: - Deferring UI component initialization only helps if the component isn’t yet rendered. If it’s already rendered than deferring initialization runs the risk that the user tries to interact with it and it’s not yet ready. - In many cases all UI components are either equally important or they depend on each other, so they all need to be initialized at the same time. - Sometimes individual components take long enough to initialize that they’ll block the main thread even if they’re run in their own tasks. The reality is that initializing each component in its own task is usually not sufficient and oftentimes not even possible. What’s usually needed is breaking up tasks within each component being initialized. Greedy components A perfect example of a component that really needs to have its initialization code broken up can be illustrated by zooming closer down into this performance trace. Mid-way through the main() function, you’ll see one of my components uses the Intl.DateTimeFormat API: Creating this object took 13.47 milliseconds! The thing is, the Intl.DateTimeFormat instance is created in the component’s constructor, but it’s not actually used until it’s needed by other components that reference it to format dates. However, this component doesn’t know when it’s going to be referenced, so it’s playing it safe and instantiating the Int.DateTimeFormat object right away. But is this the right code evaluation strategy? And if not, what is? Code evaluation strategies When choosing an evaluation strategy for potentially expensive code, most developers select one of the following: - Eager evaluation: where you run your expensive code right away. - Lazy evaluation: where you wait until another part of your program needs the result of that expensive code, and you run it then. These are probably the two most popular evaluation strategies, but after my experience refactoring my site, I now think these are probably your two worst options. The downsides of eager evaluation As the performance problem on my site illustrates pretty well, eager evaluation has the downside that, if a user tries to interact with your page while the code is evaluating, the browser must wait until the code is done evaluating to respond. This is especially problematic if your page looks like it’s ready to respond to user input, but then it can’t. Users will perceive your page as sluggish or maybe even completely broken. The more code you evaluate up front, the longer it will take for your page to become interactive. The downsides of lazy evaluation If it’s bad to run all your code right away, the next most obvious solution is to wait to run it until it’s actually needed. This way you don’t run code unnecessarily, especially if it’s never actually needed by the user. Of course, the problem with waiting until the user needs the result of running that code is now you’re guaranteeing that your expensive code will block user input. For some things (like loading additional content from the network), it makes sense to defer it until it’s requested by the user. But for most code you’re evaluating (e.g. reading from localStorage, processing large datasets, etc.) you definitely want it to happen before the user interaction that needs it. Other options The other evaluation strategies you can choose from all take an approach somewhere in between eager and lazy. I’m not sure if the following two strategies have official names, but I’m going to call them deferred evaluation and idle evaluation: - Deferred evaluation: where you schedule your code to be run in a future task, using something like setTimeout. - Idle evaluation: a type of deferred evaluation where you use an API like requestIdleCallback to schedule your code to run. Both of these options are usually better than eager or lazy evaluation because they’re far less likely to lead to individual long tasks that block input. This is because, while browsers cannot interrupt any single task to respond to user input (doing so would very likely break sites), they can run a task in between a queue of scheduled tasks, and most browsers do when that task is caused by user input. This is known as input prioritization. To put that another way: if you ensure all your code is run in short, distinct tasks (preferably less than 50ms), your code will never block user input. Important! While browsers can run input callbacks ahead of queued tasks, they cannot run input callbacks ahead of queued microtasks. And since promises and async functions run as microtasks, converting your sync code to promise-based code will not prevent it from blocking user input! If you’re not familiar with the difference between tasks and microtasks, I highly recommend watching my colleague Jake’s excellent talk on the event loop. Given what I just said, I could refactor my main() function to use setTimeout() and requestIdleCallback() to break up my initialization code into separate tasks: const main = () => { setTimeout(() => drawer.init(), 0); setTimeout(() => contentLoader.init(), 0); setTimeout(() => breakpoints.init(), 0); setTimeout(() => alerts.init(), 0); requestIdleCallback(() => analytics.init()); }; main(); However, while this is better than before (many small tasks vs. one long task), as I explained above it’s likely still not good enough. For example, if I defer the initialization of my UI components (specifically contentLoader and drawer) they’ll be less likely to block user input, but they also run the risk of not being ready when the user tries to interact with them! And while delaying my analytics with requestIdleCallback() is probably a good idea, any interactions I care about before the next idle period will be missed. And if there’s not an idle period before the user leaves the page, these callbacks may never run at all! So if all evaluations strategies have downsides, which one should you pick?. Idle-until-urgent sidesteps most of the downsides I described in the previous section. In the worst case, it has the exact same performance characteristics as lazy evaluation, and in the best case it doesn’t block interactivity at all because execution happens during idle periods. I should also mention that this strategy works both for single tasks (computing values idly) as well as multiple tasks (an ordered queue of tasks to be run idly). I’ll explain the single-task (idle value) variant first because it’s a bit easier to understand. Idle values I showed above that Int.DateTimeFormat objects can be pretty expensive to initialize, so if an instance isn’t needed right away, it’s better to initialize it during an idle period. Of course, as soon as it is needed, you want it to exist, so this is a perfect candidate for idle-until-urgent evaluation. Consider the following simplified component example that we want to refactor to use this new strategy: class MyComponent { constructor() { addEventListener('click', () => this.handleUserClick()); this.formatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', }); } handleUserClick() { console.log(this.formatter.format(new Date())); } } Instances of MyComponent above do two things in their constructor: - Add an event listener for user interactions. - Create an Intl.DateTimeFormatobject. This component perfectly illustrates why you often need to split up tasks within an individual component (rather than just at the component level). In this case it’s really important that the event listeners run right away, but it’s not important that the Intl.DateTimeFormat instance is created until it’s needed by the event handler. Of course we don’t want to create the Intl.DateTimeFormat object in the event handler because then its slowness will delay that event from running. So here’s how we could update this code to use the idle-until-urgent strategy. Note, I’m making use of an IdleValue helper class, which I’ll explain next: import {IdleValue} from './path/to/IdleValue.mjs'; class MyComponent { constructor() { addEventListener('click', () => this.handleUserClick()); this.formatter = new IdleValue(() => { return new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', }); }); } handleUserClick() { console.log(this.formatter.getValue().format(new Date())); } } As you can see, this code doesn’t look much different from the previous version, but instead of assigning this.formatter to a new Intl.DateTimeFormat object, I’m assigning this.formatter to an IdleValue object, which I pass an initialization function.. Here’s the gist of how the IdleValue class is implemented (note: I’ve also released this code as part of the idlize package, which includes all the helpers shown in this article): export class IdleValue { constructor(init) { this._init = init; this._value; this._idleHandle = requestIdleCallback(() => { this._value = this._init(); }); } getValue() { if (this._value === undefined) { cancelIdleCallback(this._idleHandle); this._value = this._init(); } return this._value; } // ... } While including the IdleValue class in my example above didn’t require many changes, it did technically change the public API ( this.formatter vs. this.formatter.getValue()). If you’re in a situation where you want to use the IdleValue class but you can’t change your public API, you can use the IdleValue class with ES2015 getters: class MyComponent { constructor() { addEventListener('click', () => this.handleUserClick()); this._formatter = new IdleValue(() => { return new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', }); }); } get formatter() { return this._formatter.getValue(); } // ... } Or, if you don’t mind a little abstraction, you can use the defineIdleProperty() helper (which uses Object.defineProperty() under the hood): import {defineIdleProperty} from './path/to/defineIdleProperty.mjs'; class MyComponent { constructor() { addEventListener('click', () => this.handleUserClick()); defineIdleProperty(this, 'formatter', () => { return new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', }); }); } // ... } For individual property values that may be expensive to compute, there’s really no reason not to use this strategy, especially since you can employ it without changing your API! While this example used the Intl.DateTimeFormat object, it’s also probably a good candidate for any of the following: - Processing large sets of values. - Getting a value from localStorage (or a cookie). - Running getComputedStyle(), getBoundingClientRect(), or any other API that may require recalculating style or layout on the main thread. Idle task queues The above technique works pretty well for individual properties whose values can be computed with a single function, but in some cases your logic doesn’t fit into a single function, or, even if it technically could, you’d still want to break it up into smaller functions because otherwise you’d risk blocking the main thread for too long. In such cases what you really need is a queue where you can schedule multiple tasks (functions) to run when the browser has idle time. The queue will run tasks when it can, and it will pause execution of tasks when it needs to yield back to the browser (e.g. if the user is interacting). To handle this, I built an IdleQueue class, and you can use it like this: import {IdleQueue} from './path/to/IdleQueue.mjs'; const queue = new IdleQueue(); queue.pushTask(() => { // Some expensive function that can run idly... }); queue.pushTask(() => { // Some other task that depends on the above // expensive function having already run... }); Note: breaking up your synchronous JavaScript code into separate tasks that can run asynchronously as part of a task queue is different from code splitting, which is about breaking up large JavaScript bundles into smaller files (and is also important for improving performance). As with the idly-initialized property strategy shown above, idle tasks queues also have a way to run immediately in cases where the result of their execution is needed right away (the “urgent” case). Again, this last bit is really important; not just because sometimes you need to compute something as soon as possible, but often you’re integrating with a third-party API that’s synchronous, so you need the ability to run your tasks synchronously as well if you want to be compatible. In a perfect world, all JavaScript APIs would be non-blocking, asynchronous, and composed of small chunks of code that can yield at will back to the main thread. But in the real world, we often have no choice but to be synchronous due to a legacy codebase or integrations with third-party libraries we don’t control. As I said before, this is one of the great strengths of the idle-until-urgent pattern. It can be easily applied to most programs without requiring a large-scale rewrite of the architecture. Guaranteeing the urgent I mentioned above that requestIdleCallback() doesn’t come with any guarantees that the callback will ever run. And when talking to developers about requestIdleCallback(), this is the primary explanation I hear for why they don’t use it. In many cases the possibility that code might not run is enough of a reason not to use it—to play it safe and keep their code synchronous (and therefore blocking). A perfect example of this is analytics code. The problem with analytics code is there are many cases where it needs to run when the page is unloading (e.g. tracking outbound link clicks, etc.), and in such cases requestIdleCallback() is simply not an option because the callback would never run. And since analytics libraries don’t know when in the page lifecycle their users will call their APIs, they also tend to play it safe and run all their code synchronously (which is unfortunate since analytics code is definitely not critical to the user experience). But with the idle-until-urgent pattern, there’s a simple solution to this. All we have to do is ensure the queue is run immediately whenever the page is in a state where it might soon be unloaded. If you’re familiar with the advice I give in my recent article on the Page Lifecycle API, you’ll know that the last reliable callback developers have before a page gets terminated or discarded is the visibilitychange event (as the page’s visibilityState changes to hidden). And since in the hidden state the user cannot be interacting with the page, it’s a perfect time to run any queued idle tasks. In fact, if you use the IdleQueue class, you can enable this ability with a simple configuration option passed to the constructor. const queue = new IdleQueue({ensureTasksRun: true}); For tasks like rendering, there’s no need to ensure tasks run before the page unloads, but for tasks like saving user state and sending end-of-session analytics, you’ll likely want to set this option to true. Note: listening for the visibilitychange event should be sufficient to ensure tasks run before the page is unloaded, but due to Safari bugs where the pagehide and visibilitychange events don’t always fire when users close a tab, you have to implement a small workaround just for Safari. This workaround is implemented for you in the IdleQueue class, but if you’re implementing this yourself, you’ll need to be aware of it. Warning! Do not listen for the unload event as a way to run the queue before the page is unloaded. The unload event is not reliable and it can hurt performance in some cases. See my Page Lifecycle API article for more details. Use cases for idle-until-urgent Any time you have potentially-expensive code you need to run, you should try to break it up into smaller tasks. And if that code isn’t needed right away but may be needed at some point in the future, it’s a perfect use case for idle-until-urgent. In your own code, the first thing I’d suggest to do is look at all your constructor functions, and if any of them run potentially-expensive operations, refactor them to use an IdleValue object instead. For other bits of logic that are essential but not necessarily critical to immediate user interactions, consider adding that logic to an IdleQueue. Don’t worry, if at any time you need to run that code immediately, you can. Two specific examples that are particularly amenable to this technique (and are relevant to a large percentage of websites out there) are persisting application state (e.g. with something like Redux) and analytics. Note: these are all use cases where the intention is that tasks should run during idle periods, so it’s not a problem if they don’t run right away. If you need to handle high-priority tasks where the intention is they should run as soon as possible (yet still yielding to input), then requestIdleCallback() may not solve your problem. Fortunately, some of my colleagues have proposals for new web platform APIs ( shouldYield(), and a native Scheduling API) that should help. Persisting application state Consider a Redux app that stores application state in memory but also needs to store it in persistent storage (like localStorage) so it can be reloaded the next time the user visits the page. Most Redux apps that store state in localStorage use a debounce technique roughly equivalent to this: let debounceTimeout; // Persist state changes to localStorage using a 1000ms debounce. store.subscribe(() => { // Clear pending writes since there are new changes to save. clearTimeout(debounceTimeout); // Schedule the save with a 1000ms timeout (debounce), // so frequent changes aren't saved unnecessarily. debounceTimeout = setTimeout(() => { const jsonData = JSON.stringify(store.getState()); localStorage.setItem('redux-data', jsonData); }, 1000); }); While using a debounce technique is definitely better than nothing, it’s not a perfect solution. The problem is there’s no guarantee that when the debounced function does run, it won’t block the main thread at a time critical to the user. It’s much better to schedule the localStorage write for an idle time. You can convert the above code from a debounce strategy to an idle-until-urgent strategy as follows: const queue = new IdleQueue({ensureTasksRun: true}); // Persist state changes when the browser is idle, and // only persist the most recent changes to avoid extra work. store.subscribe(() => { // Clear pending writes since there are new changes to save. queue.clearPendingTasks(); // Schedule the save to run when idle. queue.pushTask(() => { const jsonData = JSON.stringify(store.getState()); localStorage.setItem('redux-data', jsonData); }); }); And note that this strategy is definitely better than using debounce because it guarantees the state gets saved even if the user is navigating away from the page. With the debounce example, the write would likely fail in such a situation. Analytics Another perfect use case for idle-until-urgent is analytics code. Here’s an example of how you can use the IdleQueue class to schedule sending your analytics data in a way that ensures it will be sent even if the user closes the tab or navigates away before the next idle period. const queue = new IdleQueue({ensureTasksRun: true}); const signupBtn = document.getElementById('signup'); signupBtn.addEventListener('click', () => { // Instead of sending the event immediately, add it to the idle queue. // The idle queue will ensure the event is sent even if the user // closes the tab or navigates away. queue.pushTask(() => { ga('send', 'event', { eventCategory: 'Signup Button', eventAction: 'click', }); }); }); In addition to ensuring the urgent, adding this task to the idle queue also ensures it won’t block any other code that’s needed to respond to the user’s click. In fact, it’s generally a good idea to run all your analytics code idly, including your initialization code. And for libraries like analytics.js whose API is already effectively a queue, it’s easy to just add these commands to our IdleQueue instance. For example, you can convert the last part of the default analytics.js installation snippet from this: ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview'); Into this: const queue = new IdleQueue({ensureTasksRun: true}); queue.pushTask(() => ga('create', 'UA-XXXXX-Y', 'auto')); queue.pushTask(() => ga('send', 'pageview')); (You could also just create a wrapper around the ga() function that automatically queues commands, which is what I did). Browser support for requestIdleCallback As of this writing, only Chrome and Firefox support requestIdleCallback(). And while a true polyfill isn’t really possible (only the browser can know when it’s idle), it’s quite easy to write a fallback to setTimeout (all the helper classes and methods mentioned here use this fallback). And even in browsers that don’t support requestIdleCallback() natively, the fallback to setTimeout is definitely still better than not using this strategy because browsers can still do input prioritization ahead of tasks queued via setTimeout(). How much does this actually improve performance? At the beginning of this article I mentioned I came up with this strategy as I was trying to improve my website’s FID value. I was trying to split up all the code that ran as soon as my main bundle was loaded, but I also needed to ensure my site continued to work with some third-party libraries that only have synchronous APIs (e.g. analytics.js). The trace I showed before implementing idle-until-urgent had a single, 233ms task that contained all my initialization code. After implementing the techniques I described here, you can see I have multiple, much shorter tasks. In fact, the longest one is now only 37ms! A really important point to emphasize here is that the same amount of work is being done as before, it’s just now spread out over multiple tasks and run during idle periods. And since no single task is greater than 50ms, none of them affect my time to interactive (TTI), which is great for my lighthouse score: Lastly, since the point of all this work was to improve my FID, after releasing these changes to production and looking at the results, I was thrilled to discover a 67% reduction in FID values at the 99th percentile! Conclusions In a perfect world, none of our sites would ever block the main thread unnecessarily. We’d all be using web workers to do our non-UI work, and we’d have shouldYield() and a native Scheduling API) built into the browser. But in our current world, we web developers often have no choice but to run non-UI code on the main thread, which leads to unresponsiveness and jank. Hopefully this article has convinced you of the need to break up our long-running JavaScript tasks. And since idle-until-urgent can turn a synchronous-looking API into something that actually evaluates code in idle periods, it’s a great solution that works with the libraries we all know and use today.
https://philipwalton.com/articles/idle-until-urgent/
CC-MAIN-2022-21
refinedweb
4,405
51.68
“Drawing” from Our Learning: How to Build a Lesson Drawer in jQuery, HTML, and CSSBy Mark Cipolla In the spirit of showing how things are done at SitePoint‘s sister company Learnable—a new site where anyone can create an online course about anything at all, and then sell access to that course—I’m going to run you through a small component of Learnable’s student view: the lesson drawer. I’ve simplified the layout and styling a little so that you can easily understand what’s going on, but the JavaScript is exactly the same. In this post, I’ll cover the HTML (including some of the new HTML5 elements), CSS, and JavaScript (with a little help from jQuery) needed to build a drawer. The drawer is a large container that holds a list of the lessons in a course, which can be opened by a button. The lessons are represented by a clickable thumbnail. To view an example of what we’ll be building, check it out here. The HTML: the Structure <section class="clearfix" id="lessonBuilder"> <span id="lessonsTabTarget"><a href="#">Show Lessons</a></span> <nav id="lessonsTab" style="display: none;"> <h1>Lessons</h1> <ul class="clearfix"> <li class="tab"><a href="#"><img src="thumbnail.jpg" /></a></li> <li class="tab"><a href="#"><img src="thumbnail.jpg" /></a></li> <li class="tab"><a href="#"><img src="thumbnail.jpg" /></a></li> <li class="tab"><a href="#"><img src="thumbnail.jpg" /></a></li> </ul> </nav> </section> If you’re unfamiliar with HTML5, you’ll see I’ve used a few tags that will be new to you. The section is used to describe sections of your site, and the nav tag is used to contain navigation elements. The HTML5 tags help to reduce “div-itis”; for example, where you may have <div id="section"></div> and <div id="nav"></div>. Apart from the new tags, it’s basically standard HTML. The unordered list would contain the linked thumbnails. The JavaScript: the Magic var LEARNABLE = {}; /** * Initialises the Lesson Drawer */ LEARNABLE.lessonDrawer = (function () { var init = function () { $("#lessonsTab").hide(); $('#lessonsTabTarget').toggle(function() { $(this).addClass("shown").children('a').html("Hide Lesson Navigator"); $("nav#lessonsTab").show("slow"); return false; }, function() { $("nav#lessonsTab").hide("slow"); $(this).removeClass("shown").children('a').html("Show Lesson Navigator"); return false; }); }; // Public API return { init: init }; })(); $(document).ready(function() { LEARNABLE.lessonDrawer.init(); }); The JavaScript is where it becomes interesting. I’m going to proceed through this step by step, building it the way I would write it while explaining along the way. var LEARNABLE = {}; This creates an object that will contain the functions for your page. We’ve named it LEARNABLE, as it “namespaces” your functions. This form of writing JavaScript is called the module pattern. It’s a great way to structure your JavaScript for a number of reasons: - It reduces the number of global variables, as they are evil. - You can easily have lots of functions working together without affecting other scripts you may have running. - It’s relatively straightforward to maintain and work on. - Other developers involved in the project will be able to see what’s going on easily. var LEARNABLE = {}; /** * Initialises the Lesson Drawer */ LEARNABLE.lessonDrawer = (function () { var init = function () { ... }; // Public API return { init: init }; })(); Now we create our functions. I’ve named it lessonDrawer, and as it’s a part of the LEARNABLE codebase, it becomes LEARNABLE.lessonDrawer. LEARNABLE.lessonDrawer is a function, so it is written as = (function (){, then the code, and is closed with })();. Here are the outside bits of the function: LEARNABLE.lessonDrawer = (function () { ... })(); Count the parentheses, and you’ll see that there’s an extra set of () at the end. This means it is self-executing; when your browser has downloaded this script, it will run it, allowing it to be accessed by any other JavaScript function in your script. Well, sort of. var init = function () { ... }; // Public API return { init: init }; This little bit of trickery means that within the lessonDrawer function there are further functions, in this case called init. The tricky part is that at the end of the lessonDrawer function, it will return to your script a way to gain access to the init function. You may ask, what’s the big deal? Let’s say we changed it a little: var LEARNABLE = {}; /** * Initialises the Lesson Drawer */ LEARNABLE.lessonDrawer = (function () { var init = function () { ... }; var otherThing = function () { ... }; // Public API return { init: init }; })(); Because we’ve specifically said that we only want the init function available, no function outside of lessonDrawer can touch the function named otherThing. It’s safe inside its parent function. You can’t accidentally run it and, more importantly, when you give it to other developers, they can only use it the way you’ve specified. Now to the insides of the init function: $("#lessonsTab").hide(); First, we hide the #lessonsTab, which is our nav container. We do that in this function so that JavaScript-less users can still see the lesson drawer: $('#lessonsTabTarget').toggle(function() { .... }, function() { .... }); The jQuery Toggle method displays or hides elements that it’s told about. The first half between the $('#lessonsTabTarget').toggle(function() { and }); means that when it’s clicked, it will show the lesson drawer. Its counterpart, between the function() { and closing });, will hide the lesson drawer if it’s open: $(this).addClass("shown").children('a').html("Hide Lesson Navigator"); $("nav#lessonsTab").show("slow"); return false; This is the code for showing the lesson drawer. I’ll now explain it line by line for you: $(this).addClass("shown").children('a').html("Hide Lesson Navigator"); $(this) means whatever its parent is talking about (in this case, it’s the $('#lessonsTabTarget'). I’ve been assuming you know what $('#lessonsTabTarget') means, but for those who’ve been playing at home, it asks jQuery (represented by the $) for any elements that have an ID of lessonsTabTarget. We add a class called “ shown" to $(this), and then look through its children for an anchor. Looking back at the HTML structure we’re using, this is <span id="lessonsTabTarget"><a href="#">Show Lessons</a></span>, and on the child anchor we change the text (or its HTML) to the next text (“Hide Lesson Navigator”) as an instruction to the user that if they click the button, they will hide it). $("nav#lessonsTab").show("slow"); Now we tell it to find the nav#lessonsTab and make it appear slowly. The jQuery Show method accepts a few arguments, the first being how long you want it to take to show an element. Instead of "slow", you can use "fast" or the number of milliseconds, where 1,000 means one second (as this is typed as an integer, no quotation marks are necessary, unlike "fast" and "slow"). return false; We return false to stop the browser from following the link. (As it is, it doesn’t go anywhere, but the <a href="#" would make the page jump to the top without returning false). To summarize: - Set up an unobstructive JavaScript function any time the page contains a #lessonsTabTargetelement. - Add a class (telling the CSS that it’s “ shown“). - Change the button text. - Open the lesson tab drawer. - Stop the page from following the link. The second half is exactly the opposite! It hides the lesson drawer, removes the “ shown” class name, and changes the text back. It also stops the browser from following the link. On a side note, the return false always needs to be the last thing in your function. Lastly, we need to run the code. Our final task is to tell the document that when it’s downloaded all its resources (JavaScript and CSS, as well as images), or when it’s ready, to run the init() function. To access the init() function, you have to use its full name: LEARNABLE.lessonDrawer.init();. $(document).ready(function() { LEARNABLE.lessonDrawer.init(); }); The CSS: the Polish Adding the CSS is the last bit needed to make this a really great component. /* HTML5 tags */ header, section, footer, aside, nav, article, figure { display: block; } #lessonBuilder { min-height: 200px; width: 940px; margin: 0 auto; position: relative; } nav#lessonsTab { background-color: #26414A; width: 940px !important; margin: 0 auto; opacity: 1 !important; padding: 30px 0; z-index: 1; display: none; } nav#lessonsTab h1 { color: white; font-size: 18px; margin: 0 0 0 45px; } nav#lessonsTab ul { list-style: none; padding: 20px 0 0 45px; margin: 0; } nav#lessonsTab ul li { float: left; margin: 0 15px 40px 0; padding: 4px; height: 70px; } nav#lessonsTab ul li:hover { background-color: #C9EFFB; } nav#lessonsTab ul li a { width: 100px; display: block; text-decoration: none; } nav#lessonsTab ul li a img { border: none; } #lessonsTabTarget { border-top: 2px solid #3F6D7B; width: 940px; display: block; z-index: 2; margin-top: -2px; text-decoration: none; } #lessonsTabTarget a { background: #283D44 url('lessonnav.png') top left repeat-x; display: block; padding: 7px 20px; position: absolute; right: 0; top: 0; color: white; width: 170px; text-align: center; -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; font-weight: bold; font-size: 15px; text-decoration: none; text-shadow: 0 1px 1px #333; } #lessonsTabTarget.shown a, #lessonsTabTarget a:hover { background: #283D44 url('lessonnav.png') 0 -35px repeat-x; } /* */ .clearfix:after { clear: both; content: ' '; display: block; font-size: 0; line-height: 0; visibility: hidden; width: 0; height: 0; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } In Conclusion This nice modular component is a real-world example of effectively using JavaScript (in this case, jQuery), HTML (with some HTML5 stuff), and CSS together. As I mentioned, it’s in use in Learnable, the place where you can take or create a course online on any subject. If you want to read more from Mark, subscribe to our weekly web design newsletter, The SitePoint Design View. I hope you enjoyed (and understood) it. If you have questions, please feel free to ask via the comments below. - BrenFM - notnuts - thompsonay - Stephen Hill - Stormrider - Aaron - Ronny
https://www.sitepoint.com/drawing-from-our-learning-how-to-build-a-lesson-drawer-in-jquery-html-and-css/
CC-MAIN-2017-04
refinedweb
1,663
64.2
A Little Extra OOP Working with particle systems requires that you delve a little deeper into the wonderful world of OOP (Object-Oriented Programming). There are a few new concepts (and some you’ve already seen) that will take you a long way when working with particle systems: encapsulation, inheritance, access modifiers, polymorphism, getters and setters, static properties and methods, static constants, and throwing errors. Encapsulation Encapsulation involves exposing only what is necessary in order to use a class. You can think of it as the dials on your car radio. You don’t need to understand electronics to turn on your car radio. The circuitry is behind the scenes and the same is true about your code. You can have very complex code structures hidden using encapsulation and reveal only the bare minimum of what your user needs to interact with. This has been one of the cornerstones of PV3D and you’ll find many complex code structures beneath the sub-layer of PV3D’s commonly used classes. Inheritance Key to many applications in PV3D is the concept of inheritance. You can recognize when inheritance is in play by the “extends” keyword. The class you extend will therefore inherit all the properties and methods of the class it extends. So in the simple starter code below the new “ClassExtends” class will inherit from the Sprite class all of its methods and properties. package { import flash.display.Sprite; public class ClassExtends extends Sprite { public function ClassExtends() { } } } Inheritance saves you tons of space and labor by allowing you to write reusable code, and you can attach that code to other classes, thus extending their functionality very easily. Polymorphism It’s often joked that polymorphism is a word that will impress friends at parties, most likely it will get them going the other way. Polymorphism is the concept that an object that inherits from a class can be used in place of an instance from that class. So to cut through all the formalism, it’s all about data types. If I’ve extended a class by the Movie class then that class can be treated as the Movie datatype. Think of it as the king’s son. If the king is allowed into the thrown room, so is his son, because in a sense he is an extended version of the king. There’s much more to polymorphism of course (or it wouldn’t have such a big name), but this is enough to get you through particles. Access Modifiers You’ve already dealt with access modifiers. They give you the ability to control your encapsulation, exposing and restricting various code elements in the sub-layers of your program, defining what properties and methods are exposed for use behind the scenes. As discussed in a previous chapter access modifiers use the keywords: public (everyone), private (within your class), protected (available to descended or sub-classes), internal (same package where defined). Getters and Setters If you open up the PV3D’s DisplayObject3D class you’ll find tons of getter and setter methods and if you’ve never seen this before it may seem a little strange, but it has its roots in the “best practice” of keeping all your class properties private. But you can still access those properties through pubic methods (so you protect the private property but expose it using public methods). And since this approach is used so much special methods “get” and “set” have been created just for the process of getting and setting data. Get allows you to get the private property, and set allows you to change that private property. If you only have a get method and not set method the property is read-only…you can’t change it. In the code snippet below taken from the DisplayObject3D class you get and set the value of X rotation. The first step is to set your “_rotationX” property to private. Note: the underscore in front of the property “_rotationX” is just a convention, which indicates that the property is private. So to illustrate this principle, in the statement below the “_rotationX” property is set to private. private var _rotationX :Number; By using the get and set methods you can access the “_rotationX” property as shown: public function get rotationX():Number { if( this._rotationDirty ) updateRotation(); return Papervision3D.useDEGREES ? this._rotationX * toDEGREES : this._rotationX; } public function set rotationX( rot:Number ):void { this._rotationX = Papervision3D.useDEGREES ? rot * toRADIANS : rot; this._transformDirty = true; } Now, in your main program, all you need to do is reference rotationX to get or set your private property. For example, if want to get or set the x rotation of a cylinder use the code below: get method: cylinder.rotationX set method: cylinder.rotationX = 45; You’ll use getter/setter methods as you add various physical properties to your particles. Static Properties and Methods Static properties and methods are attached to a class, as opposed to the instance of a class. A good example of this is aligning an object to the center of the stage. You do this all the time and it would be handy to have some reusable code that does this for you automatically. Using static properties and methods allows you to do this, and you won’t have to create an instance of this class every time you need it, but you will access it directly. package utils { //Visual objects (top level objects) need to be imported. import flash.display.DisplayObject; public class Utils { public static var centerMyObject:String=”Center Object!”; public function Utils() { } //Because of polymorphism you can pass in any object that inherits from the Display Object class public static functioncenterObject1(myObject:DisplayObject):void{ myObject.x=myObject.stage.stageWidth/2-myObject.width/2; myObject.y=myObject.stage.stageHeight/2-myObject.height/2; } public static function centerObject2(myObject:DisplayObject):void{ myObject.x=myObject.stage.stageWidth/2 myObject.y=myObject.stage.stageHeight/2 } public static function centerObject3(myObject1:DisplayObject,myObject2:DisplayObject):void{ myObject2.x=-myObject1.width/2; myObject2.y=-myObject1.height/2; } }} Another important category of static classes commonly used in PV3D is the Tweener class (such as TweenLite or Caurina). Typically, an object needs to be tweened in a certain way, which makes this approach ideal. Just toss your object into a static tween method and away you go. Tweeners are handled in more detail in a later chapter. Static Constants A static constant is like a static variable, but it never changes. Just open up the ObjectDisplay3D class and you’ll see tons of them. Static constants are typically used with events and have the following form. * tells Mesh3D’s render() method to sort by measuring from the center of a triangle*/ public static const MESH_SORT_CENTER:uint = 1; The convention is to use all caps when creating static constants and the separation of words with underscores. This is what Flash does with its static constants. Throwing Errors (Try/Catch) Why in the heck would you want to throw or create an error…aren’t there enough of them? When Flash has an error it doesn’t always know what to do with that error (or provides vague information). Throwing errors (and catching them) gives you the ability to take control of the process, directing Flash on what to do for certain types of errors or providing more details to the user about that error. The example below checks to see if a video is available; if it is not available an error is thrown if(!video){ throw new Error(“No Video Available”) } It’s important to understand that when Flash encounters a throw statement that no more code can be run in the routine (its current script is terminated). It works somewhat like a return statement in a loop, but there’s more. When an error is thrown, Flash stops the current process and looks for some code that can catch what is being thrown. To catch that thrown error you can use a try/catch block as shown below: try { //statements } catch(myError:Error) { //statements } When an error is thrown, Flash looks to see if it was thrown within a try/catch block, if it was, it goes to the next position in the stack and executes its catch statement. The try/catch block gives you the ability to do something when your error occurs as opposed to stopping your code, which could potentially wreck your program. Now that you have a little more OOP under your belt, you can now proceed to build advanced particle systems.
http://professionalpapervision.wordpress.com/2009/04/16/
CC-MAIN-2014-42
refinedweb
1,421
52.39
This action might not be possible to undo. Are you sure you want to continue? ) This is an online version of the first edition of the book Programming in Lua by Roberto Ierusalimschy Lua.org, December 2003 ISBN 85-903798-1-7 The book is a detailed and authoritative introduction to all aspects of Lua programming, by Lua's chief architect. The first edition was aimed at Lua 5.0 and remains largely relevant. If you find this online version useful, please consider buying a copy of the second edition, which updates the text to Lua 5.1 and brings substantial new material. This helps to support the Lua project. For the official definition of the Lua language, see the reference manual. Copyright © 2003-2004 Roberto Ierusalimschy. All rights reserved. This online book is for personal use only. It cannot be copied to other web sites or further distributed in any form. Contents Part I · The Language • 1 - Getting Started • 1.1 - Chunks • 1.2 - Global Variables • 1.3 - Some Lexical Conventions • 1.4 - The Stand-Alone Interpreter • 2 - Types and Values • 2.1 - Nil • 2.2 - Booleans • 2.3 - Numbers • 2.4 - Strings • 2.5 - Tables • 2.6 - Functions • 2.7 - Userdata and Threads • 3 - Expressions • 3.1 - Arithmetic Operators • 3.2 - Relational Operators • 3.3 - Logical Operators • 3.4 - Concatenation • 3.5 - Precedence • 3.6 - Table Constructors • 4 - Statements • 4.1 - Assignment • 4.2 - Local Variables and Blocks • 4.3 - Control Structures • 4.3.1 - if then else • 4.3.2 - while • 4.3.3 - repeat • 4.3.4 - Numeric for • 4.3.5 - Generic for • 4.4 - break and return • 5 - Functions • 5.1 - Multiple Results • 5.2 - Variable Number of Arguments • 5.3 - Named Arguments • 6 - More about Functions • 6.1 - Closures • 6.2 - Non-Global Functions • 6.3 - Proper Tail Calls • 7 - Iterators and the Generic for • 7.1 - Iterators and Closures • 7.2 - The Semantics of the Generic for • 7.3 - Stateless Iterators • 7.4 - Iterators with Complex State • 7.5 - True Iterators • 8 - Compilation, Execution, and Errors • 8.1 - The require Function • 8.2 - C Packages • 8.3 - Errors • 8.4 - Error Handling and Exceptions • 8.5 - Error Messages and Tracebacks • 9 - Coroutines • 9.1 - Coroutine Basics • 9.2 - Pipes and Filters • 9.3 - Coroutines as Iterators • 9.4 - Non-Preemptive Multithreading • 10 - Complete Examples • 10.1 - Data Description • 10.2 - Markov Chain Algorithm • • Part II · Tables and Objects • 11 - Data Structures • 11.1 - Arrays • 11.2 - Matrices and Multi-Dimensional Arrays • 11.3 - Linked Lists • 11.4 - Queues and Double Queues • 11.5 - Sets and Bags • 11.6 - String Buffers • 12 - Data Files and Persistence • 12.1 - Serialization • 12.1.1 - Saving Tables without Cycles • 12.1.2 - Saving Tables with Cycles • 13 - Metatables and Metamethods • 13.1 - Arithmetic Metamethods • 13.2 - Relational Metamethods • 13.3 - Library-Defined Metamethods • 13.4 - Table-Access Metamethods • 13.4.1 - The __index Metamethod • 13.4.2 - The __newindex Metamethod • 13.4.3 - Tables with Default Values • 13.4.4 - Tracking Table Accesses • 13.4.5 - Read-Only Tables • 14 - The Environment • 14.1 - Accessing Global Variables with Dynamic Names • 14.2 - Declaring Global Variables • 14.3 - Non-Global Environments • 15 - Packages • 15.1 - The Basic Approach • 15.2 - Privacy • 15.3 - Packages and Files • 15.4 - Using the Global Table • 15.5 - Other Facilities • 16 - Object-Oriented Programming • 16.1 - Classes • 16.2 - Inheritance • 16.3 - Multiple Inheritance • 16.4 - Privacy • 16.5 - The Single-Method Approach • 17 - Weak Tables • 17.1 - Memoize Functions • 17.2 - Object Attributes • 17.3 - Revisiting Tables with Default Values • Part III · The Standard Libraries • 18 - The Mathematical Library • 19 - The Table Library • 19.1 - Array Size • 19.2 - Insert and Remove • 19.3 - Sort • 20 - The String Library • 20.1 - Pattern-Matching Functions • 20.2 - Patterns • 20.3 - Captures • 20.4 - Tricks of the Trade • 21 - The I/O Library • 21.1 - The Simple I/O Model • 21.2 - The Complete I/O Model • 21.2.1 - A Small Performance Trick • 21.2.2 - Binary Files • 21.3 - Other Operations on Files • 22 - The Operating System Library • 22.1 - Date and Time • 22.2 - Other System Calls • 23 - The Debug Library • 23.1 - Introspective Facilities • 23.1.1 - Accessing Local Variables • 23.1.2 - Accessing Upvalues • 23.2 - Hooks • 23.3 - Profiles • Part IV · The C API • 24 - An Overview of the C API • 24.1 - A First Example • 24.2 - The Stack • 24.2.1 - Pushing Elements • 24.2.2 - Querying Elements • 24.2.3 - Other Stack Operations • 24.3 - Error Handling with the C API • 24.3.1 - Error Handling in Application Code • 24.3.2 - Error Handling in Library Code • 25 - Extending your Application • 25.1 - Table Manipulation • 25.2 - Calling Lua Functions • 25.3 - A Generic Call Function • 26 - Calling C from Lua • 26.1 - C Functions • 26.2 - C Libraries • 27 - Techniques for Writing C Functions • 27.1 - Array Manipulation • 27.2 - String Manipulation • 27.3 - Storing State in C Functions • 27.3.1 - The Registry • 27.3.2 - References • 27.3.3 - Upvalues • 28 - User-Defined Types in C • 28.1 - Userdata • 28.2 - Metatables • 28.3 - Object-Oriented Access • 28.4 - Array Access • 28.5 - Light Userdata • 29 - Managing Resources • 29.1 - A Directory Iterator • 29.2 - An XML Parser.1 - Chunks Each-D in Unix, ctrl-Z in DOS/Windows), or call the exit function, will run the chunk in a, then the one in b, which will print the expected 1. (The -l option actually calls require, which looks for the files in a specific path. So, the previous example will not work if this path does not include the current directory. We will discuss the require function in more details in Section 8.1.) You may use the -i option to instruct Lua to start an interactive session after running the given chunks. A command line like prompt> lua -i -la -lb will Then, in interactive mode, you can type > dofile("lib1.lua") > n = norm(3.4, 1.0) > print(twice(n)) -- load your library -->. 1.2 - Global Variables Global variables do not need declarations. You simply assign a value to a global variable to create it. It is not an error to access a non-initialized variable; you just get the special value nil as the result: print(b) b = 10 print(b) --> nil --> 10 Usually you do not need to delete global variables; if your variable is going to have a short life, you should use a local variable. But, if you need to delete a global variable, just assign nil to it: b = nil print(b) --> nil After that, it is as if the variable had never been used. In other words, a global variable is existent if (and only if) it has a non-nil value. 1.3 - Some Lexical Conventions Identifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit; for instance i j i10 aSomewhatLongName _ij _INPUT You end in repeat while break false local return do for nil then else function not true elseif if or until Lua is case-sensitive: and is a reserved word, but And and AND are print is outside comments. In this case, the last line becomes an independent comment, as it starts with --. 1.4 - The Stand-Alone Interpreter The stand-alone interpreter (also called lua.c due to its source file, or simply lua due to its executable) is a small program that allows the direct use of Lua. This section presents its main options. When the interpreter loads a file, it ignores its first line if that line starts with a number sign (`#´). That feature allows the use of Lua as a script interpreter in Unix systems. If you start your program with something like #!/usr/local/bin/lua (assuming that the stand-alone interpreter is located at /usr/local/bin), or #!/usr/bin/env lua then you can call the program directly, without explicitly calling the Lua interpreter. The usage of lua is lua [options] [script [args]] Everything is optional. As we have seen already, when we call lua without arguments the interpreter enters in interactive mode. The -e option allows us to enter code directly into the command line. For instance, prompt> lua -e "print(math.sin(12))" --> -0.53657291800043 (Unix needs the double quotes to stop the shell from interpreting the parentheses.) As we previously saw, -l loads a file and -i enters interactive mode after running the other arguments. So, for instance, the call prompt> lua -i -l a.lua -e "x = 10" will load the file a.lua, then execute the assignment x = 10, and finally present a prompt for interaction. Whenever the global variable _PROMPT is defined, lua uses its value as the prompt when interacting. So, you can change the prompt with a call like this: prompt> lua -i -e "_PROMPT=' lua> '" lua> We are assuming that "prompt" is the system's prompt. In the example, the outer quotes stop the shell from interpreting the inner quotes, which are interpreted by Lua. More exactly, Lua receives the following command to run: _PROMPT=' lua> ' which assigns the string " lua> " to the global variable _PROMPT. Before it starts running arguments, lua looks for an environment variable called LUA_INIT. If there is such a variable and its content is @filename, then lua loads the given file. If LUA_INIT is defined but does not start with `@´, then lua assumes that it contains Lua code and runs it. This variable gives you great power when configuring the stand-alone interpreter, because you have the full power of Lua in the configuration. You can pre-load packages, change the prompt and the path, define your own functions, rename or delete functions, and so on. A main script can retrieve its arguments in the global variable arg. In a call like prompt> lua script a b c lua creates the table arg with all the command-line arguments, before running the script. The script name goes into index 0; its first argument (a in the example), goes to index 1, and so on. Eventual options go to negative indices, as they appear before the script. For instance, in the call prompt> lua -e "sin=math.sin" script a b lua collects the arguments as follows: arg[-3] = "lua" arg[-2] = "-e" arg[-1] = "sin=math.sin" arg[0] = "script" arg[1] = "a" arg[2] = "b" More often than not, the script only uses the positive indices (arg[1] and arg[2], in the example). 2 - Types and Values Lua")) print(type(10.4*3)) print(type(print)) print(type(type)) print(type(true)) print(type(nil)) print(type(type(X))) --> --> --> --> --> --> --> string number function function boolean nil string The last example will result in "string" no matter the value of X, because the result of type is always a string. Variables have no predefined types; any variable may contain values of any type: print(type(a)) a = 10 print(type(a)) a = "a string!!" print(type(a)) a = print a(type(a)) --> nil --> number --> string -- yes, this is valid! --> function (`a' is not initialized) Notice. 2.1 -. 2.2 - Booleans The. 2.3 - Numbers 2.4 - Strings Strings have the usual meaning: a sequence of characters. Lua is eight-bit clean and so strings may contain characters with any numeric value, including embedded zeros. That means that you can store any binary data into a string. Strings in Lua are immutable values. You cannot change a character inside a string, as you may in C; instead, you create a new string with the desired modifications, as in the next example: a = "one string" b = string.gsub(a, "one", "another") print(a) --> one string print(b) --> another string -- change string parts: \a bell \b back space \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \\ backslash \" double quote \' single quote \[ left square bracket \] right square bracket") print(10 .. "" == "10") --> true --> true Such conversions are always valid. 2.5 - Tables A When Notice print(a.x) print(a.y) -- same as a["x"] = 10 -- same as print(a["x"]) -- print(a[x]) print(a.x) print(a.y) ----put 10 in field "y" value of field "y" value of field "x" (undefined) value of field "y" --> 10 --> nil --> 10 To represent a conventional array, you simply use a table with integer keys. There is no way to declare its size; you just initialize the elements you need: -- read 10 lines storing them in a table a = {} for i=1,10 do a[i] = io.read() end When The You can introduce subtle bugs in your program if you do not pay attention to this point. 2.6 - Functions. 2.7 - Userdata and Threads The. 3 - Expressions Expressions denote values. Expressions in Lua include the numeric constants and string literals, variables, unary and binary operations, and function calls. Expressions can be also the unconventional function definitions and table constructors. 3.1 - Arithmetic Operators Lua supports the usual arithmetic operators: the binary `+´ (addition), `-´ . 3.2 - Relational Operators Lua provides the following relational operators: < > <= >= == ~= you have that a==c but". 3.3 - Logical Operators) print(nil and 13) print(false and 13) print(4 or 5) --> --> --> --> 5 nil false 4 print(false or 5) --> 5 Both and and or use short-cut evaluation, that is, they evaluate their second operand only when necessary. A useful Lua idiom is x = x or v, which is equivalent to if not x then x = v end i.e., it sets x to a default value v when x is not set (provided that x is not set to false). Another useful idiom is (a and b) or c (or simply a and b or c, because and has a higher precedence than or), which is equivalent to the C expression a ? b : c provided that b is not false. For instance, we can select the maximum of two numbers x and y with a statement like max = (x > y) and x or y When x > y, the first expression of the and is true, so the and results in its second expression (x) (which is also true, because it is a number), and then the or expression results in the value of its first expression, x. When x > y is false, the and expression is false and so the or results in its second expression, y. The operator not always returns true or false: print(not print(not print(not print(not nil) false) 0) not nil) --> --> --> --> true true false false 3.4 - Concatenation Lua denotes the string concatenation operator by ".." (two dots). If any of its operands is a number, Lua converts that number to a string. print("Hello " .. "World") print(0 .. 1) --> Hello World --> 01 Remember that strings in Lua are immutable values. The concatenation operator always creates a new string, without any modification to its operands: a = "Hello" print(a .. " World") print(a) --> Hello World --> Hello 3.5 - Precedence Operator precedence in Lua follows the table below, from the higher to the lower priority: ^ not - (unary) * / + - .. < > and or <= >= ~= == All binary operators are left associative, except for `^´ (exponentiation) and `..´ (concatenation), which are right associative. Therefore, the following expressions on the left are equivalent to those looking up in the manual and probably you will have the same doubt when you read the code again. This]) print(a[22]) --> sub --> ---"} 4 - Statements Lua supports an almost conventional set of statements, similar to those in C or Pascal. The conventional statements include assignment, control structures, and procedure calls. Lua also supports some not so conventional statements, such as multiple assignments and local variable declarations. 4*x the variable a gets the value 10 and b gets 2*x. In a multiple assignment, Lua first evaluates all values and only then executes the assignments. Therefore, we can use a multiple assignment to swap two values, as in x, y = y, x a[i], a[j] = a[j], a[i] -- swap `x' for `y' -- swap `a[i]' for `a[j]') a, b = a+1, b+1, b+2 print(a,b) a, b, c = 0 print(a,b,c) --> 0 1 nil -- value of b+2 is ignored --> 1 2 --> 0 nil nil The: a gets the first and b gets the second. 4.2 - Local Variables and Blocks Besides global variables, Lua supports local variables. We create local variables with the local statement: j = 10 local i = 1 -- global variable -- local variable Unlike global variables, local variables have their scope limited to the block where they are declared. A block is the body of a control structure, the body of a function, or a chunk (the file or string with the code where the variable is declared). x = 10 local i = 1 while i<=x do local x = i*2 print(x) i = i + 1 end if i > 20 then local x x = 20 print(x + 2) else -- local to the chunk -- local to the while body --> 2, 4, 6, 8, ... -- local to the "then" body print(x) end print(x) --> 10 --> 10 (the global one) = if a<b then print(a) local a print(a) end print(a,b) 1, 10 --> 1 -- `= nil' is implicit --> nil -- ends the block started at `then' --> 1 10 A common idiom in Lua is local foo = foo This code creates a local variable, foo, and initializes it with the value of the global variable foo. That idiom is useful when the chunk needs to preserve the original value of foo even) 4.3 - Control Structures Lua. 4.3.1 - if then else An if statement tests its condition and executes its then-part or its else-part accordingly. The elsepart is optional. if a<0 then a = 0 end if a<b then return a else return b end if line > MAXLINES then showpage() line = 0 end When you write nested ifs, you can use elseif. It is similar to an else followed by an if, but it avoids the need for multiple ends: if op == "+" then r = a + b elseif op == "-" then r = a - b elseif op == "*" then r = a*b elseif op == "/" then r = a/b else error("invalid operation") end 4.3.2 - while As usual, Lua first tests the while condition; if the condition is false, then the loop ends; otherwise, Lua executes the body of the loop and repeats the process. local i = 1 while a[i] do print(a[i]) i = i + 1 end 4.3.3 - repeat As the name implies, a repeat-until statement repeats its body until its condition is true. The test is done after the body, so the body is always executed at least once. -- print the first non-empty line repeat line = os.read() until line ~= "" print(line) 4.3.4 - Numeric for The for statement has two variants: the numeric for and the generic for. A numeric for has the following syntax: for var=exp1,exp2,exp3 do something end That loop will execute something for each value of var from exp1 to exp2, using exp3 If. 4.3.5 - Generic for The generic for loop allows you to traverse all values returned by an iterator function. We have already seen examples of the generic for: -- print all values of array `a' for i,v in ipairs(a) do print(v) end For each step in that code, i gets an index, while v gets the value associated with that index. A similar example shows how we traverse all keys of a table: -- print all keys of table `t' for k in pairs(t) do print(k) end Despite Of course, we do not need to manually declare the reverse table. We can build it automatically from the original one: revDays = {} for i,v in ipairs(days) do revDays[v] = i end The loop will do the assignment for each element of days, with the variable i getting the index (1, 2, ...) and v the value ("Sunday", "Monday", ...). 4.4 - break and return The Usually, 5 - Functions Functions" dofile 'a.lua' print [[a multi-line message]] f{x=10, y=20} type{} <--> <--> <--> <--> <--> print("Hello World") dofile ('a.lua') print([[a multi-line message]]) f({x=10, y=20}) we will have the following mapping from arguments to parameters: CALL f(3) f(3, 4) f(3, 4, 5) PARAMETERS a=3, b=nil a=3, b This function has 1 as its default argument; that is, the call incCount(), without arguments, increments count by one. When you call incCount(), Lua first initializes n with nil; the or results in its second operand; and as a result Lua assigns a default 1 to n. 5.1 - Multiple Results. These lists appear in four constructions in Lua: multiple assignment, arguments to function calls, table constructors, and return statements. To illustrate all these uses, we will assume the following definitions for the next examples: function foo0 () end function foo1 () return 'a' end function foo2 () return 'a','b' end -- returns no results -- returns 1 result -- returns 2 results In a multiple assignment, a function call as the last (or only) expression produces as many results as needed to match the variables: x,y = foo2() x = foo2() x,y,z = 10,foo2() -- x='a', y='b' -- x='a', 'b' is discarded -- x=10, y='a', z='b' If a function has no results, or not as many results as we need, Lua produces nils: x,y = foo0() x,y = foo1() x,y,z = foo2() -- x=nil, y=nil -- x='a', y=nil -- x='a', y='b', z=nil A function call that is not the last element in the list always produces one result: x,y = foo2(), 20 x,y = foo0(), 20, 30 -- x='a', y=20 -- x='nil', y=20, 30 is discarded When a function call is the last (or the only) argument to another call, all results from the first call go as arguments. We have seen examples of this construction already, with print: print(foo0()) print(foo1()) print(foo2()) print(foo2(), 1) print(foo2() .. "x") --> --> --> --> --> a a a ax b 1 (see below) When the call to foo2 appears inside an expression, Lua adjusts the number of results to one; so, in the last line, only the "a" is used in the concatenation. The print function may receive a variable number of arguments. (In the next section we will see how to write functions with variable number of arguments.) If we write f(g()) and f has a fixed number of arguments, Lua adjusts the number of results of g to the number of parameters of f, as we saw previously. A constructor also collects all results from a call, without any adjustments: a = {foo0()} a = {foo1()} a = {foo2()} -- a = {} (an empty table) -- a = {'a'} --)) print(foo(2)) print(foo(0)) print(foo(3)) --> a --> a b -- (no results) -- (no results) You can force a call to return exactly one result by enclosing it in an extra pair of parentheses: print((foo0())) print((foo1())) print((foo2())) --> nil --> a --> a Beware that a return statement does not need parentheses around the returned value, so any pair of parentheses placed there counts as an extra pair. That is, a statement like return (f()) always returns one single value, no matter how many values f returns. Maybe this is what you want, maybe not. A special function with multiple returns is unpack. It receives an array and returns as results all elements from the array, starting from index 1: print(unpack{10,20,30}) a,b = unpack{10,20,30} --> returns The first time we call it, with a single argument, i gets 1. Then the function returns t[1] followed by all results from unpack(t, 2), which in turn returns t[2] followed by all results from unpack(t, 3), and so on, until the last non-nil element. 5.2 - Variable Number of Arguments Some functions in Lua receive a variable number of arguments. For instance, we have already called print with one, two, and more arguments. Suppose now that we want to redefine print in Lua: Perhaps our system does not have a stdout and so, instead of printing its arguments, print stores them in a global variable, for later use. We can write this new function in Lua as follows: printResult = "" function print (...) for i,v in ipairs(arg) do printResult = printResult .. tostring(v) .. "\t" end printResult = printResult .. "\n" end The three dots (...) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg. Besides those arguments, the arg table function, which selects a specific return from a function: print(string.find("hello hello", " hel")) --> 6 9 print(select(1, string.find("hello hello", " hel"))) --> 6 print(select(2, string.find("hello hello", " hel"))) --> 9 Notice that a call to select has 5.3 - Named Arguments The rename function then has the freedom to check for mandatory arguments, add default values, and the like. Assuming a primitive _Window function that actually creates the new window (and that needs all arguments), we could define Window 6 - More about Functions print, we are actually talking about a variable that holds that function. Like any other variable holding any other value, we can manipulate such variables in many ways. The following example, although a little silly, shows the point: a = {p = print} a.p("Hello World") --> Hello World print = math.sin -- `print' now refers to the sine function a.p(print(1)) --> 0.841470 sin = a.p -- `sin' now refers to the print function sin(10, 20) --> 10 20 Later we will see more useful applications for this facility. If functions are values, are there any expressions that create functions? Yes. In fact, the usual way to write a function in Lua, like function foo (x) return 2*x end is just an instance of what we call syntactic sugar; in other words, it is just a pretty way to write foo = function (x) return 2*x end That is, a function definition is in fact a statement (an assignment, more specifically) that assigns a value of type "function" to a variable. We can see the expression function (x) ... end {name {name {name } = = = = = { "grauna", "arraial", "lua", "derain", IP IP IP IP = = = = "210.26.30.34"}, "210.26.30.23"}, "210.26.23.12"}, With that definition in place, you can plot the sine function with a call like plot(function (x) return math.sin(x*2*math.pi) end) (We need to massage the data a little to put values in the proper range.) When we call plot, its parameter f gets. 6.1 - Closures The interesting point in the example is that the anonymous function given to sort accesses the parameter grades, which is local to the enclosing function sortbygrade. Inside this anonymous function, grades is neither a global variable nor a local variable. We call it an external local variable, or an upvalue. (The term "upvalue" is a little misleading, because grades Now, the anonymous function uses an upvalue, i, to keep its counter. However, by the time we call the anonymous function, i is already out of scope, because the function that created that variable (newCounter) has returned. Nevertheless, Lua handles that situation correctly, using the concept of closure. Simply put, a closure is a function plus all it needs to access its upvalues correctly. If we call newCounter again, it will create a new local variable i, so we will get a new closure, acting over that new variable: c2 = newCounter() print(c2()) --> 1 print(c1()) --> 3 print(c2()) --> 2 So, c1 and c2 are In this example, we assume that Button is a toolkit function that creates new buttons; label is the button label; and action is the callback function to be called when the button is pressed. (It is actually a closure, because it accesses the upvalue digit.) The callback function can be called a long time after digitButton did its task and after the local variable digit went A cleaner way to do that is as follows: do local oldSin = math.sin local k = math.pi/180 math.sin = function (x) return oldSin(x*k) end end Now, What. 6.2 - Non-Global Functions Of This Lua) end end -- buggy When Lua compiles the call fact(n-1), in the function body, the local fact is not yet defined. Therefore, that expression calls a global fact, not the local one. To solve that problem, we must first define the local variable and then define the function: local fact fact = function (n) if n == 0 then return 1 else return n*fact(n-1) end end Now the fact inside the function refers to the local variable. Its value when the function is defined does not matter; by the time the function executes, fact already has the right value. That is the way Lua expands its syntactic sugar for local functions, so you can use it for recursive functions without worrying: local function fact (n) if n == 0 then return 1 else return n*fact(n-1) end end Of course, this trick does not work if you have indirect recursive functions. In such cases, you must use the equivalent of an explicit forward declaration: local f, g function g () ... f() ... end function f () ... g() ... end -- `forward' declarations 6.3 - Proper Tail Calls Another After f calls g, it has nothing else to do. In such situations, the program does not need to return to the calling function when the called function ends. Therefore, after the tail call, the program does not need to keep any information about the calling function in the stack. Some language implementations, such as the Lua interpreter, take advantage of this fact and actually do not use any extra stack space when doing a tail call. We say that those implementations support proper tail calls. Because a proper tail call uses no stack space, there is no limit on the number of "nested" tail calls that a program can make. For instance, we can call the following function with any number as argument; it will never overflow the stack: function foo (n) if n > 0 then return foo(n - 1) end end The problem in that example is that, after calling g, f still has to discard occasional results from g before returning. Similarly, all the following calls fail the criteria: return g(x) + 1 return x or g(x) return (g(x)) -- must do the addition -- must adjust to 1 result -- must adjust to 1 result In Lua, only a call in the format return g(...) is a tail call. However, both g and its arguments can be complex expressions, because Lua evaluates them before the call. For instance, the next call is a tail call: return x[i].foo(x[j] + a*b, i + j) As I said earlier, a tail call is a kind of goto. As such, a quite useful application of proper tail calls in Lua is for programming state machines. Such applications can represent each state by a function; to change state is to go to (or to call) a specific function. As an example, let us consider a simple maze game. The maze has several rooms, each with up to four doors: north, south, east, and west. At each step, the user enters a movement direction. If there is a door in that direction, the user goes to the corresponding room; otherwise, the program prints a warning. The goal is to go from an initial room to a final room. This game is a typical state machine, where the current room is the state. We can implement such maze with one function for each room. We use tail calls to move from one room to another. A small maze with four rooms could look like this: function room1 () local move = io.read() if move == "south" then return room3() elseif move == "east" then return room2() else print("invalid move") return room1() -- stay in the same room end end function room2 () local move = io.read() if move == "south" then return room4() elseif move == "west" then return room1() else print("invalid move") return room2() end end function room3 () local move = io.read() if move == "north" then return room1() elseif move == "east" then return room4() else print("invalid move") return room3() end end function room4 () print("congratulations!") end. 7 - Iterators and the Generic for In this chapter, we cover how to write iterators for the generic for. We start with simple iterators, then we learn how to use all the power of the generic for to write more efficient iterators. 7.1 - Iterators and Closures In this example, list_iter However, it is easier to use the generic for. After all, it was designed for that kind of iteration: t = {10, 20, 30} for element in list_iter(t) do print(element) end The generic for does all the bookkeeping from an iteration loop: It calls the iterator factory; keeps the iterator function internally, so we do not need the iter variable; The call extracts a substring from line between the given positions). Otherwise, the iterator reads a new line and repeats the search. If there are no more lines, it returns nil to signal the end of the iteration. Despite its complexity, the use of allwords is straightforward: for word in allwords() do print(word) end This is a common situation with iterators: They may be difficult to write, but are easy to use. This is not a big problem; more often than not, end users programming in Lua do not define iterators, but only use those provided by the application. 7.2 - The Semantics of the Generic for One where <var-list> is a list of one or more variable names, separated by commas, and <explist> is a list of one or more expressions, also separated by commas. More often than not, the expression list has only one element, a call to an iterator factory. For instance, in the code for k, v in pairs(t) do print(k, v) end the list of variables is k, v; the list of expressions has the single element pairs(t). Often the list of variables has only one variable too, as in for line in io.lines() do io.write(line, '\n') end We is equivalent to the following code: do local _f, _s, _var = explist while true do local var_1, ... , var_n = _f(_s, _var) _var = var_1 if _var == nil then break end block end end. 7.3 - Stateless Iterators The state of the iteration is the table being traversed (the invariant state, which does not change during the loop), plus the current index (the control variable). Both ipairs and the iterator it returns are quite simple; we could write them in Lua as follows: function iter (a, i) i = i + 1 local v = a[i] if v then return i, v end end function ipairs (a) return iter, a, 0 end When Lua calls ipairs(a) in a for loop, it gets three values: the iter function as the iterator, a The call next(t, k), where k is a key of the table t, returns a next key in the table, in an arbitrary order. (It returns also the value associated with that key, as a second return value.) The call next(t, nil) returns a first pair. When there are no more pairs, next returns nil. Some people prefer to use next directly, without calling pairs: for k, v in next, t do ... end Remember that the expression list of the for loop is adjusted to three results, so Lua gets next, t, and nil, exactly what it gets when it calls pairs(t). 7.4 - Iterators with Complex State Frequently, The iterator function. 7.5 - True Iterators The To use such iterator, we must supply the loop body as a function. If we only want to print each word, we simply use print:.) 8 - Compilation, Execution, and Errors Note the use of assert to raise an error if loadfile fails. will be a function that, when invoked, executes i = i + 1: i = 0 f(); print(i) f(); print(i) --> 1 --> 2 The loadstring function Likeua like this: -- file `foo.lua' function foo (x) print(x) end We then run the command f = loadfile("foo.lua") After this command, foo is compiled, but it is not defined yet. To define it, you must run the chunk: f() foo("ok") -- defines `foo' --> ok If you want to do a quick-and-dirty dostring (i.e., to load and run a chunk) you may call the result from loadstring directly: loadstring(s)() However, if there is any syntax error, loadstring will but the second code is much faster, because it is compiled only once, when the chunk is compiled. In the first code, each call to loadstring involves a new compilation. However, the two codes are not completely equivalent, because loadstring does not compile with lexical scoping. To see the difference, let us change the previous examples a little: local i = 0 f = loadstring("i = i + 1") g = function () i = i + 1 end The g function manipulates the local i, as expected, but f manipulates a global i, because loadstring always. 8.1 - The require Functionua then the call require"lili" will try to open the following files: lili lili.lua c:\windows\lili /usr/local/lua/lili/lili.lua The only things that require fixesua In this case, whenever require cannot find another option, it will run this fixed file. (Of course, it only makes sense to have a fixed component as the last component in a path.) Before require runs a chunk, it defines a global variable _REQUIREDNAME containing the virtual name of the file being required. We can use these facilities to extend the functionality of require. In an extreme example, we may set the path to something like "/usr/local/lua/newrequire.lua", so that every call to require runs newrequire.lua, which can then use the value of _REQUIREDNAME to actually load the required file. 8. Usually, Lua does not include any facility that cannot be implemented in ANSI C. However, dynamic linking is different. We can view it as the mother of all other facilities: Once we have it, we can dynamically load any other facility that is not in Lua. Therefore, in this particular case, Lua breaks its compatibility rules function returns. 8.3 - Errors Er") end Such combination of if not ... then error end is so common that Lua has a built-in function just for that job, called assert: print "enter a number:" n = assert(io.read("*number"), "invalid input") The assert function checks whether its first argument is not false and simply returns that argument; if the argument is false (that is, false or nil), assert raises an error. Its second argument, the message, is optional, so that if you do not want to say anything in the error message, you do not have to. Beware, however, that assert is a regular function. As such, Lua always evaluates its arguments before calling the function. Therefore, if you have something like n = io.read() assert(tonumber(n), "invalid input: " .. n .. " is not a number") Lua will always do the concatenation, even when n If you do not want to handle such situations, but still want to play safe, you simply use assert to guard the operation: file = assert(io.open(name, "r")) This is a typical Lua idiom: If io.open fails, assert will raise an error. file = assert(io.open("no-file", "r")) --> stdin:1: no-file: No such file or directory Notice how the error message, which is the second result from io.open, goes as the second argument to assert. 8.4 - Error Handling and Exceptions For Then, you call foo with pcall: if pcall(foo) then -- no errors while running `foo' ... else -- `foo' raised an error: take appropriate actions ... end Of course, you can call pcall with These mechanisms provide all we need to do exception handling in Lua. We throw an exception with error and catch it with pcall. The error message identifies the kind or error. 8.5 - Error Messages and Tracebacks Although you can use a value of any type as an error message, usually error messages are strings describing what went wrong. When there is an internal error (such as an attempt to index a nontable error Then, someone calls your function with a wrong argument: foo({x=1}) Lua points its finger to your function---after all, it was foo that called error---and not to the real culprit, the caller. To correct that, you inform error that()) 9 - Coroutines A coroutine is similar to a thread (in the sense of multithreading): a line of execution, with its own stack, its own local variables, and its own instruction pointer; but sharing global variables and mostly anything else with other coroutines. The main difference between threads and coroutines is that, conceptually (or literally, in a multiprocessor machine), a program with threads runs several threads concurrently. Coroutines, on the other hand, are collaborative: A program with coroutines is, at any given time, running only one of its coroutines and this running coroutine only suspends its execution when it explicitly requests to be suspended. Coroutine is a powerful concept. As such, several of its main uses are complex. Do not worry if you do not understand some of the examples in this chapter on your first reading. You can read the rest of the book and come back here later. But please come back. It will be time well spent. 9.1 - Coroutine Basics Lua The function coroutine.resume (re)starts the execution of a coroutine, changing its state from suspended to running: coroutine.resume(co) --> hi If we check its status, we can see that the coroutine is suspended and therefore can be resumed again: print(coroutine.status(co)) --> suspended From the coroutine's point of view, all activity that happens while it is suspended is happening inside its call to yield. When we resume the coroutine, this call to yield finally returns and the coroutine continues its execution until the next yield or until its end: coroutine.resume(co) coroutine.resume(co) ... coroutine.resume(co) coroutine.resume(co) --> co --> co 2 3 --> co 10 -- prints nothing During the last call to resume, the coroutine body finished the loop and then returned, so the coroutine is dead now. If we try to resume it again, resume returns false plus an error message: print(coroutine.resume(co)) --> false cannot resume dead coroutine Note that resume runs in protected mode. Therefore, if there is any error inside a coroutine, Lua will not show the error message, but instead will return it to the resume call. A call to resume returns, after the true that signals no errors, any arguments passed to the corresponding yield: co = coroutine.create(function (a,b) coroutine.yield(a + b, a - b) end) print(coroutine.resume(co, 20, 10)) --> true 30 10 Symmetrically, yield returns any extra arguments passed to the corresponding resume: co = coroutine.create (function () print("co", coroutine.yield()) end) coroutine.resume(co) coroutine.resume(co, 4, 5) --> co 4 5 Finally,.) 9.2 - Pipes and Filters One() send(x) end end function consumer () while true do local x = receive() io.write(x, "\n") end end -- produce new value -- send to consumer -- receive from producer -- consume new value (In that implementation, both the producer and the consumer run forever. It is an easy task to change them to stop when there is no more data to be handled.) The problem here is how to match send with Of) io.write(x, "\n") end end -- get new value -- consume new value The. 9.3 - Coroutines as Iterators To see it working, we should define an appropriate printResult function and call permgen with With. 9.4 - Non-Preemptive Multithreading As we saw earlier, coroutines are a kind of collaborative multithreading. Each coroutine is equivalent to a thread. A pair yield-resume switches control from one thread to another. However, unlike "real" multithreading, coroutines are non preemptive. While a coroutine is running, it cannot be stopped from the outside. It only suspends execution when it explicitly requests so (through a call to yield). For several applications this is not a problem, quite the opposite. Programming is much easier in the absence of preemption. You do not need to be paranoid about synchronization bugs, because all synchronization among threads is explicit in the program. You only have to ensure that a coroutine only yields when it is outside a critical region. However, with non-preemptive multithreading, whenever any thread calls a blocking operation, the whole program blocks until the operation completes. For most applications, this is an unacceptable behavior, which leads many programmers to disregard coroutines as a real alternative to conventional multithreading. As we will see here, that problem has an interesting (and obvious, with hindsight) solution. Let us assume a typical multithreading situation: We want to download several remote files through HTTP. Of course, to download several remote files, we must know how to download one remote file. In this example, we will use the LuaSocket library, developed by Diego Nehab. To download a file, we must open a connection to its site, send a request to the file, receive the file (in blocks), and close the connection. In Lua, we can write this task as follows. First, we load the LuaSocket library: require "luasocket" Then, we define the host and the file we want to download. In this example, we will download the HTML 3.2 Reference Specification from the World Wide Web Consortium site: host = "" file = "/TR/REC-html32.html" Then, we open a TCP connection to port 80 (the standard port for HTTP connections) of that site: c = assert(socket.connect(host, 80)) The operation returns a connection object, which we use to send the file request: c:send("GET " .. file .. " HTTP/1.0\r\n\r\n") The receive method always returns a string with what it read plus another string with the status of the operation. When the host closes the connection we break the receive loop. Finally, we close the connection: c:close() Now that we know how to download one file, let us return to the problem of downloading several files. The trivial approach is to download one at a time. However, this sequential approach, where we only start reading a file after finishing the previous one, is too slow. When reading a remote file, a program spends most of its time waiting for data to arrive. More specifically, it spends most of its time blocked in the call to receive. So, the program could run much faster if it downloaded all files simultaneously. Then, while a connection has no data available, the program can read from another connection. Clearly, coroutines offer a convenient way to structure those simultaneous downloads. We create a new thread for each download task. When a thread has no data available, it yields control to a simple dispatcher, which invokes another thread. To rewrite the program with coroutines, let us first rewrite the previous download code as a function: function download (host, file) local c = assert(socket.connect(host, 80)) local count = 0 -- counts number of bytes read c:send("GET " .. file .. " HTTP/1.0\r\n\r\n") while true do local s, status = receive(c) count = count + string.len(s) if status == "closed" then break end end c:close() print(file, count) end Because we are not interested in the remote file contents, this function only counts the file size, instead of writing the file to the standard output. (With several threads reading several files, the output would intermix all files.) In this new code, we use an auxiliary function (receive) to receive data from the connection. In the sequential approach, its code would be like this: function receive (connection) return connection:receive(2^10) end For the concurrent implementation, this function must receive data without blocking. Instead, if there is not enough data available, it yields. The new code is like this: function receive (connection) connection:timeout(0) -- do not block local s, status = connection:receive(2^10) if status == "timeout" then coroutine.yield(connection) end return s, status end The call to timeout(0) makes any operation over the connection a non-blocking operation. When the operation status is "timeout", it means that the operation returned without completion. In this case, the thread yields. The non-false argument passed to yield signals to the dispatcher that the thread is still performing its task. (Later we will see another version where the dispatcher needs the timed-out connection.) Notice that, even in case of a timeout, the connection returns what it read until the timeout, so receive always returns s to its caller. The next function ensures that each download runs in an individual thread: threads = {} -- list of all live threads function get (host, file) -- create coroutine local co = coroutine.create(function () download(host, file) end) -- insert it in the list table.insert(threads, co) end The table threads keeps a list of all live threads, for the dispatcher. The dispatcher is simple. It is mainly a loop that goes through all threads, calling one by one. It must also remove from the list the threads that finish their tasks. It stops the loop when there are no more threads to run: function dispatcher () while true do local n = table.getn(threads) if n == 0 then break end -- no more threads to run for i=1,n do local status, res = coroutine.resume(threads[i]) if not res then -- thread finished its task? table.remove(threads, i) break end end end end Finally, the main program creates the threads it needs and calls the dispatcher. For instance, to download four documents from the W3C site, the main program could be like this: host = "" get(host, "/TR/html401/html40.txt") get(host,"/TR/2002/REC-xhtml1-20020801/xhtml1.pdf") get(host,"/TR/REC-html32.html") get(host, "/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt") dispatcher() -- main loop My machine takes six seconds to download those four files using coroutines. With the sequential implementation, it takes more than twice that time (15 seconds). Despite the speedup, this last implementation is far from optimal. Everything goes fine while at least one thread has something to read. However, when no thread has data to read, the dispatcher does a busy wait, going from thread to thread only to check that they still have no data. As a result, this coroutine implementation uses almost 30 times more CPU than the sequential solution. To avoid this behavior, we can use the select function from LuaSocket. It allows a program to block while waiting for a status change in a group of sockets. The changes in our implementation are small. We only have to change the dispatcher. The new version is like this: function dispatcher () while true do local n = table.getn(threads) if n == 0 then break end -- no more threads to run local connections = {} for i=1,n do local status, res = coroutine.resume(threads[i]) if not res then -- thread finished its task? table.remove(threads, i) break else -- timeout table.insert(connections, res) end end if table.getn(connections) == n then socket.select(connections) end end end Along the inner loop, this new dispatcher collects the timed-out connections in table connections. Remember that receive passes such connections to yield; thus resume returns them. When all connections time out, the dispatcher calls select to wait for any of those connections to change status. This final implementation runs as fast as the first implementation with coroutines. Moreover, as it does no busy waits, it uses just a little more CPU than the sequential implementation. 10 - Complete Examples To). 10.1 - Data Description The Lua site keeps a database containing a sample of projects around the world that use Lua. We represent each entry in the database by a constructor in an auto-documented way, as the following example shows: entry{ title = "Tecgraf", org = "Computer Graphics Technology Group, PUC-Rio", url = "", contact = "Waldemar Celes", description = [[ TeCGraf is the result of a partnership between PUC-Rio, the Pontifical Catholic University of Rio de Janeiro, and <A HREF="") end If o.title Finally,() We use the string NOWORD ("\n") to initialize the prefix words and to mark the end of the text. For instance, for the following text the more we try the more we do It first checks whether that prefix already has a list; if not, it creates a new one with the new value. Otherwise, it uses the predefined function table.insert to reinitial 11 - Data Structures. 11.1 - Arrays We any attempt to access a field outside the range 1-1000 will return nil, instead of zero. You can start an array at index 0, 1, or any other value: -- creates an array with indices from -5 to 5 a = {} for i=-5, 5 do a[i] = 0 end However,). 11.2 - Matrices and Multi-Dimensional Arrays There Because in the previous example to for j=1,i do. 11.3 - Linked Lists Because tables are dynamic entities, it is easy to implement linked lists in Lua. Each node is represented by a table and links are simply table fields that contain references to other tables. For instance, to implement a basic list, where each node has two fields, next and value, we need a variable to be the list root: list = nil To insert an element at the beginning of the list, with a value v, we do list = {next = list, value = v} To traverse the list, we write: local l = list while l do print(l.value) l = l.next end Other kinds of lists, such as double-linked lists or circular lists, are also implemented easily. However, you seldom need those structures in Lua, because usually there is a simpler way to represent your data without using lists. For instance, we can represent a stack with an (unbounded) array, with a field n pointing to the top. 11.4 - Queues and Double Queues To avoid polluting the global space, we will define all list operations inside a table, properly called List. Therefore, we rewrite our last example like this: List = {} function List.new () return {first = 0, last = -1} end Now,. 11.5 - Sets and Bags Suppose you want to list all identifiers used in a program source; somehow you need to filter the reserved words out of your listing. Some C programmers could be tempted to represent the set of reserved words as an array of strings, and then to search this array to know whether a given word is in the set. To speed up the search, they could even use a binary tree or a hash table to represent the set. In Lua, an efficient"] = true, ["function"] = true, } ["end"] = true, ["local"] = true, for w in allwords() do if reserved[w] then -- `w' is a reserved word ... (Because while is a reserved word in Lua, we cannot use it as an identifier. Therefore, we cannot write while = 1; instead, we use the ["while"] = 1 notation.) You can have a clearer initialization using an auxiliary function to build the set: function Set (list) local set = {} for _, l in ipairs(list) do set[l] = true end return set end reserved = Set{"while", "end", "function", "local", } 11.6 - String Buffers Suppose you are building a string piecemeal, for instance reading a file line by line. Your typical code would look like this: -- WARNING: bad code ahead!! local buff = "" for line in io.lines() do buff = buff .. line .. "\n" end Despite To get the final contents of the buffer, we just need to concatenate all strings down to the bottom. The table.concat function iterator returns each line without the newline.) concat inserts the separator between the strings, but not after the last one, so we have to add the last newline. This last concatenation duplicates the resulting string, which can be quite big. There is no option to make concat insert this extra separator, but we can deceive it, inserting an extra empty string in t: table.insert(t, "") s = table.concat(t, "\n") The extra newline that concat adds before this empty string is at the end of the resulting string, as we wanted. 12 - Data Files and Persistence When in our data file, we b is an entry value, b[1] is the author.) local authors = {} -- a set to collect authors function Entry (b) authors[b[1]] = true end dofile("data") for name in pairs(authors) do print(name) end Notice the event-driven approach in these program fragments: The Entry function acts as a callback function, which is called during the dofile for Now. 12.1 - Serialization Frequently For 12.1.1 - Saving Tables without Cycles Our Despite its simplicity, that function does a reasonable job. It even handles nested tables (that is, tables within other tables), as long as the table structure is a tree (that is, there are no shared subtables and no cycles). A small aesthetic improvement would be to indent occasional nested tables; you can try it as an exercise. (Hint: Add an extra parameter to serialize { ["a"] = ["b"] = ["key"] } version 12, "Lua", = "another \"one\"", We can improve this result by testing for each case whether it needs the square brackets; again, we will leave this improvement as an exercise. 12.1.2 - Saving Tables with Cycles To handle tables with generic topology (i.e., with cycles and shared sub-tables) we need a different approach. Constructors cannot represent such tables, so we will not use them. To represent cycles we need names, so our next function will get as arguments the value to be saved plus its name. Moreover, we must keep track of the names of the tables already saved, to reuse them when we detect a cycle. We will use an extra table for this tracking. This table will have tables as indices and their names as the associated values. We will keep the restriction that the tables we want to save have only strings or numbers as keys. The following function serializes these basic types, returning the result: function basicSerialize (o) if type(o) == "number" then return tostring(o) else -- assume it is a string return string.format("%q", o) end end The next function does the hard work. The saved parameter is the table that keeps track of tables already saved: function save (name, value, saved) saved = saved or {} -- initial value io.write(name, " = ") if type(value) == "number" or type(value) == "string" then io.write(basicSerialize(value), "\n") elseif type(value) == "table" then if saved[value] then -- value already saved? io.write(saved[value], "\n") -- use its previous name else saved[value] = name -- save name for next time io.write("{}\n") -- create a new table for k,v in pairs(value) do -- save its fields local fieldname = string.format("%s[%s]", name, basicSerialize(k)) save(fieldname, v, saved) end[1] = {} a[1][1] = 3 a[1][2] = 4 a[1][3] = 5 a[2] = a["y"] a["x"] a["z"] a = 2 = 1 = a[1] (The actual order of these assignments may vary, as it depends on a table traversal. Nevertheless, the algorithm ensures that any previous node needed in a new definition is already defined.) If we want to save several values with shared" However, if we use the same saved table for each call to save, local t = {} save('a', a, t) save('b', b, t) then the result will share common parts: a = {} a[1] = {} a[1][1] = "one" a[1][2] = "two" a[2] = 3 b = {} b["k"] = a[1] As is usual in Lua, there are several other alternatives. Among them, we can save a value without giving it a global name (instead, the chunk builds a local value and returns it); we can handle functions (by building a table that associates each function to its name) etc. Lua gives you the power; you build the mechanisms. 13 - Metatables and Metamethods Usually, We can use setmetatable to. 13.1 - Arithmetic Metamethods In this section, we will introduce a simple example to explain how to use metatables. Suppose we are using tables to represent sets, with functions to compute the union of two sets, intersection, and the like. As we did with lists, we store these functions inside a table and we define a constructor to create new sets: Set = {} function Set.new (t) local set = {} for _, l in ipairs(t) do set[l] = true end return set end function Set.union (a,b) local res = Set.new{} for k in pairs(a) do res[k] = true end for k in pairs(b) do res[k] = true end return res end function Set.intersection (a,b) local res = Set.new{} for k in pairs(a) do res[k] = b[k] end return res end To help checking our examples, we also define a function to print sets: function Set.tostring (set) local s = "{" local sep = "" for e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}" end function Set.print (s) print(Set.tostring(s)) end Now, we want to make the addition operator (`+´) compute the union of two sets. For that, we will arrange that all tables representing sets share a metatable and this metatable will define how they react to the addition operator. Our first step is to create a regular table that we will use as the metatable for sets. To avoid polluting our namespace, we will store it in the Set table: Set.mt = {} -- metatable for sets The next step is to modify the Set.new function, which creates sets. The new version has only one extra line, which sets mt as the metatable for the tables that it creates: function Set.new (t) -- 2nd version local set = {} setmetatable(set, Set.mt) for _, l in ipairs(t) do set[l] = true end return set end After that, every set we create with Set.new will have that same table as its metatable: s1 = Set.new{10, 20, 30, 50} s2 = Set.new{30, 1} print(getmetatable(s1)) print(getmetatable(s2)) --> table: 00672B60 --> table: 00672B60 Finally, we add to the metatable the so-called metamethod, a field __add that describes how to perform the union: Set.mt.__add = Set.union Whenever Lua tries to add two sets, it will call this function, with the two operands as arguments. With the metamethod in place, we can use the addition operator to do set unions: s3 = s1 + s2 Set.print(s3) --> {1, 10, 20, 30, 50} Similarly, we may use the multiplication operator to perform set intersection: Set.mt.__mul = Set.intersection Set.print((s1 + s2)*s1) --> {10, 20, 30, 50} For each arithmetic operator there is a corresponding field name in a metatable. Besides __add and __mul, there are __sub (for subtraction), __div (for division), __unm (for negation), and __pow (for exponentiation). We may define also the field __concat, to define a behavior for the concatenation operator. When we add two sets, there is no question about what metatable to use. However, we may write an expression that mixes two values with different metatables, for instance like this: s = Set.new{1,2,3} s = s + 8 To choose a metamethod, Lua does the following: (1) If the first value has a metatable with an __add field, Lua uses this value as the metamethod, independently of the second value; (2) otherwise, if the second value has a metatable with an __add field, Lua uses this value as the metamethod; (3) otherwise, Lua raises an error. Therefore, the last example will call Set.union, as will the expressions 10 + s and "hy" + s. Lua does not care about those mixed types, but our implementation does. If we run the s = s + 8 example, the error we get will be inside Set.union: bad argument #1 to `pairs' (table expected, got number) If we want more lucid error messages, we must check the type of the operands explicitly before attempting to perform the operation: function Set.union (a,b) if getmetatable(a) ~= Set.mt or getmetatable(b) ~= Set.mt then error("attempt to `add' a set with a non-set value", 2) end ... -- same as before 13.2 - Relational Metamethods Metatables also allow us to give meaning to the relational operators, through the metamethods __eq (equality), __lt (less than), and __le (less or equal). There are no separate metamethods for the other three relational operators, as Lua translates a ~= b to not (a == b), a > b to b < a, and a >= b to b <= a. (Big parentheses: Until Lua 4.0, all order operators were translated to a single one, by translating a <= b to not (b < a). However, this translation is incorrect when we have a partial order, that is, when not all elements in our type are properly ordered. For instance, floating-point numbers are not totally ordered in most machines, because of the value Not a Number (NaN). According to the IEEE 754 standard, currently adopted by virtually every hardware, NaN represents undefined values, such as the result of 0/0. The standard specifies that any comparison that involves NaN should result in false. That means that NaN <= x is always false, but x < NaN is also false. That implies that the translation from a <= b to not (b < a) is not valid in this case.) In our example with sets, we have a similar problem. An obvious (and useful) meaning for <= in sets is set containment: a <= b means that a is a subset of b. With that meaning, again it is possible that both a <= b and b < a are false; therefore, we need separate implementations for __le (less or equal) and __lt (less than): Set.mt.__le = function (a,b) -- set containment for k in pairs(a) do if not b[k] then return false end end return true end Set.mt.__lt = function (a,b) return a <= b and not (b <= a) end Finally, we can define set equality through set containment: Set.mt.__eq = function (a,b) return a <= b and b <= a end After those definitions, we are now ready to compare sets: s1 = Set.new{2, 4} s2 = Set.new{4, 10, 2} print(s1 <= s2) --> print(s1 < s2) --> print(s1 >= s1) --> print(s1 > s1) --> print(s1 == s2 * s1) --> true true true false true Unlike arithmetic metamethods, relational metamethods do not support mixed types. Their behavior for mixed types mimics the common behavior of these operators in Lua. If you try to compare a string with a number for order, Lua raises an error. Similarly, if you try to compare two objects with different metamethods for order, Lua raises an error. An equality comparison never raises an error, but if two objects have different metamethods, the equality operation results in false, without even calling any metamethod. Again, this behavior mimics the common behavior of Lua, which always classifies strings as different from numbers, regardless of their values. Lua calls the equality metamethod only when the two objects being compared share this metamethod. 13.3 - Library-Defined Metamethods print always calls tostring to format its output.) However, when formatting an object, tostring first checks whether the object has a metatable with a __tostring field. If this is the case, tostring calls After that, whenever we call print with a set as its argument, print calls tostring that 13.4 - Table-Access Metamethods. 13.4.1 - The __index Met Now, we define the __index metamethod: Window.mt.__index = function (table, key) return Window.prototype[key] end After that code, we create a new window and query it for an absent field: w = Window.new{x=10, y=20} print(w.width) --> 100 When Lua detects that w does not have the requested field, but has a metatable with an __index field, Lua calls this __index met.prototype Now, when Lua looks for the metatable's __index field,. 13.4.2 - The __newindex Metoriented programming. In the rest of this chapter we see some of these uses. Object-oriented programming has its own chapter. 13.4.3 - Tables with Default Values The default value of any field in a regular table is nil. It is easy to change this default value with metatables: function setDefault (t, d) local mt = {__index = function () return d end} setmetatable(t, mt) end tab = {x=10, y=20} print(tab.x, tab.z) setDefault(tab, 0) print(tab.x, tab.z) --> 10 --> 10 nil 0 Now, whenever we access an absent field in tab, its __index metamethod is called and returns zero, which is the value of d for that metamethod. The setDefault function creates a new metatable for each table that needs a default value. This may be expensive if we have many tables that need default values. However, the metatable has the default value d wired into itself, so the function cannot use a single metatable for all tables. To allow the use of a single metatable for tables with different default values, we can store the default value of each table in the table itself, using an exclusive field. If we are not worried about name clashes, we can use a key like "___" for our exclusive field: local mt = {__index = function (t) return t.___ end} function setDefault (t, d) t.___ = d setmetatable(t, mt) end If we are worried about name clashes, it is easy to ensure the uniqueness of this special key. All we need is to create a new table and use it as the key: local key = {} -- unique key local mt = {__index = function (t) return t[key] end} function setDefault (t, d) t[key] = d setmetatable(t, mt) end An alternative approach to associating each table with its default value is to use a separate table, where the indices are the tables and the values are their default values. However, for the correct implementation of this approach we need a special breed of table, called weak tables, and so we will not use it here; we will return to the subject in Chapter 17. Another alternative is to memoize metatables in order to reuse the same metatable for tables with the same default. However, that needs weak tables too, so that again we will have to wait until Chapter 17. 13.4.4 - Tracking Table Accesses Both __index and __newindex are relevant only when the index does not exist in the table. The only way to catch all accesses to a table is to keep it empty. So, if we want to monitor all accesses to a table, we should create a proxy for the real table. This proxy is an empty table, with proper __index and __newindex metamethods, which track all accesses and redirect them to the original table. Suppose that t is the original table we want to track. We can write something like this: t = {} -- original table (created somewhere) -- keep a private access to original table local _t = t -- create proxy) This code tracks every access to t: > t[2] = 'hello' *update of element 2 to hello > print(t[2]) *access to element 2 hello (Notice that, unfortunately, this scheme does not allow us to traverse tables. The pairs function will operate on the proxy, not on the original table.) If we want to monitor several tables, we do not need a different metatable for each one. Instead, we can somehow associate each proxy to its original table and share a common metatable for all proxies. A simple way to associate proxies to tables is to keep the original table in a proxy's field, as long as we can be sure that this field will not be used for other means. A simple way to ensure that is to create a private key that nobody else can access. Putting these ideas together results in the following code: -- create private index local index = {} -- create metatable local mt = { __index = function (t,k) print("*access to element " .. tostring(k)) return t[index][k] -- access the original table end, __newindex = function (t,k,v) print("*update of element " .. tostring(k) .. " to " .. tostring(v)) t[index][k] = v -- update original table end } function track (t) local proxy = {} proxy[index] = t setmetatable(proxy, mt) return proxy end Now, whenever we want to monitor a table t, all we have to do is t = track(t). 13.4.5 - Read-Only Tables 14 - The Environment Lua. 14.1 - Accessing Global Variables with Dynamic Names Usually, assignment is enough for getting and setting global variables. However, often we need some form of meta-programming, such as when we need to manipulate a global variable whose name is stored in another variable, or somehow computed at run time. To get the value of this variable, many programmers are tempted to write something like loadstring("value = " .. varname)() or value = loadstring("return " .. varname)() If varname is x, for instance, the concatenation will result in "return x" (or "value = x", with the first form), which when run achieves the desired result. However, such codes involve the creation and compilation of a new chunk and lots of extra work. You can accomplish the same effect with the following code, which is more than an order of magnitude more efficient than the previous one: value = _G[varname] Because the environment is a regular table, you can simply index it with the desired key (the variable name). In a similar way, you can assign to a global variable whose name is computed dynamically, writing _G[varname] = value. Beware, however: Some programmers get a little excited with these functions and end up writing code like _G["a"] = _G["var1"], which is just a complicated way to write a = var1. A generalization of the previous problem is to allow fields in a dynamic name, such as "io.read" or "a.b.c.d". We solve this problem with a loop, which starts at _G and evolves field by field: function getfield (f) local v = _G -- start with the table of globals for w in string.gfind(f, "[%w_]+") do v = v[w] end return v end We rely on gfind, from the string library, to iterate over all words in f (where "word" is a sequence of one or more alphanumeric characters and underscores). The corresponding function to set fields is a little more complex. An assignment like a.b.c.d.e = v is exactly equivalent to local temp = a.b.c.d temp.e = v That is, we must retrieve up to the last name; we must handle the last field separately. The new setfield function also creates intermediate tables in a path when they do not exist: function setfield (f, v) local t = _G -- start with the table of globals for w, d in string.gfind(f, "([%w_]+)(.?)") do if d == "." then -- not last field? t[w] = t[w] or {} -- create table if absent t = t[w] -- get the table else -- last field t[w] = v -- do the assignment end end end This new pattern captures the field name in variable w and an optional following dot in variable d. If a field name is not followed by a dot then it is the last name. (We will discuss pattern matching at great length in Chapter 20.) With the previous functions, the call setfield("t.x.y", 10) creates a global table t, another table t.x, and assigns 10 to t.x.y: print(t.x.y) --> 10 print(getfield("t.x.y")) --> 10 14.2 - Declaring Global Variables Global The. 14.3 - Non-Global Environments only Now, when you access the "global" _G, its value is the old environment, wherein you will find the field print. You can populate your new environment using inheritance also: a = 1 local newgt = {} -- create new environment setmetatable(newgt, {__index = _G}) setfenv(1, newgt) -- set it print(a) --> 1 In this code, the new environment inherits both print and a from the old one. Nevertheless, any assignment goes to the new table. There is no danger of changing a really global variable by mistake, although you still can change them through _G: -- continuing previous code a = 10 print(a) print(_G.a) _G.a = 20 print(_G.a) --> 10 -->. 15 - Packages Many. 15.1 - The Basic Approach A This This return is not necessary, because the package is already assigned to a global variable (complex). Nevertheless, we consider a good practice that a package returns itself when it opens. The extra return costs nothing, and allows alternative ways to handle the package. 15.2 - Privacy Sometimes, a package exports all its names; that is, any client of the package can use them. Usually, however, it is useful to have private names in a package, that is, names that only the package itself can use. A convenient way to do that in Lua is to define those private names as local variables. For instance, let us add to our example a private function that checks whether a value is a valid complex number. Our example now looks like this: local P = {} complex = P local function checkComplex (c) if not ((type(c) == "table") and tonumber(c.r) and tonumber(c.i)) then error("bad complex number", 3) end end function P.add (c1, c2) checkComplex(c1); checkComplex(c2); return P.new(c1.r + c2.r, c1.i + c2.i) end ... return P What are the pros and cons of this approach? All names in a package live in a separate namespace. Each entity in a package is clearly marked as public or private. Moreover, we have real privacy: Private entities are inaccessible outside the package. A drawback of this approach is its verbosity when accessing other public entities inside the same package, as every access still needs the prefix P. A bigger problem is that we have to change the calls whenever we change the status of a function from private to public (or from public to private). There is an interesting solution to both problems at once. We can declare all functions in our package as local and later put them in the final table to be exported. Following this approach, our complex package would be like this: local function checkComplex (c) if not ((type(c) == "table") and tonumber(c.r) and tonumber(c.i)) then error("bad complex number", 3) end end local function new (r, i) return {r=r, i=i} end local function add (c1, c2) checkComplex(c1); checkComplex(c2); return new(c1.r + c2.r, c1.i + c2.i) end ... complex new = add = sub = mul = div = } = { new, add, sub, mul, div, Now we do not need to prefix any calls, so that calls to exported and private functions are equal. There is a simple list at the end of the package that defines explicitly which names to export. Most people find more natural to have this list at the beginning of the package, but we cannot put the list at the top, because we must define the local functions first. 15.3 - Packages and Files Typically, The test allows us to use the package without require. If _REQUIREDNAME is not defined, we use a fixed name for the package (complex, in the example). Otherwise, the package registers itself with the virtual file name, whatever it is. If a user puts the library in file cpx.lua and runs require"cpx", the package loads itself in table cpx. If another user moves the library to file cpx_v1.lua and runs require"cpx_v1", the package loads itself in table cpx_v1. Moreover, we can call other functions from this package without any prefix. For instance, add gets new from before. 15.5 - Other Facilities However, After loading this package, the first time the program executes pack1.foo() it will invoke that __index met. 16 - Object-Oriented Programming This definition creates a new function and stores it in field withdraw of the Account object. Now, when we call the method we have to specify on which object it has to operate: a1 = Account; Account = nil ... a1.withdraw(a1, 100.00) -- OK With? 16.1 - Classes A, a looks up in b for any operation that it does not have. To see b as the class of object a is equal to Account; so we could have used Account directly, instead of self. However, the use of self will fit nicely when we introduce class inheritance, in the next section.) After that code, what happens when we create a new account and call a method on it? a = Account:new{balance = 0} a:deposit(100.00) When we create this new account, a entry. The situation now is more or less like this: getmetatable(a).__index.deposit(a, 100.00) The metatable of a is Account and Account.__index is also Account (because the new method did self.__index = self). Therefore, we can rewrite the previous expression as Account.deposit(a, 100.00) That is, Lua calls the original deposit function, but passing a as the self parameter. So, the new account a inherited the deposit function When we call the deposit method on b, it runs the equivalent of b.balance = b.balance + v (because self is b). The expression b.balance evaluates to zero and an initial deposit is assigned to b.balance. The next time we ask for this value, the index metamethod is not invoked (because now b has its own balance field). 16.2 - Inheritance Because classes are objects, they can get methods from other classes, too. That makes inheritance (in the usual object-oriented meaning) quite easy to implement in Lua. Let us assume we have a base class like Account: Account = {balance = 0} function Account:new (o) o = o or {} setmetatable(o, self) self.__index = self return o end function Account:deposit (v) self.balance = self.balance + v end function Account:withdraw (v) if v > self.balance then error"insufficient funds" end self.balance = self.balance - v end From that class, we want to derive a subclass SpecialAccount, which allows the customer to withdraw more than his balance. We start with an empty class that simply inherits all its operations from its base class: SpecialAccount = Account:new() Up to now, SpecialAccount is just an instance of Account. The nice thing happens now: s = SpecialAccount:new{limit=1000.00} SpecialAccount inherits new from Account like any other method. This time, however, when new executes, the self parameter will refer to SpecialAccount. Therefore, the metatable of s will be SpecialAccount, whose value at index __index is also SpecialAccount. So, s inherits from SpecialAccount, which inherits from Account. When we evaluate s:deposit(100.00) Lua cannot find a deposit field in s, so it looks into SpecialAccount; it cannot find a deposit field there, too, so it looks into Account and there it finds the original implementation for a deposit. What makes a SpecialAccount special is that it can redefine any method inherited from its superclass. All we have to do is to write the new method: function SpecialAccount:withdraw (v) if v - self.balance >= self:getLimit() then error"insufficient funds" end self.balance = self.balance - v end function SpecialAccount:getLimit () return self.limit or 0 end Now, when we call s:withdraw(200.00), Lua does not go to Account, because it finds the new withdraw method in SpecialAccount first. Because s.limit is 1000.00 (remember that we set this field when we created s), the program does the withdrawal, leaving s with a negative balance. An interesting aspect of OO in Lua is that you do not need to create a new class to specify a new behavior. If only a single object needs a specific behavior, you can implement that directly in the object. For instance, if the account s represents some special client whose limit is always 10% of her balance, you can modify only this single account: function s:getLimit () return self.balance * 0.10 end After that declaration, the call s:withdraw(200.00) runs the withdraw method from SpecialAccount, but when that method calls self:getLimit, it is this last definition that it invokes. 16.3 - Multiple Inheritance Because To create a new class NamedAccount that is a subclass of both Account and Named, we simply call createClass: NamedAccount = createClass(Account, Named) To create and to use instances, we do as usual: account = NamedAccount:new{name = "Paul"} print(account:getname()) --> Paul Now let us follow what happens in the last statement. Lua cannot find the field "getname" in account. So, it looks for the field __index of account's metatable, which is NamedAccount. But NamedAccount also cannot provide a "getname" field, so Lua looks for the field __index of. 16.4 - Privacy Many First, as an extra parameter; instead, they access self directly. function directly. 16.5 - The Single-Method Approach A Its use is straightforward: d = newObject(0) print(d("get")) d("set", 10) print(d("get")) -->. 17 - Weak Tables). 17.1 - Memoize Functions A"}) function mem_loadstring (s) ... -- as before -- make values weak Actually, Using results table. However, as long as a given color is in use, it is not removed from results. So, whenever a color survives long enough to be compared with a new one, its representation also survives long enough to be reused by the new color. 17.2 - Object Attributes Another important use of weak tables is to associate attributes with objects. There are endless situations where we need to attach some attribute to an object: names to functions, default values to tables, sizes to arrays, and so on. When the object is a table, we can store the attribute in the table itself, with an appropriate unique key. As we saw before, a simple and error-proof way to create a unique key is to create a new object (typically a table) and use it as key. However, if the object is not a table, it cannot keep its own attributes. Even for tables, sometimes we may not want to store the attribute in the original object. For instance, we may want to keep the attribute private, or we do not want the attribute to disturb a table traversal. In all these cases, we need an alternative way to associate attributes to objects. Of course, an external table provides an ideal way to associate attributes to objects (it is not by chance that tables are sometimes called associative arrays). We use the objects as keys, and their attributes as values. An external table can keep attributes of any type of object (as Lua allows us to use any type of object as a key). Moreover, attributes kept in an external table do not interfere with other objects and can be as private as the table itself. However, this seemingly perfect solution has a huge drawback: Once we use an object as a key in a table, we lock the object into existence. Lua cannot collect an object that is being used as a key. If we use a regular table to associate functions to its names, none of those functions will ever be collected. As you might expect, we can avoid this drawback by using a weak table. This time, however, we need weak keys. The use of weak keys does not prevent any key from being collected, once there are no other references to it. On the other hand, the table cannot have weak values; otherwise, attributes of live objects could be collected. Lua itself uses this technique to keep the size of tables used as arrays. As we will see later, the table library offers a function to set the size of an array and another to get this size. When you set the size of an array, Lua stores this size in a private weak table, where the index is the array itself and the value is its size. 17.3 - Revisiting Tables with Default Values In Section 13.4.3, we discussed how to implement tables with non-nil default values. We saw one particular technique and commented that two other techniques need weak tables so we postponed them. Now it is time to revisit the subject. As we will see, those two techniques for default values are actually particular applications of the two general techniques that we have seen here: object attributes and memoizing. In the first solution, we use a weak table to associate to each table its default value: local defaults = {} setmetatable(defaults, {__mode = "k"}) local mt = {__index = function (t) return defaults[t] end} function setDefault (t, d) defaults[t] = d setmetatable(t, mt) end If defaults had not weak keys, it would anchor all tables with default values into permanent existence. In the second solution, we use distinct metatables for distinct default values, but we reuse the same metatable whenever we repeat a default value. This is a typical use of memoizing: local metas = {} setmetatable(metas, {__mode = "v"}) function setDefault (t, d) local mt = metas[d] if mt == nil then mt = {__index = function () return d end} metas[d] = mt -- memoize end setmetatable(t, mt) end We use weak values, in this case, to allow the collection of metatables that are not being used anymore. Given these two implementations for default values, which is best? As usual, it depends. Both have similar complexity and similar performance. The first implementation needs a few words for each table with a default value (an entry in defaults). The second implementation needs a few dozen words for each distinct default value (a new table, a new closure, plus an entry in metas). So, if your application has thousands of tables with a few distinct default values, the second implementation is clearly superior. On the other hand, if few tables share common defaults, then you should use the first one. 18 - The Mathematical Library In this chapter (and in the other chapters about the standard libraries), my purpose is not to give the complete specification of each function, but to show you what kind of functionality the library can provide. I may omit some subtle options or behaviors for clarity of exposition. The main idea is to spark your curiosity, which can then be satisfied by the reference manual. The math library comprises a standard set of mathematical functions, such as trigonometric functions (sin, cos, tan, asin, acos, etc.), exponentiation and logarithms (exp, log, log10), rounding functions (floor, ceil), max, min, plus a variable pi. The mathematical library also defines the operator `^´ to work as the exponentiation operator. All trigonometric functions work in radians. (Until Lua 4.0, they worked in degrees.) You can use the functions deg and rad to convert between degrees and radians. If you want to work in degrees, you can redefine the trigonometric functions: local sin, asin, ... = math.sin, math.asin, ... local deg, rad = math.deg, math.rad math.sin = function (x) return sin(rad(x)) end math.asin = function (x) return deg(asin(x)) end ... The math.random function generates pseudo-random numbers. We can call it in three ways. When we call it without arguments, it returns a pseudo-random real number with uniform distribution in the interval [0,1). When we call it with only one argument, an integer n, it returns an integer pseudo-random number x such that 1 <= x <= n. For instance, you can simulate the result of a die with random(6). Finally, we can call random with two integer arguments, l and u, to get a pseudo-random integer x such that l <= x <= u. You can set a seed for the pseudo-random generator with the randomseed function; its only numeric argument is the seed. Usually, when a program starts, it initializes the generator with a fixed seed. That means that, every time you run your program, it generates the same sequence of pseudo-random numbers. For debugging, that is a nice property; but in a game, you will have the same scenario over and over. A common trick to solve this problem is to use the current time as a seed: math.randomseed(os.time()) (The os.time function returns a number that represents the current time, usually as the number of seconds since some epoch.) 19 - The Table Library The table library comprises auxiliary functions to manipulate tables as arrays. One of its main roles is to give a reasonable meaning for the size of an array in Lua. It also provides functions to insert and remove elements from lists and to sort the elements of an array. 19.1 - Array Size Frequently, in Lua, we assume that an array ends just before its first nil element. This convention has one drawback: We cannot have a nil inside an array. For several applications this restriction is not a hindrance, such as when all elements in the array have a fixed type. But sometimes we must allow nils inside an array. In such cases, we need a method to keep an explicit size for an array. The table library defines two functions to manipulate array sizes: getn, which returns the size of an array, and setn, which sets the size of an array. As we saw earlier, there are two methods to associate an attribute to a table: Either we store the attribute in a field of the table, or we use a separate (weak) table to do the association. Both methods have pros and cons; for that reason, the table library uses both. Usually, a call table.setn(t, n) associates t with n in an internal (weak) table and a call table.getn(t) retrieves the value associated with t in that internal table. However, if the table t has a field "n" with a numeric value, setn updates this value and getn returns it. The getn function still has a last option: If it cannot get an array size with any of those options, it uses the naive approach: to traverse the array looking for its first nil element. So, you can always use table.getn(t) in an array and get a reasonable result. See the examples: print(table.getn{10,2,4}) print(table.getn{10,2,nil}) print(table.getn{10,2,nil; n=3}) print(table.getn{n=1000}) a = {} print(table.getn(a)) table.setn(a, 10000) print(table.getn(a)) a = {n=10} print(table.getn(a)) table.setn(a, 10000) print(table.getn(a)) --> --> --> --> 3 2 3 1000 --> 0 --> 10000 --> 10 --> 10000 By default, setn and getn use the internal table to store a size. This is the cleanest option, as it does not pollute the array with an extra element. However, the n-field option has some advantages too. The Lua core uses this option to set the size of the arg array, in functions with variable number of arguments; because the core cannot depend on a library, it cannot use setn. Another advantage of this option is that we can set the size of an array directly in its constructor, as we saw in the examples. It is a good practice to use both setn and getn to manipulate array sizes, even when you know that the size is at field n. All functions from the table library (sort, concat, insert, etc.) follow this practice. Actually, the possibility of setn to change the value of the field n is provided only for compatibility with older versions of Lua. This behavior may change in future versions of the language. To play safe, do not assume this behavior. Always use getn to get a size set by setn. 19.2 - Insert and Remove The table library provides functions to insert and to remove elements from arbitrary positions of a list. The table.insert function inserts an element in a given position of an array, moving up other elements to open space. Moreover, insert increments the size of the array (using setn). For instance, if a is the array {10, 20, 30}, after the call table.insert(a, 1, 15) a will be {15, 10, 20, 30}. As a special (and frequent) case, if we call insert without a position, it inserts the element in the last position of the array (and, therefore, moves no elements). As an example, the following code reads the program input line by line, storing all lines in an array: a = {} for line in io.lines() do table.insert(a, line) end print(table.getn(a)) --> (number of lines read) The table.remove function removes (and returns) an element from a given position in an array, moving down other elements to close space and decrementing the size of the array. When called without a position, it removes the last element of the array. With those two functions, it is straightforward to implement stacks, queues, and double queues. We can initialize such structures as a = {}. A push operation is equivalent to table.insert(a, x); a pop operation is equivalent to table.remove(a). To insert at the other end of the structure we use table.insert(a, 1, x); to remove from that end we use table.remove(a, 1). The last two operations are not particularly efficient, as they must move elements up and down. However, because the table library implements these functions in C, these loops are not too expensive and this implementation is good enough for small arrays (up to some hundred elements, say). 19.3 - Sort Another With this function, it is easy to print those function names in alphabetical order. The loop for name, line in pairsByKeys(lines) do print(name, line) end will print luaH_get luaH_present luaH_set 24 48 10 20 - The String Library The power of a raw Lua interpreter to manipulate strings is quite limited. A program can create string literals and concatenate them. But it cannot extract a substring, check its size, or examine its contents. The full power to manipulate strings in Lua comes from its string library. Some functions in the string library are quite simple: string.len(s) returns the length of a string s. string.rep(s, n) returns the string s repeated n times. You can create a string with 1M bytes (for tests, for instance) with string.rep("a", 2^20). string.lower(s) returns a copy of s with the upper-case letters converted to lower case; all other characters in the string are not changed (string.upper converts to upper case). As a typical use, if you want to sort an array of strings regardless of case, you may write something like table.sort(a, function (a, b) return string.lower(a) < string.lower(b) end) Both string.upper and string.lower follow the current locale. Therefore, if you work with the European Latin-1 locale, the expression string.upper("ação") results in "AÇÃO". The call string.sub(s,i,j) extracts a piece of the string s, from the i-th to the j-th character inclusive. In Lua, the first character of a string has index 1. You can also use negative indices, which count from the end of the string: The index -1 refers to the last character in a string, -2 to the previous one, and so on. Therefore, the call string.sub(s, 1, j) gets a prefix of the string s with length j; string.sub(s, j, -1) gets a suffix of the string, starting at the jth character (if you do not provide a third argument, it defaults to -1, so we could write the last call as string.sub(s, j)); and string.sub(s, 2, -2) returns a copy of the string s with the first and last characters removed: s = "[in brackets]" print(string.sub(s, 2, -2)) --> in brackets Remember that strings in Lua are immutable. The string.sub function, like any other function in Lua, does not change the value of a string, but returns a new string. A common mistake is to write something like string.sub(s, 2, -2) and to assume that the value of s will be modified. If you want to modify the value of a variable, you must assign the new value to the variable: s = string.sub(s, 2, -2) The string.char and string.byte functions convert between characters and their internal numeric representations. The function string.char gets zero or more integers, converts each one to a character, and returns a string concatenating all those characters. The function string.byte(s, i) returns the internal numeric representation of the i-th character of the string s; the second argument is optional, so that a call string.byte(s) returns the internal numeric representation of the first (or single) character of s. In the following examples, we assume that characters are represented in ASCII: print(string.char(97)) i = 99; print(string.char(i, i+1, i+2)) print(string.byte("abc")) print(string.byte("abc", 2)) print(string.byte("abc", -1)) --> --> --> --> --> a cde 97 98 99 In the last line, we used a negative index to access the last character of the string. The function string.format is a powerful tool when formatting strings, typically for output. It returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string. The format string has rules similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string. A simple directive is the character ` %´ plus a letter that tells how to format the argument: `d´ for a decimal number, `x´ for hexadecimal, `o´ for octal, `f´ for a floating-point number, `s´ for strings, plus other variants. Between the `%´ and the letter, a directive can include other options, which control the details of the format, such as the number of decimal digits of a floating-point number: print(string.format("pi = %.4f", PI)) d = 5; m = 11; y = 1990 --> pi = 3.1416 print(string.format("%02d/%02d/%04d", d, m, y)) --> 05/11/1990 tag, title = "h1", "a title" print(string.format("<%s>%s</%s>", tag, title, tag)) --> <h1>a title</h1> In the first example, the %.4f means a floating-point number with four digits after the decimal point. In the second example, the %02d means a decimal number (`d´), with at least two digits and zero padding; the directive %2d, without the zero, would use blanks for padding. For a complete description of those directives, see the Lua reference manual. Or, better yet, see a C manual, as Lua calls the standard C libraries to do the hard work here. 20.1 - Pattern-Matching Functions) print(string.sub(s, i, j)) print(string.find(s, "world")) i, j = string.find(s, "l") print(i, j) print(string.find(s, "lll")) --> 1 5 --> hello --> 7 11 --> 3 --> nil 3 When a match succeeds, a string.sub of the values returned by string.find would We will see later a simpler way to write such loops, using the string.gfind iterator. The string.gsub function has three parameters: a subject string, a pattern, and a replacement string. Its basic use is to substitute the replacement string for all occurrences of the pattern inside the subject string: s = string.gsub("Lua print(s) --> s = string.gsub("all print(s) --> s = string.gsub("Lua print(s) --> is cute", "cute", "great") Lua is great lii", "l", "x") axx xii is great", "perl", "tcl") Lua is great.) 20.2 - Patterns The following table lists all character classes: . %a %c %d %l %p %s %u %w %x all characters letters control characters digits lower case letters punctuation characters space characters upper case letters alphanumeric characters hexadecimal digits %z the character with representation 0 An upper case version of any of those classes represents the complement of the class. For instance, '%A' represents all non-letter characters: print(string.gsub("hello, up-down!", "%A", ".")) --> hello..up.down. 4 (The 4 is not part of the result string. It is the second result of gsub, the total number of substitutions. Other examples that print the result of gsub will: + 1 or more repetitions * 0 or more repetitions - also 0 or more repetitions ? optional (0 or 1 occurrence) The starts line Typically, this pattern is used as '%b()', '%b[]', '%b%{%}', or '%b<>', but you can use any characters as delimiters. 20.3 - Captures The capturea The function: a, b, c, quotedPart print(quotedPart) print(c) "it's all right"!]] = string.find(s, "([\"'])(.-)%1") --> it's all right --> " is the string the \quote{task} is to \em{change} that. that gsub call will change it to the <quote>task</quote> is to <em>change</em> that. Another useful example is how to trim a string: function trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end Note the judicious use of pattern formats. The two anchors (`^´ and `$´) ensure that we get the whole string. Because the '.-' tries to expand as little as possible, the two patterns '%s*' match all spaces at both extremities. Note also that, because gsub returns to The first match is the string "$[math.sin(3)]", whose corresponding capture is "[math.sin(3)]". The call to string.sub removes s were the string "hello hi, again!", after that command the word table would be {"hello", "hi", "again"} The string.gfind function offers a simpler way to write that code: words = {} for w in string.gfind(s, "(%a)") do table.insert(words, w) end The gfind function+no Now, The first statement changes each `+´ in the string to a space. The second gsub matches all twodigit That call to gfind matches all pairs in the form name=value and, for each pair, the iterator returns the corresponding captures (as marked by the parentheses in the matching string) as the values to name and value. The loop body simply calls unescape on both strings and stores the pair in the cgi table. The encode function 20.4 - Tricks of the Trade Pattern comments in a C program: '/%*.-%*/'.(";$% print(i,j) --> 1 0 **#$hello13", "%a*") In this example, the call to string.find has Now only when x is not a letter: function code (s) return (string.gsub(s, '\\(%A)', function (x) return string.format("\\%03d", string.byte(x)) end)) end The decode is like that of the previous example, but it does not include the backslashes in the final string; therefore, we can call string.char directly: end If 21 - The I/O Library The I/O library offers two different models for file manipulation. The simple model assumes a current input and a current output files, and its I/O operations operate on those files. The complete model uses explicit file handles and it adopts an object-oriented style that defines all operations as methods on file handles. The simple model is convenient for simple things; we have been using it all along the book until now. But it is not enough for more advanced file manipulation, such as reading from several files simultaneously. For those manipulations, the complete model is more convenient. The I/O library puts all its functions into the io table. 21.1 - The Simple I/O Model Avoid code like io.write(a..b..c); the call io.write(a,b,c) accomplishes the same effect with fewer resources, as it avoids the concatenations. As a rule, you should use print for quick-and-dirty programs, or for debugging, and write when you need full control over your output: > print("hello", "Lua"); print("Hi") --> hello Lua --> Hi > io.write("hello", "Lua"); io.write("Hi", "\n") --> helloLuaHi Unlike print, write adds no extra characters to the output, such as tabs or newlines. Moreover, write uses the current output file, whereas print always uses the standard output. Finally, print automatically applies tostring to its arguments, so it can also show tables, functions, and nil. The read function reads strings from the current input file. Its arguments control what is read: "*all" reads the whole file "*line" reads the next line "*number" reads a number num reads a string with up to num characters") t = string.gsub(t, ...) io.write(t) -- read the whole file -- do the job -- write the file As an example, the following code is a complete program to code a file's content using the quotedprint captures = count + 1 end ", count), line, "\n") However, to iterate on a whole file line by line, we do better to use the io.lines iterator. This program sorts a file with 4.5 MB (32K lines) in 1.8 seconds (on a Pentium 333MHz), against 0.6 seconds spent by the system sort program, 4.3 ... -3.23 234 15e12 In any case, you should always consider the alternative of reading the whole file with option "*all" from io.read and then using gfind to while true do -- good buffer size (8K) local block = io.read(size) if not block then break end io.write(block) end As a special case, io.read(0) works as a test for end of file: It returns an empty string if there is more to be read or nil otherwise. 21.2 - The Complete I/O Model For print(io.open("/etc/passwd", "w")) --> nil Permission denied 13 2 The interpretation of the error numbers is system dependent. A typical idiom to check for errors is local f = assert(io.open(filename, mode)) If the open fails,() io.input("newinput") ... io.input():close() ----save current file open a new current file do something with new input close current file io.input(temp) -- restore previous current file 21.2.1 - A Small Performance Trick Usually, will) 21.2.2 - Binary Files The simple model functions io.input and io.output always open a file in text mode (the default). In Unix, there is no difference between binary files and text files. But in some systems, notably Windows, binary files must be opened with a special flag. To handle such binary files, you must use io.open, with the letter `b´ in the mode string. Binary data in Lua are handled similarly to text. A string in Lua may contain any bytes and almost all functions in the libraries can handle arbitrary bytes. (You can even do pattern matching over binary data, as long as the pattern does not contain a zero byte. If you want to match the byte zero, you can use the class %z instead.) Typically, you read binary data either with the *all pattern, that reads the whole file, or with the pattern n, that reads n bytes. As a simple example, the following program converts a text file from DOS format to Unix format (that is, it translates sequences of carriage return-newlines to newlines). It does not use the standard I/O files (stdin/stdout), because those files are open in text mode. Instead, it assumes that the names of the input file and the output file are given as arguments to the program: local inp = assert(io.open(arg[1], "rb")) local out = assert(io.open(arg[2], "wb")) local data = inp:read("*all") data = string.gsub(data, "\r\n", "\n") out:write(data) assert(out:close()) You can call this program with the following command line: > lua prog.lua file.dos file.unix As another example, the following program prints all strings found in a binary file. The program assumes that a string is any zero-terminated sequence of six or more valid characters, where a valid character is any character accepted by the pattern validchars. In our example, that comprises the alphanumeric, the punctuation, and the space characters. We use concatenation and string.rep to create a pattern that captures all sequences of six or more validchars. The %z at the end of the pattern matches the byte zero at the end of a string. local f = assert(io.open(arg[1], "rb")) local data = f:read("*all") local validchars = "[%w%p%s]" local pattern = string.rep(validchars, 6) .. "+%z" for w in string.gfind(data, pattern) do print(w) end As a last example, the following program makes a dump of a binary file. Again, the first program argument is the input file name; the output goes to the standard output. The program reads the file in chunks of 10 bytes. For each chunk, it writes the hexadecimal representation of each byte, and then it writes the chunk as text, changing control characters to dots. local f = assert(io.open(arg[1], "rb")) local block = 10 while true do local bytes = f:read(block) if not bytes then break end for b in string.gfind(bytes, ".") do io.write(string.format("%02X ", string.byte(b))) end io.write(string.rep(" ", block - string.len(bytes) + 1)) io.write(string.gsub(bytes, "%c", "."), "\n") end Suppose we store that program in a file named vip; if we apply the program to itself, with the call prompt> lua vip vip it will produce an output like this (in a Unix machine): 6C 61 6F 5D 6C 72 28 72 ... 22 25 63 22 2C 2C 20 22 5C 6E 64 0A 6F 73 70 2C 63 73 65 20 61 65 6E 22 20 74 61 62 66 28 72 22 20 69 67 29 3D 6F 5B 29 20 2E 31 0A local f = assert(io. open(arg[1 ], "rb")). "%c", ".") , "\n").en d. 20 22 2E 22 29 22 29 0A 65 6E 21.3 - Other Operations on Files The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends. The flush function executes all pending writes to a file. Like the write function, you can call it as a function, io.flush(), to flush the current output file; or as a method, f:flush(), to flush file f. The seek function can be used both to get and to set the current position of a file. Its general form is filehandle:seek(whence, offset). The whence parameter is a string that specifies how the offset will be interpreted. Its valid values are "set", when offsets are interpreted from the beginning of the file; "cur", when offsets are interpreted from the current position of the file; and "end", when offsets are interpreted from the end of the file. Independently of the value of whence, the call returns the final current position of the file, measured in bytes from the beginning of the file. The default value for whence is "cur" and for offset is zero. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek("set") resets the position to the beginning of the file (and returns zero); and the call file:seek("end") sets the position to the end of the file, and returns its size. The following function gets the file size without changing its current position: function fsize (file) local current = file:seek() local size = file:seek("end") file:seek("set", current) return size end -- get current position -- get file size -- restore position All the previous functions return nil plus an error message in case of errors. 22 - The Operating System Library The Operating. 22.1 - Date and Time Two functions, time and date, do all date and time queries in Lua. The time function, when called without arguments, returns the current date and time, coded as a number. (In most systems, that number is the number of seconds since some epoch.) When called with a table, it returns the number representing the date and time described by the table. Such date tables have the following significant fields: year a full year month 01-12 day 01-31 hour 01-31 min 00-59 sec 00-59 isdst a boolean, true if daylight saving The first three fields are mandatory; the others default to noon (12:00:00) when not provided. In a Unix system (where the epoch is 00:00:00 UTC, January 1, 1970) running in Rio de Janeiro (which is three hours west of Greenwich), we have the following examples: -- obs: 10800 = 3*60*60 (3 hours) print(os.time{year=1970, month=1, --> 10800 print(os.time{year=1970, month=1, --> 10801 print(os.time{year=1970, month=1, --> 54000 (obs: 54000 = 10800 day=1, hour=0}) day=1, hour=0, sec=1}) day=1}) + 12*60*60) The date function, despite its name, is a kind of a reverse of the time function: It converts a number representing the date and time back to some higher-level representation. Its first parameter is a format string, describing the representation we want. The second is the numeric date-time; it defaults to the current date and time. To produce a date table, we use the format string "*t". For instance, the following code temp = os.date("*t", 906000490) produces the table {year = 1998, month = 9, day = 16, yday = 259, wday = 4, hour = 23, min = 48, sec = 10, isdst = false} Notice that, besides the fields used by os.time, the table created by os.date also gives the week day (wday, 1 is Sunday) and the year day (yday, 1 is January 1). For other format strings, os.date formats the date as a string, which is a copy of the format string where specific tags are replaced by information about time and date. All tags are represented by a `% ´ followed by a letter, as in the next examples: print(os.date("today is %A, in %B")) --> today is Tuesday, in May print(os.date("%x", 906000490)) --> 09/16/1998 All representations follow the current locale. Therefore, in a locale for Brazil-Portuguese, %B would result in "setembro" and %x in "16/09/98". The following table shows each tag, its meaning, and its value for September 16, 1998 (a Wednesday), at 23:48:10. For numeric values, the table shows also their range of possible values: `%´ If you call date without any arguments, it uses the %c format, that is, complete date and time information in a reasonable format. Note that the representations for %x, %X, and %c change according to the locale and the system. If you want a fixed representation, such as mm/dd/yyyy, use an explicit format string, such as "%m/%d/%Y". The os.clock function returns the number of seconds of CPU time for the program. Its typical use is to benchmark a piece of code: local x = os.clock() local s = 0 for i=1,100000 do s = s + i end print(string.format("elapsed time: %.2f\n", os.clock() - x)) 22.2 - Other System Calls The os.exit function terminates the execution of a program. The os.getenv function gets the value of an environment variable. It receives the name of the variable and returns a string with its value: print(os.getenv("HOME")) --> /home/lua If the variable is not defined, the call returns nil. The function os.execute runs a system command; it is equivalent to the system function in C. It receives a string with the command and returns an error code. For instance, both in Unix and in DOS-Windows, you can write the following function to create new directories: function createDir (dirname) os.execute("mkdir " .. dirname) end The os.execute function is powerful, but it is also highly system dependent. The os.setlocale function sets the current locale used by a Lua program. Locales define behavior that is sensitive to cultural or linguistic differences. The setlocale function has two string parameters: the locale name and a category, which specifies what features the locale will affect. There are six categories of locales: "collate" controls the alphabetic order of strings; "ctype" controls the types of individual characters (e.g., what is a letter) and the conversion between lower and upper cases; "monetary" has no influence in Lua programs; "numeric" controls how numbers are formatted; "time" controls how date and time are formatted (i.e., function os(os.setlocale("ISO-8859-1", "collate")) --> ISO-8859-1 The category "numeric" is a little tricky. Although Portuguese and other Latin languages use a comma instead of a point to represent decimal numbers, the locale does not change the way that Lua parses numbers (among other reasons because expressions like print(3,4) already have a meaning in Lua). Therefore, you may end with a system that cannot recognize numbers with commas, but cannot understand numbers with points either: -- set locale for Portuguese-Brazil print(os.setlocale('pt_BR')) --> pt_BR print(3,4) --> 3 4 print(3.4) --> stdin:1: malformed number near `3.4' 23 - The Debug Library The. 23.1 - Introspective Facilities The main introspective function in the debug library is the debug.getinfo function. Its first parameter may be a function or a stack level. When you call debug.getinfo(foo) for some function foo, you get a table with some data about that function. The table may have the following fields: • source --- Where the function was defined. If the function was defined in a string (through loadstring), source is that string. If the function was defined in a file, source is the file name prefixed with a `@´. • short_src --- A short version of source (up to 60 characters), useful for error messages. • linedefined --- The line of the source where the function was defined. • what --- What this function is. Options are "Lua" if foo is a regular Lua function, "C" if it is a C function, or "main" if it is the main part of a Lua chunk. • name --- A reasonable name for the function. • namewhat --- What the previous field means. This field may be "global", "local", "method", "field", or "" (the empty string). The empty string means that Lua did not find a name for the function. • nups --- Number of upvalues of that function. • func --- The function itself; see later. When foo is a C function, Lua does not have much data about it. For such functions, only the fields what, name, and namewhat are relevant. When you call debug.getinfo(n) for some number n, you get data about the function active at that stack level. For instance, if n is 1, you get data about the function doing the call. (When n is 0, you get data about getinfo itself, a C function.) If n is larger than the number of active functions in the stack, debug.getinfo returns nil. When you query an active function, calling debug.getinfo with a number, the result table has an extra field, currentline, with the line where the function is at that moment. Moreover, func has the function that is active at that level. The field name is tricky. Remember that, because functions are first-class values in Lua, a function may not have a name, or may have several names. Lua tries to find a name for a function by looking for a global variable with that value, or else looking into the code that called the function, to see how it was called. This second option works only when we call getinfo with a number, that is, we get information about a particular invocation. The getinfo function is not efficient. Lua keeps debug information in a form that does not impair program execution; efficient retrieval is a secondary goal here. To achieve better performance, getinfo has an optional second parameter that selects what information to get. With this parameter, it does not waste time collecting data that the user does not need. The format of this parameter is a string, where each letter selects a group of data, according to the following table: `n´ selects fields name and namewhat `f´ selects field func `S´ selects fields source, short_src, what, and linedefined `l´ selects field currentline `u´ selects field nup The following function illustrates the use of debug.getinfo. It prints a primitive traceback of the active stack: function traceback () local level = 1 while true do local info = debug.getinfo(level, "Sl") if not info then break end if info.what == "C" then -- is a C function? print(level, "C function") else -- a Lua function print(string.format("[%s]:%d", info.short_src, info.currentline)) end level = level + 1 end end It is not difficult to improve this function, including more data from getinfo. Actually, the debug library offers such an improved version, debug.traceback. Unlike our version, debug.traceback does not print its result; instead, it returns a string. 23.1.1 - Accessing Local Variables You can access the local variables of any active function by calling getlocal, from the debug library. It has two parameters: the stack level of the function you are querying and a variable index. It returns two values: the name and the current value of that variable. If the variable index is larger than the number of active variables, getlocal returns nil. If the stack level is invalid, it raises an error. (You can use debug.getinfo to check the validity of a stack level.) Lua numbers local variables in the order that they appear in a function, counting only the variables that are active in the current scope of the function. For instance, the code function foo (a,b) local x do local c = a - b end local a = 1 while true do local name, value = debug.getlocal(1, a) if not name then break end print(name, value) a = a + 1 end end foo(10, 20) will print a b x a 10 20 nil 4 The variable with index 1 is a (the first parameter), 2 is b, 3 is x, and 4 is another a. At the point where getlocal is called, c is already out of scope, while name and value are not yet in scope. (Remember that local variables are only visible after their initialization code.) You can also change the values of local variables, with debug.setlocal. Its first two parameters are a stack level and a variable index, like in getlocal. Its third parameter is the new value for that variable. It returns the variable name, or nil if the variable index is out of scope. 23.1.2 - Accessing Upvalues The debug library also allows us to access the upvalues that a Lua function uses, with getupvalue. Unlike local variables, however, a function has its upvalues even when it is not active (this is what closures are about, after all). Therefore, the first argument for getupvalue is not a stack level, but a function (a closure, more precisely). The second argument is the upvalue index. Lua numbers upvalues in the order they are first referred in a function, but this order is not relevant, because a function cannot have two upvalues with the same name. You can also update upvalues, with debug.setupvalue. As you might expect, it has three parameters: a closure, an upvalue index, and the new value. Like setlocal, it returns the name of the upvalue, or nil if the upvalue index is out of range. The following code shows how we can access the value of any given variable of a calling function, given the variable name: function getvarvalue (name) local value, found -- try local variables local i = 1 while true do local n, v = debug.getlocal(2, i) if not n then break end if n == name then value = v found = true end i = i + 1 end if found then return value end -- try upvalues local func = debug.getinfo(2).func i = 1 while true do local n, v = debug.getupvalue(func, i) if not n then break end if n == name then return v end i = i + 1 end -- not found; get global return getfenv(func)[name] end First, we try a local variable. If there is more than one variable with the given name, we must get the one with the highest index; so we must always go through the whole loop. If we cannot find any local variable with that name, then we try upvalues. First, we get the calling function, with debug.getinfo(2).func, and then we traverse its upvalues. Finally, if we cannot find an upvalue with that name, then we get a global variable. Notice the use of the argument 2 in the calls to debug.getlocal and debug.getinfo to access the calling function. 23.2 - Hooks print as the hook function and instructs Lua to call it only at line events. A more elaborated tracer can use getinfo to add the current file name to the trace: function trace (event, line) local s = debug.getinfo(2).short_src print(s .. ":" .. line) end debug.sethook(trace, "l") 23.3 - Profiles The next step is to run the program with this hook. We will assume that the main chunk of the program is in a file and that the user gives this file name as an argument to the profiler: prompt> lua profiler main-prog With this scheme, we get the file name in arg[1], turn on the hook, and run the file: local f = assert(loadfile(arg[1])) debug.sethook(hook, "c") -- turn on the hook f() -- run the main program debug.sethook() -- turn off the hook The Finally,) [markov.lua]:20 (prefix) find 915824 [markov.lua]:26 (insert) random 10000 sethook 1 insert 884723 1 894723 884723 That stand alone through the whole book? The solution to this puzzle is the Lua interpreter (the executable lua). This interpreter is a tiny application (with less than five hundred lines of code) that uses the Lua library to implement the stand-alone interpreter. This program handles the interface with the user, taking her files and strings to feed them to the Lua library, which does the bulk of the work (such as actually running Lua code). This ability to be used as a library to extend an application is what makes Lua an extension language. At the same time, a program that uses Lua can register new functions in the Lua environment; such functions are implemented in C (or another language) and can add facilities that cannot be written directly in Lua. This is what makes Lua an extensible language. These two views of Lua (as an extension language and as an extensible language) correspond to two kinds of interaction between C and Lua. In the first kind, C has the control and Lua is the library. The C code in this kind of interaction is what we call application code. In the second kind, Lua has the control and C is the library. Here, the C code is called library code. Both application code and library code use the same API to communicate with Lua, the so called C API. The C API is the set of functions that allow C code to interact with Lua. It comprises functions to read and write Lua global variables, to call Lua functions, to run pieces of Lua code, to register C functions so that they can later be called by Lua code, and so on. (Throughout this text, the term "function" actually means "function or macro". The API implements several facilities as macros.) The C API follows the C modus operandi, which is quite different from Lua. When programming in C, we must care about type checking (and type errors), error recovery, memory-allocation errors, and several other sources of complexity. Most functions in the API do not check the correctness of their arguments; it is your responsibility to make sure that the arguments are valid before calling a function. If you make mistakes, you can get a "segmentation fault" error or something similar, instead of a well-behaved error message. Moreover, the API emphasizes flexibility and simplicity, sometimes at the cost of ease of use. Common tasks may involve several API calls. This may be boring, but it gives you full control over all details, such as error handling, buffer sizes, and the like. As its title says, the goal of this chapter is to give an overview of what is involved when you use Lua from C. Do not bother understanding all the details of what is going on now. Later we will fill in the details. Nevertheless, do not forget that you can find more details about specific functions in the Lua reference manual. Moreover, you can find several examples of the use of the API in the Lua distribution itself. The Lua stand-alone interpreter (lua.c) provides examples of application code, while the standard libraries (lmathlib.c, lstrlib.c, etc.) provide examples of library code. From now on, we are wearing a C programmers' hat. When we talk about "you", we mean you when programming in C, or you impersonated by the C code you write. A major component in the communication between Lua and C is an omnipresent virtual stack. Almost all API calls operate on values on this stack. All data exchange from Lua to C and from C to Lua occurs through this stack. Moreover, you can use the stack to keep intermediate results too. The stack helps to solve two impedance mismatches between Lua and C: The first is caused by Lua being garbage collected, whereas C requires explicit deallocation; the second results from the shock between dynamic typing in Lua versus the static typing of C. We will discuss the stack in more detail in Section 24.2. #include #include #include #include <stdio.h> <string.h> <lua.h> <lauxlib.h> <lualib.h> int main (void) { char buff[256]; int error; lua_State *L = lua_open(); luaopen_base(L); luaopen_table(L); luaopen_io(L); luaopen_string(L); luaopen_math(L); /* /* /* /* /* /* opens opens opens opens opens opens Lua the the the the the */ basic library */ table library */ I/O library */ string lib. */ defines has print. To keep Lua small, all standard libraries are provided as separate packages, so that you do not have to use them if you do not need to. The header file Therefore, if you have compiled Lua as C code (the most common case) and are using it in C++, you must include lua.h as follows: extern "C" { #include <lua.h> } A common trick is to create a header file lua.hpp with the above code and to include this new file in your C++ programs. 24.2 - The Stack. 24.2.1 - Pushing Elements.) 24.2.2 - Querying Elements To refer to elements in the stack, the API uses indices. The first element in the stack (that is, the element that was pushed first) has index 1, the next one has index 2, and so on. We can also access elements using the top of the stack as our reference, using negative indices. In that case, -1 refers to the element at the top (that is, the last element pushed), -2 to the previous element, and so on. For instance, the call lua_tostring(L, -1) returns the value at the top of the stack as a string. As we will see, there are several occasions when it is natural to index the stack from the bottom (that is, with positive indices) and several other occasions when the natural way is to use negative indices. To check whether an element has a specific type, the API offers a family of functions lua_is*, where the * can be any Lua type. So, there are lua_isnumber, lua_isstring, lua_istable, and the like. All these functions have the same prototype: int lua_is... (lua_State *L, int index); The lua_isnumber and lua_isstring functions do not check whether the value has that specific type, but whether the value can be converted to that type. For instance, any number satisfies lua_isstring. There is also a function lua_type, which returns the type of an element in the stack. (Some of the lua_is* functions are actually macros that use this function.) Each type is represented by a constant defined in the header file lua.h: LUA_TNIL, LUA_TBOOLEAN, LUA_TNUMBER, LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, LUA_TUSERDATA, and LUA_TTHREAD. This function is mainly used in conjunction with a switch statement. It is also useful when we need to check for strings and numbers without coercions. To get a value from the stack, there are the lua_to* functions: int double const char size_t lua_toboolean (lua_State *L, int index); lua_tonumber (lua_State *L, int index); *lua_tostring (lua_State *L, int index); lua_strlen (lua_State *L, int index); It is OK to call them even when the given element does not have the correct type. In this case, lua_toboolean, lua_tonumber and lua_strlen return zero and the others return NULL. The zero is not useful, but ANSI C provides us with no invalid numeric value that we could use to signal errors. For the other functions, however, we frequently do not need to use the corresponding lua_is* function: We just call lua_to* and then test whether the result is not NULL. The lua_tostring function returns a pointer to an internal copy of the string. You cannot change it (there is a const there to remind you). Lua ensures that this pointer is valid as long as the corresponding value is in the stack. When a C function returns, Lua clears its stack; therefore, as a rule, you should never store pointers to Lua strings outside the function that got them. Any string that lua_tostring returns always has a zero at its end, but it can have other zeros inside it. The lua_strlen function returns the correct length of the string. In particular, assuming that the value at the top of the stack is a string, the following assertions are always valid: const char *s = lua_tostring(L, -1); size_t l = lua_strlen(L, -1); assert(s[l] == '\0'); assert(strlen(s) <= l); /* any Lua string */ /* its length */ 24.2.3 - Other Stack Operations Besides the above functions, which interchange values between C and the stack, the API offers also the following operations for generic stack manipulation: int void void void void void lua_gettop (lua_State *L); lua_settop (lua_State *L, int index); lua_pushvalue (lua_State *L, int index); lua_remove (lua_State *L, int index); lua_insert (lua_State *L, int index); lua_replace (lua_State *L, int index); The lua_gettop function returns the number of elements in the stack, which is also the index of the top element. Notice that a negative index -x is equivalent to the positive index gettop - x + 1. lua_settop sets the top (that is, the number of elements in the stack) to a specific value. If the previous top was higher than the new one, the top values are discarded. Otherwise, the function pushes nils on the stack to get the given size. As a particular case, lua_settop(L, 0) empties the stack. You can also use negative indices with lua_settop; that will set the top element to the given index. Using this facility, the API offers the following macro, which pops n elements from the stack: #define lua_pop(L,n) lua_settop(L, -(n)-1) The lua_pushvalue function pushes on the top of the stack a copy of the element at the given index; lua_remove removes the element at the given index, shifting down all elements on top of that position to fill in the gap; lua_insert moves the top element into the given position, shifting up all elements on top of that position to open space; finally, lua_replace pops a value from the top and sets it as the value of the given index, without moving anything. Notice that the following operations have no effect on the stack: lua_settop(L, -1); lua_insert(L, -1); /* set top to its current value */ /* move top element to the top */ To illustrate the use of those functions, here is a useful helper function that dumps the entire content of the stack: static void stackDump (lua_State *L) { int i; int top = lua_gettop(L); for (i = 1; i <= top; i++) { /* repeat for each level */ int t = lua_type(L, i); switch (t) { case LUA_TSTRING: /* strings */ printf("`%s'", lua_tostring(L, i)); break; case LUA_TBOOLEAN: /* booleans */ printf(lua_toboolean(L, i) ? "true" : "false"); break; case LUA_TNUMBER: /* numbers */ printf("%g", lua_tonumber(L, i)); break; default: /* other values */ printf("%s", lua_typename(L, t)); break; "); /* put a separator */ } printf("\n"); /* end the listing */ } } printf(" This function traverses the stack from bottom to top, printing each element according to its type. It prints strings between quotes; for numbers it uses a `%g´ format; for other values (tables, functions, etc.) it prints only their types (lua_typename converts a type code to a type name). The following program uses stackDump to further illustrate the manipulation of the API stack: #include <stdio.h> #include <lua.h> static void stackDump (lua_State *L) { ... } int main (void) { lua_State *L = lua_open(); lua_pushboolean(L, 1); lua_pushnumber(L, 10); lua_pushnil(L); lua_pushstring(L, "hello"); stackDump(L); /* true 10 nil `hello' */ lua_pushvalue(L, -4); stackDump(L); /* true 10 nil `hello' lua_replace(L, 3); stackDump(L); /* true 10 true lua_settop(L, 6); stackDump(L); /* true 10 true `hello' `hello' true */ nil nil */ */ lua_remove(L, -3); stackDump(L); /* true 10 true lua_settop(L, -5); stackDump(L); /* true */ lua_close(L); return 0; nil nil */ } uses real exceptions instead.) All structures in Lua are dynamic: They grow as needed, and eventually shrink again when possible. That means that the possibility of a memory-allocation failure is pervasive in Lua. Almost any operation may face this eventuality. Instead of using error codes for each operation in its API, Lua uses exceptions to signal these errors. That means that almost all API functions may throw an error (that is, call longjmp) instead of returning. When we write library code (that is, C functions to be called from Lua), the use of long jumps is almost as convenient as a real exception-handling facility, because Lua catches any occasional error. When we write application code (that is, C code that calls Lua), however, we must provide a way to catch those errors. 24.3.1 - Error Handling in Application Code Typically, your application code runs unprotected. Because its code is not called by Lua, Lua cannot set an appropriate context to catch errors (that is, it cannot call setjmp). In such environments, when Lua faces an error like "not enough memory", there is not much that it can do. It calls a panic function and, if the function returns, exits the application. (You can set your own panic function with the lua_atpanic function.) Not all API functions throw exceptions. The functions lua_open, lua_close, lua_pcall, and lua_load are all safe. Moreover, most other functions can only throw an exception in case of memory-allocation failure: For instance, luaL_loadfile fails if there is not enough memory for a copy of the file name. Several programs have nothing to do when they run out of memory, so they may ignore these exceptions. For those programs, if Lua runs out of memory, it is OK to panic. If you do not want your application to exit, even in case of a memory-allocation failure, then you must run your code in protected mode. Most (or all) of your Lua code typically runs through a call to lua_pcall; therefore, it runs in protected mode. Even in case of memory-allocation failure, lua_pcall returns an error code, leaving the interpreter in a consistent state. If you also want to protect all your C code that interacts with Lua, then you can use lua_cpcall. (See the reference manual for further details of this function; see file lua.c in the Lua distribution for an example of its use.) 24.3.2 - Error Handling in Library Code Lua is a safe language. That means that, no matter what you write, no matter how wrong it is, you can always understand the behavior of a program in terms of Lua itself. Moreover, errors are detected and explained in terms of Lua, too. You can contrast that with C, where the behavior of many wrong programs can only be explained in terms of the underling hardware and error positions are given as a program counter. Whenever you add new C functions to Lua, you can break that safety. For instance, a function like poke, which stores an arbitrary byte at an arbitrary memory address, can cause all sorts of memory corruption. You must strive to ensure that your add-ons are safe to Lua and provide good error handling. As we discussed earlier, each C program has its own way to handle errors. When you write library functions for Lua, however, there is a standard way to handle errors. Whenever a C function detects an error, it simply calls lua_error, (or better yet luaL_error, which formats the error message and then calls lua_error). The lua_error function clears whatever needs to be cleared in Lua and jumps back to the lua_pcall that originated that execution, passing along the error message. 25 - Extending your Application to load the chunk from file filename and calls lua_pcall to run it. In case of errors in any of these functions (e.g., a syntax error in your configuration file), the call returns a non-zero error code and pushes the error message onto the stack. As usual, our program uses lua_tostring with index -1 to get the message from the top of the stack. (We defined the error function Even. 25.1 - Table Manipulation Let us adopt that attitude: Now, we want to configure a background color for the window, too. We will assume that the final color specification is composed of three numbers, where each number is a color component in RGB. Usually, in C, those numbers are integers in some range like [0,255]. In Lua, because all numbers are real, we can use the more natural range [0,1]. A naive approach here is to ask the user to set each component in a different global variable: -- configuration file for program `pp' width = 200 height = 300 background_red = 0.30 background_green = 0.10 background_blue = 0 This approach has two drawbacks: It is too verbose (real programs may need dozens of different colors, for window background, window foreground, menu background, etc.); and there is no way to predefine common colors, so that, later, the user can simply write something like background = WHITE. To avoid these drawbacks, we will use a table to represent a color: background = {r=0.30, g=0.10, b=0} The use of tables gives more structure to the script; now it is easy for the user (or for the application) to predefine colors for later use in the configuration file: BLUE = {r=0, g=0, b=1} ... background = BLUE To get these values in C, we can do as follows: lua_getglobal(L, "background"); if (!lua_istable(L, -1)) error(L, "`background' is not a valid color table"); red = getfield("r"); green = getfield("g"); blue = getfield("b"); As usual, we first get the value of the global variable background and ensure that it is a table. Next, we use getfield to get each color component. This function is not part of the API; we must define it, as follows: #define MAX_COLOR 255 /* assume that table is on the stack top */ int getfield (const char *key) { int result; lua_pushstring(L, key); lua_gettable(L, -2); /* get background[key] */ if (!lua_isnumber(L, -1)) error(L, "invalid component in background color"); result = (int)lua_tonumber(L, -1) * MAX_COLOR; lua_pop(L, 1); /* remove number */ return result; } Again, we face the problem of polymorphism: There are potentially many versions of getfield functions, varying the key type, value type, error handling, etc. The Lua API offers a single function, lua_gettable. It receives the position of the table in the stack, pops the key from the stack, and pushes the corresponding value. Our private getfield assumes that the table is on the top of the stack; so, after pushing the key (lua_pushstring), the table will be at index -2. Before returning, getfield pops the retrieved value from the stack, to leave the stack at the same level that it was before the call. We will extend our example a little further and introduce color names for the user. The user can still use color tables, but she can also use predefined names for the more common colors. To implement this feature, we need a color table in our C application: struct ColorTable { char *name; unsigned char red, green, blue; } colortable[] = { {"WHITE", MAX_COLOR, MAX_COLOR, MAX_COLOR}, {"RED", MAX_COLOR, 0, 0}, {"GREEN", 0, MAX_COLOR, 0}, {"BLUE", 0, 0, MAX_COLOR}, {"BLACK", 0, 0, 0}, ... {NULL, 0, 0, 0} /* sentinel */ }; Our implementation will create global variables with the color names and initialize these variables using color tables. The result is the same as if the user had the following lines in her script: WHITE = {r=1, g=1, b=1} RED = {r=1, g=0, b=0} ... The only difference from these user-defined colors is that the application defines these colors in C, before running the user script. To set the table fields, we define an auxiliary function, setfield; it pushes the index and the field value on the stack, and then calls lua_settable: /* assume that table is at the top */ void setfield (const char *index, int value) { lua_pushstring(L, index); lua_pushnumber(L, (double)value/MAX_COLOR); lua_settable(L, -3); } Like other API functions, lua_settable works for many different types, so it gets all its operands from the stack. It receives the table index as an argument and pops the key and the value. The setfield function assumes that before the call the table is at the top of the stack (index -1); after pushing the index and the value, the table will be at index -3. The setcolor function defines a single color. It must create a table, set the appropriate fields, and assign this table to the corresponding global variable: void setcolor (struct ColorTable lua_newtable(L); setfield("r", ct->red); setfield("g", ct->green); setfield("b", ct->blue); lua_setglobal(L, ct->name); } *ct) { /* creates a table */ /* table.r = ct->r */ /* table.g = ct->g */ /* table.b = ct->b */ /* `name' = table */ The lua_newtable function creates an empty table and pushes it on the stack; the setfield calls set the table fields; finally, lua_setglobal pops the table and sets it as the value of the global with the given name. With those previous functions, the following loop will register all colors in the application's global environment: int i = 0; while (colortable[i].name != NULL) setcolor(&colortable[i++]); Remember that the application must execute this loop before running the user script. There is another option for implementing named colors. Instead of global variables, the user can denote color names with strings, writing her settings as background = "BLUE". Therefore, background can be either a table or a string. With this implementation, the application does not need to do anything before running the user's script. Instead, it needs more work to get a color. When it gets the value of the variable background, it has to test whether the value has type string, and then look up the string in the color table: lua_getglobal(L, "background"); if (lua_isstring(L, -1)) { const char *name = lua_tostring(L, -1); int i = 0; while (colortable[i].name != NULL && strcmp(colorname, colortable[i].name) != 0) i++; if (colortable[i].name == NULL) /* string not found? */ error(L, "invalid color name (%s)", colorname); else { /* use colortable[i] */ red = colortable[i].red; green = colortable[i].green; blue = colortable[i].blue; } } else if (lua_istable(L, -1)) { red = getfield("r"); green = getfield("g"); blue = getfield("b"); } else error(L, "invalid value for `background'"); What is the best option? In C programs, the use of strings to denote options is not a good practice, because the compiler cannot detect misspellings. In Lua, however, global variables do not need declarations, so Lua does not signal any error when a user misspells a color name. If the user writes WITE instead of WHITE, the background variable receives nil (the value of WITE, a variable not initialized), and that is all that the application knows: that background is nil. There is no other information about what is wrong. With strings, on the other hand, the value of background would be the misspelled string; so, the application can add that information to the error message. The application can also compare strings regardless of case, so that a user can write "white", "WHITE", or even "White". Moreover, if the user script is small and there are many colors, it may be odd to register hundreds of colors (and to create hundreds of tables and global variables) only for the user to choose a few. With strings, you avoid this overhead. 25.2 - Calling Lua Functions A great strength of Lua is that a configuration file can define functions to be called by the application. For instance, you can write an application to plot the graph of a function and use Lua to define the functions to be plotted. The API protocol to call a function is simple: First, you push the function to be called; second, you push the arguments to the call; then you use lua_pcall to do the actual call; finally, you pop the results from the stack. As an example, let us assume that our configuration file has a function like function f (x, y) return (x^2 * math.sin(y))/(1 - x) end and you want to evaluate, in C, z = f(x, y) for given x and y. Assuming that you have already opened the Lua library and run the configuration file, you can encapsulate this call in the following C function: /* call a function `f' defined in Lua */ double f (double x, double y) { double z; /* push functions and arguments */ lua_getglobal(L, "f"); /* function to be called */ lua_pushnumber(L, x); /* push 1st argument */ lua_pushnumber(L, y); /* push 2nd argument */ /* do the call (2 arguments, 1 result) */ if (lua_pcall(L, 2, 1, 0) != 0) error(L, "error running function `f': %s", lua_tostring(L, -1)); /* retrieve result */ if (!lua_isnumber(L, -1)) error(L, "function `f' must return a number"); z = lua_tonumber(L, -1); lua_pop(L, 1); /* pop returned value */ return z; } You call lua_pcall with the number of arguments you are passing and the number of results you want. The fourth argument indicates an error-handling function; we will discuss it in a moment. As in a Lua assignment, lua_pcall adjusts the actual number of results to what you have asked for, pushing nils or discarding extra values as needed. Before pushing the results, lua_pcall removes from the stack the function and its arguments. If a function returns multiple results, the first result is pushed first; so, if there are n results, the first one will be at index -n and the last at index -1. If there is any error while lua_pcall is running, lua_pcall returns a value different from zero; moreover, it pushes the error message on the stack (but still pops the function and its arguments). Before pushing the message, however, lua_pcall calls the error handler function, if there is one. To specify an error handler function, we use the last argument of lua_pcall. A zero means no error handler function; that is, the final error message is the original message. Otherwise, that argument should be the index in the stack where the error handler function is located. Notice that, in such cases, the handler must be pushed in the stack before the function to be called and its arguments. For normal errors, lua_pcall returns the error code LUA_ERRRUN. Two special kinds of errors deserve different codes, because they never run the error handler. The first kind is a memory allocation error. For such errors, lua_pcall always returns LUA_ERRMEM. The second kind is an error while Lua is running the error handler itself. In that case it is of little use to call the error handler again, so lua_pcall returns immediately with a code LUA_ERRERR. 25.3 - A Generic Call Function As a more advanced example, we will build a wrapper for calling Lua functions, using the vararg facility in C. Our wrapper function (let us call it call_va) receives the name of the function to be called, a string describing the types of the arguments and results, then the list of arguments, and finally a list of pointers to variables to store the results; it handles all the details of the API. With this function, we could write our previous example simply as call_va("f", "dd>d", x, y, &z); where the string "dd>d" means "two arguments of type double, one result of type double". This descriptor can use the letters `d´ for double, `i´ for integer, and `s´ for strings; a `>´ separates arguments from the results. If the function has no results, the `>´ is optional. #include <stdarg.h> void call_va (const char *func, const char *sig, ...) { va_list vl; int narg, nres; /* number of arguments and results */ va_start(vl, sig); lua_getglobal(L, func); /* get function */ /* push arguments */ narg = 0; while (*sig) { /* push arguments */ switch (*sig++) { case 'd': /* double argument */ lua_pushnumber(L, va_arg(vl, double)); break; case 'i': /* int argument */ lua_pushnumber(L, va_arg(vl, int)); break; case 's': /* string argument */ lua_pushstring(L, va_arg(vl, char *)); break; case '>': goto endwhile; default: error(L, "invalid option (%c)", *(sig - 1)); } narg++; luaL_checkstack(L, 1, "too many arguments"); } endwhile: /* do the call */ nres = strlen(sig); /* number of expected results */ if (lua_pcall(L, narg, nres, 0) != 0) /* do the call */ error(L, "error running function `%s': %s", func, lua_tostring(L, -1)); /* retrieve results */ nres = -nres; /* stack index of first result */ while (*sig) { /* get results */ switch (*sig++) { case 'd': /* double result */ if (!lua_isnumber(L, nres)) error(L, "wrong result type"); *va_arg(vl, double *) = lua_tonumber(L, nres); break; case 'i': /* int result */ if (!lua_isnumber(L, nres)) error(L, "wrong result type"); *va_arg(vl, int *) = (int)lua_tonumber(L, nres); break; case 's': /* string result */ if (!lua_isstring(L, nres)) error(L, "wrong result type"); *va_arg(vl, const char **) = lua_tostring(L, nres); break; default: error(L, "invalid option (%c)", *(sig - 1)); } nres++; } va_end(vl); } Despite its generality, this function follows the same steps of our previous example: It pushes the function, pushes the arguments, does the call, and gets the results. Most of its code is straightforward, but there are some subtleties. First, it does not need to check whether func is a function; lua_pcall will trigger any occasional error. Second, because it pushes an arbitrary number of arguments, it must check the stack space. Third, because the function may return strings, call_va cannot pop the results from the stack. It is up to the caller to pop them, after it finishes using occasional string results (or after copying them to other buffers). 26 - Calling C from Lua One of the basic means for extending Lua is for the application to register new C functions into Lua. When we say that Lua can call C functions, this does not mean that Lua can call any C function. (There are packages that allow Lua to call any C function, but they are neither portable nor robust.) As we saw previously, when C calls a Lua function, it must follow a simple protocol to pass the arguments and to get the results. Similarly, for a C function to be called from Lua, it must follow a protocol to get its arguments and to return its results. Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way.. An important concept here is that the stack is not a global structure; each function has its own private local stack. When Lua calls a C function, the first argument will always be at index 1 of this local stack. Even when a C function calls Lua code that calls the same (or another) C function again, each of these invocations sees only its own private stack, with its first argument at index 1. 26.1 - C Functions As a first example, let us see how to implement a simplified version of a function that returns the sine of a given number (a more professional implementation should check whether its argument is a number): static int l_sin (lua_State *L) { double d = lua_tonumber(L, 1); /* get argument */ lua_pushnumber(L, sin(d)); /* push result */ } return 1; /* number of results */ Any function registered with Lua must have this same prototype, defined as lua_CFunction in lua.h: typedef int (*lua_CFunction) (lua_State *L); From the point of view of C, a C function gets as its single argument the Lua state and returns (in C) an integer with the number of values it is returning (in Lua). Therefore, the function does not need to clear the stack before pushing its results. After it returns, Lua automatically removes whatever is in the stack below the results. Before we can use this function from Lua, we must register it. We do this magic with lua_pushcfunction: It gets a pointer to a C function and creates a value of type "function" to represent this function inside Lua. A quick-and-dirty way to test l_sin is to put its code directly into the file lua.c and add the following lines right after the call to lua_open: lua_pushcfunction(l, l_sin); lua_setglobal(l, "mysin"); The first line pushes a value of type function. The second line assigns it to the global variable mysin. After these modifications, you rebuild your Lua executable; then you can use the new function mysin in your Lua programs. In the next section, we will discuss better ways to link new C functions with Lua. For a more professional sine function, we must check the type of its argument. Here, the auxiliary library helps us. The luaL_checknumber function checks whether a given argument is a number: In case of errors, it throws an informative error message; otherwise, it returns the number. The modification in our function is minimal: static int l_sin (lua_State *L) { double d = luaL_checknumber(L, 1); lua_pushnumber(L, sin(d)); return 1; /* number of results */ } With the above definition, if you call mysin('a'), you get the message bad argument #1 to `mysin' (number expected, got string) Notice how luaL_checknumber automatically fills the message with the argument number (1), the function name ("mysin"), the expected parameter type ("number"), and the actual parameter type ("string"). As a more complex example, let us write a function that returns the contents of a given directory. Lua does not provide this function in its standard libraries, because ANSI C does not have functions for this job. Here, we will assume that we have a POSIX compliant system. Our function, dir, gets as argument a string with the directory path and returns an array with the directory entries. For instance, a call dir("/home/lua") may return the table {".", "..", "src", "bin", "lib"}. In case of errors, the function returns nil plus a string with the error message. #include <dirent.h> #include <errno.h> static int l_dir (lua_State *L) { DIR *dir; struct dirent *entry; int i; const char *path = luaL_checkstring(L, 1); /* open directory */ dir = opendir(path); if (dir == NULL) { /* error opening the directory? */ lua_pushnil(L); /* return nil and ... */ lua_pushstring(L, strerror(errno)); /* error message */ return 2; /* number of results */ } /* create result table */ lua_newtable(L); i = 1; while ((entry = readdir(dir)) != NULL) { lua_pushnumber(L, i++); /* push key */ lua_pushstring(L, entry->d_name); /* push value */ lua_settable(L, -3); } closedir(dir); return 1; /* table is already on top */ } The luaL_checkstring function, from the auxiliary library, is the equivalent of luaL_checknumber for strings. (In extreme conditions, that implementation of l_dir may cause a small memory leak. Three of the Lua functions it calls can fail due to insufficient memory: lua_newtable, lua_pushstring, and lua_settable. If any of these calls fails, it will raise an error and interrupt l_dir, which therefore will not call closedir. As we discussed earlier, on most programs this is not a big problem: If the program runs out of memory, the best it can do is to shut down anyway. Nevertheless, in Chapter 29 we will see an alternative implementation for a directory function that avoids this problem.) 26.2 - C Libraries A Lua library is a chunk that defines several Lua functions and stores them in appropriate places, typically as entries in a table. A C library for Lua mimics this behavior. Besides the definition of its C functions, it must also define a special function that corresponds to the main chunk of a Lua library. Once called, this function registers all C functions of the library and stores them in appropriate places. Like a Lua main chunk, it also initializes anything else that needs initialization in the library. Lua "sees" C functions through this registration process. Once a C function is represented and stored in Lua, a Lua program calls it through direct reference to its address (which is what we give to Lua when we register a function). In other words, Lua does not depend on a function name, package location, or visibility rules to call a function, once it is registered. Typically, a C library has one single public (extern) function, which is the function that opens the library. All other functions may be private, declared as static in C. When you extend Lua with C functions, it is a good idea to design your code as a C library, even when you want to register only one C function: Sooner or later (usually sooner) you will need other functions. As usual, the auxiliary library offers a helper function for this job. The luaL_openlib function receives a list of C functions and their respective names and registers all of them inside a table with the library name. As an example, suppose we want to create a library with the l_dir function that we defined earlier. First, we must define the library functions: static int l_dir (lua_State *L) { ... /* as before */ } Next, we declare an array with all functions and their respective names. This array has elements of type luaL_reg, which is a structure with two fields: a string and a function pointer. static const struct luaL_reg mylib [] = { {"dir", l_dir}, {NULL, NULL} /* sentinel */ }; In our example, there is only one function (l_dir) to declare. Notice that the last pair in the array must be {NULL, NULL}, to signal its end. Finally, we declare a main function, using luaL_openlib: int luaopen_mylib (lua_State *L) { luaL_openlib(L, "mylib", mylib, 0); return 1; } The second argument to luaL_openlib is the library name. This function creates (or reuses) a table with the given name, and fills it with the pairs name-function specified by the array mylib. The luaL_openlib function also allows us to register common upvalues for all functions in a library. For now, we are not using upvalues, so the last argument in the call is zero. When it returns, luaL_openlib leaves on the stack the table wherein it opened the library. The luaopen_mylib function returns 1 to return this value to Lua. (As with Lua libraries, this return is optional, because the library is already assigned to a global variable. Again, like in Lua libraries, it costs nothing, and may be useful occasionally.) After finishing the library, we must link it to the interpreter. The most convenient way to do it is with the dynamic linking facility, if your Lua interpreter supports this facility. (Remember the discussion about dynamic linking in Section 8.2.) In this case, you must create a dynamic library with your code (a .dll file in Windows, a .so file in Linux). After that, you can load your library directly from within Lua, with loadlib. The call mylib = loadlib("fullname-of-your-library", "luaopen_mylib") transforms the luaopen_mylib function into a C function inside Lua and assigns this function to mylib. (That explains why luaopen_mylib must have the same prototype as any other C function.) Next, the call mylib() runs luaopen_mylib, opening the library. If your interpreter does not support dynamic linking, then you have to recompile Lua with your new library. Besides that, you need some way to tell the stand-alone interpreter that it should open this library when it opens a new state. Some macros facilitate this task. First, you must create a header file (let us call it mylib.h) with the following content: int luaopen_mylib (lua_State *L); #define LUA_EXTRALIBS { "mylib", luaopen_mylib }, The first line declares the open function. The next line defines the macro LUA_EXTRALIBS as a new entry in the array of functions that the interpreter calls when it creates a new state. (This array has type struct luaL_reg[], so we need to put a name there.) To include this header file in the interpreter, you can define the macro LUA_USERCONFIG in your compiler options. For a command-line compiler, you typically must add an option like -DLUA_USERCONFIG=\"mylib.h\" (The backslashes protect the quotes from the shell; those quotes are necessary in C when we specify an include file name.) In an integrated development environment, you must add something similar in the project settings. Then, when you re-compile lua.c, it includes mylib.h, and therefore uses the new definition of LUA_EXTRALIBS in the list of libraries to open. 27 - Techniques for Writing C Functions Both the official API and the auxiliary library provide several mechanisms to help writing C functions. In this chapter, we cover special mechanisms for array manipulation, for string manipulation, and for storing Lua values in C. 27.1 - Array Manipulation "Array", in Lua, is just a name for a table used in a specific way. We can manipulate arrays using the same functions we use to manipulate tables, namely lua_settable and lua_gettable. However, contrary to the general philosophy of Lua, economy and simplicity, the API provides special functions for array manipulation. The reason for that is performance: Frequently we have an array access operation inside the inner loop of an algorithm (e.g., sorting), so that any performance gain in this operation can have a big impact on the overall performance of the function. The functions that the API provides for array manipulation are void lua_rawgeti (lua_State *L, int index, int key); void lua_rawseti (lua_State *L, int index, int key); The description of lua_rawgeti and lua_rawseti is a little confusing, as it involves two indices: index refers to where the table is in the stack; key refers to where the element is in the table. The call lua_rawgeti(L, t, key) is equivalent to the sequence lua_pushnumber(L, key); lua_rawget(L, t); when t is positive (otherwise, you must compensate for the new item in the stack). The call lua_rawseti(L, t, key) (again for t positive) is equivalent to lua_pushnumber(L, key); lua_insert(L, -2); /* put `key' below previous value */ lua_rawset(L, t); Note that both functions use raw operations. They are faster and, anyway, tables used as arrays seldom use metamethods. As a concrete example of the use of these functions, we could rewrite the loop body from our previous l_dir function from lua_pushnumber(L, i++); /* key */ lua_pushstring(L, entry->d_name); /* value */ lua_settable(L, -3); to lua_pushstring(L, entry->d_name); /* value */ lua_rawseti(L, -2, i++); /* set table at key `i' */ As a more complete example, the following code implements the map function: It applies a given function to all elements of an array, replacing each element by the result of the call. int l_map (lua_State *L) { int i, n; /* 1st argument must be a table (t) */ luaL_checktype(L, 1, LUA_TTABLE); /* 2nd argument must be a function (f) */ luaL_checktype(L, 2, LUA_TFUNCTION); n = luaL_getn(L, 1); /* get size of table */ /* /* /* /* push push call t[i] f */ t[i] */ f(t[i]) */ = result */ for (i=1; i<=n; i++) { lua_pushvalue(L, 2); lua_rawgeti(L, 1, i); lua_call(L, 1, 1); lua_rawseti(L, 1, i); } } return 0; /* no results */ This example introduces three new functions. The luaL_checktype function (from lauxlib.h) ensures that a given argument has a given type; otherwise, it raises an error. The luaL_getn function gets the size of the array at the given index (table.getn calls luaL_getn to do its job). The lua_call function does an unprotected call. It is similar to lua_pcall, but in case of errors it throws the error, instead of returning an error code. When you are writing the main code in an application, you should not use lua_call, because you want to catch any errors. When you are writing functions, however, it is usually a good idea to use lua_call; if there is an error, just leave it to someone that cares about it. 27.2 - String Manipulation When a C function receives a string argument from Lua, there are only two rules that it must observe: Not to pop the string from the stack while accessing it and never to modify the string. Things get more demanding when a C function needs to create a string to return to Lua. Now, it is up to the C code to take care of buffer allocation/deallocation, buffer overflow, and the like. Nevertheless, the Lua API provides some functions to help with those tasks. The standard API provides support for two of the most basic string operations: substring extraction and string concatenation. To extract a substring, remember that the basic operation lua_pushlstring gets the string length as an extra argument. Therefore, if you want to pass to Lua a substring of a string s ranging from position i to j (inclusive), all you have to do is lua_pushlstring(L, s+i, j-i+1); As an example, suppose you want a function that splits a string according to a given separator (a single character) and returns a table with the substrings. For instance, the call split("hi,,there", ",") should return the table {"hi", "", "there"}. We could write a simple implementation as follows. It needs no extra buffers and puts no constraints on the size of the strings it can handle. static int l_split (lua_State *L) { const char *s = luaL_checkstring(L, 1); const char *sep = luaL_checkstring(L, 2); const char *e; int i = 1; lua_newtable(L); /* result */ /* repeat for each separator */ while ((e = strchr(s, *sep)) != NULL) { lua_pushlstring(L, s, e-s); /* push substring */ lua_rawseti(L, -2, i++); s = e + 1; /* skip separator */ } /* push last substring */ lua_pushstring(L, s); lua_rawseti(L, -2, i); return 1; } /* return the table */ To concatenate strings, Lua provides a specific function in its API, called lua_concat. It is equivalent to the .. operator in Lua: It converts numbers to strings and triggers metamethods when necessary. Moreover, it can concatenate more than two strings at once. The call lua_concat(L, n) will concatenate (and pop) the n values at the top of the stack and leave the result on the top. Another helpful function is lua_pushfstring: const char *lua_pushfstring (lua_State *L, const char *fmt, ...); It is somewhat similar to the C function sprintf, in that it creates a string according to a format string and some extra arguments. Unlike sprintf, however, you do not need to provide a buffer. Lua dynamically creates the string for you, as large as it needs to be. There are no worries about buffer overflow and the like. The function pushes the resulting string on the stack and returns a pointer to it. Currently, this function accepts only the directives %% (for the character `%´), %s (for strings), %d (for integers), %f (for Lua numbers, that is, doubles), and %c (accepts an integer and formats it as a character). It does not accept any options (such as width or precision). Both lua_concat and lua_pushfstring are useful when we want to concatenate only a few strings. However, if we need to concatenate many strings (or characters) together, a one-by-one approach can be quite inefficient, as we saw in Section 11.6. Instead, we can use the buffer facilities provided by the auxiliary library. Auxlib implements these buffers in two levels. The first level is similar to buffers in I/O operations: It collects small strings (or individual characters) in a local buffer and passes them to Lua (with lua_pushlstring) when the buffer fills up. The second level uses lua_concat and a variant of the stack algorithm that we saw in Section 11.6 to concatenate the results of multiple buffer flushes. To describe the buffer facilities from auxlib in more detail, let us see a simple example of its use. The next code shows the implementation of string.upper, right from the file lstrlib.c: static int str_upper (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_checklstr(L, 1, &l); luaL_buffinit(L, &b); for (i=0; i<l; i++) luaL_putchar(&b, toupper((unsigned char)(s[i]))); luaL_pushresult(&b); return 1; } The first step for using a buffer from auxlib is to declare a variable with type luaL_Buffer, and then to initialize it with a call to luaL_buffinit. After the initialization, the buffer keeps a copy of the state L, so we do not need to pass it when calling other functions that manipulate the buffer. The macro luaL_putchar puts a single character into the buffer. Auxlib also offers luaL_addlstring, to put a string with an explicit length into the buffer, and luaL_addstring, to put a zero-terminated string. Finally, luaL_pushresult flushes the buffer and leaves the final string on the top of the stack. The prototypes of those functions are as follows: void luaL_buffinit (lua_State *L, luaL_Buffer *B); void luaL_putchar (luaL_Buffer *B, char c); void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); void luaL_addstring (luaL_Buffer *B, const char *s); void luaL_pushresult (luaL_Buffer *B); Using these functions, we do not have to worry about buffer allocation, overflows, and other such details. As we saw, the concatenation algorithm is quite efficient. The str_upper function handles huge strings (more than 1 MB) without any problem. When you use the auxlib buffer, you have to worry about one detail. As you put things into the buffer, it keeps some intermediate results in the Lua stack. Therefore, you cannot assume that the stack top will remain where it was before you started using the buffer. Moreover, although you can use the stack for other tasks while using a buffer (even to build another buffer), the push/pop count for these uses must be balanced every time you access the buffer. There is one obvious situation where this restriction is too severe, namely when you want to put into the buffer a string returned from Lua. In such cases, you cannot pop the string before adding it to the buffer, because you should never use a string from Lua after popping it from the stack; but also you cannot add the string to the buffer before popping it, because then the stack would be in the wrong level. In other words, you cannot do something like this: luaL_addstring(&b, lua_tostring(L, 1)); /* BAD CODE */ Because this is a common situation, auxlib provides a special function to add the value on the top of the stack into the buffer: void luaL_addvalue (luaL_Buffer *B); Of course, it is an error to call this function if the value on the top is not a string or a number 27.3 - Storing State in C Functions Frequently,. 27.3.1 - The Registry The registry is always located at a pseudo-index, whose value is defined by LUA_REGISTRYINDEX. A pseudo-index is like an index into the stack, except that its associated value is not in the stack. Most functions in the Lua API that accept indices as arguments also accept pseudo-indices---the exceptions being those functions that manipulate the stack itself, such as lua_remove and lua_insert. For instance, to get a value stored with key "Key" in the registry, you can use the following code: lua_pushstring(L, "Key"); lua_gettable(L, LUA_REGISTRYINDEX); The registry is a regular Lua table. As such, you can index it with any Lua value but nil. However, because all C libraries share the same registry, you must choose with care what values you use as keys, to avoid collisions. A bulletproof method is to use as key the address of a static variable in your code: The C link editor ensures that this key is unique among all libraries. To use this option, you need the function lua_pushlightuserdata, which pushes on the Lua stack a value representing a C pointer. The following code shows how to store and retrieve a number from the registry using this method: /* variable with an unique address */ static const char Key = 'k'; /* store a number */ lua_pushlightuserdata(L, (void *)&Key); /* push address */ lua_pushnumber(L, myNumber); /* push value */ /* registry[&Key] = myNumber */ lua_settable(L, LUA_REGISTRYINDEX); /* retrieve a number */ lua_pushlightuserdata(L, (void *)&Key); /* push address */ lua_gettable(L, LUA_REGISTRYINDEX); /* retrieve value */ myNumber = lua_tonumber(L, -1); /* convert to number */ We will discuss light userdata in more detail in Section 28.5. Of course, you can also use strings as keys into the registry, as long as you choose unique names. String keys are particularly useful when you want to allow other independent libraries to access your data, because all they need to know is the key name. For such keys, there is no bulletproof method of choosing names, but there are some good practices, such as avoiding common names and prefixing your names with the library name or something like it. Prefixes like lua or lualib are not good choices. Another option is to use a universal unique identifier (uuid), as most systems now have programs to generate such identifiers (e.g., uuidgen in Linux). An uuid is a 128-bit number (written in hexadecimal to form a string) that is generated by a combination of the host IP address, a time stamp, and a random component, so that it is assuredly different from any other uuid. 27.3.2 - References may return the value in r again. 27.3.3 - Upvaluesindices. leaves in function counter retrieves the current value of the first (and only) upvalue as a number. Then, function counter pushes. 28 - User-Defined Types in C In the with size 1 only as a placeholder, because C does not allow an array with size 0; we will define the actual size by the space we allocate for the array. For an array with n elements, we need sizeof(NumArray) + (n-1)*sizeof(double) bytes. (We subtract one from n because the original structure already includes space for one element.) 28.1 - Userdata Our first concern is how to represent array values in Lua. Lua provides a basic type specifically for this: userdata. A userdatum offers a raw memory area with no predefined operations in Lua. The Lua API offers the following function to create a userdatum: void *lua_newuserdata (lua_State *L, size_t size); The lua_newuserdata function allocates a block of memory with the given size, pushes the corresponding userdatum on the stack, and returns the block address. If for some reason you need to allocate memory by other means, it is very easy to create a userdatum with the size of a pointer and to store there a pointer to the real memory block. We will see examples of this technique in the next chapter. Using lua_newuserdata, the function that creates new arrays is as follows: static int newarray (lua_State *L) { int n = luaL_checkint(L, 1); size_t nbytes = sizeof(NumArray) + (n - 1)*sizeof(double); NumArray *a = (NumArray *)lua_newuserdata(L, nbytes); a->size = n; return 1; /* new userdatum is already on the stack */ } (The luaL_checkint function is a variant of luaL_checknumber for integers.) Once newarray is registered in Lua, you can create new arrays with a statement like a = array.new(1000). To store an entry, we will use a call like array.set(array, index, value). Later we will see how to use metatables to support the more conventional syntax array[index] = value. For both notations, the underlying function is the same. It assumes that indices start at 1, as is usual in Lua. static int setarray (lua_State *L) { NumArray *a = (NumArray *)lua_touserdata(L, 1); int index = luaL_checkint(L, 2); double value = luaL_checknumber(L, 3); luaL_argcheck(L, a != NULL, 1, "`array' expected"); luaL_argcheck(L, 1 <= index && index <= a->size, 2, "index out of range"); a->values[index-1] = value; return 0; } The luaL_argcheck function checks a given condition, raising an error if necessary. So, if we call setarray with a bad argument, we get an elucidative error message: array.set(a, 11, 0) --> stdin:1: bad argument #1 to `set' (`array' expected) The next function retrieves an entry: static int getarray (lua_State *L) { NumArray *a = (NumArray *)lua_touserdata(L, 1); int index = luaL_checkint(L, 2); luaL_argcheck(L, a != NULL, 1, "`array' expected"); luaL_argcheck(L, 1 <= index && index <= a->size, 2, "index out of range"); lua_pushnumber(L, a->values[index-1]); return 1; } We define another function to retrieve the size of an array: static int getsize (lua_State *L) { NumArray *a = (NumArray *)lua_touserdata(L, 1); luaL_argcheck(L, a != NULL, 1, "`array' expected"); lua_pushnumber(L, a->size); return 1; } Finally, we need some extra code to initialize our library: static const struct luaL_reg arraylib [] = { {"new", newarray}, {"set", setarray}, {"get", getarray}, {"size", getsize}, {NULL, NULL} }; int luaopen_array (lua_State *L) { luaL_openlib(L, "array", arraylib, 0); return 1; } Again, we use luaL_openlib, from the auxiliary library. It creates a table with the given name ("array", in our example) and fills it with the pairs name-function specified by the array arraylib. After opening the library, we are ready to use our new type in Lua: a = array.new(1000) print(a) --> userdata: 0x8064d48 print(array.size(a)) --> 1000 for i=1,1000 do array.set(a, i, 1/i) end print(array.get(a, 10)) --> 0.1 Running this implementation on a Pentium/Linux, an array with 100K elements takes 800 KB of memory, as expected; an equivalent Lua table needs more than 1.5 MB. 28.2 - Metatables Our current implementation has a major security hole. Suppose the user writes something like array.set(io.stdin, 1, 0). The value in io.stdin is a userdatum with a pointer to a stream (FILE*). Because it is a userdatum, array.set will gladly accept it as a valid argument; the probable result will be a memory corruption (with luck you can get an index-out-of-range error instead). Such behavior is unacceptable for any Lua library. No matter how you use a C library, it should not corrupt C data or produce a core dump from Lua. To distinguish arrays from other userdata, we create a unique metatable for it. (Remember that userdata can also have metatables.) Then, every time we create an array, we mark it with this metatable; and every time we get an array, we check whether it has the right metatable. Because Lua code cannot change the metatable of a userdatum, it cannot fake our code. We also need a place to store this new metatable, so that we can access it to create new arrays and to check whether a given userdatum is an array. As we saw earlier, there are two common options for storing the metatable: in the registry, or as an upvalue for the functions in the library. It is customary, in Lua, to register any new C type into the registry, using a type name as the index and the metatable as the value. As with any other registry index, we must choose a type name with care, to avoid clashes. We will call this new type "LuaBook.array". As usual, the auxiliary library offers some functions to help us here. The new auxiliary functions we will use are int luaL_newmetatable (lua_State *L, const char *tname); void luaL_getmetatable (lua_State *L, const char *tname); void *luaL_checkudata (lua_State *L, int index, const char *tname);.) The luaL_getmetatable function retrieves the metatable associated with tname from the registry. Finally, luaL_checkudata checks whether the object at the given stack position is a userdatum with a metatable that matches the given name. It returns NULL if the object does not have the correct metatable (or if it is not a userdata); otherwise, it returns the userdata address. Now we can start our implementation. The first step it to change the function that opens the library. The new version must create a table to be used as the metatable for arrays: int luaopen_array (lua_State *L) { luaL_newmetatable(L, "LuaBook.array"); luaL_openlib(L, "array", arraylib, 0); return 1; } The next step is to change newarray so that it sets this metatable in all arrays that it creates: static int newarray (lua_State *L) { int n = luaL_checkint(L, 1); size_t nbytes = sizeof(NumArray) + (n - 1)*sizeof(double); NumArray *a = (NumArray *)lua_newuserdata(L, nbytes); luaL_getmetatable(L, "LuaBook.array"); lua_setmetatable(L, -2); a->size = n; return 1; /* new userdatum is already on the stack */ } The lua_setmetatable function pops a table from the stack and sets it as the metatable of the object at the given index. In our case, this object is the new userdatum. Finally, setarray, getarray, and getsize have to check whether they got a valid array as their first argument. Because we want to raise an error in case of wrong arguments, we define the following auxiliary function: static NumArray *checkarray (lua_State *L) { void *ud = luaL_checkudata(L, 1, "LuaBook.array"); luaL_argcheck(L, ud != NULL, 1, "`array' expected"); return (NumArray *)ud; } Using checkarray, the new definition for getsize is straightforward: static int getsize (lua_State *L) { NumArray *a = checkarray(L); lua_pushnumber(L, a->size); return 1; } Because setarray and getarray also share code to check the index as their second argument, we factor out their common parts in the following function: static double *getelem (lua_State *L) { NumArray *a = checkarray(L); int index = luaL_checkint(L, 2); luaL_argcheck(L, 1 <= index && index <= a->size, 2, "index out of range"); /* return element address */ return &a->values[index - 1]; } After the definition of getelem, setarray and getarray are straightforward: static int setarray (lua_State *L) { double newvalue = luaL_checknumber(L, 3); *getelem(L) = newvalue; return 0; } static int getarray (lua_State *L) { lua_pushnumber(L, *getelem(L)); return 1; } Now, if you try something like array.get(io.stdin, 10), you will get a proper error message: error: bad argument #1 to `getarray' (`array' expected) 28.3 - Object-Oriented Access Our next step is to transform our new type into an object, so that we can operate on its instances using the usual object-oriented syntax, such as a = array.new(1000) print(a:size()) --> 1000 a:set(10, 3.4) print(a:get(10)) --> 3.4 Remember that a:size() is equivalent to a.size(a). Therefore, we have to arrange for the expression a.size to return our getsize function. The key mechanism here is the __index metamethod. For tables, this metamethod is called whenever Lua cannot find a value for a given key. For userdata, it is called in every access, because userdata have no keys at all. Assume that we run the following code: local metaarray = getmetatable(array.new(1)) metaarray.__index = metaarray metaarray.set = array.set metaarray.get = array.get metaarray.size = array.size In the first line, we create an array only to get its metatable, which we assign to metaarray. (We cannot set the metatable of a userdata from Lua, but we can get its metatable without restrictions.) Then we set metaarray.__index to metaarray. When we evaluate a.size, Lua cannot find the key "size" in object a, because the object is a userdatum. Therefore, Lua will try to get this value from the field __index of the metatable of a, which happens to be metaarray itself. But metaarray.size is array.size, so a.size(a) results in array.size(a), as we wanted. Of course, we can write the same thing in C. We can do even better: Now that arrays are objects, with their own operations, we do not need to have those operations in the table array anymore. The only function that our library still has to export is new, to create new arrays. All other operations come only as methods. The C code can register them directly as such. The operations getsize, getarray, and setarray do not change from our previous approach. What will change is how we register them. That is, we have to change the function that opens the library. First, we need two separate function lists, one for regular functions and one for methods: static const struct luaL_reg arraylib_f [] = { {"new", newarray}, {NULL, NULL} }; static const struct luaL_reg arraylib_m [] = { {"set", setarray}, {"get", getarray}, {"size", getsize}, {NULL, NULL} }; The new version of luaopen_array, the function that opens the library, has to create the metatable, to assign it to its own __index field, to register all methods there, and to create and fill the array table: int luaopen_array (lua_State *L) { luaL_newmetatable(L, "LuaBook.array"); lua_pushstring(L, "__index"); lua_pushvalue(L, -2); /* pushes the metatable */ lua_settable(L, -3); /* metatable.__index = metatable */ luaL_openlib(L, NULL, arraylib_m, 0); luaL_openlib(L, "array", arraylib_f, 0); return 1; } Here we use another feature from luaL_openlib. In the first call, when we pass NULL as the library name, luaL_openlib does not create any table to pack the functions; instead, it assumes that the package table is on the stack, below any occasional upvalues. In this example, the package table is the metatable itself, which is where luaL_openlib will put the methods. The next call to luaL_openlib works regularly: It creates a new table with the given name (array) and registers the given functions there (only new, in this case). As a final touch, we will add a __tostring method to our new type, so that print(a) prints array plus the size of the array inside parentheses (for instance, array(1000)). The function itself is here: int array2string (lua_State *L) { NumArray *a = checkarray(L); lua_pushfstring(L, "array(%d)", a->size); return 1; } The lua_pushfstring function formats the string and leaves it on the stack top. We also have to add array2string to the list arraylib_m, to include it in the metatable of array objects: static const struct luaL_reg arraylib_m [] = { {"__tostring", array2string}, {"set", setarray}, ... }; 28.4 - Array Access An alternative to the object-oriented notation is to use a regular array notation to access our arrays. Instead of writing a:get(i), we could simply write a[i]. For our example, this is easy to do, because our functions setarray and getarray already receive their arguments in the order that they are given to the respective metamethods. A quick solution is to define those metamethods right into our Lua code: local metaarray = getmetatable(newarray(1)) metaarray.__index = array.get metaarray.__newindex = array.set (We must run that code on the original implementation for arrays, without the modifications for object-oriented access.) That is all we need to use the usual syntax: a = array.new(1000) a[10] = 3.4 -- setarray print(a[10]) -- getarray --> 3.4 If we prefer, we can register those metamethods in our C code. For that, we change again our initialization function: int luaopen_array (lua_State *L) { luaL_newmetatable(L, "LuaBook.array"); luaL_openlib(L, "array", arraylib, 0); /* now the stack has the metatable at index 1 and `array' at index 2 */ lua_pushstring(L, "__index"); lua_pushstring(L, "get"); lua_gettable(L, 2); /* get array.get */ lua_settable(L, 1); /* metatable.__index = array.get */ lua_pushstring(L, "__newindex"); lua_pushstring(L, "set"); lua_gettable(L, 2); /* get array.set */ lua_settable(L, 1); /* metatable.__newindex = array.set */ } return 0;.) 29 - Managing Resources In our implementation of arrays in the previous chapter, we did not need to worry about managing resources. They need only memory. Each userdatum representing an array has its own memory, which is managed by Lua. When an array becomes garbage (that is, inaccessible by the program), Lua eventually collects it and frees its memory. Life is not always that easy. Sometimes, an object needs other resources besides raw memory, such as file descriptors, window handles, and the like. (Often these resources are just memory too, but managed by some other part of the system). In such cases, when the object becomes garbage and is collected, somehow those other resources must be released too. Several OO languages provide a specific mechanism (called finalizer or destructor) for that need. Lua provides finalizers in the form of the __gc metamethod. This metamethod only works for userdata values. When a userdatum is about to be collected and its metatable has a __gc field, Lua calls the value of this field (which should be a function), passing as an argument the userdatum itself. This function can then release any resource associated with that userdatum. To illustrate the use of this metamethod and of the API as a whole, in this chapter we will develop two bindings from Lua to external facilities. The first example is another implementation for a function to traverse a directory. The second (and more substantial) example is a binding to Expat, an open source XML parser. 29.1 - A Directory Iterator Previously, we implemented a dir function that returned a table with all files from a given directory. Our new implementation will return an iterator that returns a new entry each time it is called. With this new implementation, we will be able to traverse a directory with a loop like this one: for fname in dir(".") do print(fname) end To iterate over a directory, in C, we need a DIR structure. Instances of DIR are created by opendir and must be explicitly released by a call to closedir. Our previous implementation of dir kept its DIR instance as a local variable and closed that instance after retrieving the last file name. Our new implementation cannot keep this DIR instance in a local variable, because it must query this value over several calls. Moreover, it cannot close the directory only after retrieving the last name; if the program breaks the loop, the iterator will never retrieve this last name. Therefore, to make sure that the DIR instance is always released, we store its address in a userdatum and use the __gc metamethod of this userdatum to release the directory structure. Despite its central role in our implementation, this userdatum representing a directory does not need to be visible from Lua. The dir function returns an iterator function; this is what Lua sees. The directory may be an upvalue of the iterator function. As such, the iterator function has direct access to this structure, but Lua code has not (and does not need to). In all, we need three C functions. First, we need the dir function, a factory that Lua calls to create iterators; it must open a DIR structure and put it as an upvalue of the iterator function. Second, we need the iterator function. Third, we need the __gc metamethod, which closes a DIR structure. As usual, we also need an extra function to make initial arrangements, such as to create a metatable for directories and to initialize this metatable. Let us start our code with the dir function: #include <dirent.h> #include <errno.h> /* forward declaration for the iterator function */ static int dir_iter (lua_State *L); static int l_dir (lua_State *L) { const char *path = luaL_checkstring(L, 1); /* create a userdatum to store a DIR address */ DIR **d = (DIR **)lua_newuserdata(L, sizeof(DIR *)); /* set its metatable */ luaL_getmetatable(L, "LuaBook.dir"); lua_setmetatable(L, -2); /* try to open the given directory */ *d = opendir(path); if (*d == NULL) /* error opening the directory? */ luaL_error(L, "cannot open %s: %s", path, strerror(errno)); /* creates and returns the iterator function (its sole upvalue, the directory userdatum, is already on the stack top */ lua_pushcclosure(L, dir_iter, 1); return 1; } A subtle point here is that we must create the userdatum before opening the directory. If we first open the directory, and then the call to lua_newuserdata raises an error, we lose the DIR structure. With the correct order, the DIR structure, once created, is immediately associated with the userdatum; whatever happens after that, the __gc metamethod will eventually release the structure. The next function is the iterator itself: static int dir_iter (lua_State *L) { DIR *d = *(DIR **)lua_touserdata(L, lua_upvalueindex(1)); struct dirent *entry; if ((entry = readdir(d)) != NULL) { lua_pushstring(L, entry->d_name); return 1; } else return 0; /* no more values to return */ } The __gc metamethod closes a directory, but it must take one precaution: Because we create the userdatum before opening the directory, this userdatum will be collected whatever the result of opendir. If opendir fails, there will be nothing to close. static int dir_gc (lua_State *L) { DIR *d = *(DIR **)lua_touserdata(L, 1); if (d) closedir(d); return 0; } Finally, there is the function that opens this one-function library: int luaopen_dir (lua_State *L) { luaL_newmetatable(L, "LuaBook.dir"); /* set its __gc field */ lua_pushstring(L, "__gc"); lua_pushcfunction(L, dir_gc); lua_settable(L, -3); /* register the `dir' function */ lua_pushcfunction(L, l_dir); lua_setglobal(L, "dir"); return 0; } This whole example has an interesting subtlety. At first, it may seem that dir_gc should check whether its argument is a directory. Otherwise, a malicious user could call it with another kind of userdata (a file, for instance), with disastrous consequences. However, there is no way for a Lua program to access this function: It is stored only in the metatable of directories and Lua programs never access those directories. 29.2 - An XML Parser Now endelement is optional; we will use NULLterminated; function With) for l in io.lines() do assert(p:parse(l)) assert(p:parse("\n")) end assert(p:parse()) p:close() -- create new parser -- iterate over input lines -- parse the line -- add a newline -- finish document function has four main steps: • Its first step follows a common pattern: It first creates a userdatum; then it pre-initializes the userdatum with consistent values; and finally sets its metatable. The reason for the preinitialization is subtle: If there is any error during the initialization, we must make sure that the finalizer (the __gc metamethod) will find the userdata in a consistent state. • In step 2, the function creates an Expat parser, stores it in the userdatum, and checks for errors. • Step 3 ensures that the first argument to the function is actually a table (the callback table), creates a reference to it, and stores the reference into the new userdatum. • The last step initializes the Expat parser. It sets the userdatum as the object to be passed to callback functions and it sets the callback functions. Notice that these callback functions are the same for all parsers; after all, it is impossible to dynamically create new functions in C. Instead, these fixed C functions will use the callback table to decide which Lua functions they should call each time._parse calls XML_Parse, the latter function will call the handlers for each relevant element that it finds in the given piece of document. Therefore, lxp_parse first prepares an environment for these handlers. There is one more detail in the call to XML_Parse: Remember that the last argument to this function tells Expat whether the given piece of text is the last one. When we call parse without an argument sdata structure as their first argument, due to our call to XML_SetUserData when follows: close.; }
https://www.scribd.com/document/81378046/Programming-in-Lua-First-Edition
CC-MAIN-2017-13
refinedweb
33,871
62.88
Exception restrictions Posted on March 1st, 2001. This example demonstrates the kinds of restrictions imposed (at compile time) for exceptions: //: { Inning() throws BaseballException {} void event () throws BaseballException { // Doesn't actually have to throw anything } abstract void atBat() throws Strike, Foul; void walk() {} // Throws nothing } class StormException extends Exception {} class RainedOut extends StormException {} class PopFoul extends Foul {} interface Storm { void event() throws RainedOut; void rainHard() throws RainedOut; } public class StormyInning extends Inning implements Storm { // OK to add new exceptions for constructors, // but you must deal with the base constructor // exceptions: StormyInning() throws RainedOut, BaseballException {} base version does: public void event() {} // Overridden methods can throw // inherited exceptions: void atBat() throws PopFoul {} public static void main(String[] args) { try { StormyInning si = new StormyInning(); si.atBat(); } catch(PopFoul e) { } catch(RainedOut e) { } catch(BaseballException e) {} // Strike not thrown in derived version. try { // What happens if you upcast? Inning i = new StormyInning(); i.atBat(); // You must catch the exceptions from the // base-class version of the method: } catch(Strike e) { } catch(Foul e) { } catch(RainedOut e) { } catch(BaseballException e) {} } } ///:~ In Inning, you can see that both the constructor and the event( ) method say they will throw an exception, but they never do. This is legal because it allows you to force the user to catch any exceptions that you might add in overridden versions of event( ). The same idea holds for abstract methods, as seen in atBat( ). The interface Storm is interesting because it contains one method ( event( ))that is defined in Inning, and one method that isn’t. Both methods throw a new type of exception, RainedOut. When StormyInning extends Inning and implements Storm , you’ll see that the event( ) method in Storm cannot change the exception interface of event( ) in Inning. Again, this makes sense because otherwise you’d never know if you were catching the correct thing when working with the base class. Of course, if a method described in an interface is not in the base class, such as rainHard( ), then there’s no problem if it throws exceptions.. The reason StormyInning.walk( ) will not compile is that it throws an exception, while Inning.walk( ) does not. If this was allowed, then you could write code that called Inning.walk( ) and that didn’t. The overridden event( ) method shows that a derived-class version of a method may choose to not throw any exceptions, even if the base-class version does. Again, this is fine since it doesn’t break any code that is written assuming the base-class version throws exceptions. Similar logic applies to atBat( ), which throws PopFoul, an exception that is derived from Foul thrown by the base-class version of atBat( ). This way, if someone writes code that works with Inning and calls atBat( ), they must catch the Foul exception. Since PopFoul is derived from Foul, the exception handler will also catch PopFoul. The last point of interest is in main( ). Here you can see that if you] It’s useful to realize that although exception specifications are enforced by the compiler during inheritance, the exception specifications are not part of the type of a method, which is comprised of only the method name and argument types. Therefore, you cannot overload methods based on exception specifications. In addition, because an exception specification exists in a base-class version of a method doesn’t mean that it must exist in the derived-class version of the method, and this is quite different from inheriting the methods (that is, a method in the base class must also exist in the derived class). Put another way, the “exception specification interface” for a particular method may narrow during inheritance and overriding, but it may not widen – this is precisely the opposite of the rule for the class interface during inheritance. [43] ANSI/ISO C++ added similar constraints that require derived-method exceptions to be the same as, or derived from, the exceptions thrown by the base-class method. This is one case in which C++ is actually able to check exception specifications at compile time. There are no comments yet. Be the first to comment!
http://www.codeguru.com/java/tij/tij0101.shtml
CC-MAIN-2016-26
refinedweb
684
59.23
Firebase Rules for Cloud Firestore to limit maximum number of documents I have following use case.. I don't want to allow user control document limit in cloud firestore, I want to have firebase rule restrict it. For eg. I have a products collection, user can do pagination (max=10) per page. if its browser side, user can easily change and get all the products list. Is there any settings or rules to control this? 1 answer - answered 2018-01-11 20:58 Michael Bleigh You can protect this using the queryproperty of the requestobject (see docs). Basically you can write a rule with a condition on the limit: allow read: if request.query.limit != 10 The above rule will prevent the query from going through if the limit is not set to 10. See also questions close to this topic -! - Fields under custom object in Cloud Firestore have null value. How to avoid this? I the have the following model class: public class UserModel { private String userEmail, userName; public UserModel() {} public UserModel(String userEmail) { this.userEmail = userEmail; } public UserModel(String userEmail, String userName) { this.userEmail = userEmail; this.userName = userName; } //setters and getters } If I use the constructor with two arguments, both fields are correctly populated. If I use the constructor with only one argument, only first field is populated and the second has the value of null. In Firebase Realtime database, if a field has the value of null, it's not present at all in the database. What can be done to exclude the fields with nullvalues to be added in Cloud Firestore? If there is no way, the presence of these values are affecting the database somehow? This is how my documents look like: - Query comparisons with null field My Firestore collection has documents with a string field, which can be null. I was expecting that if I query: Collection("products").Where("producedDate", "<", "2018-01-15") I would get all products whose "producedDate" is earlier than "2018-10-15", including those whose "producedDate" is null. But actually I am not getting the nulls. Is this intended or it's a bug? - How to keep\add\update multiple values in the same filed inside a document in Firestore
http://codegur.com/48215678/firebase-rules-for-cloud-firestore-to-limit-maximum-number-of-documents
CC-MAIN-2018-05
refinedweb
370
65.83
Input/output Stdin and stdout You remember using cout to display a message. You can use cin to do the opposite: get input from the user. It works like this (notice the >> of cin, which are opposite those of cout): int x; cout << "Give me a number: "; cin >> x; cout << "You gave me the number " << x << endl; You can use cin for integer types, floating point types, string types, and others. It’s easiest if you ask the user to enter one value at a time, pressing Enter between each value. To acquire multiple values at once, just string them together with cin: int x; double y; short z; cout << "Enter three numeric values: "; cin >> x >> y >> z; This is equivalent to: int x; double y; short z; cout << "Enter three numeric values: "; cin >> x; cin >> y; cin >> z; More examples: double a; int x; bool p; cout << "Enter a decimal value: "; cin >> a; cout << "Enter an integer value: "; cin >> x; cout << "Enter a 0 for FALSE, anything else for TRUE: "; cin >> p; cin only collects input up to the first space or newline. It can be used to obtain multiple inputs. It knows when to delimit (i.e. start looking for the next input) when it reaches a space or newline (or tab). Here’s the same example as above, but using just one cin: double a; int x; bool p; cout << "Enter a decimal, integer, and boolean value: "; cin >> a >> x >> p; We can get strings in the usual way: string word; cout << "Enter a word: "; cin >> word; However, using that technique, you cannot get strings that have spaces. To get strings that have spaces in them, we have to use this method: string s; // get a whole line of text from the user // and save into the variable s getline(cin, s); That method gets a whole line of text, which could have spaces. Printing with precision When printing “floating-point values” (such as floats, doubles, etc.) we often need to show a specific number of digits after the decimal point. This is known as the “precision” of the number. The actual precision of the value will not change; we will only change the printed precision. The following will show three digits after the decimal point: cout.precision(3); cout.setf(ios::fixed, ios::floatfield); Here is a complete example: #include <iostream> using namespace std; int main() { double x; cout << "Enter value for x: "; cin >> x; cout.precision(3); cout.setf(ios::fixed, ios::floatfield); cout << "You entered " << x << endl; return 0; } For example, Enter value for x: 4.444444 You entered 4.444 Enter value for x: 0.0000001 You entered 0.000 Enter value for x: 123.45678 You entered 123.457 Notice how the last printout rounded up; the value of “x” inside the program has not changed, however. File Input #include <fstream> Basic operations ifstream f("myfile.txt"); // read as text if(f.is_open()) { } f.close(); ifstream f("myfile.bin", ios::in | ios::binary); // read as binary data If you have your filename in a string, you have to convert it to a “C-style” (old-style) string first: string filename = "myfile.txt"; ifstream f(filename.c_str()); Reading ASCII reading is just like cin: int x; f >> x; Binary reading reads into char arrays (byte arrays). The amount to read must always be specified: char title[31]; // reserve space for a terminating \0 f.read(title, 30); title[30] = 0; // set the terminating \0 Seeking You can jump to some byte position in the file with seekg: f.seekg(52); // go to byte 52 Boost Filesystem library The Boost Filesystem library provides cross-platform access to files and directories (standard C++ does not). #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> using namespace boost::filesystem; Here are some of the things you can do with a path: path p("somedir/somefile.txt"); bool ex = exists(p); int size = file_size(p); string pathstr = p.string(); string ext = p.extension(); Here is how to read a directory (doing this recursively is left as an exercise for the reader): path p("testdir"); for(directory_iterator it(p); it != directory_iterator(); ++it) { path p2 = it->path(); if(is_directory(p2)) { } else if(is_regular_file(p2)) { } } When compiling, be sure to include the Boost Filesystem library with -lboost_filesystem -lboost_system: g++ -Wall -ansi -o simple-ls -lboost_filesystem -lboost_system simple-ls.cpp Example: Hexdump #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> using namespace boost::filesystem; using namespace std; int main() { int offset = 1024; string filename = "test.bin"; path p(filename); if(exists(p)) { ifstream f(filename.c_str(), ios::binary); if(f.is_open()) { f.seekg(offset); char bs[16]; int filelength = file_size(p); for(int pos = offset; pos < filelength; pos += 16) { cout << hex << setfill('0') << setw(8) << pos << " "; f.read(bs, 16); for(int i = 0; i < 16; i++) { cout << hex << setfill('0') << setw(2) << (int)(unsigned char)bs[i] << " "; if(i == 7) { cout << " "; } } cout << " |"; for(int i = 0; i < 16; i++) { if(bs[i] >= 32 && bs[i] <= 126) { cout << bs[i]; } else { cout << "."; } } cout << "|" << endl; } f.close(); } else { cout << "File cannot be opened." << endl; } } else { cout << "File doesn't exist." << endl; } return 0; }
http://csci221.artifice.cc/lecture/input-output.html
CC-MAIN-2017-30
refinedweb
872
64.1
Create your rqt plugin packageDescription: Entry point for creating your rqt plugin either in python or C++. Tutorial Level: BEGINNER Next Tutorial: rqt/Tutorials/Writing a Python Plugin rqt/Tutorials/Writing a C++ Plugin Contents - Intro - Prerequisite & assumption - Steps to create rqt plugin pkg - Write a plugin code - Install & Run your plugin - Option Intro This tutorial will show you how to create a plugin to integrate your custom user interface into ROS' GUI framework rqt. When you want to run your code after writing it, refer to rqt/UserGuide about how to run and so on. A complete set of all files in this tutorial using python is available ongithub. These rqt plugins are also useful because they bring up than an empty widget. For example rqt_bag. Refer to the Usability Resources for design guidelines. Prerequisite & assumption - Have QWidget-based GUI that you want to integrate into ROS by using rqt. Assumes ROS groovy or later, and catkin as a buildsystem by default. For fuerte, this thread might be of your help. - This tutorial is written based on Ubuntu 12.10 (initiated on 3/12/2013) Examples in this page use python. With C++, replace rqt_gui_py with rqt_gui_cpp Steps to create rqt plugin pkg Create an Empty Package Before getting started, let's create an empty package to called rqt_mypkg, somewhere in your package path.: roscreate-pkg rqt_mypkg rospy rqt_gui rqt_gui_py catkin_create_pkg rqt_mypkg rospy rqt_gui rqt_gui_py Modify package.xml Add export tag So your plugin can be discovered, you must declare the plugin in either package.xml for catkin, or manifest.xml for rosbuild: 1 <package> 2 : 3 <!-- all the existing tags --> 4 <export> 5 <rqt_gui plugin="${prefix}/plugin.xml"/> 6 </export> 7 : 8 </package> Complete `package.xml` example. Remove build_depend (Optional) If you're writing your plugin in python that doesn't require building, you can omit build_depend tags. Create plugin.xml file Then you create the referenced file plugin.xml with additional meta information regarding the plugin: 1 <library path="src"> 2 <class name="My Plugin" type="rqt_mypkg.my_module.MyPlugin" base_class_type="rqt_gui_py::Plugin"> 3 <description> 4 An example Python GUI plugin to create a great user interface. 5 </description> 6 <qtgui> 7 <!-- optional grouping... 8 <group> 9 <label>Group</label> 10 </group> 11 <group> 12 <label>Subgroup</label> 13 </group> 14 --> 15 <label>My first Python Plugin</label> 16 <icon type="theme">system-help</icon> 17 <statustip>Great user interface to provide real value.</statustip> 18 </qtgui> 19 </class> 20 </library> Consider the available plugins and their grouping when deciding where to place your plugin. Attributes of library element in plugin.xml Usually you can just copy the example and modify wherever you feel necessary to get the plugin to work. Here are some explanations about xml attributes of the library element for those who need to know more. /library@path - The package-relative path which gets added to sys.path. /library/class@name - The name of the plugin, which must be unique within a package. /library/class@type - The concatenated name of the package, module and class, which is used for the import statement. (Form: package.module.class) /library/class@base_class_type For Python plugins which use the rospy client library the value is rqt_gui_py::Plugin. /library/description - The description of the plugin. /library/qtgui - This tag contains additional optional information about the package. If none are provided, the name of the plugin is used as the label for the plugin in the menu and the description is displayed as a status tip. /library/qtgui/group (optional, multiple) Enables grouping of plugins. Group tags can contain a label, icon and statustip tag. The groups form a hierarchy of menus where the plugin is added as the leaf. The groups of different plugins are merged based on their label (icons and statustip may be overridden by other plugins when they are defined differently). /library/qtgui/label - Overrides the label with which the plugin appears in the menu. /library/qtgui/icon - Defines the icon that should be shown beside the label (depending on the type of attribute). /library/qtgui/icon@type file (default): the icon value is a package-relative path to an image. theme: the icon value names an icon defined by the Icon Naming Specification. resource: the icon value names a Qt resource. /library/qtgui/statustip - Overrides the status tip that is shown when hovering over the plugin label. Write a plugin code Writing code is explained on separate pages for python | C++ respectively. Coding rule for rqt Mostly follow the general ROS coding style guide C++ | Python - List dependency, import in an alphabetical order rqt in python defines some rules Also, python in rqt defines documenting rules here. Choice of programming language in rqt Mainly because of the ease of maitainance, many rqt plugins are written in python, and it is strongly recommended for new plugins to be written in python. C++ is completely acceptable in rqt. Only if: you need the extra performance of C++ or want to access libraries only available in C++ (i.e. rqt_image_view) you are far more comfortable with C++ than Python You can find out in which language the existing rqt plugins are written at rqt/Plugins page. Go to the page of each plugin and find its source repository where you can look at the source code. Install & Run your plugin See the Running rqt section for how to run your plugin. With catkin, no matter which method in the link above you want to run your plugin, you need to install it via CMake which puts the script into a package-specific folder which is not on the PATH. Add macros to your setup.py (reference). For example, after adding the line the section that contains it might look like : from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rqt_mypkg'], package_dir={'': 'src'}, ) setup(**d) Also make sure in your CMakeLists.txt, to uncomment a line: catkin_python_setup() Add install macro that puts the script into a location where it is rosrun-able is declared. For example: install(PROGRAMS scripts/rqt_mypkg DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) Add the following lines to call the resource and plugin.xml install(DIRECTORY resource DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) install(FILES plugin.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) These scripts can be run by: $ rosrun rqt_mypkg rqt_mypkg Detail for rosbuild is TBD. Ask maintainers if you need to know immediately, or feel free to modify this wiki once you figure it out.. A very short description how to install your plugin in fuerte (because catkin does not work very well in fuerte) can be found at: If your plugin does not show up under the Plugins menu when you launch rqt, you may need to run: rqt --force-discover Option Do not forget to add enough info into package.xml, just as with every ROS package. Unit testing rqt plugins Needless to say, making & maintaining unit test codes is strongly recommended, but not required. Unit test codes can be best stored under /test folder on the root directory of a package. Area covered by unit testing can only be business & application logic. There seems to be no convenient way to do unit test for visual components (ref). If you have better idea, please open a discussion in rqt community. This is very interesting topic. For integrated test, using rosunit is highly recommended. To run your plugin directly You can add your rqt plugin to the system PATH so that you can run it on-the-fly without using other tools such as rosrun, rqt_gui and so on. It is not, however, recommended to put it to PATH in order to keep system common space cleaner. Only if you dare to do so, there's a way. Running custom rqt plugins directly is NOT recommended (discussion 1, 2, 3). Do this only when you're really in need. Add 1 line: scripts=['%RELATIVE_PATH_TOYOUR_EXECUTABLE%'] to your setup.py (reference). For example after adding the line the section that contains it might look like : d = generate_distutils_setup( packages=['rqt_mypkg'], package_dir={'': 'src'}, scripts=['scripts/rqt_mypkg'] ) Once you're done, run: $ cd %TOPDIR_YOUR_CATKIN_WS% $ catkin_make This will yield a relay script to %TOPDIR_YOUR_CATKIN_WS%devel/bin, which you can call if you're already sourced %TOPDIR_YOUR_CATKIN_WS%devel/setup.bash% (or similar, as you wish). Practices to follow on making rqt plugins - Same as general GUI development, you should pay attention to from which thread you're updating GUI. Although nodes that are instantiated from rqt plugins run as different thread in the same process, callback function that is given to node handler (NodeHandle in C++ / rospy.Subscriber (for example)) runs in the main thread, which enables to update GUI from there. Apply common GUI software architecture (eg. MVC) For the same reason, you should ideally separate Plugin class (rqt_gui_cpp::Plugin or rqt_gui_py.plugin.Plugin) and your widgets' implementation.
https://wiki.ros.org/rqt/Tutorials/Create%20your%20new%20rqt%20plugin
CC-MAIN-2021-25
refinedweb
1,470
55.54
I’m learning abort nested loops and I’ve gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work. It has to be an “advanced nested loop” for the assignment to be approved. def createTable(rows, columns): rows = int(input("Enter number of rows: ")) columns = int(input("Enter number of columns: ")) for row in range(rows): if row%2 == 0: for col in range(0, columns): if col%2 == 1: if col != columns - 1: print(" ", end="") else: print(" ") else: print("|", end="") else: print("-" * (columns - 1)) return True createTable(1, 2) Answer I have made one iteration of the code which you want. It prints the correct output for even and odd number of rows and columns. It is very similar to the outputs you want. When you provide further clarification for your question, I can provide an updated code. rows = 20 columns = 41 for i in range(rows): if i%2 == 0: output = "| " * (columns//2) print(output) else: output = "-" * ((columns//2)*2 - 1) print(output) The output can be visualised below. Hope this solves your query. Based on the code provided by the question provider, I have edited the code and the following code will work in the same manner as you want it to with nested loops. def createtable(rows, columns): for row in range(rows): if row%2 == 0: for col in range(0, ((columns+1)//2)*2, 2): print("| ", end="") print() else: print("-" * (((columns+1)//2)*2 - 1)) return True Tested for both these cases. createTable(20, 40) createTable(20, 41) createTable(2, 1)
https://www.tutorialguruji.com/python/creating-a-table-with-nested-loops-in-python/
CC-MAIN-2021-21
refinedweb
283
70.23
I want this program to calculate an actors age at the time a movie they made was released, the user inputs all the data... I dont know C just learning but this is the layout I thought of any help would be appreciated, this does not compile #include <stdio.h> int main(void) { char: actors_name[40]; scanf("%s", actors_name); char: film_name[40]; scanf("%s", film_name); int bday; int releaseyear; int age int filmage; printf("What is the actors name?\n"); scanf("%s", actorname); printf("What is the film name?\n"); scanf("%s", film_name); printf("What is the actors birthday?\n); scanf("%d", bday); printf("What is the films release year?\n"); scanf("%d", &releaseyear); 2008- bday = age 2008 - filmrelease = filmage printf("When %s, actorname filmed %s, film_name he was %sage, years old. %s, actorname is currently %age, and he is a Zodiac sIGN, %sfilmname was made %s, filmage) }
https://www.daniweb.com/programming/software-development/threads/132365/new-to-c-program-code-to-calculate-age
CC-MAIN-2017-09
refinedweb
148
72.05
multiple values I want to have a 3 attributes for a certain group of items. for example: name - bob country- US job- developer what can i use to store all 3 in one place? arrays can only store 1 (the specific index), and hashmap can only store 2 (value and key). i want to be able to access a value at any point. if i call the country, i want to return US (so 6 labels in total). i was thinking have a hundred arrays would be very inefficent, so what could i do? 3 AnswersNew Answer public class Person { String name; String country; String job; ... } In main(): Person p1=new Person; Person p2=new Person; ... koala Use an array: Person[] p=new[] Person; (the syntax might be wrong, lol)
https://www.sololearn.com/Discuss/1815136/multiple-values
CC-MAIN-2021-17
refinedweb
130
74.08