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
Type: Posts; User: Assmaster Couldn't you just try, and print'em out? Anyhoo: // argc = the count of space separated "words" in the commandline: argc = 7 // Each "word" has its own index in the argv array: argv[0] =... Firstly... Like Andreas said... new should not return NULL according to the standard. If allocation fails, it should throw a std::bad_alloc exception, and therefore you should not need to check for... Some code would be nice... At the very least your fprintf line and the variables it uses. So you basically want to stop using std::string and std::vector, and instead use c-style strings and arrays? Well it will work. But why on earth would you want to do that? Stay with std::vector... In fact... This won't work at all, and that's probably the error you're recieving. When the compiler sees a templated function like yours, and you instantiate it for one type, it will compile the... What's this m_bool variable? You've used it twice, but havent defined it anywhere. And why does setdata need to be templated? If it's only to save you the trouble of writing one setdata for each... p++ would be the same address as &p[1] p[0] != p but *p p[1] != p+sizeof(data_type) but rather *(p+1). Also... p+sizeof(data_type) would only be the same address as p++ if data_type is char.... Umm.. I don't think I understand what you're asking, but there's nothing wrong with the single line of code you posted. (Except from a missing ';' that is!) And certainly nothing that should end up... Erase only takes one iterator parameter. It's simply .erase(i). But... What's with the usage of the this pointer here? You aren't by any chance deriving from std::list or something? In that case..... If you have already implemented the operator == char* for your class (Looks like you have), and the Text member-variable contains the actual c-string: bool CStr::operator ==(const CStr& rhs) {... The obious thing to do, would be to simply move the definition of a into the for-loop's curlies. That way it will be constructed/destructed each iteration. (Giving you an empty stream each time) ... Is there any perticular reason you are using a char[10] and not a std::string? std::string Result; std::string Str("Hello Gurus, good day!"); int n = 10; Result = Str.substr(Str.size() - n , n); Why not use a std::vector? std::vector<int> temp(int n){ int i; std::vector<int> array(n); for (i=0;i<n;i++) array[i] = i; return array; } This way the returned array will be... Use a std::ostringstream to build the string before passing it to the messagebox: #include <sstream> ... std::ostringstream message; message << "This is a text with a number: " << 100 << ", and... Just square the value of the 8bit variable. The 8bit value 256, will then end up being 65536 (the max for a 16bit variable), but 0 will still be 0. Is that what you wanted? unsigned char some_value... Since you are passing the struct as a cMyStruct* to the function, how can you not know? The function will recieve a cMyStruct and since member-variable-names are known at compile time, just check the... No it doesn't. You can't declare variables in the header without using extern. That will lead to one variable being defined for each of the cpp files that include the header. This is the reason for... I really don't understand why you need to do any casting here. Assuming you only only have one CNode::SetVehicle function (no overloading), it will have to take a cvehiculo* as a parameter to be able... doNonVirtual() returns a void, and you're trying to pass that to the << operator of cout. That shouldn't and doesn't work. Well what type does the VehicleList.Add() function take as a parameter? I assume it's a cVehicle*, and in that case, it doesn't matter if the create function returns a cVehicle*, cCar* or a cVan*. You shouldn't put "using namespace whatever;" in any header file. Doing that will result in that namespace being used by all files that include your header. Something that in turn can result in name... It's not a book, but a good reference none the less: Use std::bitset: #include <iostream> #include <fstream> #include <bitset> int main() { std::ifstream InFile("binary.txt"); std::bitset<8> Byte; Use an unsigned char. The value 129 overflows the signed char variable. You're trying to set the reference to the pointer to NULL. C++ doesn't allow references to be NULL.
http://forums.codeguru.com/search.php?s=2d54373393024e0f8aca550cca3cc2a8&searchid=5797103
CC-MAIN-2014-52
refinedweb
790
77.13
On Jan 25, 2010, at 9:15 PM, Jarek Gawor wrote: > IMHO, I don't think we should worry about the JAXB conversion now > unless there is no other way to fix the given problem. It might help > things in long long term but right now I think it is important to get > things running first. I especially don't want to debug 2 versions of > all the builders. If we keep the same basic idea of the tomcat builder as we have now, I agree. If we decide to replace digester for processing web.xml, jaxb is the only plausible choice IMO. Similarly if we decide to write a "universal" web builder that uses the new spec "add-a-servlet" apis we'll need a jaxb web.xml model. I haven't investigated thoroughly but I suspect that we could eliminate most of the weird convolutions in the tomcat integration if we did our own web.xml processing so we could easily control which objects get used for web context, servlet wrapper, etc. It's possible that we could also do this by changing the digester rules but I find these very hard to understand and debug compared with modified jaxb objects. And, just because I think replacing digester would simplify the code a lot doesn't necessarily mean that right now is the best time to do it. thanks david jencks > > Jarek > > On Mon, Jan 25, 2010 at 9:42 PM, David Jencks > <david_jencks@yahoo.com> wrote: >> >> agree. I think it would good for Geronimo to construct the >>>> metadata-complete web.xml and pass it to Tomcat to handle the rest. >>>> >>>> Btw, in TomcatModuleBuilder.addGBeans() there is a bit of code that >>>> (re)writes a web.xml. Does anybody know why is that (still) needed? >>>> The comment above that bit of code talks about when web.xml is >>>> missing >>>> (in jaxws case) but the code seems to be writing an empty web.xml >>>> even >>>> if web.xml is present and has Java EE namespace. >>> >>> The only way to be sure is to take it out and see what happens :-) >>> IIRC the main purpose is to write the metada-complete web.xml out >>> for >>> tomcat to find... but I may not RC. >>> >>> thanks >>> david jencks >>> >>>> >>>> Jarek >>>> >>>> On Mon, Jan 25, 2010 at 1:31 PM, David Jencks <david_jencks@yahoo.com >>>> > >>>> wrote: >>>>> >>>>> On Jan 25, 2010, at 7:20 AM, Ivan wrote: >>>>> >>>>>> Hi, >>>>>> Recently, I am looking at the annoation and web fragment in >>>>>> Servlet >>>>>> 3.0. After checking some integration codes, it seems that we have >>>>>> different >>>>>> strategy for Tomcat and Jetty, in Tomcat plugin, after doing some >>>>>> verification and web service process work, Geronimo will pass the >>>>>> web.xml >>>>>> file directly to Tomcat, and then Tomcat will parse the web.xml >>>>>> file >>>>>> and >>>>>> call the addChild method to register all the servlets to >>>>>> context. While >>>>>> in >>>>>> Jetty plugin, all the work is done in Servlet GBean and Jetty >>>>>> will not >>>>>> check >>>>>> the web.xml file (At least for servlet configurations). >>>>>> So in Geronimo 3.0, who will be resposible for the annotation >>>>>> and web >>>>>> fragment scanning. For Tomcat, one way is still to let Tomcat >>>>>> does it, >>>>>> actually I found some related codes are added in ContextConfig >>>>>> class. >>>>>> Although I found some errors while trying it, it should be easy >>>>>> to >>>>>> solve. >>>>>> Another way is to scan by Geronimo, then create a gbean for each >>>>>> servlet >>>>>> like Jetty, or just generate a full web.xml file. >>>>>> Personally, I wish to do it by Geronimo, so that Geronimo >>>>>> could have >>>>>> a >>>>>> full control of it, which keeps the same way with Jetty. Also, >>>>>> I have >>>>>> another idea about improving the class scanning, IIRC, many >>>>>> builders >>>>>> require >>>>>> annoation scanning or file scanning, like web-builder, >>>>>> webservice-builder, >>>>>> etc. I am thinking that whether we could do all the scanning >>>>>> work in >>>>>> one >>>>>> round, not a new round search would be triggered by each builder. >>>>>> Maybe, we >>>>>> could add some methods like registerScanningHandler in the >>>>>> DeploymentContext, and once the temp bundle is installed, all the >>>>>> scanning >>>>>> work be will done in one round. >>>>>> Any comment ? Thanks ! >>>>> >>>>> In tomcat, I think we have to let tomcat create the servlet >>>>> wrapper >>>>> objects. >>>>> Several people have tried to turn them into gbeans but it >>>>> conflicts >>>>> with >>>>> tomcat's attempt to manage the component lifecycle. I think we >>>>> could >>>>> write >>>>> a jaxb-based processor to replace the tomcat digester one and >>>>> this might >>>>> simplify our code. >>>>> >>>>> I would prefer that geronimo scan for annotations and construct a >>>>> complete >>>>> web.xml from them and then process the web.xml either through >>>>> our code >>>>> (like >>>>> in jetty) or through the web containers code (like in tomcat). >>>>> >>>>> Another possibility would be to use the new servlet 3.0 apis for >>>>> adding >>>>> servlets etc to a web app. We might be able to write a single >>>>> processor >>>>> to >>>>> read through the metadata-complete web.xml and call the >>>>> appropriate >>>>> methods >>>>> to construct the web app. At the moment I don't recall any >>>>> geronimo-specific configuration that applies to specific servlets, >>>>> filters, >>>>> or listeners so this code might not need to look in geronimo >>>>> plans very >>>>> much. >>>>> >>>>> I like your idea of combining the annotation scanning. >>>>> >>>>> thanks >>>>> david jencks >>>>> >>>>> >>>>>> Ivan >>>>> >>>>> >>> >> >> >> >> -- >> Ivan >> >>
http://mail-archives.apache.org/mod_mbox/geronimo-dev/201001.mbox/%3C09D8A876-DBF1-4E06-961E-48EFEF02F270@yahoo.com%3E
CC-MAIN-2016-07
refinedweb
872
72.87
The following form allows you to view linux man pages. #include <stdio.h> int fseek(FILE *stream, long offset, int whence); long ftell(FILE *stream); void rewind(FILE *stream); int fgetpos(FILE *stream, fpos_t *pos); int fsetpos(FILE *stream, fpos_t *pos); equiva- lent repo- sition a text stream. The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error. EBADF The stream specified is not a seekable stream. EINVAL The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR. webmaster@linuxguruz.com
http://www.linuxguruz.com/man-pages/ftell/
CC-MAIN-2017-39
refinedweb
104
66.03
- 0shares - Facebook0 - Twitter0 - Google+0 - Pinterest0 - LinkedIn0 Arrays. There are two types of arrays: One dimensional array: In some cases, it is better to store the data items in a sequence of main memory locations, each of which can be accessed directly. Such a data structure is called an array. In C. Declaring one dimensional array: An array can be declared by specifying its data type and size as follows: data-type variable[size of array]; Suppose you want to store the marks of ten students in an array then array for storing marks can be declared C programming language, all the array elements are numbered, starting at 0. For example, the assignment statement marks [4] = 83; It stores the value 83 in the fifth location of the array because the numbering starts with 0. Thus, the last array element will have subscript one less than the size of the array. That means the array subscript will be in the range of 0 to 9. Consider the following program that reads marks of ten students and prints the marks that are above average. # include <stdio. h> # include <conio. h> void main () { int marks[10], j, sum, avg; for (j = 0; j < 10; j ++) { printf (“enter marks:”); scanf (“%d”, marks [j]); } sum = 0; for (j = 0; j < 10 ; j ++) sum = sum + marks [j]; avg = sum/10; printf (“list of marks above average\n”); for (j = 0; j < 10; j ++) if (marks [j] > avg) printf (“\n %d”, marks[j]); } In the above example, the first for loop allows the user to enter 10 marks and stores them in the marks array. The second loop finds the sum of all the marks and then the average marks are calculated. Finally the last for loop compares the marks of each student with the average marks and prints those that are greater than average. Initializing one dimensional array: Consider the following example in which the program demonstrates the initialization of an array: CODE: # include <stdio. h> # include <conio. h> # define len 5 void main () { int a [len] = {10, 34, 16, 40, 22}, j, sum, avg; sum = 0; for (j = 0; j < len; j ++) sum = sum + a [j]; avg = sum / 5; printf (“\nthe average of given five numbers is %d”, avg); } The above program used the variable len that is a constant and is defined as 5. int a [len] = {10, 34, 16, 40, 22} We can also omit the size of the array, leaving an empty pair of brackets following the array name such as: int a [] = {10, 34, 16, 40, 22}; If the size of the array is not defined, the compiler will count the number of items in the initialization list and fix that as the array size. If the number of values supplied is less than the actual number of items in the list then extra spaces in the array will be filled in with zeros. If the number of values supplied is greater than the actual number of items then the compiler will give an error message. Compile time Array Initialization: Compile time array initialization and simple array initialization are the same. Consider the following line of code which can be called as array initialized at compilation time: data-type variable [size of array] = {list of variables}; Run time Array initialization: We can initialize an array at run time that is by using the scanf statement. Consider the following lines of code: for (int x = 0; x < 9; x ++) { printf (“Enter elements of array”); scanf (“%d”, &arr [x]); } Run time initialization of array is done when we have an array of large size or when the user wants to enter elements according to his need. Two dimensional arrays: There are many problems in which the data being processed can be naturally organized as a table.]; It. EXAMPLE: To calculate the average marks in the four tests for each of the twenty five students, it is necessary to calculate the sum of the entries in each row and to divide each of these sums by 4. The following program can be used to carry out this computation and to display the average marks for each student. # include < stdio. h> # include < conio. h> void main() { int marks [50][10], i, j, student, test, sum, avg; printf (“enter number of students”); scanf (“%d”, &student); printf (“enter number of tests”); scanf (“%d”, &test); printf (“enter marks of each students in one line”); for (i = 0; i < student; i ++) for (j = 0; j < test; j ++) scanf (“%d”, marks [i][j]); for (i = 0; i < student; i++) { sum = 0; for (j = 0; j < test; j ++) sum = sum + marks [i][j]; avg = sum / test; printf (“average marks for student %d are %d”, i+1, avg; } } Matrix Transpose: The transpose of a two dimensional array is one formed by interchanging the rows and columns of the original matrix. For example, if Then the transpose of A is If the matrix has the same number of rows and columns, it is called a square matrix. The following program reads a square matrix and prints its transpose. # include <stdio. h> # include <conio. h> void main() { int i, j, a [10][10], n, holder; printf (“\nenter size of square matrix(max. 10):”); scanf (“%d”, n); printf (“enter each row in one line\n”); for (i = 0; i < n; i ++) { for (j = 0; j < n; j ++) scanf (“%d”, &a [i][j]); } for (i = 0; i < n; i ++) for(j = i + 1; j < n; j ++) { holder = a [i][j]; a [i][j] = a [j][i]; a [j][i] = holder; } printf (“\n*****THE TRANSPOSE*****\n”); for (i = 0; i < n; i ++) { printf (“\n”); for (j = 0; j < n; j ++) printf (“%d”, a[i][j]); } } Initializing Two-Dimensional Array The following program demonstrates the initializing of a two dimensional array and count the number of positive values in it. # include <stdio. h> # include <conio. h> #define row 3 # define col 4 void main() { int i, j, pos; int a [row][col] = { {4,45,-6,9}, {-8,22,-37,10}, {50,-5,62,85} }; pos = 0; for (i = 0; i < row; i ++) for (j = 0; j < col; j ++) if (a [i][j] > 0) pos = pos+1; printf (“the number of positive values = %d”, pos); } In the above program note the format used to initialize the array, an outer set of braces and then 3 inner sets of braces, each with 4 items separated by commas as well. Run time initialization of Array: Consider the following example in which the two dimensional array is initialized at run time: CODE: # include <stdio. h> # include <conio. h> void main () { int array [3][4]; int x, y, k; printf (“Enter elements of array”); for (x = 0; x < 3; x ++) { for (y = 0; y < 4; y ++) { scanf (“%d”, &array [x][y]); } } for (x = 0; x < 3; x++) { for (y = 0; y < 4; y ++) { printf (“%d”, array [x][y]); } } getch (); }
http://www.tutorialology.com/c-language/arrays/
CC-MAIN-2017-47
refinedweb
1,147
57.23
Back to index Go to the source code of this file. Definition at line 120 of file tfm.c. { /* No magic number for our extensions => forget it. */ if (data[0] != 'K' && data[1] != 'N') return _FALSE; *spacing = data[(0* 4) + 2]; /* Third byte of first word. */ /* First two bytes of second word. */ *style = (data[(1 * 4)] << 8) + data[(1 * 4) + 1]; /* Last byte of second word, signed two-complement. */ *weight = data[(1 * 4) + 3]; if (*weight >= 128) *weight -= 256; /* Effectively all four bytes of third word. */ *typeface_id = (data[(2 * 4) + 0] << 24) + (data[(2 * 4) + 1] << 16) + (data[(2 * 4) + 2] << 8) + (data[(2 * 4) + 3]); return _TRUE; } Definition at line 54 of file tfm.c. { unsigned n = nwords * 4; void *buf = (void *) malloc (n); if (buf == NULL) {BCLOSE(tfm_fp); Fatal("(tfm): out of memory error!\n");} read_multi (buf, 1, n, tfm_fp); if (FEOF(tfm_fp)) { BCLOSE(tfm_fp); Fatal("dvilj(tfm): Could not read %u bytes from TFM file.\n", n); exit (1); } /* If OUTBUF is null, free what we just read, else return it. */ if (outbuf) { *outbuf = buf; } else { free (buf); } } Definition at line 155 of file tfm.c. { /* Don't use a structure for this, since then it might occupy more than the exactly four bytes that we need. */ unsigned char *char_info; FILEPTR tfm_fp; unsigned char *header_data; unsigned char *width_raw; /* array of 1-byte data */ unsigned long4 *width_table; /* array of 4-byte fixes */ unsigned i; unsigned lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np; #ifdef KPATHSEA char *full_name = kpse_find_tfm (name); if (full_name == NULL) { return _FALSE; } tfm_fp = xfopen (full_name, FOPEN_RBIN_MODE); #else /* not KPATHSEA */ char full_name[STRSIZE]; if (findfile(TFMpath, name, 0, full_name, _TRUE, 0)) { /* fprintf(ERR_STREAM,"full_name=<%s>\n", full_name);*/ tfm_fp = BINOPEN(full_name); if (tfm_fp == FPNULL) { /* this can happen, if the calculation for max number of open * files has to be corrected */ fprintf(ERR_STREAM,"Error: file <%s> could not be opened\n", full_name); return _FALSE; } } else { Warning("tfm file %s.tfm not found on path <%s>\n", name, TFMpath); return _FALSE; } #endif /* not KPATHSEA */ (void) TFM_GET_TWO (); /* word length of file */ lh = TFM_GET_TWO (); /* words of header data */ bc = TFM_GET_TWO (); /* smallest character code */ ec = TFM_GET_TWO (); /* largest character code */ nw = TFM_GET_TWO (); /* words in width table */ nh = TFM_GET_TWO (); /* words in height table */ nd = TFM_GET_TWO (); /* words in depth table */ ni = TFM_GET_TWO (); /* words in italic correction table */ nl = TFM_GET_TWO (); /* words in lig/kern table */ nk = TFM_GET_TWO (); /* words in kern table */ ne = TFM_GET_TWO (); /* words in extensible char table */ np = TFM_GET_TWO (); /* words of font parameter data */ tfm_get_n (tfm_fp, lh, &header_data); /* Only two headerbyte words are required by the TFM format, so don't insist on all this extra stuff. */ if (lh > 2) { get_bcpl (header_data + (2 * 4), ret->coding_scheme); } else { ret->coding_scheme[0] = 0; } if (lh > 12) { get_bcpl (header_data + (12 * 4), ret->family); } else { ret->family[0] = 0; } /* Sorry for the convoluted logic. The idea is that if the family is HPAUTOTFM, we better have our extensions -- so if we don't have enough header words, or if we don't find what we need in the header words, something's seriously wrong, and we shouldn't claim to have succeeded at reading a good TFM file. */ if (strcmp ((char *)ret->family, "HPAUTOTFM") == 0 && (lh < 20 || !get_pcl_info (&(header_data[18 * 4]), &ret->spacing, &ret->style, &ret->weight, &ret->typeface_id))) { BCLOSE (tfm_fp); return _FALSE; } /* Initialize our returned array of widths to zero, since the TFM file need not contain info for all character codes. */ for (i = 0; i < bc; i++) { ret->widths[i] = 0; } for (i = ec + 1; i < 256; i++) { ret->widths[i] = 0; } /* The char_info is one word (four bytes) for each character in the font. */ tfm_get_n (tfm_fp, ec - bc + 1, &char_info); /* The width table is just nw words. */ tfm_get_n (tfm_fp, nw, &width_raw); width_table = (unsigned long4 *) malloc (nw * 4); if (width_table == NULL) {BCLOSE(tfm_fp); Fatal("dvilj(tfm): out of memory!\n");} /* But the width table contains four-byte numbers, so have to convert from BigEndian to host order. */ for (i = 0; i < nw; i++) { unsigned byte_offset = i * 4; unsigned b1 = width_raw[byte_offset]; unsigned b2 = width_raw[byte_offset + 1]; unsigned b3 = width_raw[byte_offset + 2]; unsigned b4 = width_raw[byte_offset + 3]; width_table[i] = (b1 << 24) + (b2 << 16) + (b3 << 8) + b4; } /* For each character, retrieve and store the TFM width. */ for (i = bc; i <= ec; i++) { unsigned char w_i = char_info[(i - bc) * 4]; ret->widths[i] = width_table[w_i]; } /* Throw away everything up to the second font parameter. (Could just seek, but I don't want to pull in the include files, etc.) */ if (np >= 2) { tfm_get_n (tfm_fp, nh + nd + ni + nl + nk + ne + 1, NULL); ret->interword = TFM_GET_FOUR (); } else { ret->interword = 0; } free (header_data); free (char_info); free (width_raw); free (width_table); BCLOSE (tfm_fp); return _TRUE; }
https://sourcecodebrowser.com/tetex-bin/3.0/dviljk_2tfm_8c.html
CC-MAIN-2016-44
refinedweb
773
62.21
Perl: How to Write a Module Here's to write a module in Perl by a example. Save the following 3 lines in a file and name it mymodule.pm. # -*- coding: utf-8 -*- # perl package mymodule; # declaring the module sub f1($){$_[0]+1} # module body # more code here 1 # module must return a true value Then, call it like the following way: # -*- coding: utf-8 -*- # perl use mymodule; # import the module print mymodule::f1(5); # call the function This is the simplest illustration of writing a package in Perl and calling its function. Module vs Package A “module” is simply a file of Perl code. To load a module, use require name;. package is a Perl keyword. When a file has declaration package name;, it creates its own namespace, and the file must must return a value true (any number, string, as the last line will do). Basically, all Perl modules intended to be used as library, are declared as packages. The word “module” and “package” are often used interchangably to mean “library”. Sometimes in a technical context, the word “module” refers to a file, and the word “package” refers to the namespace. Module File Path Correspondence Module/package name corresponds to the file's name/path. For example, if you have a module at abc.pm you load it like this: use abc; module file can be grouped into directories. If you have a module with subdirs, named: GameX/sound.pm you can load it like this use GameX::sound; The double colon :: corresponding to directory separator /. See also: Perl: List Available Modules, List Module Search Paths
http://xahlee.info/perl/perl_writing_a_module.html
CC-MAIN-2021-39
refinedweb
269
72.36
Maybe your file associations are messed up. See what assoc .py and ftype Python.File have to say. If %* is missing, that would explain it. C:>assoc .py .py=Python.File C:>ftype Python.File Python.File="C:Python27python.exe" "%1" %*[@]}" See and try the solution described in: You are likely using an extension module which will not work in a sub interpreter. In short, add to the Apache configuration: WSGIApplicationGroup %{GLOBAL} I would try doing somehting like this. os.system("appcfg.py arg1 arg2 arg3") I would look into this portion of the os documentation. Goodluck.;! You are not grabbing the output from that command. That's why you see nothing although the command was executed. There are several ways how to do that. This are the most common: // test.php <?php $value = 123; // will output redirect directly to stdout passthru("php -f test1.php $value"); // these functions return the outpout echo shell_exec("php -f test1.php $value"); echo `php -f test1.php $value`; echo system("php -f test1.php $value"); // get output and return var into variables exec("php -f test1.php $value", $output, $return); echo $output; ?> You should separate headers from body printing additional newline: #!C:Python33python.exe import cgitb cgitb.enable() print("Content-Type: text/html;charset=utf-8") print() # <----------- addtional newlnie for header/body separation. print("Hello World!")?
http://www.w3hello.com/questions/importing-a-python-script-from-another-script-and-running-it-with-arguments
CC-MAIN-2018-17
refinedweb
223
62.85
Nested Classes Java allows classes to be nested inside another class. These are called nested classes. Why use Nested Classes? - Nested classes are used to logically group classes that are used in one place. Good examples are utility classes. - Nested classes can increase encapsulation. Nested classes have access to private fields of the class. Instead of exposing the class fields to other class, the class can be nested and there the parents class fields can be declared private. - Nested classes can result in clean and maintainable code by defining classes in places where the code should will be used. Static Nested Classes Static nested classed are defined with the static keyword. Defining Static Nested Class Accessing Static Nested Inner Class The static nested inner class is accessed in the same way as other static members of the class. OuterClass.NestedInner nestedInner = new OuterClass.NestedInner(); The nested static class will not have access to the non-static member variables. It accesses the outer class member variable just like any other class. The nesting is just for logical organisation. Inner Classes An inner class is a class defined inside another class as a member of the class. The inner class have access to the outer class fields and methods. An instance of an inner class can only exists within an object of the outer class. Defining inner class public class OuterClass { class InnerClass { //code for the inner class here //inner class have access to OuterClass fields and methods } } Instantiating an inner class The inner class can be used outside the outer class. To use it outside the outer class, the outer class needs to be instantiated first, then the inner class can be instantiated. OuterClass outerClass = new OuterClass(); //we first need an object of the OuterClass to create the InnerClass object OuterClass.InnerClass innerClass = outerClass.new InnerClass(); Shadowing If the outer class defines a similar field as in the inner class, the outer class field will be shadowed. To access it you will need to fully qualify it. public class OuterClass { int shadowedField = 5; class InnerClass { int shadowedField = 10; public InnerClass() { } void test(){ //refer to the InnerClass shadowedField field shadowedField = shadowedField + 5; //to refer to the OuterClass shadowedField, we have to qualify it //use OuterClass.this.shadowedField shadowedField = OuterClass.this.shadowedField; } } }
https://java-book.peruzal.com/class/nested_classes.html
CC-MAIN-2018-22
refinedweb
379
57.06
NP .NET Profiler is designed to assist in troubleshooting performance, memory and first chance exception issues in .NET Applications. You can download the tool from here. Which version of the profiler to use (x86 or x64) ? If you are running x86 process on x64-bit machine, please use x86 profiler. If the IIS AppPool is configured to run 32-bit web applications, please use x86 profiler Profiler is still “Waiting for process to start....” Here are common causes : - Folder permission Make sure the np.exe is at c:\temp\np and not in Desktop or My Document or User folder Give IIS apppool user account, permission to c:\temp\np folder Remove the read-only attribute from the c:\temp\np folder - 32-bit or 64-bit If the AppPool is 64-bit, use the 64-bit np.exe. If the AppPool is configued to run 32-bit, please use x86 profiler If the process is x86, please use the x86 profiler - Check the event log for errors from CLR runtime - Collect DebugView Logs “Failed to CoCreate profiler” in the event log .NET CLR Runtime failed to create the COM object, make sure the profiler is running under admin privileges Use x86 profiler for 32-bit process running on 64-bit machine No logs files are created Make sure IIS AppPool user account has write access to the output folder. Make sure at least one request is submitted. "Files in use" error message when reading the output files Make sure the application is closed before reading the output files Profiler crashes when reading large files Use x64-bit profiler to read large log files captured using x86-bit profiler Make sure there is enough free hard disk space Profiler returns empty reports Make sure the namespace settings during collection is correct, *.* is not a valid namespace option When profiling Windows Azure process, the profiler is still “Waiting for process to start....”]. In the list of application pools, why is 'DefaultAppPool' missing ? Thank you for reporting this bug…it looks like a zero-based-index bug…it is always skipping the first AppPool name. It will be fixed in the next release. How do you use this with the ASP.NET Development Server in Visual Studio 2010 Professional. I have my site running and selected "Web App Hosted in Visual Studio" from the Advanced Options but it just says "Waiting for process to start…" There is a bug In the current release (4.9.3.0). Please follow this workaround blogs.msdn.com/…/profiling-visual-studio-development-web-server.aspx I get comment 'Failed to cocreate Profiler". How can I delete all of the np.net profiler from my system. My guess is you were trying to profiler a website and terminated the np.exe process before clicking on the "stop profiling" button or didn’t do the IIS reset after clicking on the "stop profiling" button. Please follow these steps : 1. Open a cmd window, type set COR_ENABLE_PROFILING 2. If the environment variable is not define, just do IISreset. This should resolve the problem 3. If the environment variable is set to 1, goto Control Panel | System | Advanced tab | Environment Variables | System Variables and set the COR_ENABLE_PROFILING to 0 and do IIS reset Please let me know if the problem exists even after executing these steps. It could be another 3rd party profiler trying to enable profiling. You can get the profiler details from COR_PROFILER or COR_PROFILER_PATH environment variables Hi Prashant, after reading your answer, I decided to try step 3 ( although I skipped the IISreset, which I thought would cause too many problems) and it worked. The error message in the Event Viewer has disappeared. Thanks so much. Helga Glad it got resolved. Hi Prashant, I am trying to use your profiler in Server 2003, IIS 6. In profiler, I am unable to get past the "Waiting for process to start…" message. When I check Event Viewer, I am receiving the "Failed to CoCreate profiler" message. I have followed the steps outlined above, but no success. Using DebugView, I can confirm that the Cor_Enable_Profiling and Cor_Profiler variables are set. However, the first message I receive is: "wizardIIS7ReadThreadProc() : Failed to create IWbemLocator object. Err code = 80040154" I have confirmed that following the installation steps on an environment that utilizes IIS 7 results on a working profiler. Does this mean that this debugger is specifically looking for IIS 7? Do you have any other recomendations on troubleshooting this issue? Hi Jasper, There was a bug in the NPProfiler.dll that impacts only 2003 machines. Can you please download this new version of the dll and let me know if it works for you. Note : this version of the dll is not signed Hi Prashant, I am trying to profile a Windows Store App written in C++. The tool is stuck at “Waiting for profiler to load …”. Do you know what might be the cause? Thanks. Hi Gokhan, NP .NET Profiler can profiler only managed Windows Store Apps (Apps developed using C#/VB.NET) For C++, please use PerfView, here is the link blogs.msdn.com/…/publication-of-the-perfview-performance-analysis-tool.aspx Hi Prashant, It looks this tool does not support Windows Store Apps. Do you have any new version of it supporting Windows Store Apps? Thanks. Hi Gokahan, To profile Windows Store App you need to use NPStoreApp.exe. Here are steps blogs.msdn.com/…/troubleshooting-performance-issues-in-windows-store-apps.aspx Hi Prashant, Do I need to have visual studio in my machine? Also, wonder why do I need to give IIS apppool user account, permission to working folder? If my application talks to an app server instead of IIS, can't I use this tool for profiling? I'm new to performance engineering please help. Hi Prasanna, You don’t need Visual Studio on the machine. Yes, you need to give AppPool user account write access to output folder. By default, the AppPool user account has write access to c:temp, so if you extract and run np.exe from to c:temp, you don’t have to give any additional permissions. If your application is talking to another service/server on same/remote machine, you can still profile your application. You will get data only for your application. Here is the step-by-steps tutorial for troubleshooting performance issues in web applications : blogs.msdn.com/…/troubleshooting-performance-issues-in-web-application.aspx Please let me know if you have any questions Marcelo, The error code 32 is ERROR_SHARING_VIOLATION. Before opening the reports we need to end the process. Can you please retry to open the trace files again. I am able to open the trace files you shared in the skydrive without any errors. It looks like ToolStripMenuItem is taking time just before calling BevelControl::OnPaint() ok Hi Prashant, I am trying to use NP Profiler on Win XP SP3 and it is failing to profile the application. The NPProfiler.dll is failing to register using RegSvr32. You have posted a fix for Win 2003 but the link is no longer accessible. Can you please share it again. .NET Profiler version 4.9.3.0 does not work on 32-bit Windows XP SP3. Dependecy walker for npprofiler.dll shows that it imports InitializeCriticalSectionEx from kernel32.dll which does not exist on the kernel32.dll version that's installed on my machine. Event Viewer shows this error when trying to profile: .NET Runtime version 4.0.30319.1008 – Loading profiler failed during CoCreateInstance. Profiler CLSID: '{594203B3-BF17-4261-B362-F28A68185A0D}'. HRESULT: 0x8007007f. Process ID (decimal): 9212. Message ID: [0x2504]. Hi Prashanth, When I run the profiler for asp.net, it shows Waiting for process to start. I have the exe in c:\temp\np. I can see that in the Even log it shows profiler loaded successfully. But I do not see profiler loaded in the profiling window. Any help? Can I use this tool in production environment? What kind of overload this tool takes?
https://blogs.msdn.microsoft.com/webapps/2012/09/28/faq-on-np-net-profiler/
CC-MAIN-2019-09
refinedweb
1,340
66.64
No SUID-sandbox - joakimwallden last edited by Hi. I have asked this question at Google Product Forums › Google Chrome Help Forum, but did not get a real answer, so I try here as well. Using Opera 31.0.1857.0 developer on Ubuntu 15.04 64-bit, browser://sandbox/ reports: Sandbox Status SUID Sandbox Nej Namespace Sandbox Ja PID namespaces Ja Network namespaces Ja Seccomp-BPF sandbox Ja Seccomp-BPF sandbox supports TSYNC Ja Yama LSM enforcing Ja You are adequately sandboxed. This is new with Chromium 42: SUID Sandbox disabled and Namespace Sandbox added. Is Namespace Sandbox supposed to replace SUID Sandbox, or why is SUID disabled? Thanks. - ruario last edited by The key point is You are adequately sandboxed. SUID sandbox is not needed if your kernel supports the other required features (kernels of 3.17 or newer almost always will and some older kernels if they have been suitably patched by your distro). P.S. The sandbox is still SUID in post install of packaging because not everyone has a suitable kernel. P.P.S. It seems that I still have an employee badge but I have left Opera now, following the shut down of the Desktop team in Olso. - joakimwallden last edited by Hi and thank you for the reply. It said “You are adequately sandboxed.” also when there was only SUID, PID namespaces and Network namespaces, before Seccomp-BPF (when legacy Seccomp was disabled by default) and before Yama. So Namespace Sandbox can be seen as a replacement for SUID? The changelog¹ for Chromium (where SUID is called “setuid”) isn’t very clear (to me), and the documentation² is outdated. ¹ ² Sorry to read the P.P.S. - joakimwallden last edited by LinuxSandboxing was updated 12 May. The new version of the document adds: .” So the answer is that SUID is disabled because the new Namespace Sandbox replaces it (if possible).
https://forums.opera.com/topic/9692/no-suid-sandbox
CC-MAIN-2019-35
refinedweb
317
65.42
Manages scene graph rendering and event handling. More... #include <Inventor/SoSceneManager.h> Manages scene graph rendering and event handling. SoSceneManager provides Open Inventor rendering and event handling inside a window provided by the caller. The scene manager is able to render in only a portion of a window if desired. The SoWinRenderArea class employs an SoSceneManager, and handles most all the details for setting up a window, converting Windows messages to Open Inventor events, automatically redrawing the scene when necessary, and so on. It is simplest to use a render area when rendering in an entire window. The SoSceneManager class is available for programmers not using the SoXt / SoWin or SoQt libraries. SoWinRenderArea, SoGLRenderAction, SoHandleEventAction Enum which indicates the desired antialiasing algorithm. This is used by the antialiasing API. Constructor. Destructor. Activates the scene manager. The scene manager will only employ sensors for automatic redraw while it is active. Typically, the scene manager should be activated whenever its window is visible on the screen, and deactivated when its window is closed or iconified. Deactivates the scene manager. The scene manager will only employ sensors for automatic redraw while it is active. Typically, the scene manager should be activated whenever its window is visible on the screen, and deactivated when its window is closed or iconified. Enables the realTime global field update which normally happen right after a redraw. Returns the antialiasing mode set using the setAntialiasing(float,AntialiasingMode) method. Returns AUTO by default. Parameters set using the setAntialiasing(SoAntialiasingParameters*) method may change the antialiasing mode, but do not affect the value returned by this method. Therefore this method does not necessarily return the current actual antialiasing mode. Returns the antialiasing parameters set using the setAntialiasing(SoAntialiasingParameters*) method. Returns null by default. A quality value set using the setAntialiasing(float,AntialiasingMode) method may modify internal parameters, but does not affect the value returned by this method. Therefore this method does not necessarily return the current actual antialiasing parameters. Returns the antialiasing quality set using the setAntialiasing(float,AntialiasingMode) method. Returns 0.0 by default. Parameters set using the setAntialiasing(SoAntialiasingParameters*) method override internal parameters, but do not affect the value returned by this method. Therefore this method does not necessarily return the current actual antialiasing quality. Gets the default priority of the redraw sensor. Returns TRUE if there is currently a render callback registered. Processes the passed event by applying an SoHandleEventAction to the scene graph managed here. Returns TRUE if the event was handled by a node. Reinitializes graphics. This should be called, for instance, when there is a new window. Applies an SoGLRenderAction to the scene graph managed here. Note that this method just applies an SoGLRenderAction that traverses the scene graph and makes the necessary rendering calls for each node. It is not the same as calling the render method on an Open Inventor render area or viewer object. The viewer's render method will typically do pre-rendering operations like adjusting the near/far clip planes, as well as post-rendering operations like calling "swap buffers" to make the rendered content visible. Also it is possible to call a viewer's render method without explicitly making an OpenGL render context current (the viewer takes care of that). When calling this method, the application is responsible for providing a current OpenGL render context that is known to Open Inventor through an SoGLContext object. If there is no current OpenGL render context, Open Inventor may throw an exception or crash, depending on the API language and system environment. viewer->bindNormalContext(); viewer->getSceneManager()->render(); viewer->unbindNormalContext(); SoGLContext* ctx = SoGLContext::getCurrent( true ); ctx->bind(); viewer->getSceneManager()->render(); ctx->unbind(); Schedules a redraw for some time in the near future. If there is no render callback set, or this is not active, no redraw will be scheduled. Setup a callback that returns TRUE if rendering should be aborted. It allows some Open Inventor nodes to stop their work, if requested, in order to keep reasonable interactivity. When using Open Inventor standard GUI classes, the callback is setup by default to return TRUE if MousePress events are pending during a STILL frame.Since Open Inventor 9.5. Enable (or disable) antialiasing with specific parameters. Use one of the subclasses of SoAntialiasingParameters. The antialiasing mode is determined by which subclass is used to set the parameters. For example, passing an SoFXAAParameters object automatically sets FXAA mode. Note that the parameters are overridden if a quality and mode are subsequently set using the setAntialiasing(float,AntialiasingMode) method. Enable (or disable) antialiasing with specified quality and mode. Specific antialiasing parameters will be set automatically based on the quality value. Note that the quality and mode settings are overridden if specific antialiasing parameters are subsequently set using the setAntialiasing(SoAntialiasingParameters*) method. The default mode is AUTO but this may be overridden by setting the environment variable OIV_ANTIALIASING_DEFAULT_MODE (see SoPreferences). Sets an event listener which is called when the antialiasing configuration is modified. It is useful to define this listener because the scene manager is not responsible for the pixelformat changes required for the FSAA and accumulation algorithms. The Open Inventor viewer classes use the listener to automatically switch the pixel format (not necessary for application to handle this when using a viewer class). Defines the auto interactive mode. Default is FALSE. When this mode is activated, the sceneManager will decide depending on scenegraph changes to switch to interactive mode or not. Default value can be changed through OIV_AUTO_INTERACTIVE_MODE envvar.Since Open Inventor 9.2 Defines the window background color when in RGB mode. This is the color the scene manager viewport is cleared to when render() is called. Default is black (0,0,0). See also setBackgroundColorRGBA(). Setting the background color will automatically call the scheduleRedraw() method. The default value can be set using the environment variable OIV_BACKGROUND_COLOR. Specify three floats (R, G, B) in the range 0. to 1., separated by spaces. Defines the window background color when in RGBA mode. This is the color the scene manager viewport is cleared to when render() is called. Default is transparent black (0,0,0,0). The default RGB color (but NOT alpha) can be set using the environment variable OIV_BACKGROUND_COLOR or by calling setBackgroundColor(). User supplied render action. Highlights fall into this category. SceneManager will never delete a render action passed to this method. return the renderAction 0.Since Open Inventor 9.2 User supplied handle event action. This should not be done in the middle of event handling. Passing NULL turns event handling off. SceneManager will never delete a handle event action passed to this method.Since Open Inventor 9.2 Indicates that the scene manager is in interactive mode or not. This is usually called by Inventor viewer classes, but it is also usefull for custom application viewer. It mainly setup SoInteractionElement for all used actions (preRenderAction and renderAction).Since Open Inventor 9.2 Defines the origin of the viewport within the window. The origin (0,0) is the lower left corner of the window. Sets the priority of the redraw sensor. Sensors are processed based on priority, with priority values of 0 processed immediately. The default priority for the scene manager redraw sensor is 10000. The render callback provides a mechanism for automatically redrawing the scene in response to changes in the scene graph. The scene manager employs a sensor to detect scene graph changes. When the sensor is triggered, the render callback registered here is invoked. If the callback is set to NULL (the default), auto-redraw is turned off. If the application is not using an Open Inventor render area or viewer, the callback should make sure that an OpenGL render context is current, then call the scene manager render() method. See the render() method for more information. If the application is using an Open Inventor render area or viewer, then the callback should call render() method on the render area or viewer object. The callback should not modify any nodes in the scene graph before or after calling the render() method. The modification will be detected by the scene manager, which will schedule another call to the render callback, resulting in continuous calls to the render callback. If necessary the callback can temporarily disable notification by calling enableNotify() on the node that will be modified. Defines the color mode (TRUE - RGB mode, FALSE - color map mode). Default is RGB mode. Only a subset of Open Inventor nodes will render correctly in color map mode. Basically, when in color index mode, lighting should be turned off (the model field of SoLightModel should be set to BASE_COLOR ), and the SoColorIndex node should be used to specify colors. Defines the scene graph which is managed here. This is the Open Inventor scene which will be traversed for rendering and event processing. Sets the OpenGL context to be shared by the scene manager. This avoids the necessity to re-generate textures and display lists if they are already available in another OpenGL context (another viewer context, for instance). Defines the size of the viewport within the window. Default is to render the entire window region. Set options for supersampling when "still" (not interacting). When quality is greater than 0, still images will be automatically supersampled. Defines current viewport region to use for rendering. This can be used instead of setting the size and origin separately. Defines the size of the window in which the scene manager should render. This size must be set before render() and processEvent() are called.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_scene_manager.html
CC-MAIN-2022-05
refinedweb
1,584
50.02
>>:1, Insightful) Re:Needed? (Obligatory reply) (Score:5, Insightful) I always print out the manuals, faqs and howtos I read frequently. I also print out important e-mails. Incomplete PHP5 (Score:4, Insightful) another book on the subject, but i prefer to see up to date copies of books such as this hitting the shelves than "1001 ways to do everything you need with Kudos to the PHP team. Re:Needed? (Obligatory reply) (Score:5, Insightful) yes, but....:The online PHP documentation could be improved (Score:1, Insightful) Real programmers only write in... (Score:4, Insightful):Needed? (Obligatory reply) (Score:3, Insightful) trusting the latest snippet from php1337haX0rs.com. What do you do if you need to actually parse html? Use templating that a designer can understand? Even easily manipulate text data? PHP embeds scripting in webpages. Its rarely reusable and it often leads to a mess. Its also the kind of thing we used to flame Microsoft for (scriptable email?). Most other solutions sit outside your webpage (and can often even manipulate your webserver) to generate a page for you.: .ini files? What's the best way to read in an apps config file and perhaps even write it back out? How can I write a random cookie to someone and use that value as a lookup into a database of current state and other information (and expire said info for out-of-date sessions)? Can I easily use XML for configs rather than Books can show best practices, hazards in using certain functions, how some suites of functions best interact with other uses, etc. A book may also elide certain functions that are older and perhaps better replicated in newer functions - code waiting to die (once that PHP2 stuff gets redone). This sort of thing has no place in documentation for a list of functions. We could call is "user manual" vs. "reference manual". Online docs for PHP are a great reference manual. of domains as vhosts, which is what a lot of cheap hosting is about, they are not going to want to enable mod_perl, since every script will be sharing the same interpreter and this is not at all secure. I think I read that mod_perl 2 would help with the latter, but even if this is the case, since nobody runs Apache 2 it doesn't really matter. So PHP makes it easy to inline code which a lot of people like, especially beginners, and fits well for current hosting limitations. There also is the bad reason that there are a lot of crappy free CGIs out there, like the dreck on Matt's Scripts that are security nightmares so some admins have stomped on CGI access because of this. PHP has no advantage here, since there are plenty of PHP security nightmares out there, but the Perl ones have been around longer and been exploited longer, especially the evil 'formmail.pl'. Another PHP plus is that it is easier to sandbox off PHP for admins who have unknown users posting code on their servers. Personally I feel sorry for people stuck using PHP. I use mod_perl, DBI, and HTML::Template, and a few other really great CPAN modules, and when I get stuck going back to PHP to do work I find the tools very inconsistent and limited compared to Perl, especially in database programming. But if I were to set up a 'cheap webspace' server I would not trust users with Perl unless I worked hard to cripple it, while I could adequately cripple PHP fairly quickly. defense of the Java book authors, the actual web documentation for some of those technologies is very scarce, but this is certainly not the case for PHP! Re:With PHP5, why not use Perl? (Score:3, Insightful) And, until recently the entire language had a flat namespace. If you wanted to create a module to do something you just sort of picked a starting prefix for all your function names and hope that they don't collide with anything. This is surely fine when the language is young, and it must look rather appealing to the beginner -- as in, "Hey, neat, no worrying about all those complicated classes or scoping or namespaces or anything, I just have this extremely long list of functions that I can call." And that sort of organization really doesn't scale. It would not be able to support the 10,000 (or whatever) modules that CPAN offers for Perl. And as the number of PHP modules balloons they realized in 5.x that they needed much stronger class-like typing and organzation, instead of just having a long list of a bunch of functions. So, yes, PHP is terribly easy to learn... but that isn't necessarily good from the standpoint of security or long-term language health.
https://developers.slashdot.org/story/04/01/12/1532254/core-php-programming/insightful-comments
CC-MAIN-2017-17
refinedweb
807
69.11
Class to maintain data and optimization model for 2d shift estimation. More... #include <rrel_shift2d_est.h> Class to maintain data and optimization model for 2d shift estimation. This class is an adaptation of rrel_homography2d_est to compute a 2D shift instead of a 2D homography. Definition at line 20 of file rrel_shift. Definition at line 10 of file rrel_shift2d_est.cxx. Constructor from vnl_vectors. Definition at line 33 of file rrel_shift2d_est.cxx. Destructor. Definition at line 47 of file rrel_shift2d_est.cxx. Definition at line 117 of file rrel_shift2d_est.cxx. Compute unsigned fit residuals relative to the parameter estimate. Implements rrel_estimation_problem. Definition at line 69 of file rrel_shift 58 of file rrel_shift2d_est.cxx. Total number of correspondences. Implements rrel_estimation_problem. Definition at line 52 of file rrel_shift has. Gaussian error, so the Euclidean distance residual has 2 degrees of freedom. Reimplemented from rrel_estimation_problem. Definition at line 40 of file rrel_shift 85 of file rrel_shift2d_est.cxx. Definition at line 56 of file rrel_shift2d_est.h. Definition at line 60 of file rrel_shift2d_est.h. Definition at line 61 of file rrel_shift2d_est.h.
http://public.kitware.com/vxl/doc/release/contrib/rpl/rrel/html/classrrel__shift2d__est.html
crawl-003
refinedweb
174
54.29
Hi We are testing 2.9 upgrade but found some issues with the toolbar We upgrade by updating the react-flexmonster and flexmonster libraries to 2.9. Our project is a ‘create react app’ project. Hello, Thank you for reaching out. We assume the reason for this issue may be the Toolbar customization performed on your side. Please note that the new “Share” tab was introduced in 2.9. It is hidden by default; still, it takes its place in the array of tabs that you may customize. We suggest checking if your customization is not tied to tabs’ indexes. We suggest using their id to avoid similar situations. If the issue remains or you do not use the Toolbar customization, please send us a sample where the issue would be reproducible. Looking forward to hearing from you. Kind regards, Illia Hi Illia We removed the customization bit, now the toolbar is showing the default icons, and we found that the ‘connect’, ‘open’, ‘export’, ‘grid’, ‘charts’, ‘format’ icons had no response. Unfortunately it’s not easy for me to send you a sample due to company policies. I am suspecting some we might have missed to update some dependencies. The upgrade was done manually by updating the libraries react/react-flexmonster/react-dom/flexmonster to the following versions “flexmonster”: “2.9.1”, “react”: “^17.0.1”, “react-dom”: “^17.0.1”, “react-flexmonster”: “2.9.1-1” Can you see if we missed something? Again due to company restrictions we cannot install the flexmonster cli. regards Dan Hello, Dan, Thank you for your feedback. Could you please clarify that the Toolbar customization is disabled entirely, and the issue remains? If the customization is partly disabled, please send us the customization function passed as a handler of the beforetoolbarcreated event. It would allow us to test the behavior locally. If the customization is completely disabled, we suggest clearing the browser’s cache and performing the hard reload of the page. It is required to make sure all the latest Flexmonster files are used on the page. Concerning the sample, do you think it would be possible to provide us with access to some isolated part of your environment so that we could test the behavior? You can use dummy data or leave the report empty if needed. Finally, we would like to ask you for an illustration (for example, a screen record) of the behavior. Also, please check if any errors are displayed in the console when attempting to use the Toolbar. Looking forward to your reply. Best regards, Illia Hi Illia Yes all toolbar customization is disabled entirely, the issue remains. Control-refreshed the page, the issue still remains. Found some errors in console, doesn’t seem to be related? but here it is.. index.js:1 Warning: Failed prop type: The prop `alignContent` of `Grid` must be used on `container`. at WithStyles(ForwardRef(Grid)) () at Pivot () index.js:1 Warning: Failed prop type: Invalid prop `fullWidth` of type `string` supplied to `ForwardRef(Dialog)`, expected `boolean`. at Dialog () at WithStyles(ForwardRef(Dialog)) () at FormDialog () at Pivot () index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of PivotTable which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: at div at PivotTable () Hello, Dan, Thank you for the details. We reproduced the behavior using an older version of the CSS file with the latest version of the component. Please make sure the latest version of styles is used in your project. The required CSS file can be found in the “flexmonster” npm package. It is automatically updated along with the package itself. Please check if your imports point specifically to this file, e.g., import 'flexmonster/flexmonster.css';. Looking forward to your feedback. Regards, Illia Hi Illia Indeed we customize the flexmonster css to integrate with our UI. That was done by changing flexmonster.less and generate css. Do you know what are the changes in flexmonster.less? regards KL Hello, Dan, We suggest checking out our documentation dedicated to CSS customization: Сustomizing appearance (please see the “Further customization” section). This section describes the recommended approach of adding custom styles that would not cause any issues during updating. Please let us know if it helps. Kind regards, Illia Hi Illia Updating the less files fixed the issue. Thanks for your help. Hi Illia We didn’t notice much of a performance change after upgrading. In this page it mentions Flexmonster now “styles 3 times faster”, specifically what does it mean? Are there any changes we should be making to improve performance of 2.9 upgrade? Hello, Thank you for your question. By saying “style 3 times as fast” we mean up to three times better performance when loading CSV and JSON data sets. You do not need to make any additional changes after updating the component to receive the improved performance. Feel free to contact us if other questions arise. Kind regards, Illia Hi Illia We use streaming csv data sources but didn’t see much change in performance. Under what conditions are performances improved? (eg, csv of particular data types?) Hello, Dan. Performance is improved for some specific cases when using JSON or CSV data sources. For example, datasets containing many unique members can be analyzed much faster in the major 2.9 version of the component. The difference may not be so significant for average datasets with fewer unique members. Feel free to contact us if other questions occur. Best regards, Illia
https://www.flexmonster.com/question/upgrade-to-2-9-toolbar-issues/
CC-MAIN-2021-39
refinedweb
931
67.76
Search results Create the page "Page name here" on this wiki! See also the search results found. - Studies > Center of Biblical Survey > Study of Scripture - (insert page name here) Here you can provide a brief introduction to the topic being studied3 KB (416 words) - 15:45, 3 September 2015 - grow! To suggest a book for this reading group, please discuss it on this page. To view previous book discussions, please see this page. your name here!831 bytes (149 words) - 02:05, 16 December 2009 - learning project. To join this project, add your name to the list of confirmed participants, and then add the page to your watchlist so that you can keep up8 KB (853 words) - 17:22, 17 August 2015 - INTRODUCTORY PHYSICS TEXT ETC. GOES HERE. The page should contain: - Links to other categries Links to other pages recent discussions Proper Graphics and1 KB (190 words) - 01:13, 12 September 2009 - goal. This page is the start of a series of related activities that will be created here during the first half of 2007. Visit the planning page to see some10 KB (1,436 words) - 10:45, 17 August 2015 - Scientific terminology (section Discussion Page)Wikiversity, you can list your name here. If you post on the discussion page, please use three tildes ~ to sign your name. You do NOT have to join Wikiversity4 KB (329 words) - 01:56, 8 August 2015 - Here is an example of an "external link": Google.com. Try creating a link from this page section to another Wikiversity page. Example: [[Main Page]]4 KB (709 words) - 14:41, 13 March 2013 - who have enrolled. [[Category:]] <--please include subject name. By default, this page is included in the category with the same name as this page.3 KB (264 words) - 18:06, 20 August 2015 - unit name assessment item(s) name "extension request” Email message body should include: Your name and student ID unit name assessment item(s) name length3 KB (1,267 words) - 07:34, 4 August 2015 - If you are an active participant in this project, you can list your name here (this can help small projects grow and the participants communicate better;5 KB (553 words) - 23:02, 1 October 2014 - and replace "IMAGENAME" with the name of the file you uploaded (not including the "Image:" prefix). Save the page, and make sure to add it to your Watchlist64 KB (598 words) - 20:13, 29 May 2015 - page content makes a wiki an effective tool for collaborative authoring. Q. Where can I learn more about editing Wikiversity webpages? A. Click here for12 KB (1,430 words) - 16:06, 27 June 2015 - suggestions via email, Moodle discussion or by editing this page. Note: Unselected topics have been moved here. Editor tasks Marking Editing Printing Recently11 KB (529 words) - 00:34, 8 September 2015 - (UTC) Lrbabe 13:53, 10 May 2007 (UTC) CQ 20:57, 24 May 2007 (UTC) (Add name here) User:JWSchmidt/quiz - Another way to make test/quiz questions. The14 KB (1,698 words) - 15:12, 20 January 2015 - create a new page is to go here. In the shortcut box, type the name of your page and click "Create page". Make sure your page is appropriately titled. If9 KB (1,493 words) - 20:13, 19 October 2012 - Wikiversity pages indicate who the active participants are. If you are an active participant in this department, you can list your name here (this can help6 KB (831 words) - 04:52, 20 November 2011 - Userpagelikeplanotse to set up your user page in a hurry. Detail instruction is provided here on this page. You should of course replace my name (Tony) and my username2 KB (237 words) - 15:37, 24 January 2015 - your Wikiversity user name, your real name (if different), and your student ID. The convener will then "drop by" to check your page, help you to set it185 bytes (27 words) - 22:16, 11 March 2010 - your name (or your sign in name on Wikiversity) and today's date. Type the company information If you have a company, put that name and address here. Otherwise15 KB (69 words) - 22:31, 7 September 2015 - Wikiversity namespace. Simply make a link to the name of the lesson (lessons are independent pages in the main namespace) and start writing! You should6 KB (565 words) - 21:49, 23 September 2015 View (previous 20 | next 20) (20 | 50 | 100 | 250 | 500)
https://en.wikiversity.org/wiki/Special:Search/Page_name_here
CC-MAIN-2015-40
refinedweb
735
68.2
1.0 Introduction Data is an important part of a program. In fact, programs are written so that data can be captured, processed, stored and presented to the user. The success of a program depends on how well data has been organized and used. In this post, we will be looking at data types and expressions in programming in C language. 2.0 Data Type All data has an underlying type. The number of persons in a room is an integer. It cannot be a fraction. On the other hand, the average rainfall received by a city in a year is a floating point number, because there are always some digits after the decimal point. Without further ado, we can list the basic data types in C language, which are, 2.1 char The basic type char is for storing characters. A char is basically an integer; it stores the integer code for a character. A character is stored in a byte. This is true for characters in the ASCII character set. However, with special libraries, it is possible to provide for all the languages supported by Unicode with multi-byte characters. But, to start with, we will assume the default 1 byte character and the ASCII character set. By default, a variable of type char may have a value 0 to 255 or -128 to 127 depending upon the processor architecture. The first 32 codes, 0-31, in ASCII are control characters and are used for signalling to devices like printers and video terminals. For example, carriage return (13) and line feed (10) cause the cursor to return to the first column and the next line on a video terminal. And, code zero is the null character, used to mark the end of a text string.The printable characters in ASCII are from 32 through 126. ASCII code 127 is for delete. The qualifier signed or unsigned can be added to char. An unsigned char variable can store a value in the range 0 through 255. A signed char variable can store values between -128 and 127 in 2s complement machines. 2.2 int The basic type int is for storing integers. An int is normally 32 bits long. The qualifiers short and long can be applied to int. A short int is 16 bits long and a long int is 64 bits long. Normally "int" is omitted after short and long. That is "short x" means "short int x" and "long y" means "long int y". A signed or unsigned qualifier may be used with int. The unsigned qualifier is more common and it is often used for bit masks. 2.3 float and double The float, double and long double are single, double and extended precision floating point data types respectively. The float, double and long double occupy 4, 8 and 16 bytes of memory respectively. Of the three, double is mostly used, as it provides a balance between accuracy and economy of storage space. 3.0 Identifiers Identifier names can be constructed with uppercase and lowercase alphabets, underscore and digits. The first character must be an alphabet. As a convention, symbolic constant names are made of uppercase characters, whereas variable names are made up of lower case alphabets. In both cases, digits and underscore may be used. 4.0 typedef typedef defines a new name for an existing type. This helps in defining meaningful names for involved declarations. For example, typedef unsigned char __uint8_t; typedef unsigned short int __uint16_t; typedef unsigned int __uint32_t; typedef unsigned long int __uint64_t; typedef __uint8_t uint8_t; typedef __uint16_t uint16_t; typedef __uint32_t uint32_t; typedef __uint64_t uint64_t; which defines easy to remember 8, 16, 32 and 64-bit unsigned integers. However, it is not necessary to include these typedefs in your C program. You can include the file stdint.h, and the types uint8_t, uint16_t, etc. become available automatically. For example, consider the following program. // try2.c #include <stdio.h> #include <string.h> #include <stdint.h> int main () { printf ("__WORDSIZE = %d bits\n", __WORDSIZE); printf ("sizeof (int) = %d bytes, sizeof (int *) = %d bytes\n", (int) sizeof (int), (int) sizeof (int *)); printf ("sizeof (uint8_t) = %d byte\n", (int) sizeof (uint8_t)); printf ("sizeof (uint16_t) = %d bytes\n", (int) sizeof (uint16_t)); printf ("sizeof (uint32_t) = %d bytes\n", (int) sizeof (uint32_t)); printf ("sizeof (uint64_t) = %d bytes\n", (int) sizeof (uint64_t)); } After compiling and running the above program, we get following results. $ gcc try2.c -o try2 $ ./try2 __WORDSIZE = 64 bits sizeof (int) = 4 bytes, sizeof (int *) = 8 bytes sizeof (uint8_t) = 1 byte sizeof (uint16_t) = 2 bytes sizeof (uint32_t) = 4 bytes sizeof (uint64_t) = 8 bytes 5.0 Enumeration An enumeration is a series of some constants. The default value of the first constant is zero. The default value of a constant is the value of predecessor plus 1. The default value can be overridden my explicit assignment. For example, consider the enumeration, enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; here, the value of Sunday is zero and that of Saturday is 6. For example, #include <stdio.h> #include <string.h> enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; int main () { enum Day weekday = Saturday; printf ("weekday = %d\n", weekday); } The above program prints weekday as 6. If we had defined the enumeration as enum Day {Sunday = 1, Monday, Tuesday, Wednesday = 7, Thursday, Friday, Saturday}; The above program would have printed week day as 10 (for Saturday). 6.0 Boolean type C does not have a boolean data type. However the integer type has provided for the boolean type. The value zero (0) is considered false and anything non-zero is true. Since 1 is non-zero, we can say 1 is true. We can provide the boolean type with an enumeration, as in the example below. #include <stdio.h> #include <string.h> typedef enum {False, True} Boolean; int main () { Boolean over = False; int i = 0; printf ("over = %d\n", over); while (!over) { printf ("i = %d\n", i); i++; if (i > 2) over = True; } printf ("over = %d\n", over); } And, after compilation and running the program, we get the following results. $ gcc try4.c -o try $ ./try over = 0 i = 0 i = 1 i = 2 over = 1 For using the boolean type, it is not really necessary to define the typedef enum Boolean. With the C99 standard, C provides the type bool which can have the value false or true. To get this functionality, one has to include the file stdbool.h. Using the stdbool.h file, #include <stdio.h> #include <string.h> #include <stdbool.h> int main () { bool over = false; int i = 0; printf ("over = %d\n", over); while (!over) { printf ("i = %d\n", i); i++; if (i > 2) over = true; } printf ("over = %d\n", over); } And, the result is the same as before. $ gcc try4.c -o try $ ./try over = 0 i = 0 i = 1 i = 2 over = 1 7.0 Declarations All variables need to be declared before use. We have seen declaration such as, int i; char buffer [20]; double radius; There are two terms, declarations and definitions for variables. A definition for a variable introduces the name of the variable and sets aside storage for the variable. For example, int num; is a definition of variable num, as it introduces the name, num, and storage is set aside for it. But, there are cases, where the variable is defined in some other file and we just need its name for using it. For example, extern int counter; Here, the declaration, extern int counter, says that counter is an integer and is defined elsewhere. So no storage is set aside for it, only the name is introduced in this declaration. The name, counter, can now be used in expressions. 7.1 const qualifier The const qualifier in a declaration specifies that the value of the variable would not be changed in that scope. For example, const double pi = 3.14159265358979323844; const int scores [] = {34, 67, 98, 23}; If const is applied before an array, it means that the values of the array elements would not be changed. 8.0 Storage class There are two properties associated with variable names, scope and lifetime. The scope of a variable name is the portion of the program in which the variable name is visible and can be used. The lifetime of a variable is the time the variable is "live"; the time during which a variable has valid memory and retains its value. Collectively, the scope and lifetime define the storage class of a variable. There are four storage classes: automatic, external, static and register. 8.1 Automatic Automatic variables are defined inside functions. The storage for these variables is allocated on the stack. The variables can be defined using the keyword auto. However, auto is the default and is generally not mentioned. The scope and lifetime for automatic variables is the point of definition to the end of the block. Automatic variables are not initialized. 8.2 External As opposed to automatic variables which are internal to functions, there are variables that are external to functions. These are global variables and are a part of the data segment. The scope of these variables is the point of definition to the end of program. However, if there is an automatic variable with the same name, the automatic variable gets precedence and the scope of global variable is obscured by the automatic variable bearing the same name. The lifetime of the external variables is the lifetime of the program. The external variables are initialized to zero at the time of definition. The difference between definition and declaration is most significant for external variables. An external variable is defined in one file. It is declared with the extern qualifier in other files of the program. Once declared, it can be used in expressions. 8.3 Static We have seen that automatic variables come and go in functions. Once a function exits, the value of the automatic variables is lost. However, if a variable is declared with the static keyword, it retains its value between different function invocations. So their lifetime is that of the program. If an external variable or a function is declared static, it is only visible in the file of the definition. It can not be accessed from other files. 8.4 Register Register variables are automatic variables. By the putting the keyword "register" in front of a variable, it is suggested to the compiler that the variable would be heavily used in calculations, and, so the compiler could place the variable in a register. The compiler is free to ignore the suggestion and place the variable where it deems fit. However, it is not possible to take the address of a variable declared with the register keyword and this true even when the variable is not stored in a register. 9.0 Operators 9.1 Arithmetic Operators C has the four binary arithmetic operators, +, -, * and / for addition, subtraction, multiplication and division respectively. The precedence of * and / is higher than that of + and -. Binary arithmetic operators associate left to right. Then, there is the modulus operator, %, which gives the remainder of division of two integers. If x and y are two integers, x / y gives the integer quotient, in which the fraction has been truncated and x % y gives the remainder. If x is divisible by y, the remainder is zero. The modulus operator is not defined for float or double operands. C also has the unary + and -. The precedence of unary + and - is higher than that of binary * and /. Unary + and - operators associate right to left. 9.2 Relational Operators The relational operators are <, <=, >, >=, == and !=. The first four of these, that is, <, <=, > and >= have the same precedence. The other two, == and != have a lower precedence. The relational operators associate left to right and have a lower precedence as compared to binary arithmetic operators. A word of caution about the equality operator, ==. It is a common error to write the equality operator as =, which is obviously wrong as = is the assignment operator. This error is common and is difficult to debug. 9.3 Logical Operators There are two logical operators, && and ||. These have a precedence less than that of relational operators. Of the two, the operator && has a higher precedence. The value of an expression involving relational and/or logical operators is zero if it is false and 1 if it is true. Expressions involving logical operators are evaluated left to right and the evaluation stops as soon as the truth or falsehood value of the expression is established. For example, consider the statement, while (x < a || y < b || z < c) ... In above example, if (x < a) evaluates as true, the other two conditions are not checked and the loop continues. If (x < a) evaluates as false, then (y < b) is checked. If (y < b) evaluates as true, the third condition is not checked and the loop continues. If both (x < a) and (y < b) evaluate as false then the third condition, (z < c) is checked and if it evaluates as true, the loop continues. If it evaluates as false, the loop terminates. 9.4 Unary negation Operator The unary negation operator ! converts an operand with value non-zero to zero and zero to 1. This is quite useful in writing condition for while loops. For example, int over = 0; while (over == 0) ... can be written as, int over = 0; while (!over) ... which is more intuitive and sounds better. 10.0 Type conversion In an expression, there may be implicit type conversions. The basic principle is that the "lower" type is promoted to the "higher" type and the expression is evaluated. For example, if there is a mix of integer and float, the integer is converted to float for evaluation. Or, if there is a mix of float and double, float is converted to double for evaluation. char types are treated as small integers; char is freely mixed with integers in expressions. As per the language specification, printable characters are guaranteed to be positive. An important type conversion is type cast, that is, we force a variable to a particular type. For example, the function sqrt (double) expects a double argument and returns a double and we wish to find the square root of an integer. While passing the integer to the sqrt function, we type cast it to a double. #include <stdio.h> #include <string.h> #include <math.h> int main () { int num = 99; double ret = sqrt ((double) num); printf ("square root = %f\n", ret); } We can compile and run this program. $ gcc try2.c -o try2 -lm $ ./try2 square root = 9.949874 In the above example, it is as if num is assigned to a variable of type double, which is passed to the sqrt function. The value of variable num is not affected. 11.0 Increment and decrement operators C has increment (++) and decrement (--) operators. The increment operator adds 1 to its operand, while the decrement operator subtracts 1. The operator can be used as a prefix, that is, before the operand and, postfix, after the operand. For example, // add 1 to i (prefix) ++i; // add 1 to i (postfix) i++; // subtract 1 from i (prefix) --i; // subtract 1 from i (postfix) i--; So, what is the difference between prefix and postfix? In case of prefix, the value is incremented or decremented before use. In case of postfix, the value of the operand is incremented or decremented after use. If these operators are used in standalone mode, as in examples above, it does not matter, whether prefix or postfix mode is used. The effect is the same in both modes. But, consider the case, k = a [j++]; First a [j] is assigned to k, and then, the index j is incremented. As another example, consider, i = *++ptr; which increments the pointer ptr and, then, the value pointed by ptr is assigned to i. But, if we use postfix increment, i = *ptr**; the value pointed by ptr is first assigned to i and, then, ptr is incremented. 12.0 Assignment operators The assignment operator evaluates the expression on the right and the value is stored in the variable on the left. The left side of assignment operator must be a variable. Quite often, we find assignment statements such as, i = i + 10; In C, this can be written as, i += 10; which is more efficient in addition to being compact. In C, var op= expr;is a shorthand for var = var op (expr); The op can be any one of the binary arithmetic operator, +, -, *, /, %, and, also, any one of the binary bitwise operator, <<, >>, &, | and ^. It is important to note the parentheses around expr. So x *= y + 10; means x = x * (y + 10); and, not, x = x * y + 10; 13.0 Bitwise operators C has following binary bitwise operators: &, for bitwise AND, |, for bitwise inclusive OR, ^, for bitwise exclusive OR, <<, for left shift and >>, for right shift. Also there is the unary ~ operator for 1s complement. These bitwise operators can be applied to all integer types, char, signed short, unsigned short, signed int, unsigned int, etc. The bitwise operators cannot be applied to float, double and long double types. We should be careful in using signed integers for bitwise operations as right shift operation fills in sign bits on the left, whereas the expectation might have been that of zero. So, by default, unsigned integers should be used for bitwise operations and signed integers should be used only when they are really required. In C programming,It is best to use bitwise operators with unsigned integers because, if you use signed operands for bitwise operations, the sign bit can bring in unexpected results. Also, bit masks are hardly a signed quantity. we often encounter flags, which are of type int and are bit masks, which means the individual bits mean some setting value. For example, consider the open system call to create and open a new a file. int open (const char *pathname, int flags, mode_t mode); The third parameter, mode, is for file permissions of the newly created file. The bit mask for some the permissions are, We can set bits in the operand with the | operator. To reset bits, we use do an & operation of the operand with a bit mask having the relevant bits set as 0 and the rest as 1. For example, mode_t mode; mode = 0; // Set read, write and execute permissions for user mode |= S_IRWXU; // Set read, write and execute permissions for group mode |= S_IRWXG; // Set read, write and execute permissions for others mode |= S_IRWXO; // remove read, write and execute permissions for others mode &= ~S_IRWXO; // Check whether read, write and execute bits are set for user if ((mode & S_IRWXU) == S_IRWXU) .... Note the expression to check whether read, write and execute bits are set for user. A common error is to check whether (mode & S_IRWXU) is true. The correct expression is to first find (mode & S_IRWXU) and then check whether it is equal to S_IRWXU. 14.0 Conditional expressions Consider the if statement, if (a >= 0) x = a; else x = -a; The if statement can be replaced with a conditional expression using the ternary operator, ?: x = (a >= 0) ? a : -a; The ternary operator combines three expressions expr1 ? expr2 : expr3 First expr1 is evaluated. If it evaluates true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated. If expr1 is true, expr2 is the value of the whole expression, otherwise, expr3 is the value of the whole expression. 15.0 Precedence and associativity table The following table gives the precedence and associativity rules for operators in C language.
https://www.softprayog.in/programming/c-programming-tutorial-data-types-and-expressions
CC-MAIN-2021-17
refinedweb
3,269
65.01
Is there any robot framework keyword to sort a list of strings which has special characters? I have a list of strings which contains special characters in it, The list is below: 1.Kevin_richard 2.Dan_ronald 3.Daniel_white 4.David_jacob 5.eddie_bacon To sort the list in ascending order I have used Sort List(The strings are sorted alphabetically and the numbers numerically) keyword from collections library. *** Settings *** *** Test Cases *** TC Title Sort the given list of usernames in ascending order *** Keywords *** Sort the given list of usernames in ascending order ${sorted_order_asc}= Copy List ${default_order_username} //default order represents list of five user names Sort List ${sorted_order_asc} On executing the above script, the list is sorted in the following order: - Daniel_white - Dan_ronald - David_jacob - eddie_bacon - Kevin_richard But this is not the expected sort order. In the above list, Dan_ronald has to be at the top of the list. Sort List ignores special characters hence underscore after Dan is skipped and checks for the next alphabet(r vs i). As a result of it, Daniel_white tops the list. Any help to sort out this issue will be appreciated. 2 answers - answered 2018-11-08 08:00 A. Kootstra This can be most easily achieved by using a python function in the below example a custom robot keyword is created that takes a string with the correct character sort order. This then uses that to sort the list items accordingly. *** Settings *** Library Collections *** Variables *** @{list} ... Kevin_richard ... Dan_ronald ... Daniel_white ... David_jacob ... eddie_bacon *** Test Cases *** Standard Sorting ${sorted_list} Sort List Custom ${list} ${result} Create List ... Dan_ronald ... Daniel_white ... David_jacob ... Kevin_richard ... eddie_bacon Lists Should Be Equal ${sorted_list} ${result} Reverse Sorting ${alphabet_reverse} Set Variable zyxwvutsrqpomnlkjihgfedcbaZYXWVUTSRQPOMNLKJIHGFEDCBA9876543210_${SPACE} ${sorted_list} Sort List Custom ${list} ${alphabet_reverse} ${result} Create List ... eddie_bacon ... Kevin_richard ... David_jacob ... Daniel_white ... Dan_ronald Lists Should Be Equal ${sorted_list} ${result} *** Keywords *** Sort List Custom [Documentation] ... Sort a list using a custom sort order ... ... This keyword sorts a list according to a custom sort order ... when given, or the default one when not provided. ... ... Arguments: ... - input_list {list} a list of strings to be sorted. ... - alphabeth {string} a string of characters according to which order they ... must be sorted. ... ... Returns: {list} the sorted list. ... [Arguments] ${input_list} ${alphabet}=${SPACE}_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ${ns} Create Dictionary alphabet=${alphabet} input_list=${input_list} ${sorted} Evaluate sorted(input_list, key=lambda word: [alphabet.index(c) for c in word]) namespace=${ns} [Return] ${sorted} - answered 2018-11-08 08:37 Todor Sort List ignores special characters hence underscore after Dan is skipped and checks for the next alphabet(r vs i). That is not so - Sort Listdoes not modify the members in any way, nor it skips any charterers. When it ran, it compared the 'i'to '_'and (somehow) decided 'i' is with a smaller character code than the '_'. In fact, the Sort Listis just a wrapper over python's sort()method. I've ran your source list in a repl, and it came out sorted in the expected way - 'Dan_' before 'Daniel_': >>> a = ["Kevin_richard", "Dan_ronald", "Daniel_white", "David_jacob", "eddie_bacon"] >>> a ['Kevin_richard', 'Dan_ronald', 'Daniel_white', 'David_jacob', 'eddie_bacon'] >>> a.sort() >>> a ['Dan_ronald', 'Daniel_white', 'David_jacob', 'Kevin_richard', 'eddie_bacon'] There is something else troubling - in normal sorting "Kevin" should come before "eddie" (the capital latin letters are with codes before the small ones), but that is not the output in your question's body. In fact, your output looks like sorted case-insensitive, something the keyword cannot do for sure. Which leads me to think there is more to this: - Are you sure the sample list you've pasted is precisely the same as the one you're working with in your code? It could be with Unicode charters that resemble the latin ones (like Cyrillic, there are collisions on the visual outlook on many of them), which were not pasted in the question as-is. - Are there any whitespace characters around the source values? If yes, that will influence the sorting (and could explain the 'eddie' case) - strip them before doing the sort, if you want to compare just the names. - Is the code sample everything you do to get this result? - Finally - I've removed the numbers in front of the values - they would have influenced the sorting a lot, but have to ask - they are not in the source values, right?
http://quabr.com/53202261/is-there-any-robot-framework-keyword-to-sort-a-list-of-strings-which-has-special
CC-MAIN-2018-47
refinedweb
704
61.06
Channel. Let’s learn channelz through a simple example which uses channelz to help debug an issue. The helloworld example from our repo is slightly modified to set up a buggy scenario. You can find the full source code here: client, server. Client setup: The client will make 100 SayHello RPCs to a specified target and load balance the workload with the round robin policy. Each call has a 150ms timeout. RPC responses and errors are logged for debugging purposes. Running the program, we notice in the log that there are intermittent errors with error code DeadlineExceeded (as shown in Figure 1). However, there’s no clue about what is causing the deadline exceeded error and there are many possibilities: Figure 1. Program log screenshort Let’s turn on grpc INFO logging for more debug info and see if we can find something helpful. Figure 2. gRPC INFO log As shown in Figure 2, the info log indicates that all three connections to the server are connected and ready for transmitting RPCs. No suspicious event shows up in the log. One thing that can be inferred from the info log is that all connections are up all the time, therefore the lost connection hypothesis can be ruled out. To further narrow down the root cause of the issue, we will ask channelz for help. Channelz provides gRPC internal networking machinery stats through a gRPC service. To enable channelz, users just need to register the channelz service to a gRPC server in their program and start the server. The code snippet below shows the API for registering channelz service to a grpc.Server. Note that this has already been done for our example client. import "google.golang.org/grpc/channelz/service" // s is a *grpc.Server service.RegisterChannelzServiceToServer(s) // call s.Serve() to serve channelz service A web tool called grpc-zpages has been developed to conveniently serve channelz data through a web page. First, configure the web app to connect to the gRPC port that’s serving the channelz service (see instructions from the previous link). Then, open the channelz web page in the browser. You should see a web page like Figure 3. Now we can start querying channelz! Figure 3. Channelz main page As the error is on the client side, let’s first click on TopChannels. TopChannels is a collection of root channels which don’t have parents. In gRPC-Go, a top channel is a ClientConn created by the user through Dial or DialContext, and used for making RPC calls. Top channels are of Channel type in channelz, which is an abstraction of a connection that an RPC can be issued to. Figure 4. TopChannels result So we click on the TopChannels, and a page like Figure 4 appears, which lists all the live top channel(s) with related info. As shown in Figure 5, there is only one top channel with id = 2 (Note that text in square brackets is the reference name of the in memory channel object, which may vary across languages). Looking at the Data section, we can see there are 15 calls failed out of 100 on this channel. Figure 5. Top Channel (id = 2) On the right hand side, it shows the channel has no child Channels, 3 Subchannels (as highlighted in Figure 6), and 0 Sockets. Figure 6. Subchannels owned by the Channel (id = 2) A Subchannel is an abstraction over a connection and used for load balancing. For example, you want to send requests to “google.com”. The resolver resolves “google.com” to multiple backend addresses that serve “google.com”. In this example, the client is set up with the round robin load balancer, so all live backends are sent equal traffic. Then the (logical) connection to each backend is represented as a Subchannel. In gRPC-Go, a SubConn can be seen as a Subchannel. The three Subchannels owned by the parent Channel means there are three connections to three different backends for sending the RPCs to. Let’s look inside each of them for more info. So we click on the first Subchannel ID (i.e. “4[]”) listed, and a page like Figure 7 renders. We can see that all calls on this Subchannel have succeeded. Thus it’s unlikely this Subchannel is related to the issue we are having. Figure 7. Subchannel (id = 4) So we go back, and click on Subchannel 5 (i.e. “5[]”). Again, the web page indicates that Subchannel 5 also never had any failed calls. Figure 8. Subchannel (id = 6) And finally, we click on Subchannel 6. This time, there’s something different. As we can see in Figure 8, there are 15 out of 34 RPC calls failed on this Subchannel. And remember that the parent Channel also has exactly 15 failed calls. Therefore, Subchannel 6 is where the issue comes from. The state of the Subchannel is READY, which means it is connected and is ready to transmit RPCs. That rules out network connection problems. To dig up more info, let’s look at the Socket owned by this Subchannel. A Socket is roughly equivalent to a file descriptor, and can be generally regarded as the TCP connection between two endpoints. In grpc-go, http2Client and http2Server correspond to Socket. Note that a network listener is also considered a Socket, and will show up in the channelz Server info. Figure 9. Subchannel (id = 6) owns Socket (id = 8) We click on Socket 8, which is at the bottom of the page (see Figure 9). And we now see a page like Figure 10. The page provides comprehensive info about the socket like the security mechanism in use, stream count, message count, keepalives, flow control numbers, etc. The socket options info is not shown in the screenshot, as there are a lot of them and not related to the issue we are investigating. The Remote Address field suggests that the backend we are having a problem with is “127.0.0.1:10003”. The stream counts here correspond perfectly to the call counts of the parent Subchannel. From this, we can know that the server is not actively sending DeadlineExceeded errors. This is because if the DeadlineExceeded error is returned by the server, then the streams would all be successful. A client side stream’s success is independent of whether the call succeeds. It is determined by whether a HTTP2 frame with EOS bit set has been received (refer to the gRFC for more info). Also, we can see that the number of messages sent is 34, which equals the number of calls, and it rules out the possibility of the client being stuck somehow and results in deadline exceeded. In summary, we can narrow down the issue to the server which serves on 127.0.0.1:10003. It may be that the server is slow to respond, or some proxy in front of it is dropping requests. Figure 10. Socket (id = 8) As you see, channelz has helped us pinpoint the potential root cause of the issue with just a few clicks. You can now concentrate on what’s happening with the pinpointed server. And again, channelz may help expedite the debugging at the server side too. We will stop here and let readers explore the server side channelz, which is simpler than the client side. In channelz, a Server is also an RPC entry point like a Channel, where incoming RPCs arrive and get processed. In grpc-go, a grpc.Server corresponds to a channelz Server. Unlike Channel, Server only has Sockets (both listen socket(s) and normal connected socket(s)) as its children. Here are some hints for the readers: You should notice that the number of messages received by the server socket is the same as sent by the client socket (Socket 8), which rules out the case of having a misbehaving proxy (dropping request) in the middle. And the number of messages sent by the server socket is equal to the messages received at client side, which means the server was not able to send back the response before deadline. You may now look at the server code to verify whether it is indeed the cause. Server setup: The server side program starts up three GreeterServers, with two of them using an implementation (server{}) that imposes no delay when responding to the client, and one using an implementation (slowServer{}) which injects a variable delay of 100ms - 200ms before sending the response. As you can see through this demo, channelz helped us quickly narrow down the possible causes of an issue and is easy to use. For more resources, see the detailed channelz gRFC. Find us on github at.
https://grpc.io/blog/a_short_introduction_to_channelz/
CC-MAIN-2019-22
refinedweb
1,454
71.75
This is an updated version of the article originally posted on 29th March 2014 at Programmer’s Ranch. The source code for this article is available at the Gigi Labs BitBucket repository. In this article, we’re going to learn how we can write text in our window. To do this, we’ll use the SDL_ttf library. Setting it up is almost identical to how we set up SDL_image in “Loading Images in SDL2 with SDL_image“. You need to download the Visual C++ development libraries from the SDL_ttf homepage: Then, extract the lib and include folders over the ones you have in your sdl2 folder. You should end up with an SDL_ttf.h in your include folder, and you should get SDL2_ttf.lib and a few DLLs including SDL_ttf.dll in your lib\x86 and lib\x64 folders. In your Linker -> Input, you’ll then need to add SDL2_ttf.lib: Good. Now, let’s start with the following code which is a modified version of the code from about halfway through “Displaying an Image in an SDL2 Window“: #include <SDL.h> int main(int argc, char ** argv) { bool quit = false; SDL_Event event; SDL_Init(SDL_INIT_VIDEO); SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); while (!quit) { SDL_WaitEvent(&event); switch (event.type) { case SDL_QUIT: quit = true; break; } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } The first thing we need to do in order to use SDL_ttf is include the relevant header file: #include <SDL_ttf.h> Then, we initialise the SDL_ttf library right after we call SDL_Init(): TTF_Init(); …and we clean it up just before we call SDL_Quit(): TTF_Quit(); Right after we initialise our renderer, we can now load a font into memory: TTF_Font * font = TTF_OpenFont("arial.ttf", 25); TTF_OpenFont() takes two parameters. The first is the path to the TrueType Font (TTF) that it needs to load. The second is the font size (in points, not pixels). In this case we’re loading Arial with a size of 25. A font is a resource like any other, so we need to free the resources it uses near the end: TTF_CloseFont(font); We can now render some text to an SDL_Surface using TTF_RenderText_Solid(). which takes the font we just created, a string to render, and an SDL_Color which we are passing in as white in this case: SDL_Color color = { 255, 255, 255 }; SDL_Surface * surface = TTF_RenderText_Solid(font, "Welcome to Gigi Labs", color); We can then create a texture from this surface as we did in “Displaying an Image in an SDL2 Window“: SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, surface); And yet again, we should not forget to release the resources we just allocated near the end, so let’s do that right away: SDL_DestroyTexture(texture); SDL_FreeSurface(surface); Now all we need is to actually render the texture. We’ve done this before; just add the following just before the end of your while loop: SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); Okay, now before we actually run this program, we need to put our Arial TTF font somewhere where our program can find it. Go to C:\Windows\Fonts, and from there copy the Arial font into the Debug folder where your executable is compiled. This will result in several TTF files, although we’re only going to use arial.ttf. We will also need the usual SDL2.dll, along with the SDL_ttf DLLs (libfreetype-6.dll, zlib1.dll and SDL2_ttf.dll): Great, now let’s admire the fruit of our work: Nooooooooooooooo! This isn’t quite what we were expecting, right? This is happening because the texture is being stretched to fill the contents of the window. The solution is to supply the dimensions occupied by the text in the dstrect parameter of SDL_RenderCopy() (as we did in “Displaying an Image in an SDL2 Window“). But how can we know these dimensions? If you check out Will Usher’s SDL_ttf tutorial, you’ll realise that a function called SDL_QueryTexture() can give you exactly this information (and more). So before our while loop, let’s add the following code: int texW = 0; int texH = 0; SDL_QueryTexture(texture, NULL, NULL, &texW, &texH); SDL_Rect dstrect = { 0, 0, texW, texH }; Finally, we can pass dstrect in our call to SDL_RenderCopy(): SDL_RenderCopy(renderer, texture, NULL, &dstrect); Let’s run the program now: Much better! 🙂 In this article, we learned how to use the SDL_ttf to render text using TTF fonts in SDL2. Using the SDL_ttf library in a project was just the same as with SDL_image. To actually use fonts, we first rendered text to a surface, then passed it to a texture, and finally to the GPU. We used SDL_QueryTexture() to obtain the dimensions of the texture, so that we could render the text in exactly as much space as it needed. We also learned how we can set up our project to use the same path regardless of whether we’re running from Visual Studio or directly from the executable.
https://gigi.nullneuron.net/gigilabs/2015/11/13/
CC-MAIN-2020-05
refinedweb
830
60.14
The generated controller code includes commented code that allows you to add a route for the controller. Change the code in App_Start/WebApiConfig.cs with the following lines that create an entity data model, also known as EDM, for the OData endpoint and add a route to this OData endpoint. using System.Web.Http; using System.Web.Http.OData.Builder; using Games.Models; namespace Games { public static class WebApiConfig { public static void Register(HttpConfiguration config) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Game>("Games"); config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel()); } } } The System.Web.Http.OData.Builder.ODataConventionModelBuilder class allows you to automatically map CLR classes to an EDM model based on a set of default naming conventions. You can have more control over the generating process by calling ODataModelBuilder methods to create the EDM. The call to the EntitySet method registers an entity set as part of the model. In this case, the name of the entity set is specified as Games in the single argument, and the conventions assume the controller is named GamesController. You can make additional calls to EntitySet to create the EMD model for each entity set you want to make available in a single endpoint. Finally, the call to config.Routes.MapODataRoute maps the specified OData route and adds it to the OData endpoint. The first parameter specifies a friendly name for the route, and the second parameter sets the URI prefix for the endpoint. Thus, the URI for the Games entity set is /odata/Games. Obviously, it is necessary to add the hostname and port to the URI. For example, if the project URL is, the URI for the Games entity set will be. The third parameter is the pre-built Microsoft.Data.Edm.IEdmModel that is retrieved from the builder with a call to the GetEdmModel method. In order to check the project URL, right-click on the project name ( Games) in Solution Explorer, select Properties, click on Web, and read the configuration in the Project URL textbox. Working with the OData Endpoint You can press F5 to start debugging, and the OData endpoint will be ready to process requests. You can use either Telerik Fiddler or the curl utility to compose and send requests to the endpoint with different headers and check the results returned by the OData endpoint. Telerik Fiddler is a free Web debugging proxy with a GUI. The curl utility is a free and open source command line tool to transfer data to/from a server and it supports a large number of protocols. You can easily install curl in any Windows version from the Cygwin package installation option, and execute it from the Cygwin Terminal. I'll provide examples for both Fiddler and curl. I'll always use as my project URL in the samples (don't forget to replace it with your project URL in your own code). If you send an HTTP GET request to, you will receive the service document with the list of entity sets for the OData endpoint. In this case, the only entity set is Games. You can execute the following line in a Cygwin terminal to retrieve the service document with curl. curl -X GET "" The following lines show the raw HTTP response: <?xml version="1.0" encoding="utf-8"?> <service xml: <workspace> <atom:titleDefault</atom:title> <collection href="Games"> <atom:titleGames</atom:title> </collection> </workspace> </service> In Fiddler, click Composer or press F9, select GET in the dropdown menu in the Parsed tab, and enter in the textbox at the right-hand side of the dropdown (see Figure 1). Then, click Execute and double click on the 200 result that appears on the capture log. If you want to see the raw response, just click on the Raw button below the Request Headers panel (see Figure 2). Figure 1: Composing a request in Fiddler. Figure 2: Reading the raw response for the request in Fiddler. If you add $metadata to the previous URI, the OData endpoint will return the service metadata document that describes the data model of the service with the Conceptual Schema Definition Language (CSDL) XML language. You can execute the following line in a Cygwin terminal to retrieve the service metadata document with curl. In Fiddler, you don't need to add a backslash ( \) before the dollar sign ( $); you can enter the raw URI:. curl -X GET "\$metadata" The following lines show the raw HTTP response: <?xml version="1.0" encoding="utf-8"?> <edmx:Edmx <edmx:DataServices m: <Schema Namespace="Games.Models" xmlns=""> <EntityType Name="Game"> <Key> <PropertyRef Name="GameId" /> </Key> <Property Name="GameId" Type="Edm.Int32" Nullable="false" /> <Property Name="Name" Type="Edm.String" /> <Property Name="Category" Type="Edm.String" /> <Property Name="ReleaseYear" Type="Edm.Int32" Nullable="false" /> </EntityType> </Schema> <Schema Namespace="Default" xmlns=""> <EntityContainer Name="Container" m: <EntitySet Name="Games" EntityType="Games.Models.Game" /> </EntityContainer> </Schema> </edmx:DataServices> </edmx:Edmx> Establish a breakpoint at the first line of the Post method within the GamesController class to see all the work done under the hood by ASP.NET Web API OData. Then, compose and execute an HTTP POST request to in Fiddler with the following values in the request headers and request body: - Request headers: Content-Type: application/json - Request body: { "Name":"Tetris 2014","Category":"Puzzle","ReleaseYear":2014 } You can achieve the same effect with the following curl command: curl -H "Content-Type: application/json" -d '{ "Name":"Tetris 2013","Category":"Puzzle","ReleaseYear":2013 }' -X POST "" The request specifies that the body will use JSON and the Post method in C# receives a Game instance. This method works the same way as an ASP.NET MVC controller Post method, in which you check the ModelState.IsValid property value. public async Task<IHttpActionResult> Post(Game game) In this case, the model is valid, and when you continue with the execution, either Fiddler or curl will display the following HTTP 201 Created response with the URI for the recently generated element:: HTTP/1.1 201 Created Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Location: Server: Microsoft-IIS/8.0 DataServiceVersion: 3.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcZ2FzdG9uXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTNcUHJvamVjdHNcR2FtZXNcR2FtZXNcb2RhdGFcR2FtZXM=?= X-Powered-By: ASP.NET Date: Sat, 12 Jul 2014 04:09:44 GMT Content-Length: 151 { "odata.metadata":"","GameId":1,"Name":"Tetris 2014","Category":"Puzzle","ReleaseYear":2014 } If you send an HTTP GET request to, you will receive the details for the recently saved element in the default JSON light serialization format. OData 3.0 introduced the JSON light serialization format to reduce footprint. The following two curl commands will produce the same result and will end in a call to the GetGame method with the key parameter that retrieves the Game from the database based on the received key value. (In Fiddler, you just need to add Accept: application/json to Request headers.) curl -X GET "" curl -H "Accept: application/json" -X GET "" With or without the Accept: application/json line added to the request headers, the result will use the JSON light serialization format: { "odata.metadata":"","GameId":1,"Name":"Tetris 2014","Category":"Puzzle","ReleaseYear":2014 } If you want to receive the response with the older OData v2 JSON "verbose" serialization format, you just need to add the Accept: application/json;odata=verbose line to the request headers. For example, the following curl command retrieves the same game with the verbose JSON format: url -H "Accept: application/json;odata=verbose" -X GET "" The third option is to use the Atom Pub XML serialization format. If you want this format, you just need to add the Accept: application/atom+xml line to the request headers. The following curl command retrieves the same game with the Atom Pub XML format: curl -H "Accept: application/json;odata=verbose" -X GET "" The GetGame method is decorated with the [EnableQuery] attribute; hence, you can use OData query parameters. For example, the following HTTP GET request uses the $select option to specify that it just wants the Name property to be included in the response body:. In curl, you need to add a backslash ( \) before the dollar sign ( $): curl -X GET "?\$select=Name" The following lines show the raw HTTP response that only includes the requested property value: { "odata.metadata":"","Name":"Tetris 2014" } The GetGames method is also decorated with the [EnableQuery] attribute. Thus, you can use the $filter query option to select the games that satisfy a specific predicate expression. For example, the following HTTP GET request uses the $filter option with the eq (equal) operator to retrieve the game whose name is equal to Tetris 2014:'Tetris%202014' In curl, you need to add a backslash ( \) before the dollar sign ( $): curl -X GET "?\$filter=Name%20eq%20'Tetris%202014'" The following lines show the raw HTTP response: { "odata.metadata":"","value":[ { "GameId":1,"Name":"Tetris 2014","Category":"Puzzle","ReleaseYear":2014 } ] } The code for the GetGames method simply includes the [EnableQuery] attribute and is just one line that returns an IQueryable<Game>. As you can see, ASP.NET Web API OData performs a lot of work under the hood to parse and translate the OData query options and operators to a Linq query. Conclusion As you have learned from this simple example, ASP.NET Web API OData allows you to take advantage of your existing knowledge of both APS.NET MVC and the ASP.NET Web API to easily create OData endpoints. The good news is that you can customize all the components and easily add features, such as complex server-side behavior modification via the addition of OData actions. Enjoy! Gastón Hillar is a senior contributing editor at Dr. Dobb's.
http://www.drdobbs.com/open-source/using-odata-from-aspnet/240168672?pgno=2
CC-MAIN-2015-11
refinedweb
1,612
54.22
The W3C Document Object Model was an early effort to gain fine-grained control over a document in memory. This hack introduces you to how DOM works. The Document Object Model or DOM () is a W3C-specified recommendation set that provides facilities to "allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page" (). In other words, DOM is a tree-based API that allows you to pick an XML document (or HTML document) apart into its constituent parts, examine those parts, change them, and stuff them back into a document. The first release of DOM came out in 1998 as a single document, with a second edition appearing in 2000 (). Level 2 of DOM appeared later in 2000 and consists of not less than six modules: Core, Views, Events, Style, Traversal, Range, and HTML. You can get the whole package in a single ZIP archive at. Level 3 just reached recommendation status. It adds a Validation module () and a Load and Save module (). It also updates the Core module (). DOM represents documents as a hierarchy or tree of nodes. These nodes include Document, Element, Comment, and Text. These nodes are specified as interfaces that can be implemented by an application of DOM. Usually, the methods specified by these interfaces can manipulate the nodes in some way. Here is a sampling of a few of the methods specified in the Element interface: getAttribute lets you retrieve an attribute by name, and setAttribute adds a new attribute with a value. The NS variants let you retrieve an attribute by local name and namespace URI, plus add an attribute with qualified name, namespace URI, and a value. These return a list of all descendent elements with the give tag name. The NS version uses a local name and a namespace URI. hasAttribute returns true when it finds an attribute with the given name; likewise, hasAttributeNS returns true when it finds an attribute with the given local name and namespace URI. In general, DOM stores whole documents in memory, which works fine when you are dealing with small or even medium size files; however, with large files you are likely to experience performance hits. Other APIs?such as SAX [Hack #97], which is event-based?are a better choice for processing large documents. DOM is implemented in a number of languages, such as Java and Python (). This hack demonstrates a few small applications that use DOM: DOM Inspector, and Python and Java programs that are run at the command line. The Mozilla and Firefox browsers offer a feature called DOM Inspector (). DOM Inspector provides a handy, straightforward DOM view of a document. With DOM Inspector, you can examine and even edit attributes in any web document using DOM techniques, and you can navigate through the hierarchy of the document with a two-paned window that allows a variety of document and node views. In Firefox, you can access this feature by choosing Tools DOM Inspector. If you were already viewing time.xml in Firefox, it would appear in the DOM Inspector when you invoke the tool. If not, you could enter the URL for the file in the address bar and then click Inspect. time.xml is shown in DOM Inspector in Figure 7-2. (I have turned off anonymous content, and the detection of whitespace nodes under the View menu, plus the display of id and class attributes by clicking the small window button on the upper-right of the left pane.) The nodes in time.xml are represented in tree form in the left pane, and the atomic node (an element) is highlighted. Information about the atomic node is displayed in the right pane. There, for example, you can see that atomic has a signal attribute node with a value of true. The representation of node names as #document, #comment, or #text, with the preceding #, comes from the DOM specification. You can edit attribute values with DOM Inspector. Select a node with attributes in the left pane, and then select an attribute from that node in the right pane. Right-click and select Edit from the menu. You can then change the value of the attribute, but only temporarily?that is, only for the document in memory (you can't write your changes to disk ). Try a document such as time.html that uses style attributes with CSS values. When you edit such values, you can see the change immediately in the browser window. With the browser window in the background, click on a node name such as hour or minute in the DOM Inspector, or right-click on the name and select Blink Element from the menu. When you click on the name, watch in the browser window: you will see a red, blinking box surrounding the node whose name you clicked. So DOM Inspector is a navigation aid. This will be helpful when you are looking at larger, more complex documents. Click through some of the other menus to see what other features DOM Inspector has. Then, open a more complex document to see a more intricate representation of the file in DOM. For example, go to and bring up DOM Inspector. Navigate through the nodes in the left pane and select h2. Then, in the right pane, click on the menu button next to the words Object-DOM Node in the pane's title bar. Choose CSS Style Rules and you will see a listing of style information that applies to the subject node. The Python programming language is growing in popularity. It is easy to learn?if you have any programming background?and is easy to use. Python handles XML well, and has a number of modules to do so; for example, xml.dom.minidom, which is one of Python's implementations of DOM (). Our first example will show how to use minidom with Python's command-line interface. Assuming that you have downloaded () and installed Version 2.3.3 (or later) of Python, type the command python while in the working directory to see the following prompt: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Now, for each line prefixed by >>> in Example 7-19, enter the given command, and the command will be followed by the given output; for example, after you enter lines 1, 2, and 3, you should get the output on lines 4, 5, and 6. >>> from xml.dom import minidom >>> doc = minidom.parse("time.xml") >>> doc.toxml() u'<?xml version="1.0" ?>\n<!-- a time instant --><time timezone="PST">\n <hour>1 1</hour>\n <minute>59</minute>\n <second>59</second>\n <meridiem>p.m.</meridiem> \n <atomic signal="true"/>\n</time>' >>> print doc.toxml() <?xml version="1.0" ?> <!-- a time instant --><time timezone="PST"> <hour>11</hour> <minute>59</minute> <second>59</second> <meridiem>p.m.</meridiem> <atomic signal="true"/> </time> >>> hr = doc.getElementsByTagName("hour")[0] >>> print hr.toxml() <hour>11</hour> >>> ^Z Line 1 imports the minidom package. On line 2, minidom's parse() method places the document time.xml in a DOM structure named doc. On line 3, minidom's toxml() method outputs the document, as stored, to standard output (lines 4-6). Without the print command, the contents of doc are printed out in raw form; however, with print, you get the nicely formatted output seen on lines 8 through 15. Line 16 uses the getElementsByTagName() method to grab the hour node ([0] specifies the first item in the structure holding the element), and line 17 prints it out. The Ctrl-Z on line 19, followed by Enter, ends the Python command-line session. Here's another example. In the file archive you will find the document time.py (Example 7-20), a program that uses the minidom module to convert time.xml into an HTML document. import xml.dom.minidom dom = xml.dom.minidom.parse("time.xml") hour = dom.getElementsByTagName("hour")[0] minute = dom.getElementsByTagName("minute")[0] second = dom.getElementsByTagName("second")[0] meridiem = dom.getElementsByTagName("meridiem")[0] def getText(nodelist): rc = "" for node in nodelist: if node.nodeType = = node.TEXT_NODE: rc = rc + node.data return rc def doTime(time): print "<html>" print "<title>Time Instant</title>" print "<body>" print "<h2>Time Instant</h2>" print " <ul>" doHour(hour) doMinute(minute) doSecond(second) doMeridiem(meridiem) print " </ul>" print "</body>" print "</html>" def doHour(hour): print " <li>Hour: %s</li>" % getText(hour.childNodes) def doMinute(minute): print " <li>Minute: %s</li>" % getText(minute.childNodes) def doSecond(second): print " <li>Second: %s</li>" % getText(second.childNodes) def doMeridiem(meridiem): print " <li>Meridiem: %s</li>" % getText(meridiem.childNodes) doTime(dom) This program parses time.xml, and then uses the getElementsByTagName() method to grab four nodes of interest out of dom: hour, minute, second, and meridiem. Each of these is used in the method definitions on lines 30 through 40. In these definitions, the getText() method (line 9) is called with the childNodes attribute, which retrieves a list of all the child nodes (only text nodes in these cases). In each print call, %s is replaced by the string value returned by getText(). getText() creates an empty string rc and then uses a for loop to collect all the child nodes, if they are text nodes (node.TEXT_NODE tests for that). The doTime() method on line 16 pulls everything together: the manually printed HTML tags and the method calls doHour(), doMinute(), doSecond(), and doMeridiem(), which together form the HTML list item (li) elements. Finally, here is a little bit of DOM as implemented by Java () as part of Sun's Java API for XML Processing, or JAXP (). Java 1.4 and later come standard with JAXP and DOM built in. The file BitODom.java, found in the file archive, has code similar to the command-line Python script shown in Example 7-19. import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import java.io.File; import java.io.IOException; import org.xml.sax.SAXException; public class BitODom { static Document document; public static void main(String[ ] args) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); NodeList list; Node node; document = builder.parse(new File(args[0])); list = document.getElementsByTagName("hour"); node = list.item(0); System.out.println(node); } } The classes imported on lines 1, 2, and 3 were added by Sun. DocumentBuilder allows you to obtain DOM Document instances from an XML document, and DocumentBuilderFactory lets applications get a parser that produces DOM object trees. ParserConfigurationException throws an exception if there is a configuration problem. The interfaces imported on lines 4, 5, and 6 are APIs specified by the W3C. A Document represents an entire XML (or HTML) document. NodeList provides an abstract order-list of nodes, and Node represents an individual node in the DOM. The File class (line 7) helps the parser accept a file for parsing. IOException and SAXException (lines 8 and 9) help the program figure out what to do if there is a problem in main() (line 16). Line 13 instantiates a Document, and lines 18 and 19 build an object from which we can call the parser( ) method (line 23). The NodeList and Node (lines 20 and 21) are necessary for actually doing something with the nodes in document?first placing the hour node in list (line 24), then using the item() method to extract the node from list and put it in node (line 25), then finally printing the node (line 26). Both the source and compiled class files are already in the file archive (BitODom.java and BitODom.class). To recompile the source file, run javac from a command prompt while in the working directory: javac BitODom.java Then run the program with time.xml: java BitODom time.xml Your program output should be: <hour>11</hour> Try BitODom on other documents that contain the hour element (find the files with grep "<hour>" *.xml). This little Java program just gives you a starting point with DOM. Now that you have a basic understanding of how DOM works in Java, you can consult the DOM APIs and start adding other method calls or using attributes on your own to manipulate and change your XML documents (). "Dive into Python," by Mark Pilgrim: Python in a Nutshell, by Alex Martelli (O'Reilly), pages 494-511 Java 1.4 DOM APIs: Java Version 1.4 DOM tutorial: Microsoft's DOM Developer's Guide, with help for programming in C/C++, Visual Basic, and JScript:
https://etutorials.org/XML/xml+hacks/Chapter+7.+Advanced+XML+Hacks/Hack+96+Inspect+and+Edit+XML+Documents+with+the+Document+Object+Model/
CC-MAIN-2021-31
refinedweb
2,137
66.33
Search found 6 matches Search found 6 matches • Page 1 of 1 - Thu May 24, 2012 8:01 am - Forum: Volume 6 (600-699) - Topic: 623 - 500! - Replies: 187 - Views: 44077 Re: 623 - 500! In this problem we must precalculate all possible factorials, and print them out when requested. Calculate factorials of 1 to 1000 takes so mush time. What is the good way to find them? bignum f[1001]; int main(){ int n; f[0] = bignum("1"); f[1] = bignum("1"); for (int i = 2; i <= 1000; i++) f[i] = ... - Sun May 20, 2012 4:42 pm - Forum: Volume 4 (400-499) - Topic: 495 - Fibonacci Freeze - Replies: 222 - Views: 30890 Re: 495 - Fibonacci Freeze I got TL for this problem. My algorithm that find n'th fibonacci number is not fast. Can someone help me? int main(){ int n; while (cin >> n) { bignum a, b; a = bignum(); // This means a = 0 b = bignum(); b.digits = 1; b.a[0] = '1'; // This means b = 1 if (n == 0) cout << "The Fibonacci number for "... - Sun May 20, 2012 1:08 pm - Forum: Volume 3 (300-399) - Topic: 371 - Ackermann Functions - Replies: 196 - Views: 28788 Re: 371 - Anckerman Functions Thank you Brian... - Sat May 19, 2012 9:56 pm - Forum: Volume 3 (300-399) - Topic: 371 - Ackermann Functions - Replies: 196 - Views: 28788 Re: 371 - Anckerman Functions Hello. I was wondering if you might be able to help me! Why I got RE for this problem? Here is my code: Thank You Code: Select all Removed! - Sat Mar 17, 2012 5:28 pm - Forum: Volume 100 (10000-10099) - Topic: 10038 - Jolly Jumpers - Replies: 445 - Views: 79930 Re: 10038 - Jolly Jumpers Can Someone help me? What's the problem of this code??? :-/ #include <iostream> using namespace std; int main(){ int n; while (cin >> n) { int m, j, d; cin >> m; bool jolly = true; bool inc1 = false; if (n > 1) { cin >> j; d = max(j, m) - min(j, m); if (d == n - 1) inc1 = false; else if (d == 1) inc... - Tue Jan 03, 2012 6:33 pm - Forum: Volume 2 (200-299) - Topic: 272 - TEX Quotes - Replies: 136 - Views: 35742 Re: 272 - TeX Quotes Hi guys! What is the wrong of this code? #include <iostream> #include <cstring> #include <string> using namespace std; string s; void Shift(int i){ s += s[s.length() - 1]; for (int j = s.length() - 2; j > i; j--) s[j + 1] = s[j]; } int main(){ while (getline(cin, s)) { if (s.length() > 0) { int j = ... Search found 6 matches • Page 1 of 1
https://onlinejudge.org/board/search.php?author_id=97582&sr=posts
CC-MAIN-2020-05
refinedweb
422
90.7
Dave Thomas and Andy Hunt, the pragmatic programmers, have been interviewed about software development. They discuss topics such as how software development is more like gardening than architecture, firing tracer bullets, and the stratification of developer jobs. Excerpt on Gardening "Andy Hunt: Instead of that very neat and orderly procession, which doesn't happen even in the real world with buildings, software is much more like gardening. You do plan. You plan that." Read the interview with the pragmatic programmers: Gardening with Tracer Bullets Interview: Pragmatic Programmers on Software Gardening (12 messages) - Posted by: Dion Almaer - Posted on: February 25 2004 08:28 EST Threaded Messages (12) - Interview: Pragmatic Programmers on Software Gardening by Ian Mitchell on February 25 2004 11:48 EST - Problem? by Larry Edelstein on February 25 2004 20:00 EST - Problem? by Ian Mitchell on February 26 2004 12:33 EST - Repition reaps rewards by Neil Ellis on February 26 2004 08:09 EST - Repition reaps rewards by Ian Mitchell on February 26 2004 12:43 EST - We do need to keep repeating Best Practices by Chris Mountford on February 26 2004 20:09 EST - refactored mixed metaphor: gardening with stakes in the ground? by Chris Mountford on February 26 2004 20:17 EST - Interview: Pragmatic Programmers on Software Gardening by Daniel Holmes on February 25 2004 14:28 EST - Analogy of buildings v/s garden by Chandra Tanwani on February 26 2004 00:11 EST - Gardens. by Jonathan Sharp on February 26 2004 00:32 EST - Gardens. by Felicity Fendi on February 26 2004 13:39 EST - Gardening concept by John Gagon on February 27 2004 13:33 EST Interview: Pragmatic Programmers on Software Gardening[ Go to top ] OK, I need to vent about something. The principles they talk about have been known and expounded upon for at least ten years that I can remember. The authors are not saying anything new. - Posted by: Ian Mitchell - Posted on: February 25 2004 11:48 EST - in response to Dion Almaer None of this is the fault of either Thomas or Hunt. The simple fact is that the industry as a whole only pays lip service to best practices, and continues to shovel code regardless. A case in point is the "tracer bullet" technique they refer to. Back in the day we were talking about the same thing, except we called it "sliver" or "stovepipe" prototyping - a stake in the ground to find how the requirements squish and move in the areas of greatest risk. The gardening metaphor is another example. We have known for many, many years that the development process is really one of cultivation. In the mid-nineties I wrote an article for ROAD or JOOP about how the development process can be described as fractalform and I recall that Jim Rumbaugh and others were saying similar things at the same time. What I really want to read about now is not a rehash of best practices, but how the blazes we can get them to actually stick. Problem?[ Go to top ] What I really want to read about now is not a rehash of best practices, but how the blazes we can get them to actually stick. - Posted by: Larry Edelstein - Posted on: February 25 2004 20:00 EST - in response to Ian Mitchell Ian - I'm wondering if you're thinking more about getting the influence to make the practices stick, or how to implement them. Problem?[ Go to top ] Ian - I'm wondering if you're thinking more about getting the - Posted by: Ian Mitchell - Posted on: February 26 2004 12:33 EST - in response to Larry Edelstein > influence to make the practices stick, or how to implement them. Personally I'd settle for the influence to implement them, even just once! ;-) Repition reaps rewards[ Go to top ] That may be true, but the more times something gets said the more likely it is that oneday someone will listen. As practises and technologies change the metaphors and established wisdom have to be rephrased and often relearnt. There's no harm in that. We see this in business, religion, politics, art etc. The same ideas carry on but often the lessons have to be relearnt. And why? Well it's a whole bunch of new people how need to learn and most youngsters think a new idea is better than an old idea, isn't it. - Posted by: Neil Ellis - Posted on: February 26 2004 08:09 EST - in response to Ian Mitchell Management will learn to listen to developers, when the requirements team listen to them, and the requirements team will learn to listen when customers listen to them and customers will listen to the company when the company produces what it required. And the company will produce what the customer wants when the developers listen to the managers, and the managers listen to the requirements team and the requirements team listen to the customer and the customer ... We all look for someone to blame, but the reasons things are like they are is a general demanding culture that doesn't care about quality, workmanship, quality of life or in fact any human values - just output and consumption. So if we want things to improve we just gotta keep fighting our little battles and hell even if nothing else changes our self-respect will and that's gotta be worth something. Anyway it's always refreshing to here from these guys as they have a good way of capturing the essence of coding as a craft. Repition reaps rewards[ Go to top ] Alas, I know you are right. We need repetition to stand any chance in the larger struggle, and we do need authors like Hunt and Thomas to address the up-and-coming bunch. - Posted by: Ian Mitchell - Posted on: February 26 2004 12:43 EST - in response to Neil Ellis In the meantime, reality shall continue to exact its own revenge (fade to bitter, twisted cackling)... We do need to keep repeating Best Practices[ Go to top ] Just a note to say I think it's important that best practices such as those mentioned in the article, and those enumerated in The Pragmatic Programmer, although not new, are continually "rehashed". - Posted by: Chris Mountford - Posted on: February 26 2004 20:09 EST - in response to Ian Mitchell The problem I face more regularly than not is that developers simply are not aware of best practice. Perhaps it's just my bad luck, but the developers who know, adopt and extend best practice are in the minority. Of course they're a pleasure to work with. Perhaps the repetition and re-presentation of these ideas will help those of us who have to continually explain them to others and to have a greater selection of metaphors and anecdotes to use when trying to convert a blank stare into an "a-ha!". Beyond this, what is necessary is that less experienced developers (in a rapidly expanding industry, these are surely a vast majority) have experience doing things badly, and doing things well. From this they'll learn. I have found The Pragmatic Programmer and other stuff from Andy and Dave (like the article) to be very accessible to less experienced developers and useful in my crusade to improve practices. Ian Mitchell, I share your frustration with hearing things that are presented as if they are new though I think the assumption that an article on Software Engineering will necessarily be chocked with ground-breaking edge-bleeding ideas is one that will need to be challenged more as the discipline and the profession matures. Moores law does not require a revolution in development practices every week - about the only thing that does is the hype engine that sells products to clueless IT Managers. I look forward to the day when the average age of a useful computer book is measured in decades and since the web I tend to prefer to buy books with better longevity for much the same reason. I look forward to the era beyond the big bang of the computer revolution towards consolidation. I think that era will be even more exciting. refactored mixed metaphor: gardening with stakes in the ground?[ Go to top ] Ian, I just noticed you managed to remove a disconcerting mixed metaphor! "gardening with tracer bullets" isn't really as compelling as your use of a "stake in the ground". - Posted by: Chris Mountford - Posted on: February 26 2004 20:17 EST - in response to Ian Mitchell Interview: Pragmatic Programmers on Software Gardening[ Go to top ] OK, I'll be the first to extend this analogy this way. - Posted by: Daniel Holmes - Posted on: February 25 2004 14:28 EST - in response to Dion Almaer I guess this is why when management wants the developers (the garden) to be more productive they shovel on the manure :-) Analogy of buildings v/s garden[ Go to top ] Hi - Posted by: Chandra Tanwani - Posted on: February 26 2004 00:11 EST - in response to Dion Almaer The software (as a product) and software management are two different things. A software application is more closer to building than a garden. A garden is closer analogy from project management perspective, I think. The building shape is not changed frequently because the expectations are very much defined in the beginning, which is not the case for Software. Also, changing the building shape is visible effort, while in software, everything is virtual:). It is not the software or software developer who is at fault, it is just that the expectations from the software are not realistic. But we will be at that point soon, when customer wants to change the shape of building (software) and it will be done fast enough to meet the expectations. Read this next move in programming: Gardens.[ Go to top ] I like the analogy around the garden, I can definitely relate to the concept that you start with something neat and tidy, then end up with something that can be different to what is expected. Also, continuing the gardening concept, if the garden is too large (as is in my case at home), then you'll never get full coverage and end up with some parts that are pretty disorganised. Recovering these can be the worst. Also, if you don't water enough, or don't use fertiliser then the plants will end up looking pretty dead. Further, if the soil is too hard, then the carrots end up being pretty curly and don't taste so good. In fact generally you should grow carrots in pots with soft soil so they end up nice and straight. - Posted by: Jonathan Sharp - Posted on: February 26 2004 00:32 EST - in response to Dion Almaer You could hire a gardener to help you out as you are too busy at work......then the landscape architect to help design the thing in the first place - this is kind of expensive, and generally they don't like to get their hands dirty - but prefer to work with concepts. Anyway, I can definitely relate to the stratification of roles. As an architect, it can be pretty difficult to influence designers and developers sometimes due to lack of visibility of what is actually happening. Further, at this lack of visibility continues, one can find that the project can drift off in directions that are not always desirable. BTW. Has anyone read that UNIX book - the Magic Garden? Great read - very complicated. Gardens.[ Go to top ] I also like the analogy around the garden. - Posted by: Felicity Fendi - Posted on: February 26 2004 13:39 EST - in response to Jonathan Sharp Agile stuff is great as manure. Gardening concept[ Go to top ] I think depending on the tier you are working on, - Posted by: John Gagon - Posted on: February 27 2004 13:33 EST - in response to Dion Almaer It's like doing a little bit of artwork, poetry (in something like lojban) and logic puzzles. I do like the garden concept because it implies evolution and the need to maintain and cope with unexpected situations...however, I don't think it is *that* out of control. The requirement changes end up killing certain plants rather than them dying on their own or looking different than what a developer expects. (you also have to deal with pests...you can use unit testing). Anyhow, back to artwork/poetry/puzzles. The poetry is in the syntactic choices available in the language. The artwork is a direct analog to UI building. The puzzles are solving problems step by step in middle tiers. It is also like sorting baseball cards too (you can sort by RMI/batting average, alphabetically etc)...you have to organize concepts into groups. (ie: namespaces, packages, classes, database tables). The artwork is becoming however more and more dominant...it is just interactive artwork. Much of the details can be solved almost automatically in RAD tools. Artwork, novel and poetry writing also require a lot of the same type of personal space and concentration. Cube farms are not so good at doing software or writing novels. John
http://www.theserverside.com/discussions/thread.tss?thread_id=24168
CC-MAIN-2015-22
refinedweb
2,194
57.71
Playing With Java Optional A container object which may or may not contain a non-null value Introduction During your life as a Java developer, you have surely encountered a NullPointerException. Read on if this is the exception you encounter the most. I imagine you might be thinking something like, “Yes, I agree, NullPointerExceptions is a pain for any Java developer, novice or expert, but there’s not much we can do about them.“ This is a common feeling in the programming world. Until Java 8 introduced Optional. Optional allows an object to wrap those nullable values. The intention is to finally give us the ability to express a type for the returned value more clearly. Instead of using a Java annotation, which is not checked at compile-time, Optional allows you to boost your methods and indicate that your method probably returns “empty” (and not null) values. The NullPointerException problem Before diving into the usage of Optional, let’s understand what issue it promises to resolve. When we create a java application, we will surely use method chaining to de-reference object properties, which can easily make us fall into the trap of NullPointerException. String authorZipCode = book.getAuthor().getAddress().getZipCode(); In the above code snippet, there could be a NullPointerException in any get method invocations. Therefore, the Optional class solves this problem by wrapping the object we want and manipulating it. Importing Optional First, we start by importing the Optional class located under java.util. import java.util.Optional; Creating Optional object We can build an Optional object by using the empty() method. it will create an empty optional for us. Output: Optional.empty But if we want to create Optional objects with values, we can use the of() method which will create an Optional the value passed in parameter. output: Optional[Hello World] However, if the value passed in the parameter is null it will throw a NullPointerException. So if the value can be null we have to use the ofNullable(T value) method. output: Optional.empty Optional[Hello World] Checking Value Once the Optional object is created, the existence of the values inside the Optional object can be checked with the isPresent() method. output: false true Or vice versa, use the isEmpty() method but it is only available from Java 11. output: true false Conditional Action It is possible to check some conditions and perform some operations on the Optional object with the ifPresent() method. but this is possible only if the Optional object has a value, otherwise, it will do nothing. output: 11 In Java 9, a method called ifPersentOrElse() has been added to further manipulate conditions if Optional has no value with Runnable action. output: Other Return Value When all values are wrapped with Optional, they can be extracted with the get() method. output: Hello World Default Value If we use the get() method to get the value of the Optional object, but this last has a null as a value, It will not differ from not using the Optional, so to make the difference there is a method called orElse(T other) which gives us the ability to do something else in case of null value. output: Hello World Or we could do another thing than just return it by using the orElseGet() method. output: Hello World In Java 9, The or() method has been added to perform and return an Optional value for an optional that returns the original value. output: Optional[Hello World] For Optional without a value, it will return as the value in the or() statement. output: Optional[Default] Exception If we don’t want to return or do anything after checking that the value is null we can throw an Exception as well. output: java.lang.IllegalArgumentException Conditional Return We can verify the returned value of Optional objects with a method filter() to extract the values we want and remove the unwanted values with a condition. output: true false Transforming Value You can change the value in the Optional object that contains the value with the map() method. output: HELLO WORLD But in case of manipulation of an Optional of Optional, we have to use the flatMap() method. output: HELLO WORLD Stream In Java 9, Optional objects can be converted to Streams and can be operated as Streams. output: [HELLO WORLD] Conclusion In this article, we have introduced most of the important features of the Optional class. It allows developers to avoid redundant null checks by returning values that may or may not be present. Understanding its usefulness and how to apply it using simple techniques is an important part of mastering modern Java.
https://medium.com/swlh/playing-with-java-optional-70ffecb9da33?source=post_internal_links---------0----------------------------
CC-MAIN-2020-50
refinedweb
775
50.77
quirky csv On Thursday 24, November 2011 08:51:16 you wrote: > I have a large number of large comma-separated text files that I am > trying to import. "insheet" is not working; it imports the data, but > many lines are missing. I think the reason is the file contains string > fields that a) have embedded spaces, and b) are not enclosed in > quotes. I've run across this and found that, unless you want to write your own csv parser (which is trickier than you might think), you will have to work outside of Stata. That said, it is easy to automate from a do file. I've found Python's csv parser to be quite robust and able to write out the csv files in such a way that Stata will happily read them. The approach I took was to just parse the entire directory of csv's and then import those into Stata. However, let's say you wanted to make a script that you call for each file from within Stata, then the python code should look like this (assuming python 2.7 and actually commas as the separators. Note that whitespace is very important in python): #!/usr/bin/env python # reprocess_csv.py # make files readable for stata import sys import csv DELIMITER = "," def reprocess(in_fn, out_fn): with open(in_fn, 'rb') as in_fd: with open(out_fn, 'wb') as out_fd: reader = csv.reader(in_fd, delimiter=DELIMITER) writer = csv.writer(out_fd, delimiter=DELIMITER) writer.writerows(reader) if __name__ == "__main__": reprocess(sys.argv[1], sys.argv[2]) and then in stata: local my_original_file "bad.csv" tempfile good ! python reprocess_csv.py `my_original_file' `good' insheet using `good', comma I did write this on the fly, so there may be typos that I didn't catch, but it is based on code I've used previously that works reliably. -- James Sams sams.james@gmail.com * * For searches and help try: * * *
http://www.stata.com/statalist/archive/2011-11/msg01289.html
CC-MAIN-2015-35
refinedweb
318
65.52
CodePlexProject Hosting for Open Source Software Hi All, I've got a problem that I can't think of a satisfactory solution to at the moment. I'm looking for some advice. The problem is actually relatively simple. One of the modules I'm dealing with is tiny, all it provides in the UI is a single combobox but the functionality it provides is pretty all encompassing, I'm wondering if anyone has faced this and has a solution. The combobox allows the user to effectively switch the context of the whole application. It publishes one event and subscribes to one event. The published event tells the rest of the subscribed modules to switch context to a certain state. The switching for some modules initiate calls to serialised data on the local machine and for other modules it initiates calls to various WCF services. At that same moment it publishes this event it also goes into a disabled state preventing any more switching. The event it subscribes too is published by a module once it has completed its work and has switched context. The problem is that I don't just want it to go back into an enabled state until *all* the subscribers have successfully completed switching. Effectively the responses will come back in totally random order over various periods of time. I can think of a solution but it doesn't seem particularly robust frankly. I was thinking that when a module subscribes to the "switch context" event it could also register itself with the combobox module, then the combobox could evaluate a list of these subscribes to check for responses, once all responses are in and successful it would then re-enable. Almost a bit like XAML multibinding but for cross-module comms. This almost feels like a mini framework within CAL, maybe I'm also missing something in my knowledge of the EventAggregator. Any ideas would be great. Hi, A possible approach could be adding a property to your event to access the amount of subscribers it has. For example: public class SwitchContextEvent : CompositeWpfEvent<FundOrder> { public int SubscriptionsCount { get { return this.Subscriptions.Count; } } } Since you know how many subscribers there are when you publish the event you can wait until you get the same amount of responses to enable the ComboBox again. Please let me know if this helps. Damian Schenkelman That sounds like an awesome solution. I'm going to have a play with that. Thank You! Jammer 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://compositewpf.codeplex.com/discussions/57214
CC-MAIN-2017-39
refinedweb
449
63.59
This actually works pretty well and I want people to know that I didn’t spend a lot of time researching so I’m sure I’m about to hear that I did this all wrong from everyone, but here was my problem. I was getting plans from an architect in PDF format and I needed to use them for 3D model in blender. Here’s the process I used to get it in to blender. Import PDF in to Inkscape. Save File as Inkscape (inkscapes native format is SVG) Go to blender and import SVG You now have a million curves in blender. {note: after being set straight ignore the lower section and do this Select all of the curves and make sure you have an active curve object as the main selection. Hit Ctrl - J Hit Alt - c } Here is the script I wrote that was a waste of time because I didnt’ know the not section above: Open the console window in blender so you can see status. Select all of the curves with at least one of the curves being actively selected as well. Run the script and press the button in the 3d view to convert all of the curves into a single mesh. Watch the console, the script can take about fifteen minutes if you have thousands of curves which I did And voila, a single mesh from a pdf. I am posting the script here for others (it’s really simple I wrote it in about fifteen minutes), but it did the job for me. The script simply converts thousands of curves into a single mesh. I am posting it here for posterity or in case it is useful in some way to someone else. I am sure there is someone out there that is going to say… you idiot… press Ctrl-alt-F1-Shift-S or something completely non intuitive and I could have converted these curves with a single command, but blenders biggest weakness is figuring that magical combination out on your own, for me it’s easier just to write a python script. {I was RIGHT!!! see below} # #####. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> that's Dr. Peppy of course bl_info = { "name": "Curves to Single Object", "author": "Nick Keeline(nrk)", "version": (0, 0), "blender": (2, 7, 7), "location": "View3D > Tool Shelf > Curves to Single Object", "description": "Allows you to select millions of curves and convert them to meshes and combine them all in to a single object", "wiki_url": "NA" "NA", "tracker_url": "NA" "NA", "category": "Object"} import bpy from bpy.props import BoolProperty, EnumProperty from bpy.types import Operator, Panel class VIEW3D_PT_tools_CamPaint(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'TOOLS' bl_label = "Curves to Single Object" bl_context = "objectmode" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): active_obj = context.active_object layout = self.layout col = layout.column(align=True) col.operator("curve2obj.cur2obj", text="Curves to Object") class CameraPaint(Operator): """Setup a Camera to Paint on a Mesh""" bl_idname = "curve2obj.cur2obj" bl_label = "Curves to Single Object" bl_register = True bl_undo = True @classmethod def poll(cls, context): if not context.active_object: return False else: return ((context.active_object.type == 'CURVE')) def execute(self, context): # Make variable that is the current .blend file main data blocks blend_data = context.blend_data scene = bpy.context.scene objects = bpy.context.selected_objects curveobj = objects[0] i = 1 numselectedobjs = len(bpy.context.selected_objects) for obj in objects: print ('Converting ' + str(i) + ' of ' + str(numselectedobjs) + ' percent done:' + str(100*(float(i)/float(numselectedobjs)))) # Deselect All bpy.ops.object.select_all(action='DESELECT') # Select the object obj.select = True scene.objects.active = obj bpy.ops.object.convert(target='MESH') i = i + 1 for obj in objects: # Select the object obj.select = True scene.objects.active = obj scene.objects.active = objects[0] bpy.ops.object.join() return {'FINISHED'} def register(): bpy.utils.register_module(__name__) def unregister(): bpy.utils.unregister_module(__name__) if __name__ == "__main__": register()
https://blenderartists.org/t/pdf-to-blender-mesh-conversion/671843
CC-MAIN-2020-50
refinedweb
641
57.16
Key Takeaways - .NET MAUI (.NET Multi-platform App UI) will bring a lot of consistency to the developer experience, and enables some new, innovative experiences for developers - Some of the main goals of .NET MAUI are about modernizing the design capabilities, and extending from mobile to desktop platforms starting with Windows and macOS - Single project is a solution to align more closely with this developer focus while still providing all the native platform access important for delivering truly native experiences and it will be the default experience for new projects. - The migration from Xamarin.Forms to .NET MAUI will be well defined, and the development team will try to make it smooth as possible. - .NET MAUI will bring a lot of options to choose from and to decide what is best way for developers to design and develop their apps .NET MAUI is an evolution of the Xamarin.Forms toolkit, aimed at improving app performance and simplifying multi-platform app development. The framework will provide a single codebase with built-in resources to access the native API for all modern operating systems (Android, iOS, macOS, Windows). Developers will be able to develop multi-platform applications under a single project structure, adding different resources or source code files for different platforms when necessary. With all this great plan on the roadmap, InfoQ decided to interview David Ortinau, currently principal program manager for Mobile Developer Tools at Microsoft focused on Xamarin.Forms and now on .NET MAUI - to talk about .NET MAUI, the goals behind it, it’s future, and the migration path from Xamarin.Forms. InfoQ: What is the .NET MAUI project and what are the main goals behind it? David Ortinau: It all begins with unification. We are moving our client application development to .NET 6 from .NET Framework, using the same base class library (BCL) as other application types, and modernizing our project system to align with the rest of .NET. Today Xamarin projects use what I call a "frankenproj" which is a series of workarounds that are legacy from when Xamarin wasn't yet part of Microsoft. This will bring a lot of consistency to the developer experience, and enables some new, innovative experiences for developers in .NET MAUI. Our goals are driven by our customers. We spend a huge amount of time learning from companies and developers about how we can help them achieve more success. To that end we are investing focused effort to improve overall quality of the product, and application performance and size. These two are ongoing goals, and we are already seeing positive signs in our ad hoc benchmarks that .NET MAUI will be a nice step forward from Xamarin.Forms. Our other two goals are about modernizing the design capabilities, and extending from mobile to desktop platforms starting with Windows and macOS. When Xamarin.Forms was created over seven years ago, the market trend was to deliver a platform-specific look and feel for your apps. Over time this trend has moved towards delivering a more consistent design for the app no matter where it runs. .NET MAUI is making controls easier to customize, and adopting a unified default design that is more aligned to your goals. InfoQ: Currently Microsoft and community support for Xamarin.Forms are great! But, what will happen with Xamarin.Essentials and all of those great third-party libraries which we use today in Xamarin.Forms projects? Ortinau: Xamarin.Essentials has proven to be so fundamental that it has been merged into .NET MAUI. No matter what kind of client application you are developing, you have everything you need at your fingertips. The code is designed to be linker safe, so your application only compiles the features you use in your app. All active libraries in the ecosystem should migrate to .NET 6. Those that have already adopted .NET Standard should find this to be a similarly simple upgrade. Libraries that implement Xamarin.Forms UI will have a bit more work to do when they depend on Xamarin.Forms types. We are currently navigating this transition in our own codebase where we have introduced a compatibility namespace for bringing forward Xamarin.Forms code that hasn't yet been ported to our new handler control pattern. As we port controls then .NET MAUI benefits from the improvements and the compatibility controls are no longer needed. So, what I'm trying to show is that there's a continuum of change that UI library maintainers can travel from basic compatibility to fully ported. We have talked to commercial component vendors eager to make this transition to continue serving their customers. If you use one of these, please let them know of your interest in seeing .NET MAUI support from day one. We have a monthly call that is welcome to anyone where we have open dialogue between our engineering team and library maintainers. This is all about helping the ecosystem make this transition successfully. We are in this together! InfoQ: There are many competitors currently developing different alternatives to .NET MAUI. What is your opinion about this situation? Ortinau: I reject the framing that within the .NET ecosystem this is a battle and a competition. One of the great things about being open source is the ecosystem can grow many options for developers. Uno offers a development experience that is extremely familiar to Windows developers, and uses Xamarin. Similarly, WPF developers can feel very at home and productive with Avalonia. Having options such as those in the .NET ecosystem means .NET MAUI is empowered to address other needs of .NET customers. InfoQ: If we are beginning a new project today, should we go with Xamarin.Forms or wait for .NET MAUI? Ortinau: Use Xamarin.Forms, without hesitation! The migration to .NET MAUI will be well defined, and we are taking care to make it as smooth as possible. Now, once we get to the middle of 2021 you may wish to consider starting with .NET MAUI instead. Keep an eye on the .NET blog for news about the progress with .NET MAUI to determine if enough of the pieces are there for your application needs to begin using it. In addition to how many of the controls and layouts have been ported, look for essential productivity tooling for things like hot reload, hot restart, and multi-targeting for single project experiences. Of course, I encourage everyone to dip your toes into the .NET MAUI waters throughout the previews, and please share your interest and feedback to our team on GitHub. InfoQ: Last year, there were a couple of Blazor mobile bindings mentioning .NET MAUI, and some of the last .NET Conf sessions involved Blazor and MAUI desktop scenarios. What is the role of .NET MAUI in the whole Blazor context? Ortinau: In .NET 6 we are shipping Blazor hybrid experiences for desktop. This means you can use Blazor web components to build app experiences that also have seamless access to native device services necessary for delivering desktop features, such as online/offline, file system, location, notifications, and much more. This is made possible by building upon the .NET MAUI toolkit and shipping the first control from the mobile bindings experiment, the BlazorWebView. You have full access to all the desktop controls and APIs from .NET MAUI in addition to the HTML and CSS a Blazor web developer is already using today. Because it's all .NET code, there is no bridging back and forth between the Blazor context and .NET MAUI. It really is seamless! InfoQ: Microsoft recently released the .NET Upgrade Assistant. Are there any plans for a similar tool related to .NET MAUI and Xamarin.Forms, or something to set a smooth migration path? Ortinau: Absolutely! Now that the .NET MAUI design is beginning to stabilize, we have a more solid idea of what the migration work will need to look like. Look for more details about this mid-year. InfoQ: The most exciting thing about .NET MAUI is the single-project experience. What is the motivation behind it, what are the problems the single project is solving? Ortinau: Xamarin was born in a world of bringing 1:1 native mobile development to .NET developers. It was also done outside of Microsoft during a period when not everything was open source, and the result was a solution with multiple app projects with specific build requirements plus shared library projects for business logic. This has been an accepted complexity for years. We interview developers all the time, both within our ecosystem and those with zero .NET experience. Common things we hear are that managing platform specifics (think images, fonts, etc.) is a hassle, managing NuGets across multiple projects is confusing, and the multiplicity of projects in the solution just doesn't match how developers think about their applications. Developers think first about a single application experience, and occasionally about platform specific scenarios. So, "single project" is a solution to align more closely with this developer focus while still providing all the native platform access important for delivering truly native experiences. Many aspects of what we call "single project" will be available to everyone using .NET MAUI, regardless of whether or not you choose to reduce multiple projects down to a single one. For example, you will be able to leverage the library project to manage images, fonts, resources, and to multi-target code per platform. Those features can be adopted ad hoc as they are beneficial to your applications. Single project will be the default experience for new projects. For existing projects I recommend you adopt the aspects of this experience that you want first, and then think carefully about whether you should go all the way and reorganize your solution. InfoQ: A good part of the community would appreciate VS Code support. Is there any plan to provide that kind of support for .NET MAUI development? Ortinau: This is not on our roadmap to bring official support for .NET MAUI to Visual Studio Code, but that doesn't mean we don't have good news for you! The Comet experiment focuses on how .NET MAUI would look to a developer who prefers the Model-View-Update pattern over MVVM, C# over XAML, and VS Code over Visual Studio. Because Comet is .NET 6 and is based on .NET MAUI, it also works for .NET MAUI apps that don't use MVU (yay .NET!). You won't get amazing XAML IntelliSense and much else, but it's a great start that supports .NET 6 previews, single project, device selection, and debugging. Check out the April 2021 Xamarin Community Standup on YouTube with Jonathan Peppers if you would like to see this in action. If you're interested in seeing VS Code get official support, please engage with the Comet project. About the Interviewee David Ortinau is a principal program manager for Mobile Developer Tools at Microsoft, focused on Xamarin.Forms. A .NET developer since 2002, and versed in a range of programming languages, Ortinau has developed web, environmental, and mobile experiences for a wide variety of industries. After several successes with tech startups and running his own software company, Ortinau joined Microsoft to follow his passion: crafting tools that help developers create better app experiences. When not at a computer or with his family, Ortinau is running through the woods. Community comments
https://www.infoq.com/articles/net-maui/?topicPageSponsorship=e1950208-7a4d-42ed-8906-f5e1979efcf0&itm_source=articles_about_dotnet&itm_medium=link&itm_campaign=dotnet
CC-MAIN-2021-21
refinedweb
1,893
57.57
1. Revision History 1.1. Revision 2 Destroy and options: if the function is materialized only at compile-time through or the upcoming "immediate functions" ( ), there is no reason to make this part of the function. Instead, the user can choose their own alignment when they pin this down into a std::array or some form of C array storage. 1.2. Revision 1 Create future directions section, follow up on Library Evolution Working Group comments. Change to . Add more code demonstrating the old way and motivating examples. Incorporate LEWG feedback, particularly alignment requirements illuminated by Odin Holmes and Niall Douglass. Add a feature macro on top of having . 1.3. Revision 0 Initial release. 2. Motivation I’m very keen on std::embed. I’ve been hand-embedding data in executables for NEARLY FORTY YEARS now. — Guy "Hatcat" Davidson, June 15, 2018 Every C and C++ programmer -- at some point -- attempts to large chunks of non-C++ data into their code. Of course, expects the format of the data to be source code, and thusly the program fails with spectacular lexer errors. Thusly, many different tools and practices were adapted to handle this, as far back as 1995 with the tool. Many industries need such functionality, including (but hardly limited to): Financial Development representing coefficients and numeric constants for performance-critical algorithms; Game Development assets that do not change at runtime, such as icons, fixed textures and other data Shader and scripting code; Embedded Development storing large chunks of binary, such as firmware, in a well-compressed format placing data in memory on chips and systems that do not have an operating system or file system; Application Development compressed binary blobs representing data non-C++ script code that is not changed at runtime; and Server Development configuration parameters which are known at build-time and are baked in to set limits and give compile-time information to tweak performance under certain loads SSL/TLS Certificates hard-coded into your executable (requiring a rebuild and potential authorization before deploying new certificates). In the pursuit of this goal, these tools have proven to have inadequacies and contribute poorly to the C++ development cycle as it continues to scale up for larger and better low-end devices and high-performance machines, bogging developers down with menial build tasks and trying to cover-up disappointing differences between platforms. MongoDB has been kind enough to share some of their code below. Other companies have had their example code anonymized or simply not included directly out of shame for the things they need to do to support their workflows. The author thanks MongoDB for their courage and their support for . The request for some form of or similar dates back quite a long time, with one of the oldest stack overflow questions asked-and-answered about it dating back nearly 10 years. Predating even that is a plethora of mailing list posts and forum posts asking how to get script code and other things that are not likely to change into the binary. This paper proposes to make this process much more efficient, portable, and streamlined. Here’s an example of the ideal: #include<embed> int main ( int , char * []) { constexpr std :: span < const std :: byte > fxaa_binary = std :: embed ( "fxaa.spirv" ); // assert this is a SPIRV file, compile-time static_assert ( fxaa_binary [ 0 ] == 0x03 && fxaa_binary [ 1 ] == 0x02 && fxaa_binary [ 2 ] == 0x23 && fxaa_binary [ 3 ] == 0x07 , "given wrong SPIRV data, check rebuild or check the binaries!" ) auto context = make_vulkan_context (); // data kept around and made available for binary // to use at runtime auto fxaa_shader = make_shader ( context , fxaa_binary ); for (;;) { // ... // and we’re off! // ... } return 0 ; } 3. Scope and Impact is an extension to the language proposed entirely as a library construct. The goal is to have it implemented with compiler intrinsics, builtins, or other suitable mechanisms. It does not affect the language. The proposed header to expose this functionality is , making the feature entirely-opt-in by checking if either the proposed feature test macro or header exists. 4. Design Decisions avoids using the preprocessor or defining new string literal syntax like its predecessors, preferring the use of a free function in the namespace. 's design is derived heavily from community feedback plus the rejection of the prior art up to this point, as well as the community needs demonstrated by existing practice and their pit falls. 4.1. Current Practice Here, we examine current practice, their benefits, and their pitfalls. There are a few cross-platform (and not-so-cross-platform) paths for getting data into an executable. 4.1.1. Manual Work Many developers also hand-wrap their files in (raw) string literals, or similar to massage their data -- binary or not -- into a conforming representation that can be parsed at source code: Have a file with some data, for example: data . json { "Hello" : "World!" } Mangle that file with raw string literals, and save it as : raw_include_data . h R "json( { "Hello": "World!" })json " Include it into a variable, optionally made , and use it in the program: constexpr #include<iostream> #include<string_view> int main () { constexpr std :: string_view json_view = #include"raw_include_data.h" ; // { "Hello": "World!" } std :: cout << json_view << std :: endl ; return 0 ; } This happens often in the case of people who have not yet taken the "add a build step" mantra to heart. The biggest problem is that the above C++-ready source file is no longer valid in as its original representation, meaning the file as-is cannot be passed to any validation tools, schema checkers, or otherwise. This hurts the portability and interop story of C++ with other tools and languages. Furthermore, if the string literal is too big vendors such as VC++ will hard error the build (example from Nonius, benchmarking framework). 4.1.2. Processing Tools Other developers use pre-processors for data that can’t be easily hacked into a C++ source-code appropriate state (e.g., binary). The most popular one is , which outputs an array in a file which developers then include. This is problematic because it turns binary data in C++ source. In many cases, this results in a larger file due to having to restructure the data to fit grammar requirements. It also results in needing an extra build step, which throws any programmer immediately at the mercy of build tools and project management. An example and further analysis can be found in the §8.1.1 Pre-Processing Tools Sadness and the §8.1.2 python Sadness section. 4.1.3. , resource files, and other vendor-specific link-time tools ld Resource files and other "link time" or post-processing measures have one benefit over the previous method: they are fast to perform in terms of compilation time. A example can be seen in the §8.1.3 ld Sadness section. 4.1.4. The tool incbin There is a tool called [incbin] which is a 3rd party attempt at pulling files in at "assembly time". Its approach is incredibly similar to , with the caveat that files must be shipped with their binary. It unfortnately falls prey to the same problems of cross-platform woes when dealing with VC++, requiring additional pre-processing to work out in full. 4.2. Prior Art There has been a lot of discussion over the years in many arenas, from Stack Overflow to mailing lists to meetings with the Committee itself. The latest advancements that had been brought to WG21’s attention was p0373r0 - File String Literals. It proposed the syntax and , with a few other amenities, to load files at compilation time. The following is an analysis of the previous proposal. 4.2.1. Literal-Based, constexpr A user could reasonably assign (or want to assign) the resulting array to a variable as its expected to be handled like most other string literals. This allowed some degree of compile-time reflection. It is entirely helpful that such file contents be assigned to constexpr: e.g., string literals of JSON being loaded at compile time to be parsed by Ben Deane and Jason Turner in their CppCon 2017 talk, constexpr All The Things. 4.2.2. Literal-Based, Null Terminated (?) It is unclear whether the resulting array of characters or bytes was to be null terminated. The usage and expression imply that it will be, due to its string-like appearance. However, is adding an additional null terminator fitting for desired usage? From the existing tools and practice (e.g., or linking a data-dumped object file), the answer is no: but the syntax makes the answer seem like a "yes". This is confusing: either the user should be given an explicit choice or the feature should be entirely opt-in. 4.2.3. Encoding Because the proposal used a string literal, several questions came up as to the actual encoding of the returned information. The author gave both and to separate binary versus string-based arrays of returns. Not only did this conflate issues with expectations in the previous section, it also became a heavily contested discussion on both the mailing list group discussion of the original proposal and in the paper itself. This is likely one of the biggest pitfalls between separating "binary" data from "string" data: imbuing an object with string-like properties at translation time provide for all the same hairy questions around source/execution character set and the contents of a literal. 4.3. Design Goals Because of the aforementioned reasons, it seems more prudent to take a "compiler intrinsic"/"magic function" approach. The function takes the form: constexpr span < const byte > embed ( string_view resource_identifier ); is a processed in an implementation-defined manner to find and pull resources into C++ at constexpr time. The most obvious source will be the file system, with the intention of having this evaluated as a core constant expression. We do not attempt to restrict the to a specific subset: whatever the implementation accepts (typically expected to be a relative or absolute file path, but can be other identification scheme), the implementation should use. 4.3.1. Implementation Defined Calls such as , , and are meant to be evaluated in a context (with "core constant expressions" only), where the behavior is implementation-defined. The function has unspecified behavior when evaluated in a non-constexpr context (with the expectation that the implementation will provide a failing diagnostic in these cases). This is similar to how include paths work, albeit interacts with the programmer through the preprocessor. There is precedent for specifying library features that are implemented only through compile-time compiler intrinsics ( , , and similar utilities). Core -- for other proposals such as p0466r1 - Layout-compatibility and Pointer-interconvertibility Traits -- indicated their preference in using a magic function implemented by intrinsic in the standard library over some form of construct. However, it is important to note that [p0466r1] proposes type traits, where as this has entirely different functionality, and so its reception and opinions may be different. As is meant to exist at compile-time only, it may be prudent to rely on p1073r0 - immediate (constexpr!) functions. However, these are only design decisions to more clearly express the intent of the paper. This paper does not explicitly rely on [p1073r0] at this time. 4.3.2. Binary Only Creating two separate forms or options for loading data that is meant to be a "string" always fuels controversy and debate about what the resulting contents should be. The problem is sidestepped entirely by demanding that the resource loaded by represents the bytes exactly as they come from the resource. This prevents encoding confusion, conversion issues, and other pitfalls related to trying to match the user’s idea of "string" data or non-binary formats. Data is received exactly as it is from the resource as defined by the implementation, whether it is a supposed text file or otherwise. and behave exactly the same concerning their treatment of the resource. 4.3.3. Constexpr Compatibility The entire implementation must be usable in a context. It is not just for the purposes of processing the data at compile time, but because it matches existing implementations that store strings and huge array literals into a variable via . These variables can be : to not have a constexpr implementation is to leave many of the programmers who utilize this behavior without a proper standardized tool. 5. Help Requested The author of this proposal is extremely new to writing standardese. While the author has read other papers and consumed the standard, there is a definite need for help and any guidance and direction is certainly welcome. The author expects that this paper may undergo several revisions and undertake quite a few moments of "bikeshedding". 5.1. Feeling Underrepresented? The author has consulted dozens of C++ users in each of the Text Processing, Video Game, Financial, Server, Embedded and Desktop Application development subspaces. The author has also queried the opinions of Academia. The author feels this paper adequately covers many use cases, existing practice and prior art. If there is a use case or a problem not being adequately addressed by this proposal, the author encourages anyone and everyone to reach out to have their voice heard. 5.2. Bikeshedding 5.2.1. Alternative Names Some people feel that is not a good name for this function. Therefore, here are some alternative names contribute by the community, in order of very good to very terrible: embed embed_resource slurp constexpr_read static_read static_resource static_include cfsread 5.2.2. Answered Questions Is inin std :: vector < std :: byte >])? constexpr No, but can be persuaded otherwise. Do not want to lock this feature down as a dependency to these other papers in-flight. Is it desireable to make templated so it can return other kinds of views / types at constexpr time, since the standard does not yet have a concept of a constexprtemplated so it can return other kinds of views / types at constexpr time, since the standard does not yet have a concept of a constexpr std :: embed oror reinterpret_cast ++ std :: bless ?? std :: launder Yes. Should (std::embed revision 0) just be replaced with(std::embed revision 0) just be replaced with std :: embedded ?? std :: span Yes. covers all of the use cases here, is , and makes the most sense. cannot be returned because cannot be named until it is deduced by the actual value being returned. It is a poor interface to force the user to always or the return. (LEWG confirmed.) Should the return be const-qualified, as inbe const-qualified, as in std :: span ?? std :: span < const std :: byte > Yes. (LEWG confirmed.) What is the lookup scheme for files and other resources? Implementation defined. We expect compilers to expose an option similar to , , or whatever tickles the implementer’s fancy. (LEWG confirmed.) Pulling in large data files on every compile might be expensive? We fully expect implementations to employ techniques already in use for compilation dependency tracking to ensure this is not a frequent problem past the first compilation. Is this more suitable for WG14 (the standards C committee) rather than WG21 (the standards C++ committee)? The author does not think that the C standards committee will be the best place for some feature of this variety at this time. All of the typical solutions that would work in C were rejected previously (preprocessor or special literal). Indication has shown that the C standards committee might be able to support this idea and come up with a better design than WG21 or provide more fine-grained mechanisms for it, but there is no evidence that they are either interested or have the time. (Raised in LEWG, confirmed in general post-LEWG discussion.) Is a magic library function in a header the most desirable? Other proposals for other avenues have fallen flat and not garnered enough support. Preprocessor directives are rountinely discouraged in multiple LEWG, EWG and discussion at conferences. Many individuals want this to work with nicely so they can confirm other compile-time computation. The only dissent to this so far is with people who use and , who find that the preprocessing done by these tools will not have the contents embedded. Icecream’s team has been contacted about this. They have advised the use of to solve this problem. As brought to my attention by users, however, the option is notoriously incomplete/unsatisfactory in its implementation. This brings up the question: do we change std::embed to work before Phase 7 of compilation as some kind of preprocessing directive because and have incomplete/unfinished implementations? My current feeling is that and should improve their implementation of . Contorting into a preprocessor directive that will receive much greater Strongly Against opposition from everyone in the Language group is very much a non-starter. 6. Changes to the Standard Wording changes are relative to [n4762]. 6.1. Intent The intent of the wording is to provide a function that has implementation-defined behavior but returns the specified constexpr span representing the bytes of the resource the passed-in string_view represents. The wording also explicitly disallows the usage of the function outside of a core constant expression, meaning it is ill-formed if it is attempted to be used at not-constexpr time (std::embed calls should not show up as a function in the final executable). 6.2. Proposed Feature Test Macro The proposed feature test macro is . 6.3. Proposed Wording Append to §16.3.1 General [support.limits.general]'s Table 35 one additional entry: Append to §19.1 General [utilities.general]'s Table 38 one additional entry: Add a new section §19.20 Compile-time Resources [const.res]: 7. Future Direction Many developers in all spaces are concerned that does not allow to be used. This means that the bytes cannot be viewed -- at time -- as more complex entities. There are 2 directions to solve this problem. This paper proposes neither of the fixes at this time. The first is to word a , , and/or that can work on this memory at constexpr time. The second is to use a more blunt hammer and simply template , specifying it as follows: template < typename T = std :: byte > constexpr span < const T > embed ( string_view resource_identifier ); This would supply the data and view it as a type . However, this brings up questions of destructors and similar for when the data goes away. It also gets in the way of caching. Is it possible for an implementation to cache the retrieved storage based solely on since a destructor could run over the data? If destructors or constructors are run based on type then the data cannot be the same between template instantions even with the same . A way to help with this would be to and not have to worry about such problems. The good news is that such a templated transformation can be applied to at a later date with no API breakage, provided the templated arguments are defaulted in the function. We do not propose any of these future directions at this time. 8. Appendix 8.1. Sadness Other techniques used include pre-processing data, link-time based tooling, and assembly-time runtime loading. They are detailed below, for a complete picture of today’s sad landscape of options. 8.1.1. Pre-Processing Tools Sadness Run the tool over the data ( ) to obtain the generated file ( xxd - i xxd_data . bin > xxd_data . h ): xxd_data . h unsigned char xxd_data_bin [] = { 0x48 , 0x65 , 0x6c , 0x6c , 0x6f , 0x2c , 0x20 , 0x57 , 0x6f , 0x72 , 0x6c , 0x64 , 0x0a }; unsigned int xxd_data_bin_len = 13 ; Compile : main . cpp #include<iostream> #include<string_view> // prefix as constexpr, // even if it generates some warnings in g++/clang++ constexpr #include"xxd_data.h" ; template < typename T , std :: size_t N > constexpr std :: size_t array_size ( const T ( & )[ N ]) { return N ; } int main () { static_assert ( xxd_data_bin [ 0 ] == 'H' ); static_assert ( array_size ( xxd_data_bin ) == 13 ); std :: string_view data_view ( reinterpret_cast < const char *> ( xxd_data_bin ), array_size ( xxd_data_bin )); std :: cout << data_view << std :: endl ; // Hello, World! return 0 ; } Others still use python or other small scripting languages as part of their build process, outputting data in the exact C++ format that they require. There are problems with the or similar tool-based approach. Lexing and Parsing data-as-source-code adds an enormous overhead to actually reading and making that data available. Binary data as C(++) arrays provide the overhead of having to comma-delimit every single byte present, it also requires that the compiler verify every entry in that array is a valid literal or entry according to the C++ language. This scales poorly with larger files, and build times suffer for any non-trivial binary file, especially when it scales into Megabytes in size (e.g., firmware and similar). 8.1.2. Sadness python Other companies are forced to create their own ad-hoc tools to embed data and files into their C++ code. MongoDB uses a custom python script, just to get their data into C++: import os import sys def jsToHeader ( target , source ) : outFile = target h = ['# include "mongo/base/string_data.h"' ,'# include "mongo/scripting/engine.h"' ,' namespace mongo {' ,' namespace JSFiles {' , ] def lineToChars ( s ) : return ',' . join ( str ( ord ( c )) for c in ( s . rstrip () + '\n' )) + ',' for s in source : filename = str ( s ) objname = os . path . split ( filename )[ 1 ]. split ( '.' )[ 0 ] stringname =' _jscode_raw_' + objname h . append (' constexpr char' + stringname + "[] = {" ) with open ( filename , 'r' ) as f : for line in f : h . append ( lineToChars ( line )) h . append ( "0};" ) # symbols aren’t exported w/o this h . append (' extern const JSFile % s ;' % objname ) h . append (' const JSFile % s = { "%s" , StringData ( % s , sizeof ( % s ) - 1 ) };' % ( objname , filename . replace ( '\\' , '/' ), stringname , stringname )) h . append ( "} // namespace JSFiles" ) h . append ( "} // namespace mongo" ) h . append ( "" ) text = '\n' . join ( h ) with open ( outFile ,' wb' ) as out : try : out . write ( text ) finally : out . close () if __name__ == "__main__" : if len ( sys . argv ) < 3 : "Must specify [target] [source] " sys . exit ( 1 ) jsToHeader ( sys . argv [ 1 ], sys . argv [ 2 : ]) MongoDB were brave enough to share their code with me and make public the things they have to do: other companies have shared many similar concerns, but do not have the same bravery. We thank MongoDB for sharing. 8.1.3. Sadness ld A full, compilable example (except on Visual C++): Have a file ld_data.bin with the contents . Hello , World ! Run . ld - r binary - o ld_data . o ld_data . bin Compile the following with main . cpp : c ++ - std = c ++ 17 ld_data . o main . cpp #include<iostream> #include<string_view> #ifdef __APPLE__ #include<mach-o/getsect.h> #define DECLARE_LD(NAME) extern const unsigned char _section$__DATA__##NAME[]; #define LD_NAME(NAME) _section$__DATA__##NAME #define LD_SIZE(NAME) (getsectbyname("__DATA", "__" #NAME)->size) #elif (defined __MINGW32__) /* mingw */ #define DECLARE_LD(NAME) \ extern const unsigned char binary_##NAME##_start[]; \ extern const unsigned char binary_##NAME##_end[]; #define LD_NAME(NAME) binary_##NAME##_start #define LD_SIZE(NAME) ((binary_##NAME##_end) - (binary_##NAME##_start)) #else /* gnu/linux ld */ #define DECLARE_LD(NAME) \ extern const unsigned char _binary_##NAME##_start[]; \ extern const unsigned char _binary_##NAME##_end[]; #define LD_NAME(NAME) _binary_##NAME##_start #define LD_SIZE(NAME) ((_binary_##NAME##_end) - (_binary_##NAME##_start)) #endif DECLARE_LD ( ld_data_bin ); int main () { // impossible //static_assert(xxd_data_bin[0] == 'H'); std :: string_view data_view ( reinterpret_cast < const char *> ( LD_NAME ( ld_data_bin )), LD_SIZE ( ld_data_bin ) ); std :: cout << data_view << std :: endl ; // Hello, World! return 0 ; } This scales a little bit better in terms of raw compilation time but is shockingly OS, vendor and platform specific in ways that novice developers would not be able to handle fully. The macros are required to erase differences, lest subtle differences in name will destroy one’s ability to use these macros effectively. We ommitted the code for handling VC++ resource files because it is excessively verbose than what is present here. N.B.: Because these declarations are , the values in the array cannot be accessed at compilation/translation-time. 9. Acknowledgements A big thank you to Andrew Tomazos for replying to the author’s e-mails about the prior art. Thank you to Arthur O’Dwyer for providing the author with incredible insight into the Committee’s previous process for how they interpreted the Prior Art. A special thank you to Agustín Bergé for encouraging the author to talk to the creator of the Prior Art and getting started on this. Thank you to Tom Honermann for direction and insight on how to write a paper and apply for a proposal. Thank you to Arvid Gerstmann for helping the author understand and use the link-time tools. Thank you to Tony Van Eerd for valuable advice in improving the main text of this paper. Thank you to Lilly (Cpplang Slack, @lillypad) for the valuable bikeshed and hole-poking in original designs, alongside Ben Craig who very thoroughly explained his woes when trying to embed large firmware images into a C++ program for deployment into production. For all this hard work, it is the author’s hope to carry this into C++. It would be the author’s distinct honor to make development cycles easier and better with the programming language we work in and love. ♥
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1040r2.html
CC-MAIN-2020-10
refinedweb
4,146
53.31
KQueue evtmgr backend fails to register for write events The root of the problem is that the GHC.Event.KQueue.toFilter function has type GHC.Event.Internal.Event -> Filter with GHC's Event being a bitmask which can represent read events, write events or a combination of those. It happens that the event manager requests it's backend to be notified about read and write events on some fd, and because the kqueue EVFILT_*s are not bitmasks, the above function cannot capture this, silently dropping the desire to be notified about write events. The following program triggers the problematic behaviour: import Control.Concurrent ( forkIO, killThread ) import Control.Exception ( finally ) import Control.Monad.Trans.Resource ( runResourceT ) import Control.Monad.IO.Class ( liftIO ) import qualified Data.ByteString as BS import Data.Conduit ( ($$), ($=) ) import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import qualified Data.Conduit.Network as CN import Data.IORef ( newIORef, modifyIORef', readIORef) main :: IO () main = CN.runTCPClient (CN.clientSettings 5555 "192.168.2.11") client where logMsg cnt = CL.mapM $ \bs -> liftIO $ do modifyIORef' cnt (+ 1) readIORef cnt >>= \x -> putStrLn $ "msg #" ++ show x ++ " of size: " ++ show (BS.length bs) return bs client ad = do reader <- forkIO (runResourceT $ CN.appSource ad $$ CL.mapM_ ( \bs -> (liftIO . putStrLn) $ "read " ++ show (BS.length bs) ++ " bytes")) cnt <- newIORef ( 0 :: Int ) let runPipe = runResourceT $ CB.sourceFile "cool-linux-distro.iso" $$ logMsg cnt $= CN.appSink ad runPipe `finally` (killThread reader) Having a nc -l -p 5555 > /dev/null running on another machine is sufficient to sink the data. Assuming that we can read bigfile.iso faster than we can send out over the socket, the send syscall will at some point give an EAGAIN as can be seen in the truss output: write(1,"msg #20 of size: 32752\n",23) = 23 (0x17) sendto(12,"\f\2409\0\M^RA\^T\M-&A\M-'\M-d8"...,32752,0x0,NULL,0x0) = 32752 (0x7ff0) read(13,"\M^?\0'\\\M-B\M-:+\^]D\M-0\M-="...,32752) = 32752 (0x7ff0) poll({ 1/POLLOUT },1,0) = 1 (0x1) msg #21 of size: 32752 write(1,"msg #21 of size: 32752\n",23) = 23 (0x17) sendto(12,"\M^?\0'\\\M-B\M-:+\^]D\M-0\M-="...,32752,0x0,NULL,0x0) = 19204 (0x4b04) sendto(12,"\M-j$2\M^BH\M-#-\^A\M-E\^O\M^Y\a"...,13548,0x0,NULL,0x0) ERR#35 'Resource temporarily unavailable' SIGNAL 26 (SIGVTALRM) sigprocmask(SIG_SETMASK,{ SIGVTALRM },0x0) = 0 (0x0) sigreturn(0x7fffffff9c60) ERR#35 'Resource temporarily unavailable' kevent(3,{ 12,EVFILT_READ,EV_ADD|EV_ONESHOT,0x0,0x0,0x0 },1,0x0,0,{ 0.000000000 }) = 0 (0x0) _umtx_op(0x800c71ed0,UMTX_OP_WAIT_UINT_PRIVATE,0x0,0x0,0x0) ERR#4 'Interrupted system call' SIGNAL 26 (SIGVTALRM) sigprocmask(SIG_SETMASK,{ SIGVTALRM },0x0) = 0 (0x0) sigreturn(0x7fffffffdc00) ERR#4 'Interrupted system call' _umtx_op(0x800c71ed0,UMTX_OP_WAIT_UINT_PRIVATE,0x0,0x0,0x0) ERR#4 'Interrupted system call' SIGNAL 26 (SIGVTALRM) Not the sendto call on fd 12 resulting in ERR#35, soon followed by an kevent call for that same fd and only EVFILT_READ set. This makes little sense as it was an attempt to write that just failed. This is caused by toFilter giving precedence to read events, dropping the write event. Not starting the reader thread prevents bad things from happening as then the write events are properly passed thru to kqueue. I have an initial version of a patch fixing this.
https://gitlab.haskell.org/ghc/ghc/issues/13903
CC-MAIN-2020-16
refinedweb
556
59.8
Often in the forums we see questions about having SELECT-like functionality on local data (that is, on a DataSet, without accessing a database). There are a number of operations that the ADO.NET classes can perform on the client which are often good enough for many scenarios, and on this post I want to discuss one in particular. Given a DataTable, how do we select only the rows that meet certain criteria? Enter DataView.RowFilter. This little gem is mentioned on Sorting and Filter Data Using a DataView on MSDN, but I often talk to developers who are unaware of how to use this property. RowFilter is an expression string that can be evaluated to true or false, and uses the syntax described in the DataColumn.Expression documentation. But enough talk and pointers. Here's a super-fast way of trying out some expressions for yourself (save this to a file named dv.cs if you build with the command line shown). // Build with: %windir%\Microsoft.NET\Framework\v2.0.50727\csc.exe dv.cs using System; using System.Data; using System.Windows.Forms; namespace NS { public class DoIt { [STAThread] public static void Main(string[] args) { DataTable table = new DataTable(); table.Columns.Add(new DataColumn("ID", typeof(int))); table.Columns.Add(new DataColumn("Name", typeof(string))); table.Columns.Add(new DataColumn("Date", typeof(DateTime))); table.Rows.Add(new object[] { 1, "Charlie", DateTime.Now }); table.Rows.Add(new object[] { 2, "Candy", DateTime.Now.AddHours(2) }); DataView dv = new DataView(table); DataGridView view = new DataGridView(); view.DataSource = dv; view.Dock = DockStyle.Fill; Form form = new Form(); form.Text = "DataView RowFilter Sample"; Label label = new Label(); label.Dock = DockStyle.Bottom; TextBox box = new TextBox(); box.Dock = DockStyle.Top; box.TextChanged += delegate { try { dv.RowFilter = box.Text; label.Text = ""; } catch(Exception exception) { label.Text = exception.Message; } }; form.Controls.Add(view); form.Controls.Add(box); form.Controls.Add(label); Application.Run(form); } } } As you type, the RowFilter property is updated, and if the expression isn't correct, the error message is displayed at the bottom of the window. To get you started, try some of these filters: - ID < 2 (displays row with ID=1) - Name like 'ch*' (displays row with Name=Charlie) - Name like 'ch%' (displays row with Name=Charlie) - Name like 'c%' (displays both rows) - ID % 2 = 0 (displays row with ID=2, divisible by 2) There is more functionality available - I strongly recommend reading through the Expression page on MSDN. Enjoy! This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at. That’s very handy – thanks. I’m working on app where I have to use RowFilter extensively but the one thing I’m really having trouble with is testing columns that are nulls as part of the filter. You are meant to be able to do something like IsNull(EmployeeNickname,”) = ” but I can’t get this to work – it just doesn’t match at all even when I know that column has many null values. I’ve also tried it with a numeric field – eg: IsNull(LastPayRiseAmount,0) = 0 but that doesn’t work either. The MSDN documentation on IsNull is awful – there’s no proper explanation of testing null columns at all and I can’t work out how else it’s meant to work other than what all the examples I’ve seen suggest which all suggest the above examples should work. I’ve hunted all over for info on how to get IsNull to work – any ideas? Forget the above comment – I’d coped the code from an example in which RowStateFilter was set to DataViewRowState.ModifiedCurrent – and that would never return any matches as it is a static dataset I’m looking up. (And yes, the word "idiot" springs to my mind as well!) After my DataView.RowFilter post , the next obvious step is of course a short post on using the DataView.Sort
https://blogs.msdn.microsoft.com/marcelolr/2007/03/05/using-dataview-rowfilter/
CC-MAIN-2017-34
refinedweb
662
57.16
Results 1 to 1 of 1 - Join Date - May 2001 - Location - Kenilworth, Warwickshire, England - 292 - Thanks - 6 - Thanked 0 Times in 0 Posts Empty User Defined Contact field with vba (OL 2007) I have some vba code running in outlook 2007. This code successfully writes a series of contact fields out to a nominated excel spreadsheet. the code snippet that does this for a user defined field is: Set rng = wks.Cells(i, j) If itm.UserProperties("ChequeNo") <> "" Then rng.Value = itm.UserProperties("ChequeNo") End If j = j + 1 What I want to be able to do after writing the current value out to excel, is to empty the field in outlook. I have tried all sorts of code within the if...endif block, but cannot get it to work. You will gather that I am very much beginner. Can anyone help please Mike Ch
https://windowssecrets.com/forums/showthread.php/143799-Empty-User-Defined-Contact-field-with-vba-%28OL-2007%29
CC-MAIN-2017-43
refinedweb
145
74.49
2006/7/26, Alex Blewitt <alex.blewitt@gmail.com>: > On 26/07/06, Denis Kishenko <dkishenko@gmail.com> wrote: > > Frequently hash code is a sum of several other hashes. Such implementation > > kill hash idea, it's terrible. > > I agree that simple addition is not a good thing. However, exclusive > or can work just as well, as can a simple multiplication of numbers by > primes. > > > and many others... also I have found such "algorithms" =)> > > private long* *token; > > > > public int hashCode() { > > return (int) token; > > } > > This isn't an incorrect hash function, and if there's only one token, > it doesn't really matter that much. Even if the token itself isn't > widely distributed, chances are the bottom few bits are going to be > distributed fairly evenly, and often it's the bottom part of a > hashcode that's considered rather than the top part. So, it's not > optimal, but shifting some bits around doesn't make that much > difference. > > > The most of hashCode() functions are implemented in different ways. It's not > > problem, but it looks like scrappy, there is no single style. And finally we > > have class *org.appache.harmony.misc.HashCode *for this aim! > > Interesting, but I wonder what the impact is of using an additional > class to calculate the hash from each time is going to be. Hopefully a > decent JIT will remove much of the problem, but bear in mind that the > hashCode may get called repeatedly during a single operation with a > collection (and in the case that it's already in the collection, may > be called by every other operation on that collection too. You might > find that even a simple (say) sort of a list would easily overwhelm > the nursery generation of a generational GC. > > Of course, it's difficult to say without measuring it and knowing for sure :-) > > > But only several classes are using it. I suggest integrate HashCode in > > all hashCode() implementations (about 200 files), I can do this. Anybody > > else can improve HashCode work. > > > > Any comments? > > There are other approaches that could be used instead of this. For > example, the value of the hashCode could be cached in a private > variable and then invalidated when any setValue() methods are called. I agree with your concern and suggested solution. > One could even imagine a superclass performing this caching work: > > public abstract class HashCode { > private boolean valid = false; > private int hash; > public final int hashCode() { > if (!valid) { > hash = recalculateHashCode(); > valid = true; > } > return hash; > } > protected abstract int recalculateHash(); > protected void invalidate() { valid = false; } > } > > Of course, you could use the HashCode object to calculate the hash value :-) > > Such an approach won't work when the class hierarchy cannot be > changed, of course. That's exactly our case in public API... But we can use it in our private API (org.apache.harmony.*) > Lastly, an easier approach is to use a tool (such as Eclipse) to > generate the implementation of hashCode() automatically based on the > non-static, non-final variables of a class. This one sounds like (a) > the easiest, and (b) all-round better performant than any of the > above. Good idea! SY, Alexey > > Alex. > > --------------------------------------------------------------------- >
http://mail-archives.apache.org/mod_mbox/harmony-dev/200607.mbox/%3Cc3755b3a0607270132t7d427f1ao38b6d66666486a80@mail.gmail.com%3E
CC-MAIN-2016-26
refinedweb
521
63.39
First, some code cleanup. I had a lot of hard-coded paths in my fixtures. All fixtures used to start with: from fit.ColumnFixture import ColumnFixture import sys blogger_path = "C:\\eclipse\\workspace\\blogger" sys.path.append(blogger_path) import Blogger This is clearly sub-optimal and requires a lot of copy-and-paste among modules. To simplify it, I turned the blogger directory into a package by simply adding to that directory an empty file called __init__.py. I also moved Blogger.py (the main functionality module) and its unit test module, testBlogger.py, to a subdirectory of blogger called src. I made that subdirectory a package too by adding to it another empty __init__.py file. Now each fixture module can do: from fit.ColumnFixture import ColumnFixture from blogger.src.Blogger import get_blog There's one caveat here: the parent directory of the blogger directory -- in my case C:\eclipse\workspace -- needs to be somewhere on the Python module search path. In FitNesse it's easy to solve this issue by adding C:\eclipse\workspace to the classpath via this variable definition which will go on the main suite page: !path C:\eclipse\workspace When invoking the Python interpreter from a command line, one way of making sure that C:\eclipse\workspace is in the module search path is to add it to the PYTHONPATH environment variable, for example in a .bash_profile file. For our example though, the fixture modules are always invoked within the FitNesse/PyFIT framework, so we don't need to worry about PYTHONPATH. Now to the SetUp page functionality. If you create this page as a sub-page of a suite, then every test page in that suite will automatically have SetUp prepended to it by FitNesse. I created a SetUp page (its URL is) with the following content: !|BloggerFixtures.Setup| |setup?| |true| I also created the corresponding Setup.py fixture, with the following code: from fit.ColumnFixture import ColumnFixture from blogger.src.Blogger import get_blog blog_manager = None class Setup(ColumnFixture): _typeDict={ "setup": "Boolean" } def setup(self): global blog_manager blog_manager = get_blog() return (blog_manager != None) def get_blog_manager(): global blog_manager return blog_manager The setup method invokes the get_blog function from the Blogger module in order to retrieve the common Blogger instance used by all the fixtures in our test suite. I did this because I wanted to encapsulate the common object creation in one fixture class (Setup), then have all the other fixture classes cal the get_blog_manager function from the Setup module. Another benefit is that only the Setup module needs to know about the physical location of the Blogger module, via the line: from blogger.src.Blogger import get_blog All other fixture classes need only do: from Setup import get_blog_manager since they are in the same directory with Setup.py. A SetUp page can also be used to pass values to the application via methods in the Setup class. Assume we need to pass the path to a configuration file. One way of accomplishing this is to define a FitNesse variable in the SetUp page, like this: !define CONFIG_PATH {C:\config} The FitNesse syntax for referencing a variable is ${variable}, so we can pass it as an argument to our Setup fixture like this: !|BloggerFixtures.Setup|${CONFIG_PATH}| |setup?| |true| When the page is rendered by FitNesse, ${CONFIG_PATH} is automatically replaced with its value, so on the rendered page we'll see: In the Setup fixture class, we can get the value of the argument like this: config_path = self.getArgs()[0] One other thing we could do in the SetUp page is to include the DeleteAllEntries fixture, so that we can be sure that each test page will start with a clean slate in terms of the blog entries. I moved the old code from parts 1 and 2 of the tutorial here. You can see the new code here. 2 comments: nice blog! Very Informative blog
http://agiletesting.blogspot.com/2005/01/pyfit-tutorial-part-3.html
CC-MAIN-2019-35
refinedweb
649
54.93
Introduction to Python User Input While programming very often we are required to take input from the user so as to manipulate the data and process it thereafter. This ensures the dynamism and robustness of the program as it is not hardcoded and it can successfully execute at any random value given by the user. In this topic, we are going to learn about Python User Input. In today’s article, we would learn about this concept of accepting input from the user at run time of the program for Python programming language and process that data. This ensures proper communication between the program and the outside world. Methods of Inputting Data The following are the ways of inputting data from the user: – - input() - raw_input() Both basically do the same task, the only difference being the version of Python which supports the two functions. raw_input was used in older versions of Python and it got replaced by input() in recent Python versions. In this article, we would discuss input() as it is used in recent versions of Python. Working of Python Input() When we use the input() function in our program the flow of execution is halted till the user inputs the data and clicks the Enter button. After that, the value input by the user gets stored in some variable in the form of a string. No matter what data type the user intended their data to be, it gets stored as a string only. It needs to explicitly typecast to the desired format before use. Later we will look at such an example where if we do not typecast the data it will result in an error. Now let us have a look at the syntax of input() Syntax input([<prompt from user>]) Now let us see some examples and discuss how to use input() to accept data from users for different scenarios. Examples of Python User Input Here are the following examples mention below: Example #1 Inputting normal text from the keyboard Code: string1 = input() print(string1) Output Explanation In the first line, we used the input() function to take input from the user and store it in the variable named string1. After we press the Enter button, we are instructed to provide our input by the show of a blank input box with a cursor blinking. When we provide the input and press the Enter button then that value gets stored in the variable named string1. In the next line when we are printing the variable we actually see that the input provided by us is actually printed in the console. Example #2 Inputting number from the console and finding its square Code: print("Enter number to find the square:") number = input() print("The Square of number {}".format(number,number**2)) Output Explanation Here we encounter a TypeError and if read the errorMessage it suggests to us that the first argument i.e. number variable string datatype. And because of that, it is not able to perform the power operation on that. It is important to note here that the type of the input data is always taken as a string, so it must be typecast to the desired datatype before it can be worked on. Let us correct the code and have a look at the output. Code print("Enter number to find the square:") number = input() number = int(number) print("The square of the number {} is {}".format(number,number**2)) Output Example #3 Inputting multiple numbers and finding out the maximum from them Code: import numpy as np print("How many numbers we want to find the maximum of:") n=int(input()) numbers = [] for i in range(0, n): ele = int(input("Enter elements: ")) numbers.append(ele) print("The Maximum Number is:", max(numbers)) Output Example #4 Inputting sentence and counting the number of characters in that Code: print("Enter the sentence :") sentence = input() length = len(sentence) print("The number of characters in the sentence is {}".format(length)) Output Conclusion Finally, it is time to draw closure to this article. In today’s article, we learned about the input() function of Python. We looked at the syntax and discussed different examples and use cases. So next time you write a Python program do remember to use the concepts of input() and test your program on many random user input data. Recommended Articles This is a guide to Python User Input. Here we discuss the methods,working and the examples of Python User Input along with the appropriate syntax. You may also have a look at the following articles to learn more –
https://www.educba.com/python-user-input/
CC-MAIN-2020-24
refinedweb
767
58.01
Bamboo This README follows master, which may not be the currently published version! Use the docs for the published version of Bamboo. Bamboo is part of the thoughtbot Elixir family of projects. Flexible and easy to use email for Elixir. - Adapter based so it can be used with Mandrill, SMTP, or whatever else you want. Comes with a Mandrill adapter out of the box. - Deliver emails in the background. Most of the time you don’t want or need to wait for the email to send. Bamboo makes it easy with Mailer.deliver_later - Easy to format recipients. You can do new_email(to: Repo.one(User))and Bamboo can format the User struct if you implement Bamboo.Formatter. - Works out of the box with Phoenix. Use views and layouts to make rendering email easy. - Very composable. Emails are just a Bamboo.Email struct and can be manipulated with plain functions. - Easy to unit test. Because delivery is separated from email creation, no special functions are needed, just assert against fields on the email. - Easy to test delivery in integration tests. Helpers are provided to make testing easy and robust. - View sent emails during development. Bamboo comes with a plug that can be used in your router to view sent emails. See the docs for the most up to date information. We designed Bamboo to be simple and powerful. If you run into anything that is less than exceptional, or you just need some help, please open an issue. Adapters The Bamboo.MandrillAdapter and Bamboo.SendGridAdapter are being used in production and have had no issues. It’s also pretty simple to create your own adapter. Feel free to open an issue or a PR if you’d like to add a new adapter to the list. Bamboo.ConfigAdapter- See BinaryNoggin/bamboo_config_adapter declare config at runtime. Bamboo.MailgunAdapter- Ships with Bamboo. Thanks to @princemaple. Bamboo.MailjetAdapter- See moxide/bamboo_mailjet. Bamboo.MandrillAdapter- Ships with Bamboo. Bamboo.SendGridAdapter- Ships with Bamboo. Bamboo.SMTPAdapter- See fewlinesco/bamboo_smtp. Bamboo.SparkPostAdapter- See andrewtimberlake/bamboo_sparkpost. Bamboo.PostmarkAdapter- See pablo-co/bamboo_postmark. Bamboo.SendcloudAdapter- See linjunpop/bamboo_sendcloud. Bamboo.SesAdapter- See kalys/bamboo_ses. Bamboo.LocalAdapter- Ships with Bamboo. Stores email in memory. Great for local development. Bamboo.TestAdapter- Ships with Bamboo. Use in your test environment. To switch adapters, change the config for your mailer: # In your config file config :my_app, MyApp.Mailer, adapter: Bamboo.LocalAdapter Installation - Add bamboo to your list of dependencies in mix.exs: def deps do # Get from hex [{:bamboo, "~> 1.1"}] # Or use the latest from master [{:bamboo, github: "thoughtbot/bamboo"}] end - Ensure bamboo is started before your application: def application do [applications: [:bamboo]] end Getting Started Do you like to learn by watching? Check out the free Bamboo screencast from DailyDrip. It is a wonderful introduction to sending and testing emails with Bamboo. It also covers some of the ways that Bamboo helps catch errors, how some of the internals work, and how to format recipients with the Bamboo.Formatter protocol. Bamboo breaks email creation and email sending into two separate modules. This is done to make testing easier and to make emails easy to pipe/compose. # In your config/config.exs file # # There may be other adapter specific configuration you need to add. # Be sure to check the adapter's docs. For example, Mailgun requires a `domain` key. config :my_app, MyApp.Mailer, adapter: Bamboo.MandrillAdapter, api_key: "my_api_key" # Somewhere in your application defmodule MyApp.Mailer do use Bamboo.Mailer, otp_app: :my_app end # Define your emails defmodule MyApp.Email do import Bamboo.Email def welcome_email do new_email( to: "john@gmail.com", from: "support@myapp.com", subject: "Welcome to the app.", html_body: "<strong>Thanks for joining!</strong>", text_body: "Thanks for joining!" ) # or pipe using Bamboo.Email functions new_email |> to("foo@example.com") |> from("me@example.com") |> subject("Welcome!!!") |> html_body("<strong>Welcome</strong>") |> text_body("welcome") end end # In a controller or some other module Email.welcome_email |> Mailer.deliver_now # You can also deliver emails in the background with Mailer.deliver_later Email.welcome_email |> Mailer.deliver_later Delivering Emails in the Background Often times you don’t want to send email right away because it will slow down things like web requests in Phoenix. Bamboo offers deliver_later on your mailers to send emails in the background so that your requests don’t block. By default delivering later uses Bamboo.TaskSupervisorStrategy. This strategy sends the email right away, but does so in the background without linking to the calling process, so errors in the mailer won’t bring down your app. If you need something more custom you can create a strategy with Bamboo.DeliverLaterStrategy. For example, you could create strategies for adding emails to a background processing queue such as exq or toniq. Composing with Pipes (for default from address, default layouts, etc.) defmodule MyApp.Email do import Bamboo.Email import Bamboo.Phoenix def welcome_email do base_email |> to("foo@bar.com") |> subject("Welcome!!!") |> put_header("Reply-To", "someone@example.com") |> html_body("<strong>Welcome</strong>") |> text_body("Welcome") end defp base_email do # Here you can set a default from, default headers, etc. new_email |> from("myapp@example.com") |> put_html_layout({MyApp.LayoutView, "email.html"}) |> put_text_layout({MyApp.LayoutView, "email.text"}) end end Handling Recipients The from, to, cc and bcc addresses can be passed a string, or a 2 item tuple. Sometimes doing this can be a pain though. What happens if you try to send to a list of users? You’d have to do something like this for every email: # This stinks. Do you want to do this every time you create a new email? users = for user <- users do {user.name, user.email} end new_email(to: users) To circumvent this, Bamboo has a Bamboo.Formatter protocol. See the Bamboo.Email and Bamboo.Formatter docs for more info and examples. Using Phoenix Views and Layouts Phoenix is not required to use Bamboo. However, if you do use Phoenix, you can use Phoenix views and layouts with Bamboo. See Bamboo.Phoenix Viewing Sent Emails Bamboo comes with a handy plug for viewing emails sent in development. Now you don’t have to look at the logs to get password resets, confirmation links, etc. Just open up the sent email viewer and click the link. See Bamboo.SentEmailViewerPlug Here is what it looks like: Mandrill Specific Functionality (tags, merge vars, templates, etc.) Mandrill offers extra features on top of regular SMTP email like tagging, merge vars, templates, and scheduling emails to send in the future. See Bamboo.MandrillHelper. SendGrid Specific Functionality (templates and substitution tags) SendGrid offers extra features on top of regular SMTP email like transactional templates with substitution tags. See Bamboo.SendGridHelper. Testing You can use the Bamboo.TestAdapter along with Bamboo.Test to make testing your emails straightforward. # Using the mailer from the Getting Started section defmodule MyApp.Registration do use ExUnit.Case use Bamboo.Test test "welcome email" do # Unit testing is easy since the email is just a struct user = new_user email = Email.welcome_email(user) assert email.to == user # The =~ checks that the html_body contains the text on the right assert email.html_body =~ "Thanks for joining" end test "after registering, the user gets a welcome email" do # Integration test with the helpers from Bamboo.Test user = new_user MyApp.Register(user) assert_delivered_email MyApp.Email.welcome_email(user) end end See documentation for Bamboo.Test for more examples, and remember to use Bamboo.TestAdapter. About thoughtbot Bamboo. Contributing Before opening a pull request, please open an issue first. Once we’ve decided how to move forward with a pull request: $ git clone $ cd bamboo $ mix deps.get $ mix test Once you’ve made your additions and mix test passes, go ahead and open a PR! Thanks! Thanks to @mtwilliams for an early version of the SendGridAdapter.
https://hexdocs.pm/bamboo/readme.html
CC-MAIN-2018-51
refinedweb
1,281
62.04
Data::Tree - a hash-based tree-like data structure use Data::Tree; my $DT = Data::Tree::->new(); $DT->set('First::Key',[qw(a b c]); $DT->get('First::Key'); # should return [a b c] $DT->get_scalar('First::Key'); # should return a $DT->get_array('First::Key'); # should return (a, b, c) A simple hash-based nested tree. Decrement the numeric value of the given key by one. Remove the given key and all subordinate keys. Return the value associated with the given key. May be an SCALAR, HASH or ARRAY. Return the values associated with the given key as a list. Return the value associated with the given key as an SCALAR. Increment the numeric value of the given key by one. Set the value of the given key to the given value. Data::Tree - A simple hash-based tree. Dominik Schulz <dominik.schulz@gauner.org> This software is copyright (c) 2012 by Dominik Schulz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/~tex/Data-Tree-0.16/lib/Data/Tree.pm
CC-MAIN-2014-42
refinedweb
178
59.7
A further convenience is that you can set up a script to run pyuic4 (and pyrcc4 for icons) and make that the build command in the project's debug dialog box. The script can check for files changed since the last pyuic4 compilation and only change those. Here's a csh script I wrote a couple of years ago for a PyQt project I was doing then. (Watch out for spurious line breaks.) I forget which tool shows the output to this, but it's someplace fairly obvious -- perhaps the OS Commands tool. (In fact, you can make an OS Tool command that runs a script like this and run it manually as desired.) ____________________________________________________________________ #!/bin/csh # WingIDE build script to automatically update changed ui files # Modify as appropriate and make the build command for your Wing project # Mitchell L Model, dev at software-concepts.org, November 2010 # # If using Python 2 remove the -py3 near the end of the script # ### CHANGE THIS: set top = /path/to/where/the/directories/containing/your/ui/files/are set PYBIN = /opt/local/Library/Frameworks/Python.framework/Versions/Current/bin foreach dir (ui ui/dialog) cd $cdtop/$dir echo Updating UI files in $PWD foreach filnam(*.ui) set module_name = $filnam:r if (! -e ${module_name}_ui.py || -M $module_name.ui > -M ${module_name}_ui.py) then /usr/local/bin/pyuic4 -x -o ${module_name}_ui.tmp1 ${module_name}.ui /usr/bin/sed -e 's/import icons_rc/from icons_rc import */g' ${module_name}_ui.tmp1 >! ${module_name}_ui.tmp2 /usr/bin/sed -e 's/from \([a-z].*[[:>:]]\)/from .\1/g' ${module_name}_ui.tmp2 >! ${module_name}_ui.py rm -f ${module_name}_ui.tmp1 ${module_name}_ui.tmp2 echo ' ' ${module_name}_ui.py updated `date +'%H:%M'` endif end end cd $cdtop if (-M Resources/icons.qrc > -M icons_rc.py) then ${PYBIN}/pyrcc4 -py3 -o icons_rc.py Resources/icons.qrc echo icons_rc.py updated `date +'%H:%M'` endif exit 0 ____________________________________________________________________
http://wingware.com/pipermail/wingide-users/2012-June/009781.html
CC-MAIN-2015-06
refinedweb
315
60.31
Problem Description You may have heard of the book ‘2001 - A Space Odyssey’ by Arthur C. Clarke, or the film of the same name by Stanley Kubrick. In it a spaceship is sent from Earth to Saturn. The crew is put into stasis for the long flight, only two men are awake, and the ship is controlled by the intelligent computer HAL. But during the flight HAL is acting more and more strangely, and even starts to kill the crew on board. We don’t tell you how the story ends, in case you want to read the book for yourself :-) After the movie was released and became very popular, there was some discussion as to what the name ‘HAL’ actually meant. Some thought that it might be an abbreviation for ‘Heuristic ALgorithm’. But the most popular explanation is the following: if you replace every letter in the word HAL by its successor in the alphabet, you get … IBM. Perhaps there are even more acronyms related in this strange way! You are to write a program that may help to find this out. Input The input starts with the integer n on a line by itself - this is the number of strings to follow. The following n lines each contain one string of at most 50 upper-case letters. Output For each string in the input, first output the number of the string, as shown in the sample output. The print the string start is derived from the input string by replacing every time by the following letter in the alphabet, and replacing ‘Z’ by ‘A’. Print a blank line after each test case. Sample Input 2 HAL SWERC Sample Output String #1 IBM String #2 TXFSD 题意就是:输入一个大写的字符串,输出每一个大写字母后的一个大写字母。 如果遇到Z就输出A。 注意每一个测试后都有一个空行。 水题一个! import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t =sc.nextInt(); int ti=0; while(t-->0){ String str = sc.next(); System.out.println("String #"+(++ti)); for(int i=0;i<str.length();i++){ if(str.charAt(i)=='Z'){ System.out.print("A"); }else{ System.out.print((char)(str.charAt(i)+1)); } } System.out.println(); System.out.println(); } } }
https://blog.csdn.net/qq_26525215/article/details/51557062
CC-MAIN-2018-30
refinedweb
363
72.87
. Code-Behind ProgrammingEditor's Note: This article continues Chapter 5, "Web Forms." The previous parts are: Code-Behind Programming While it's perfectly legal to put HTML and code in the same ASPX file, in the real world you should segregate the two by placing them in separate files. Proper separation of code and data is achieved in ASP.NET by using a technique called code-behind programming. A Web form that uses code-behind is divided into two parts: an ASPX file containing HTML, and a source code file containing code. Here are two reasons why all commercial Web forms should employ code-behind: - Robustness. If a programming error prevents the code in an ASPX file from compiling, the error won't come to light until the first time the page is accessed. Careful testing will take care of this, but how often do unit tests achieve 100 percent code coverage? - Maintainability. ASP files containing thousands of lines of spaghetti-like mixtures of HTML and script are not uncommon. Clean separation of code and data makes applications easier to write and to maintain. - Create a CS file containing event handlers, help methods, and other code-everything that would normally appear between <script> and </script> tags in an ASPX file. Make each of these source code elements members of a class derived from System.Web.UI.Page. - In your Page-derived class, declare protected fields whose names mirror the IDs of the controls declared in the ASPX file. For example, if the Web form includes a pair of TextBox controls whose IDs are UserName and Password, include the following statements in your class declaration: protected TextBox UserName; protected TextBox Password; Without these fields, the CS file won't compile because references to UserName and Password are unresolvable. At run time, ASP.NET maps these fields to the controls of the same name so that reading UserName.Text, for example, reads the text typed into the TextBox control named UserName. - Compile the CS file into a DLL and place the DLL in a subdirectory named bin in the application root. - benefits of embedding code in an ASPX file but none of the drawbacks. The application in the next section demonstrates code-behind at work. The Lander Application In 1969, Neil Armstrong landed the Apollo 11 Lunar Excursion Module (LEM) on the moon with just 12 seconds of fuel to spare. You can duplicate Armstrong's feat with a Web-based lunar lander simulation patterned after the lunar lander game popularized on mainframe computers in the 1970s. This version of the game is built from an ASP.NET Web form, and it uses code-behind to separate code and HTML. It's called Lander, and it's shown in Internet Explorer in Figure 5-12. Its source code appears in Figure 5-13. To run the program, copy Lander.aspx to your PC's \Inetpub\wwwroot directory. If \Inetpub\wwwroot lacks a subdirectory named bin, create one. Then compile Lander.cs into a DLL and place the DLL in the bin subdirectory. Here's the command to compile the DLL: csc /t:library Lander.cs Next, start your browser and type into the address bar. Begin your descent by entering a throttle value (any percentage from 0 to 100, where 0 means no thrust and 100 means full thrust) and a burn time in seconds. Click the Calculate button to input the values and update the altitude, velocity, acceleration, fuel, and elapsed time read-outs. Repeat until you reach an altitude of 0, meaning you've arrived at the moon's surface. A successful landing is one that occurs with a downward velocity of 4 meters per second or less. Anything greater and you dig your very own crater in the moon. Figure 5-12. The Lander application. Lander.aspx is a Web form built from a combination of ordinary HTML and ASP.NET server controls. Clicking the Calculate button submits the form to the server and activates the DLL's OnCalculate method, which extracts the throttle and burn time values from the input fields and updates the onscreen flight parameters using equations that model the actual flight physics of the Apollo 11 LEM. Like many Web pages, Lander.aspx uses an HTML table with invisible borders to visually align the page's controls. Lander.aspx differs from the ASPX files presented thus far in this chapter in that it contains no source code. Lander.cs contains the form's C# source code. Inside is a Page-derived class named LanderPage containing the OnCalculate method that handles Click events fired by the Calculate button. Protected fields named Altitude, Velocity, Acceleration, Fuel, ElapsedTime, Output, Throttle, and Seconds serve as proxies for the controls of the same names in Lander.aspx. LanderPage and OnCalculate are declared public, which is essential if ASP.NET is to use them to serve the Web form defined in Lander.aspx. Lander.aspx <%@ Page <hr> <table cellpadding="8"> <tr> <td>Altitude (m):</td> <td><asp:Label</td> </tr> <tr> <td>Velocity (m/sec):</td> <td><asp:Label</td> </tr> <tr> <td>Acceleration (m/sec2):</td> <td><asp:Label</td> </tr> <tr> <td>Fuel (kg):</td> <td><asp:Label</td> </tr> <tr> <td>Elapsed Time (sec):</td> <td><asp:Label</td> </tr> <tr> <td>Throttle (%):</td> <td><asp:TextBox</td> </tr> <tr> <td>Burn Time (sec):</td> <td><asp:TextBox</td> </tr> </table> <br> <asp:Button <br><br> <hr> <h3><asp:Label</h3> </form> </body> </html> Lander.cs using System; using System.Web.UI; using System.Web.UI.WebControls; public class LanderPage : Page { const double gravity = 1.625; // Lunar gravity const double landermass = 17198.0; // Lander mass protected Label Altitude; protected Label Velocity; protected Label Acceleration; protected Label Fuel; protected Label ElapsedTime; protected Label Output; protected TextBox Throttle; protected = alt2.ToString ("f1"); Velocity.Text = vel2.ToString ("f1"); Acceleration.Text = acc.ToString ("f1"); Fuel.Text = fuel2.ToString ("f1"); ElapsedTime.Text = time2.ToString ("f1"); } } }Figure 5-13. The Lander source code. How Code-Behind Works A logical question to ask at this point is "How does code-behind work?" The answer is deceptively simple. When you put Web forms code in an ASPX file and a request arrives for that page, ASP.NET derives a class from System.Web.UI.Page to process the request. The derived class contains the code that ASP.NET extracts from the ASPX file. When you use code-behind, ASP.NET derives a class from your class-the one identified with the Inherits attribute-and uses it to process the request. In effect, code-behind lets you specify the base class that ASP.NET derives from. And since you write the base class, you control everything that goes in it. Figure 5-14 shows (in ILDASM) the class that ASP.NET derived from LanderPage the first time Lander.aspx was requested. You can clearly see the name of the ASP.NET-generated class-Lander_aspx-as well as the name of its base class: LanderPage. Figure 5-14. DLL generated from a page that uses code-behind. Using Code-Behind Without Precompiling: the Src Attribute If you like the idea of separating code and data into different files but for some reason would prefer not to compile the source code files yourself, you can use code-behind and still allow ASP.NET to compile the code for you. The secret? Place the CS file in the same directory as the ASPX file and add a Src attribute to the ASPX file's @ Page directive. Here's how Lander.aspx's Page directive would look if it were modified to let ASP.NET compile Lander.cs: <%@ Page Inherits="LanderPage" Src="Lander.cs" %> Why anyone would want to exercise code-behind this way is a question looking for an answer. But it works, and the very fact that the Src attribute exists means someone will probably find a legitimate use for it. Using Non-ASP.NET Languages in ASP.NET Web Forms Code embedded in ASPX files has to be written in one of three languages: C#, Visual Basic .NET, or JScript. Why? Because even though compilers are available for numerous other languages, ASP.NET uses parsers to strip code from ASPX files and generate real source code files that it can pass to language compilers. The parsers are language-aware, and ASP.NET includes parsers only for the aforementioned three languages. To write a Web form in C++, you either have to write a C++ parser for ASP.NET or figure out how to bypass the parsers altogether. Code-behind is a convenient mechanism for doing the latter. Code-behind makes it possible to code Web forms in C++, COBOL, and any other language that's supported by a .NET compiler. Figure 5-15 contains the C++ version of Lander.cs. Lander.cpp is an example of managed C++. That's Microsoft's term for C++ code that targets the .NET Framework. When you see language extensions such as __gc, which declares a managed type, being used, you know you're looking at managed C++. The following command compiles Lander.cpp into a managed DLL and places it in the current directory's bin subdirectory: cl /clr lander.cpp /link /dll /out:bin\Lander.dll You can replace the DLL created from the CS file with the DLL created from the CPP file and Lander.aspx is none the wiser; it still works the same as it did before. All it sees is a managed DLL containing the LanderPage type identified by the Inherits attribute in the ASPX file. It neither knows nor cares how the DLL was created or what language it was written in. Lander.cpp #using <system.dll> #using <mscorlib.dll> #using <system.web.dll> using namespace System; using namespace System::Web::UI; using namespace System::Web::UI::WebControls; public __gc class LanderPage : public Page { protected: static const double gravity = 1.625; // Lunar gravity static const double landermass = 17198.0; // Lander mass Label* Altitude; Label* Velocity; Label* Acceleration; Label* Fuel; Label* ElapsedTime; Label* Output; TextBox* Throttle; = (new Double (alt2))->ToString ("f1"); Velocity->Text = (new Double (vel2))->ToString ("f1"); Acceleration->Text = (new Double (acc))->ToString ("f1"); Fuel->Text = (new Double (fuel2))->ToString ("f1"); ElapsedTime->Text = (new Double (time2))->ToString ("f1"); } } };Figure 5-15. Managed C++ version of Lander.cs. Editor's Note: This sample chapter continues in the article titled, Web Forms: Web Forms and Visual Studio .NET. About the Author Jeff Prosise makes his living programming Microsoft .NET and teaching others how. # # # There are no comments yet. Be the first to comment!
http://www.codeguru.com/columns/chapters/article.php/c6671/Programming-Microsoft-NET.htm
CC-MAIN-2014-42
refinedweb
1,766
58.48
Expect Stocks to Make New Highs as the Economy Firms Up Recession fears are everywhere. The US-China trade war, Middle East violence, impeachment in DC, protests in Hong Kong, and Brexit have all weighed on the economy. These fears are likely overblown. Consumer economic data remains robust and the Fed has cut rates twice as manufacturing has softened. US stocks have posted robust gains. And the 3 month/10 year spread in Treasuries has uninverted. I wrote in August that Optimism is on the Menu; A Recession is Not: US stocks were 90% likely to gain 6.7% in the next 12 months. Since that date, the S&P 500 has risen by 4.3%. I am now expecting the S&P to post new all-time highs and gain about 11% over the next year. These return projections come from my Market Model. The model is a fully-connected neural network ingesting 164 data points back to 1992. Full code is on my GitHub under post 63. The Consumer is Strong The consumer drives the US economy. So far things are holding up well. Consumer sentiment has rebounded in October: Retail Sales growth continues: Consumer spending growth remains steady: There has been no noticeable increase in layoffs: Manufacturing Has Slowed, But The Fed Has Acted Manufacturing has weakened. The September ISM PMI recorded its lowest reading since June of 2009 at 47.8 and has been falling for months. Per the ISM, the PMI is a “composite index based on the diffusion indexes of five of the indexes with equal weights: New Orders (seasonally adjusted), Production (seasonally adjusted), Employment (seasonally adjusted), Supplier Deliveries (seasonally adjusted), and Inventories.” I found that the summary PMI index to be most correlated with three of these sub-indexes: New Orders, Production, Employment. import numpy as np import pandas as pd import matplotlib.pyplot as plt from pathlib import Path path = Path("Desktop") df = pd.read_csv(path/'Market Data - ISM2.csv') corr = df.corr() fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(corr,cmap='coolwarm', vmin=-1, vmax=1) fig.colorbar(cax) ticks = np.arange(0,len(df.columns),1) ax.set_xticks(ticks) plt.xticks(rotation=90) ax.set_yticks(ticks) ax.set_xticklabels(df.columns) ax.set_yticklabels(df.columns) plt.show() Source: Institute for Supply Management I created a new equal-weighted composite of these three indexes. Since 1980, in every expansion, this new index sustained a drop from a relative high into the 45-49 range. There is price memory at these levels, and 2019 is no different. Each drop coincided with mid-cycle Fed rate cuts. In 1985-86, 1995-96, 1998, and 2002-2003, the index rebounded and the expansion continued. The Fed is banking on the same outcome here. There are other green shoots to point to. The manufacturing slowdown in the U.S. may be driven by temporary influences such as the GM strike. Certain bellwether industrial companies such as Fastenal are posting strong results. The IHS Markit US Manufacturing PMI was 51.1 for September 2019, its highest reading since April. The Empire State Manufacturing Survey has rebounded since June: As has the Philly Fed Index: The Trade War is Far From Over As I wrote here in August, do not expect a trade deal before the 2020 U.S. presidential election. Only political desperation will drive a grand bargain. Impeachment proceedings in D.C. and continued protests in Hong Kong have weakened both leaders. This may be driving the recent negotiations and talk of a mini-deal. Look to President Trump’s poll numbers in the Midwest and to his support in the Senate for his next move on trade. Look for how far unrest spreads in China for insight into President Xi’s intentions. In the meantime, the current mini-deal seems unstable as best and fake news at worst. President Trump enjoys touting stock market gains. What he is currently seeing is a market that has withstood his trade war. Since the January 22, 2018 start of the trade war (Wikipedia), the S&P 500 has gained 4.8%. Those are not world-beating returns…oh wait, they are. (source: Yahoo Finance) The President surely keep tabs on GDP growth. It’s natural to fear a Carter or Bush 41 recession. A same-party or credible third-party challenger could doom reelection. So far, the US economy continues strong growth (source: Bureau of Economic Analysis): Public Sector Driven Risk Has Yet to Take Us Down I have written here, here, and here that society operates in shifting cycles of confidence between the public and private sectors. We are in a private-sector driven cycle where technology, capital, and private enterprise are ascendant. In these cycles, the greatest risks emerge from the out of power group. A miscalculated move by a public sector actor can derail progress. The US-China trade war is a poster child of these actions. But, to date, the US economy has held up pretty well. I expect it to continue to do.
https://www.complexityeverywhere.com/no-recession-in-sight/
CC-MAIN-2021-10
refinedweb
843
58.99
Every Android app has a unique application ID that looks like a Java package name, such as com.example.myapp. This ID uniquely identifies your app on the device and in Google Play Store. If you want to upload a new version of your app, the application ID (and the certificate you sign it with) must be the same as the original: android { defaultConfig { applicationId "com.example.myapp" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" } ... } When you create a new project in Android Studio, the applicationId exactly matches the Java-style package name you chose during setup. However, the application ID and package name are independent of each other beyond this point. You can change your code's package name (your code namespace) and it will not affect the application ID, and vice versa (though, again, you should not change your application ID once you publish your app). However, changing the package name has other consequences you should be aware of, so see the section about how to change the package name. And although the application ID looks like a traditional Java package name, the naming rules for the application ID are a bit more restrictive: - It must have at least two segments (one or more dots). - Each segment must start with a letter. - All characters must be alphanumeric or an underscore [a-zA-Z0.. Change the package name Although your project's package name matches the application ID by default, you can change it. However, if you want to change your package name, be aware that the package name (as defined by your project directory structure) should always match the package attribute in the AndroidManifest.xml file, as shown here: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns: The Android build tools use the package attribute for two things: - It applies this name as the namespace for your app's generated R.javaclass. Example: With the above manifest, the Rclass will be com.example.myapp.R. - It uses it to resolve any relative class names that are declared in the manifest file. Example: With the above manifest, an activity declared as <activity android:is resolved to be com.example.myapp.MainActivity. As such, the name in the package attribute should always match your project's base package name where you keep your activities and other app code. Of course, you can have sub-packages in your project, but then those files must import the R.java class using the namespace from the package attribute, and any app components declared in the manifest must add the missing sub-package names (or use fully-qualified package names). If you want to refactor your package name completely, be sure you update the package attribute as well. As long as you use Android Studio's tools to rename and refactor your packages, then these automatically stay in sync. (If they don't stay in sync, your app code can't resolve the R class because it's no longer in the same package, and the manifest won't identify your activities or other components.) You must always specify the package attribute in your project's main AndroidManifest.xml file. If you have additional manifest files (such as for a product flavor or build type), be aware that the package name supplied by the highest-priority manifest file is always used in the final merged manifest. For more information, see Merge multiple manifest files. One more thing to know: Although you may have a different name for the manifest package and the Gradle applicationId, the build tools copy the application ID into your APK's final manifest file at the end of the build. So if you inspect your AndroidManifest.xml file after a build, don't be surprised that the package attribute has changed. The package attribute is where Google Play Store and the Android platform actually look to identify your app; so once the build has made use of the original value (to namespace the R class and resolve manifest class names), it discards that value and replaces it with the application ID.
https://developer.android.com/studio/build/application-id.html?authuser=0
CC-MAIN-2020-50
refinedweb
684
58.82
Dates And Time In Python Page Contents References - timeanddate.com. - Working with Time Zones, WC3. - The Science of Timekeeping, HP. - Timezones and Python , Julien Danjou. - Dealing with Timezones in Python, Armin Ronacher. - Problems with Python and timezones, Lennart Regebro Introduction The referenced article, "The Science Of Timekeeping", gives a really nice introduction to time and the history of how we measure time. Combined with the reference WC3 article we can get an idea of how our concept of time originated from observable phenomena like sunrise and sunset, the seasons etc, and how now it is based on more abstract standards like the the transition between the two hyperfine levels of the ground state of the cesium-133 atom. All of this is important for us to realise that there is no really universal definition of time that is the same all over the world, except for something called UTC. Countries have their own timezones, not all of which differ in a regular pattern, where daylight saving time (DST) may be active or not depending on the time of year, and worse, there are crazy things like leap days end even leap seconds! In 1884, ... the Greenwich observatory was accepted as source of the world’s standard time ... ... GMT has evolved to UTC ... GMT was based on mean solar time. UTC is based on a definition of the second that is nearly a million times more accurate ... based on a quantum resonance within a caesium atom ... ... UTC is established by the Bureau International des Poids et Mesures (BIPM) based on an a aggregate of data from timing laboratories throughout the world, and from input from the International Earth Rotation Service (IERS). "Computerphile" gives a really good summary: Time Standards Note that these are NOT time zones! Solar Time - Time set based on the local position of the sun. - E.g. sundial time. - Day lengths vary depending on season - effects accumulate. UT1 - Based on the Earth's rotation, from which the mean solar day is derived. - Modern continuation of GMT. TAI - Atomic clock based standard based on the average of hundres of atmoic clocks throught the world. - Basis for UTC. - Never adjusted and always continuous. I.e., no leap seconds. UTC - Based on TAI with leap seconds added to keep it within 0.9 seconds of UT1. - Modified to be related to UT1 using leap seconds. UTC ticks with the same frequency as TAI - very accurate and stable - but is phase aligned in jumps of leap-seconds to UT1 - Related to UT1 so that the "wall clock" relates to the human day - i.e., when it is day and night. - Not continuous because of leap seconds. Unix Epoch - A.k.a. just the "Epoch". - Seconds elapsed since 00:00:00 UTC on January 1, 1970 Time Zones & Daylight Saving Hours The Stack Overflow "timezone" tag has an excellent explanation and is well worth a read! The world uses UTC. By agreement we've all said we'll use UTC to agree on the same standard of time. The added complexity to the mix is time zones. At a UTC time of X in some parts of the world it will be day and in others it will be night, so in regions of the world the UTC time is offset so that 12pm is roughly what we would perceive as midday in terms of sun position. For historical reasons UTC+0 is GMT - the mean solar time at the Royal Observatory in Greenwich. The following is an image of the world timezones as found on Wikipedia. From the above, we can see that if we lived in, for example, Malta, we would use UTC+1 as our time base. But, note that a time zone is not the same as an offset! We can also see that timezones are as much political as they are geographic. To make life even more complicated there are daylight saving hours to consider. In countries where the potion of the day that is light moves depending on season an offset of +/- 1 hour (or fractional or multiple) can be applied to the time. This is purely a human thing so that we get more of the "day" time in the light! Figuring out your machine's local time zone can be suprisingly difficult. The same author's first blog about the problems with Python and timezones is a good read too. Of particular note is the TZ Database. Time Zone != Offset A time zone can not be represented solely by an offset from UTC. Many time zones have more than one offset due to daylight saving time (aka "summer time") rules. The dates that offsets change are also part of the rules for the time zone, as are any historical offset changes... - An offset is just a number that represents how far a particular date/time value is ahead or behind UTC... - A time zone contains much more: - A name or ID that can be used to identify the zone. - One or more offsets from UTC - The specific dates and times that the zone transitions between offsets... One can determine the correct offset, given a time zone and a datetime. But one cannot determine the correct time zone given just an offset. Using Dates & Times in Python The referenced articles by Julien Danjou and Armin Ronacher both make the following very poinient point: Python datetime objects, by default are not timezone aware!. This can be read directly from the Python docs, but wasn't something I'd taken enough notice of until reading those articles! An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, to locate itself relative to other aware objects. An aware object is used to represent a specific moment in time that is not open to interpretation. ... For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo, that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfoobjects capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect. Thus, when using dates/time in Python always use aware objects so that there is no ambiguity in what time is being represented and always store time in UTC: An aware current UTC datetime can be obtained by calling datetime.now(pytz.utc). Why do we want to do this? As Danjou points out, without this the datetime object will have no timezone information, so later on in the code, can we be sure it is representing a time in UTC? There would be no way to tell! He suggests treating any datetime without a timezone as a bug! Never use unware datetime objects. Always make sure you get timezone aware objects and even better objects using UTC with the timezone information set to UTC: datetime.now(pytz.utc)! As Danjou recommends, as well as using aware datetime objects you should also store and retreive dates/times in ISO 8601 format by using datetime.datetime.isoformat(). To store and retreive date/time use ISO 8601 format, supported by the Python iso8601 package. Examples Get The Current Time as UTC >>> import datetime >>> import pytz >>> datetime.datetime.now(pytz.utc) datetime.datetime(2018, 3, 18, 12, 36, 52, 315868, tzinfo=<UTC>) Output Current Time In ISO 8601 Format >>> import datetime >>> import pytz >>> datetime.datetime.now(pytz.utc).isoformat() '2018-03-18T12:41:07.591469+00:00' Input Current Time In ISO 8601 Format >>> import datetime >>> import pytz >>> import iso8601 >>> a = datetime.datetime.now(pytz.utc).isoformat() >>> a '2018-03-19T07:53:48.225000+00:00' >>> iso8601.parse_date(a) datetime.datetime(2018, 3, 19, 7, 53, 48, 225000, tzinfo=<FixedOffset '+00:00' datetime.timedelta(0)>) Convert Local Time To UTC Copied verbatim from this SO answer. import pytz, datetime local = pytz.timezone ("America/Los_Angeles") # See the TZ Database... naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone(pytz.utc) utc_dt.strftime ("%Y-%m-%d %H:%M:%S") Convert DateTime To Epoch (datetime.datetime(year,month,day[,hours[,mins[,secs[,usecs[,tzinfo]]]]]) - datetime.datetime(1970,1,1)).total_seconds() # Py 2 datetime.datetime(year,month,day[,hours[,mins[,secs[,usecs[,tzinfo]]]]]).strftime('%s') # Py 3
https://jehtech.com/python/time.html
CC-MAIN-2021-49
refinedweb
1,397
64.51
Hello, I have just discovered a strange bug in Vala 0.44.3 Consider the code bellow: using GLib; public class ABC : GLib.Object { public static int main (string[] args) { Object a = new Object (typeof (ABC)); assert (a.get_type () == typeof (ABC)); return 0; } } The code looks valid and compiles, but it does not run. You will get the following error: (process:9209): GLib-GObject-CRITICAL **: 23:15:21.563: g_object_new_is_valid_property: object class 'GObject' has no property named '\u0001' So I did some digging and found that the code gen is doing something very wrong, as this is the generated C code: gint abc_main (gchar** args, gint args_length1) { gint result = 0; GObject* a = NULL; GObject* _tmp0_; #line 6 "../test.vala" _tmp0_ = g_object_new (G_TYPE_OBJECT, TYPE_ABC, NULL); #line 6 "../test.vala" a = _tmp0_; #line 8 "../test.vala" _vala_assert (G_TYPE_FROM_INSTANCE (a) == TYPE_ABC, "a.get_type () == typeof (ABC)"); #line 10 "../test.vala" result = 0; #line 10 "../test.vala" _g_object_unref0 (a); #line 10 "../test.vala" return result; #line 67 "test.c" } As you can see the g_object_new (...) is incorrect. Or is this the new behaviour for this? How do you set construct-only properties if you can’t do it this way? Regards Gustav Hartvigsson
https://discourse.gnome.org/t/glib-object-new-problem/1348
CC-MAIN-2019-35
refinedweb
198
69.28
I find Flash games on Facebook great fun. Not playing them, of course, that’s boring. As you may remember from my previous post, “winning at Puzzle Adventures“, I like to take a look into their guts and figure out how they work, and whether or not I can get insane scores with no effort. When I discovered Candy Crush Saga, I was intrigued. All my friends appeared mad about this game, sending me so many requests for candy that their dentist would surely commit harakiri. I started playing a bit, and it wasn’t long until I had to stop playing, since the game only allows you a set number of lives per hour in an attempt to either extract money from you or coax you into spamming your friends with requests for the game, to increase its popularity. Cheating at online games This, however, wouldn’t do, so I fired up the Swiss army knife of web debugging, Charles Proxy (it’s a fantastic tool for this job). I started looking at the requests the game was making to the server, and saw one that looked promising: "currentUser": { "lives": 5, "maxLives": 5, } I added a breakpoint and edited lives to always be 5, which did allow me to play for ever, no matter how much I lost. Yay for non-existent server checks! This wasn’t great, though. Sure, I could play as much as I want, but I don’t want to play at all! I wanted to see if I could make the game much easier somehow. Looking some more, I found the call that loads the level, and the level details specify the number of colors to use on the level. Since the game is played by getting candy of one color to line up in a row, fewer colors means a considerably easier game. However, too few colors and the game won’t end at all! I discovered that four colors is the sweet spot, and edited the level accordingly: { "levelData":{ "numberOfColours":4, "gameModeName":"Light up", "pepperCandyMax":1, "pepperCandySpawn":3, "chameleonCandyMax":0 }, } Success! There were only four colors in the level, and the game pretty much cascaded into a huge victory after two or three moves. Diving deeper Even this, though, was very time-consuming. The game has 500 levels, and, with 3 minutes per level, it would take way too long to win every single one. I needed to discover a faster way to “play” games. Helpfully, the server gives you a list of all the API methods when there’s an error: com.king.saga.api.CurrentUserResponse poll(); com.king.saga.api.GetMessagesResponse getMessages(); [Lcom.king.saga.api.ApiItemInfo; unlockItem(java.lang.String, java.lang.String); com.king.saga.api.ApiGameEnd gameEnd(com.king.saga.api.ApiGameResult); com.king.saga.api.GameInit gameInit(); com.king.saga.api.ApiGameStart gameStart(int, int); com.king.saga.api.PeekMessagesResponse peekMessages(); com.king.saga.api.GetMessagesResponse removeMessages([Ljava.lang.Long;, boolean); com.king.saga.api.GameInit gameInitLight(); com.king.saga.api.ApiGameEnd gameEnd2(com.king.saga.api.ApiGameResult); Looking at those and the responses, we can immediately see that the gameEnd method is very interesting indeed: { "score":373400, "variant":0, "seed":1384024506403, "reason":0, "timeLeftPercent":-1, "cs":"040a6a", "episodeId":34, "levelId":4 } What’s this? It looks like we can just tell the game we finished a level, without any other hassle. I tried to replay that request by changing the score, but nothing happened. Nothing happened if I specified different episode ids, either. There must be some signature we can’t duplicate, and the “cs” field sounds awfully close to “checksum”. I was very close to solving the whole puzzle, but the checksum field means that I will have to fake the signature (which, unless the Candy Crush developers are clueless, should contain a secret key). There’s really no way to figure out how the signature is produced without looking at the source, so that’s what I did. Using my trusty Flash decompiler, I rummaged around in the source code, and found that the cs parameter is basically an MD5 of the following: "episodeId:levelId:score:timeLeftPercent:userId:seed:secretkey" Finding the secret key took a bit more digging, but, with the final piece of the puzzle uncovered, I could finally make make requests to the server and make it seems as if we legitimately finished a game. I’m not sure if you really have to make the gameStarted call, or if you can pass in any random seed you want, but I think the call is optional. At this point, I could pretty much finish any level I want, with any score I want, in about half a second. A script to make it easier However, having to do all this in a shell (or curl) was still too hard. To remove that final obstacle, i wrote a small CCrush Python class with various methods to make automatically winning in the game easier. Here’s the listing: import requests import hashlib import json import random import time import sys class CCrush(object): def __init__(self, session): self.session = session def hand_out_winnings(self, item_type, amount): item = [{"type": item_type, "amount": amount}] params = { "_session": self.session, "arg0": json.dumps(item), "arg1": 1, "arg2": 1, "arg3": "hash", } return requests.get("", params=params) def add_life(self): params = {"_session": self.session} return requests.get("", params=params) def start_game(self, episode, level): params = {"_session": self.session, "arg0": episode, "arg1": level} response = requests.get("", params=params) return response.json()["seed"] def end_game(self, episode, level, seed, score=None): if score is None: score = random.randrange(3000, 6000) * 100 dic = { "timeLeftPercent": -1, "episodeId": episode, "levelId": level, "score": score, "variant": 0, "seed": seed, "reason": 0, } dic["cs"] = hashlib.md5("%(episodeId)s:%(levelId)s:%(score)s:%(timeLeftPercent)s:userid:%(seed)s:thesecret" % dic).hexdigest()[:6] params = {"_session": self.session, "arg0": json.dumps(dic)} response = requests.get("", params=params) return response def play_game(self, episode, level, score=None): seed = self.start_game(episode, level) return self.end_game(episode, level, seed, score) if __name__ == "__main__": ccrush = CCrush(sys.argv[1]) episode = int(sys.argv[2]) level = int(sys.argv[3]) seed = ccrush.start_game(episode, level) ccrush.end_game(episode, level, seed) This script can be invoked with python ccrush.py <sessionid> <episode> <level>, and it will automatically pass that level with a random score. Here’s the result: The script doesn’t actually work without the secret key, but that’s left as an exercise for the reader. It does work for getting extra lives for free, or extra helper items/gold, though. My aim with this post is less about telling people how to cheat in the game and more about the thought process behind analyzing these things. NOTE: After the amazing response to this post, I feel like I need to clarify something: It’s not a bug, or a fault on the part of the developers of Candy Crush that this is possible. Spending time and effort implementing anti-cheat measures would just be wasted, since it brings them no benefit (the most cheaters can do is brag to their friends, and they most probably weren’t going to pay anyway). So, I’m not implying that King should fix this, or that they don’t know what they’re doing. If I were developing Candy Crush, I wouldn’t put in any anti-cheating code either (as I said above, it would bring no benefit). I hope you enjoyed this short exploration of game APIs, and got a bit more knowledge in the process. For more posts like this, you can read my “winning” series, subscribe to my mailing list below to be notified of new posts, or follow me on Twitter.
https://www.stavros.io/posts/winning-candy-crush/?
CC-MAIN-2021-31
refinedweb
1,290
64.1
Fabulous Adventures In Coding Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric. do? var m1 = new MyHandle(123);try{ // do something}finally{ m1.Dispose();}// Sanity checkDebug.Assert(m1.Handle == 0); Everything work out there? Yep, we're good. m1 begins its life with Handle set to 123, and after the dispose it is set to zero. How about this? var m2 = new MyHandle(123);try{ // do something}finally{ ((IDisposable)m2).Dispose();}// Sanity checkDebug.Assert(m2.Handle == 0); Does that do the same thing? Surely casting an object to an interface it implements does nothing untoward, right? . Wrong. This boxes m2. Boxing makes a copy, and it is the copy which is disposed, and therefore the copy which is mutated. m2.Handle stays set to 123. So what does this do, and why? var m3 = new MyHandle(123);using(m3){ // Do something}// Sanity checkDebug.Assert(m3.Handle == 0); Based on the previous example you probably think that this boxes m3, mutates the box, and therefore the assertion fires, right? Right? Is that what you thought? You'd be perfectly justified in thinking that there is a boxing performed in the finally because that's what the spec says. The spec says that the "using" statement's expansion when the expression is a non-nullable value type is finally { ((IDisposable)resource).Dispose();} However, I'm here today to tell you that the disposed resource is in fact not boxed in our implementation of C#. The compiler has an optimization: if it detects that the Dispose method is exposed directly on the value type then it effectively generates a call to finally { resource.Dispose();} without the cast, and therefore without boxing. Now that you know that, would you like to change your answer? Does the assertion fire? Why or why not? Give it some careful thought. The assertion still fires, even though there is no boxing. The relevant line of the spec is not the one that says that there's a boxing cast; that's a red herring. The relevant bit of the spec is: A using statement of the form "using (ResourceType resource = expression) statement" corresponds to one of three possible expansions. [...] A using statement of the form "using (expression) statement" has the same three possible expansions, but in this case ResourceType is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement. That is to say, our program fragment is equivalent to: var m3 = new MyHandle(123);using(MyHandle invisible = m3){ // Do something}// Sanity checkDebug.Assert(m3.Handle == 0); which is equivalent to var m3 = new MyHandle(123);{ MyHandle invisible = m3; try { // Do something } finally { invisible.Dispose(); // No boxing, due to optimization }}// Sanity checkDebug.Assert(m3.Handle == 0); It is the invisible copy which is disposed and mutated, not m3. And that's why the compiler can get away with not boxing in the finally. The thing that it is not boxing is invisible and inaccessible and therefore there is no way to observe that the boxing was skipped. Once again the moral of the story is: mutable value types are enough pure evil to turn you all into hermit crabs, and therefore should be avoided. foreach and the special structs on the generic collections Enumerators would like a word :) At least the expansion of that sugar is reasonable (as in doesn't surprise most people) While totally agreeing with everything you've said, mutable value types could be an argument for adding support for C++ style copy constructors and out-of-scope destructors for C# value types. I think all readers of your blog now agree that mutable value types are evil... But I wonder why this rule is so often not applied in the .NET Framework classes (DictionaryEntry, GCHandle, Point, Size...) @Thomas Levesque: I don't think that "mutable value types are evil" was known in the .NET 1.0 timeframe, at least not as well as we know it now, and all of your examples are from 1.0. A case could be made for e.g. List<T>.Enumerator, though you're not normally supposed to directly access that type, so it's (plausibly) less of an issue. This self-mutating struct is indeed very nasty, very evil. Let's never speak of it again. GCHandle's mutability is hidden far away from the average user. There are often places that platform designers are doing this that appear evil but are well understood. I think Point is a legacy of trying to play along with POINT: msdn.microsoft.com/.../dd162805%28v=vs.85%29.aspx, likewise Size It's still quite nasty. DictionaryEntry is pure evil @Jonathan Pryor, you're right of course... but WPF (.NET 3.0) also has its own Point and Size structures, and they're also mutable. @Shuggy, yes, I think that's because it's mapped directly to the unmanaged structure... The WPF structs (like Point and Size) have to be mutable because XAML cannot create immutable objects (it can only call default constructors and set properties). The real question is why they are structs, seeing as how they have to be mutable. I'd guess that it's an optimization. You could potentially have millions of Point objects, and performance could really suffer if the memory footprint doubled and each one had to be individually allocated, initialized, and GCed. Re: "Suppose you have an immutable value type that is also disposable". Suppose you have an invisible purple dragon. Disposing the value changes its state (though not necessarily the bits of the struct). If its state can change, then it isn't immutable. @Gabe @Thomas: XAML can create immutable objects just fine (it can create strings and other primitives, after all), but Xaml2006 has no way of explicitly declaring instances of immutable types with non-default constructors. This renders immutable types with more than one member somewhat useless in XAML. Your only option is to declare a default TypeConverter such that you could put a string representation in XAML and have it converted to an instance of an immutable type. Then you could do this: <SomeObject Location="(0, 2)" /> e.g., where 'Location' is an immutable 'Point' with (x, y) members.. Xaml2009 includes support for non-default constructors, but the syntax is relatively verbose, and Xaml2009 wasn't around in .NET 3.0, so we're stuck with some mutable value types. "foreach" is different - per language spec, it does not expand to using but rather directly to try/finally, and the spec also explicitly says that, for enumerators which are value types, Dispose() is called directly without boxing. The difference is that foreach calls different methods several times on the enumerator, so you can write a perverted implementation that would be able to spot boxing on that final Dispose() call. I can not agree wholesale with the statement that "mutable value types are enough pure evil to turn you all into hermit crabs." The real problem is when we try to treat values as objects. This is a flaw in the "everything is an object" concept. When a struct implements an interface (especially if the interface implies mutability) you are treating a value like an object. Your example is analogous to the much simpler scenario of assigning the value of 'int i' to 'int j', incrementing the value of j, and expecting i to change as well. (I understand that an integer is "immutable," but I take the position that however j comes to be incremented, it is an implementation detail, whether the processor chooses to twiddle some bits [mutate] or wholly overwrite a value. The difference is philosophical; Schrodinger's cat is doing our math.) As long as structs are used only as "complex values," and are designed in this spirit, things tend to go okay. (I've written up these thoughts in a more elaborate and drown out manner at snarfblam.com/words) If you're implementing an interface with a struct, that's a clear sign you're doing something wrong. @snarfblam It most certainly isn't. Implementing an interface that implies mutability is, but many values types perfectly reasonably implement things like: IEquatable<T>, IFormattable, IComparable<T> to name but a few. Interfaces do *not* imply boxing (take a look at the constrained opcode if you want to know why) but this is an implementation detail anyway since immutability means it doesn't matter if you take a copy (in boxing) anyway. actually I just read your blog and you have bigger problems. If you cannot differentiate between a variable and the value contained within the variable I think you need to have a serious think about your CS skills. compare: public class X { public readonly Point P2; public Point P2 public readonly int X1; public int X2 } and have a read of Eric's previous post: blogs.msdn.com/.../mutating-readonly-structs.aspx There are extreme tricks you can do: but this is still not altering the value, it's altering the variable (by aliasing to the same location) Fundamentally immutable value types are different from mutable ones because a whole class of bugs simply cannot happen, especially in the circumstances where you treat one as an object. You who blog post conflates treating values like object and the important distinction to remember which is very simple. Value types have copy value semantics, reference types have "copy the reference value semantics", Eric of course, explains it better: blogs.msdn.com/.../the-stack-is-an-implementation-detail.aspx @Shuggy: I dunno, he seems to have a pretty ok grasp: he's talking about integer values being immutable doesn't mean integer variables are. Also, wouldn't you like a way to call unexposed interface members without boxing? By the way, I beleive he was referring to treating values as objects philospically, not actual boxing, re: opcodes. As a C++ dev, I also can't agree with the /idea/ of mutable value types as evil. I think them having *exactly the same syntax* is bad, but I can't think of a good alternative which keeps focus on reference types. But simply changing the syntax coloring of value types solves that issue. (I also change the interface and delegate colors in case someone is doing something silly in a library). Perhaps allowing explicit references to values would help? I don' tknow. The real issue, as always, is whether the programmer understands the language - something that language design can never really ensure (though it certainly has a huge effect!).
http://blogs.msdn.com/b/ericlippert/archive/2011/03/14/to-box-or-not-to-box-that-is-the-question.aspx
CC-MAIN-2015-32
refinedweb
1,769
55.03
When I sat down and started working out how they would work together, I realised that having all three parts working together was next to impossible, simply for the reason that MD5 encryption is one way only. Once some data has been encrypted, it cannot then be decrypted, and since the trial period code needed to store a date to be checked when the application starts up, not only did it need to encrypt it, but also decrypt it when it came to checking the date. So, I started investigating two way encryption and how it works in VB.NET (Thanks for pointing me in the right direction PsychoCoder First of all, there are no decent tutorials or even explanations of what RSA Encryption is and does on the internet. I found a few which explained or gave code for different aspects of RSA, but nothing that put it all together. Hopefully, this tutorial will correct this. Secondly, as with the other tutorials I've written recently, once I figured out what the code here was doing, it all became rather easy. Ok, so on with the show. RSA Encryption was invented in 1977 by three guys by the names of Rivest, Shamir, and Adlman. This is where it gets it's name. It is recommended you use RSA (or some other type of asynchronous encryption) for encrypting small amounts of data, like passwords. First of all, what you need to do, as with the MD5 encryption, is import the necessary namespaces: 'Import the cryptography namespaces Imports System.Security.Cryptography Imports System.Text Now, on your form, add 4 TextBoxes, and 3 Buttons. Set the Multiline property for TextBoxes 2, 3 and 4 to True. Next we will need to declare some variables. Since these will be used throughout our code, I decided to put them just under Public Class Form1, like so: Public Class Form1 'Declare global variables Dim textbytes, encryptedtextbytes As Byte() Dim rsa As New RSACryptoServiceProvider Dim encoder As New UTF8Encoding After this is ready, double-click on Button1 in your IDE and paste the following code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim TexttoEncrypt As String = TextBox1.Text 'Use UTF8 to convert the text string into a byte array textbytes = encoder.GetBytes(TexttoEncrypt) 'encrypt the text encryptedtextbytes = rsa.Encrypt(textbytes, True) 'Convert the encrypted byte array into a Base64 string for display purposes TextBox2.Text = Convert.ToBase64String(encryptedtextbytes) End Sub As you can see, before we use RSA to encrypt the data, we need to convert it into Byte format with the UTF8 Encoder. So, in effect, we are actually encrypting the data twice. Once from String to Byte, and then from Byte, to another Byte. The final line converts the encrypted data from Byte format, to Base64 String format in order to display it in TextBox2. Once more, return to your IDE, but this time double click Button2. Here is your code: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'get the decrypted clear text byte array textbytes = rsa.Decrypt(encryptedtextbytes, True) 'convert the byte array to text using the same encoding format that was used for encryption TextBox1.Text = encoder.GetString(textbytes) End Sub As you can see here, to get the original data, you need to run the encrypted data through the RSA decryptor, then through the UTF8 Encoder again. When you test this application, after clicking Button1 to encrypt the data, delete the contents of TextBox1. When you click Button2, you should see the original text appear in TextBox1. Using RSA to encrypt and decrypt data is that simple. There is one more aspect of RSA that I will look at here, more as a point of interest than any useful application. The way RSA works is that it uses 2 'keys' to encrypt and decrypt the data. The first is a public key (and in this tutorial is used to encrypt the data) , and the second is a private key (to decrypt the data). For encrypting text files and the like, one user could encrypt it using the public key, send the encrypted data to another user, who then uses the private key to unlock the file and decrypt it. These keys are stored in Byte format, which means that if we want to take a look at them, they will need to be converted into a Base64 String, like so: 'Create an RSAParameters type Dim Parameters As New RSAParameters 'export the key and other algorithm values Parameters = rsa.ExportParameters(True) 'display the private key. Base64 encode the text to make display easier TextBox4.Text = Convert.ToBase64String(Parameters.D) 'display the public key. Base64 encode the text to make display easier TextBox3.Text = Convert.ToBase64String(Parameters.Modulus) Well, that's about all I've been able to discover about RSA Encryption, but hopefully it will be enough for you to work out how it works and how you can manipulate it to do what you want with it. If you have any questions about it, or comments, please post them here, and I will look into it for you. Happy coding, Bort
http://www.dreamincode.net/forums/topic/67705-rsa-encryption-in-vbnet/
CC-MAIN-2017-26
refinedweb
869
62.78
Manning's Countdown to 2014 . Use discount code crdotd14 all month for 50% off every deal. A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics Register / Login JavaRanch » Java Forums » Java » Servlets Author Can I pick your brains on globally accessing XML resources? Chris Corbyn Ranch Hand Joined: Jan 14, 2007 Posts: 114 posted Sep 09, 2007 05:17:00 0 In my servlet/JSP app I have a handful of XML files which all sit in /WEB-INF and get accessed from various different places (Filters, Controllers, Beans...). I started out using servletContext.getResourceAsStream() and then using DocumentBuilder to create a new Document object. The problem with that was that I was: a) Needing to pass ServletContext around all components which need to read XML files b) Creating multiple instances of the same Document needlessly. So with that in mind I set about trying to create a singleton called DocumentFactory which contains ServletContext and a Map of already built Documents. Early on in the FrontController invoke: DocumentFactory.getInstance().init(servletContext). /* Creates and registers XML resources org.mayo.util; import javax.servlet.ServletContext; import java.util.Map; import java.util.HashMap; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; /** * Prevents the overhead of repeatedly opening the same document in XML format * by registering created documents for global access. * @author Chris Corbyn <chris@w3style.co.uk> */ final public class DocumentFactory { /** This class as a singleton */ protected static DocumentFactory instance = null; /** The current ServletContext where resources can be found */ protected ServletContext context; /** The map which holds the registry internally */ protected Map<String,Document> map; /** * Constructor. */ protected DocumentFactory() { setMap(new HashMap<String,Document>()); } /** * Get the instance of this DocumentFactory. * @return DocumentFactory */ public synchronized static DocumentFactory getInstance() { if (instance == null) { instance = new DocumentFactory(); } return instance; } /** * Initialize the DocumentFactory with the ServletContext. * @param ServletContext context */ final public void init(ServletContext context) { this.setContext(context); } /** * Set the Map which holds the registry. * @param Map<String,Document> map */ protected void setMap(Map<String,Document> map) { this.map = map; } /** * Get the Map which holds the registry. * @return Map<String,Document> */ protected Map<String,Document> getMap() { return map; } /** * Set the ServletContext. * @param ServletContext context */ protected void setContext(ServletContext context) { this.context = context; } /** * Get the ServletContext. * @return ServletContext */ public ServletContext getContext() { return context; } /** * Get or create Document from the provided resource path. * Null is returned if no resource exists at the given path. * @param String path * @return Document */ public Document getDocument(String path) { Document document = null; Map<String,Document> map = getMap(); if (!map.containsKey(path)) { InputStream is = getContext().getResourceAsStream(path); if (is == null) { return document; } try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); document = builder.newDocumentBuilder().parse(is); map.put(path, document); } catch (Exception e) { System.out.println( "Document building for path '" + path + "' failed. " + e); } } return map.get(path); } /** * Cleanup after this object is no longer needed. */ final public void destroy() { getMap().clear(); instance = null; } } This worked great when I was just working within my servlet . But just recently I tried using it in a JavaBean from a JSP file. It always returns NULL for any document that wasn't used previously. The only difference between trying to use it from a JSP/JavaBean and using it from the servlet is that RequestDispatcher.forward() has been called. I've pinned the problem down to this line: InputStream is = getContext().getResourceAsStream(path); if (is == null) { return document; } Is there a reason why servletContext (from the Servlet, before forward() was called) will not fetch resources *after* forward() has been called? Is that a more elegant way to do what I'm trying to do? Basically I just want a convenience class that can grab me a XML file from WEB-INF and can be accessed from anywhere within the current context. Thanks for the help if anybody actualy gets to the end of this thread Chris Corbyn Ranch Hand Joined: Jan 14, 2007 Posts: 114 posted Sep 09, 2007 05:53:00 0 EDIT | Scrap that. Confused [ September 09, 2007: Message edited by: Chris Corbyn ] Chris Corbyn Ranch Hand Joined: Jan 14, 2007 Posts: 114 posted Sep 09, 2007 07:04:00 0 Drum roll please..... <navigation> ... </naviagtion> That was the root of my problem. I've got fat fingers. Now suddenly I don't care if I have to put try/catch around every call to DocumentFactory.getDocument() because I'd rather know what the problem is than just having a null return value I agree. Here's the link: subject: Can I pick your brains on globally accessing XML resources? Similar Threads Get rid of line numbers Tomcat servlet-mapping bypass if real file requested problem to get values in hasmap in bean:write Problem while using Map in ActionForm JSF2.0 custom component development All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/364857/Servlets/java/pick-brains-globally-accessing-XML
CC-MAIN-2013-48
refinedweb
810
50.43
Hi,On Sun, Mar 19, 2000 at 02:20:56PM +1100, Rusty Russell wrote:> The sysctl internal interface is horrible: if you don't #if> CONFIG_SYSCTL everywhere (yuk), you get much bloat, and *worse*,> register_sysctl_table() always "fails".Yes. Returning a null table if you try to register one is obviously thecorrect thing to do: the caller can then avoid trying to dereference thetable if we aren't running with CONFIG_SYSCTL. > + /* NULL would mean failure. */> + return (struct ctl_table_header *)1;Eek, that looks _much_ worse! The caller has no idea that this isn't avalid pointer.--Stephen-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.rutgers.eduPlease read the FAQ at
https://lkml.org/lkml/2000/3/21/211
CC-MAIN-2015-48
refinedweb
120
64.61
How to sort next.js blog posts by date Recently, I added a new article to my blog and quickly realised the blog post list was sorted alphabetically. I wanted the blog posts with the most recent date at the top instead of having the post sorted alphabetically. In this article, I share how to sort your blog posts by the most recent date. Convert the date string to a date object To sort the blog post by date, we need to convert the date string variable to a Date Object. Every blog post has a date string included in the post’s Front Matter. Manually writing code that converts a date string to a Javascript Date object can be difficult and time-consuming, I used Luxon to simplify the process. Luxon is an npm library that simplifies working with dates and times in JavaScript. npm install Luxon Import it into the component file that renders your blog post list. /components/postList/postList.jsimport { dateTime } from 'Luxon' The dateTime.fromFormat() converts the date string to a Javascript Date Object. fromFormat() is a function that creates a DateTime from a text string( date string), and fmt(the format the string is expected to be in) parsers the input string using a date format we pass in as a second parameter. fromFormat() takes two arguments, a date string and a format string. DateTime.fromFormat('09-06-2022, 'm-d-yyyy') This will format the date string into a date object that looks like 06–09–2022. I fetch the date string variable from the date included in every blog post’s Front Matter. Example of the date string included in the Front Matter in the blog post markdown file. With this date format mm-dd-yyyy, the post list will be sorted by the most recent month => day => year. This way, the blog post with the most recent month, day, and year stays at the top of the post list. when I tested using the date format (dd-mm-yyyy), I did not get the desired result with the sort function. Order blog post by most recent date Now that the date string has been converted to a Javascript Date object, use the javascript built-in sort function to sort the blog posts in descending order. In the src folder, go to the component displaying your blog post list, create a variable sortBlogPostsByDatesort and assign the sort function code to the variable /components/postLists/postLists.js const sortBlogPostsByDate = posts.sort((a, b) => {const beforeDate = DateTime.fromFormat(a.frontmatter.date, 'm-d-yyyy')const afterDate = DateTime.fromFormat(b.frontmatter.date, 'm-d-yyyy')return afterDate - beforeDate}) The new Array data sortBlogPostsByDate contains the sorted blog posts with the most recent article displayed at the top of the list. Finally using a javascript map function, loop through the sorted post data to display the blog posts list on the dom. return (<div className="postlist">{posts && sortBlogPostsByDate.map((post) => { return ( <DivList key={post.slug}> <Link href={{ pathname: `/${post.slug}` }}> <PostTitle href={`/${post.slug}`}> {post.frontmatter.title} </PostTitle> </Link> <PostData> <PostTag>{post.frontmatter.tags}</PostTag> <PostDate className="post-date"> {post.frontmatter.date} </PostDate> </PostData> <PostText>{post.frontmatter.description}</PostText> </DivList> ) })} </div>) Your Blog post list should be sorted now, with the most recent post at the top of the list. Final Result! Articles you might find helpful Setup a Newsletter with Next.js and Mailchimp.
https://agirlcodes.medium.com/how-to-sort-next-js-blog-posts-by-date-1665b641842b
CC-MAIN-2022-33
refinedweb
569
65.73
This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python. First, we launch 4 IPython engines with ipcluster start -n 4 in a console. Then, we create a client that will act as a proxy to the IPython engines. The client automatically detects the running engines. from IPython.parallel import Client rc = Client() Let's check the number of running engines. rc.ids To run commands in parallel over the engines, we can use the %px magic or the %%px cell magic. %%px import os print("Process {0:d}.".format(os.getpid())) We can specify which engines to run the commands on using the --targets or -t option. %%px -t 1,2 # The os module has already been imported in the previous cell. print("Process {0:d}.".format(os.getpid())) By default, the %px magic executes commands in blocking mode: the cell returns when the commands have completed on all engines. It is possible to run non-blocking commands with the --noblock or -a option. In this case, the cell returns immediately, and the task's status and the results can be polled asynchronously from the IPython interactive session. %%px -a import time time.sleep(5) The previous command returned an ASyncResult instance that we can use to poll the task's status. print(_.elapsed, _.ready()) The %pxresult blocks until the task finishes. %pxresult print(_.elapsed, _.ready()) IPython provides convenient functions for most common use-cases, like a parallel map function. v = rc[:] res = v.map(lambda x: x*x, range(10)) print(res.get()) You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).
http://nbviewer.jupyter.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter05_hpc/09_ipyparallel.ipynb
CC-MAIN-2017-47
refinedweb
303
66.23
Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by Sebastian Raschka. All code examples are released under the MIT license. If you find this content useful, please consider supporting the work by buying a copy of the book. Other code examples and content are available on GitHub. The PDF and ebook versions of the book are available through Leanpub. %load_ext watermark %watermark -a 'Sebastian Raschka' -p numpy Sebastian Raschka numpy 1.12.1 This appendix offers a quick tour of the NumPy library for working with multi-dimensional arrays in Python. NumPy (short for Numerical Python) was created by Travis Oliphant in 2005, by merging Numarray into Numeric. Since then, the open source NumPy library has evolved into an essential library for scientific computing in Python and has become a building block of many other scientific libraries, such as SciPy, Scikit-learn, Pandas, and others. What makes NumPy so particularly attractive to the scientific community is that it provides a convenient Python interface for working with multi-dimensional array data structures efficiently; the NumPy array data structure is also called ndarray, which is short for n-dimensional array. In addition to being mostly implemented in C and using Python as a "glue language," the main reason why NumPy is so efficient for numerical computations is that NumPy arrays use contiguous blocks of memory that can be efficiently cached by the CPU. In contrast, Python lists are arrays of pointers to objects in random locations in memory, which cannot be easily cached and come with a more expensive memory-look-up. However, the computational efficiency and low-memory footprint come at a cost: NumPy arrays have a fixed size and are homogeneous, which means that all elements must have the same type. Homogenous ndarray objects have the advantage that NumPy can carry out operations using efficient C loops. Besides being more efficient for numerical computations than native Python code, NumPy can also be more elegant and readable due to vectorized operations and broadcasting, which are features that we will explore in this appendix. While this appendix should be sufficient to follow the code examples in this book if you are new to NumPy, there are many advanced NumPy topics that are beyond the scope of this book. If you are interested in a more in-depth coverage of NumPy, I selected a few resources that could be useful to you: NumPy is built around ndarrays objects, which are high-performance multi-dimensional array data structures. Intuitively, we can think of a one-dimensional NumPy array as a data structure to represent a vector of elements -- you may think of it as a fixed-size Python list where all elements share the same type. Similarly, we can think of a two-dimensional array as a data structure to represent a matrix or a Python list of lists. While NumPy arrays can have up to 32 dimensions if it was compiled without alterations to the source code, we will focus on lower-dimensional arrays for the purpose of illustration in this introduction. Now, let us get started with NumPy by calling the array function to create a two-dimensional NumPy array, consisting of two rows and three columns, from a list of lists: import numpy as np lst = [[1, 2, 3], [4, 5, 6]] ary1d = np.array(lst) ary1d array([[1, 2, 3], [4, 5, 6]]) By default, NumPy infers the type of the array upon construction. Since we passed Python integers to the array, the ndarray object ary1d should be of type int64 on a 64-bit machine, which we can confirm by accessing the dtype attribute: ary1d.dtype dtype('int64') If we want to construct NumPy arrays of different types, we can pass an argument to the dtype parameter of the array function, for example np.int32 to create 32-bit arrays. For a full list of supported data types, please refer to the official NumPy documentation. Once an array has been constructed, we can downcast or recast its type via the astype method as shown in the following example: float32_ary = ary1d.astype(np.float32) float32_ary array([[ 1., 2., 3.], [ 4., 5., 6.]], dtype=float32) float32_ary.dtype dtype('float32') In the following sections we will cover many more aspects of NumPy arrays; however, to conclude this basic introduction to the ndarray object, let us take a look at some of its handy attributes. For instance, the itemsize attribute returns the size of a single array element in bytes: ary2d = np.array([[1, 2, 3], [4, 5, 6]], dtype='int64') ary2d.itemsize 8. (Note that 'int64' is just a shorthand for np.int64.) To return the number of elements in an array, we can use the size attribute, as shown below: ary2d.size 6 And the number of dimensions of our array (Intuitively, you may think of dimensions as the rank of a tensor) can be obtained via the ndim attribute: ary2d.ndim 2 If we are interested in the number of elements along each array dimension (in the context of NumPy arrays, we may also refer to them as axes), we can access the shape attribute as shown below: ary2d.shape (2, 3) The shape is always a tuple; in the code example above, the two-dimensional ary object has two rows and three columns, (2, 3), if we think of it as a matrix representation. Similarly, the shape of the one-dimensional array only contains a single value: np.array([1, 2, 3]).shape (3,) Instead of passing lists or tuples to the array function, we can also provide a single float or integer, which will construct a zero-dimensional array (for instance, a representation of a scalar): scalar = np.array(5) scalar array(5) scalar.ndim 0 scalar.shape () In the previous section, we used the array function to construct NumPy arrays from Python objects that are sequences or nested sequences -- lists, tuples, nested lists, iterables, and so forth. While array is often our go-to function for creating ndarray objects, NumPy implements a variety of functions for constructing arrays that may come in handy in different contexts. In this section, we will take a quick peek at those that we use most commonly -- you can find a more comprehensive list in the official documentation. The array function works with most iterables in Python, including lists, tuples, and range objects; however, array does not support generator expression. If we want parse generators directly, however, we can use the fromiter function as demonstrated below: def generator(): for i in range(10): if i % 2: yield i gen = generator() np.fromiter(gen, dtype=int) array([1, 3, 5, 7, 9]) # using 'comprehensions' the following # generator expression is equivalent to # the `generator` above generator_expression = (i for i in range(10) if i % 2) np.fromiter(generator_expression, dtype=int) array([1, 3, 5, 7, 9]) Next, we will take at two functions that let us create ndarrays of consisting of either ones and zeros by only specifying the elements along each axes (here: three rows and three columns): np.ones((3, 3)) array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) np.zeros((3, 3)) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) Creating arrays of ones or zeros can also be useful as placeholder arrays, in cases where we do not want to use the initial values for computations but want to fill it with other values right away. If we do not need the initial values (for instance, '0.' or '1.'), there is also numpy.empty, which follows the same syntax as numpy.ones and np.zeros. However, instead of filling the array with a particular value, the empty function creates the array with non-sensical values from memory. We can think of zeros as a function that creates the array via empty and then sets all its values to 0. -- in practice, a difference in speed is not noticeable, though. NumPy also comes with functions to create identity matrices and diagonal matrices as ndarrays that can be useful in the context of linear algebra -- a topic that we will explore later in this appendix. np.eye(3) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) np.diag((3, 3, 3)) array([[3, 0, 0], [0, 3, 0], [0, 0, 3]]) Lastly, I want to mention two very useful functions for creating sequences of numbers within a specified range, namely, arange and linspace. NumPy's arange function follows the same syntax as Python's range objects: If two arguments are provided, the first argument represents the start value and the second value defines the stop value of a half-open interval: np.arange(4., 10.) array([ 4., 5., 6., 7., 8., 9.]) Notice that arange also performs type inference similar to the array function. If we only provide a single function argument, the range object treats this number as the endpoint of the interval and starts at 0: np.arange(5) array([0, 1, 2, 3, 4]) Similar to Python's range, a third argument can be provided to define the step (the default step size is 1). For example, we can obtain an array of all uneven values between one and ten as follows: np.arange(1., 11., 2) array([ 1., 3., 5., 7., 9.]) The linspace function is especially useful if we want to create a particular number of evenly spaced values in a specified half-open interval: np.linspace(0., 1., num=5) array([ 0. , 0.25, 0.5 , 0.75, 1. ]) In this section, we will go over the basics of retrieving NumPy array elements via different indexing methods. Simple NumPy indexing and slicing works similar to Python lists, which we will demonstrate in the following code snippet, where we retrieve the first element of a one-dimensional array: ary = np.array([1, 2, 3]) ary[0] 1 Also, the same Python semantics apply to slicing operations. The following example shows how to fetch the first two elements in ary: ary[:2] # equivalent to ary[0:2] array([1, 2]) If we work with arrays that have more than one dimension or axis, we separate our indexing or slicing operations by commas as shown in the series of examples below: ary = np.array([[1, 2, 3], [4, 5, 6]]) ary[0, 0] # upper left 1 ary[-1, -1] # lower right 6 ary[0, 1] # first row, second column 2 ary[0] # entire first row array([1, 2, 3]) ary[:, 0] # entire first column array([1, 4]) ary[:, :2] # first two columns array([[1, 2], [4, 5]]) ary[0, 0] 1 In the previous sections, you learned how to create NumPy arrays and how to access different elements in an array. It is about time that we introduce one of the core features of NumPy that makes working with ndarray so efficient and convenient: vectorization. While we typically use for-loops if we want to perform arithmetic operations on sequence-like objects, NumPy provides vectorized wrappers for performing element-wise operations implicitly via so-called ufuncs -- short for universal functions. As of this writing, there are more than 60 ufuncs available in NumPy; ufuncs are implemented in compiled C code and very fast and efficient compared to vanilla Python. In this section, we will take a look at the most commonly used ufuncs, and I recommend you to check out the official documentation for a complete list. To provide an example of a simple ufunc for element-wise addition, consider the following example, where we add a scalar (here: 1) to each element in a nested Python list: lst = [[1, 2, 3], [4, 5, 6]] for row_idx, row_val in enumerate(lst): for col_idx, col_val in enumerate(row_val): lst[row_idx][col_idx] += 1 lst [[2, 3, 4], [5, 6, 7]] This for-loop approach is very verbose, and we could achieve the same goal more elegantly using list comprehensions: lst = [[1, 2, 3], [4, 5, 6]] [[cell + 1 for cell in row] for row in lst] [[2, 3, 4], [5, 6, 7]] We can accomplish the same using NumPy's ufunc for element-wise scalar addition as shown below: ary = np.array([[1, 2, 3], [4, 5, 6]]) ary = np.add(ary, 1) ary array([[2, 3, 4], [5, 6, 7]]) The ufuncs for basic arithmetic operations are add, subtract, divide, multiply, and exp (exponential). However, NumPy uses operator overloading so that we can use mathematical operators ( +, -, /, *, and **) directly: ary + 1 array([[3, 4, 5], [6, 7, 8]]) ary**2 array([[ 4, 9, 16], [25, 36, 49]]) Above, we have seen examples of binary ufuncs, which are ufuncs that take two arguments as an input. In addition, NumPy implements several useful unary ufuncs, such as log (natural logarithm), log10 (base-10 logarithm), and sqrt (square root). Often, we want to compute the sum or product of array element along a given axis. For this purpose, we can use a ufunc's reduce operation. By default, reduce applies an operation along the first axis ( axis=0). In the case of a two-dimensional array, we can think of the first axis as the rows of a matrix. Thus, adding up elements along rows yields the column sums of that matrix as shown below: ary = np.array([[1, 2, 3], [4, 5, 6]]) np.add.reduce(ary) # column sumns array([5, 7, 9]) To compute the row sums of the array above, we can specify axis=1: np.add.reduce(ary, axis=1) # row sums array([ 6, 15]) While it can be more intuitive to use reduce as a more general operation, NumPy also provides shorthands for specific operations such as product and sum. For example, sum(axis=0) is equivalent to add.reduce: ary.sum(axis=0) # column sums array([5, 7, 9]) As a word of caution, keep in mind that product and sum both compute the product or sum of the entire array if we do not specify an axis: ary.sum() 21 Other useful unary ufuncs are: A topic we glanced over in the previous section is broadcasting. Broadcasting allows us to perform vectorized operations between two arrays even if their dimensions do not match by creating implicit multidimensional grids. You already learned about ufuncs in the previous section where we performed element-wise addition between a scalar and a multidimensional array, which is just one example of broadcasting. Naturally, we can also perform element-wise operations between arrays of equal dimensions: ary1 = np.array([1, 2, 3]) ary2 = np.array([4, 5, 6]) ary1 + ary2 array([5, 7, 9]) In contrast to what we are used from linear algebra, we can also add arrays of different shapes. In the example above, we will add a one-dimensional to a two-dimensional array, where NumPy creates an implicit multidimensional grid from the one-dimensional array ary1: ary3 = np.array([[4, 5, 6], [7, 8, 9]]) ary3 + ary1 # similarly, ary1 + ary3 array([[ 5, 7, 9], [ 8, 10, 12]]) Keep in mind though that the number of elements along the explicit axes and the implicit grid have to match so that NumPy can perform a sensical operation. For instance, the following example should raise a ValueError, because NumPy attempts to add the elements from the first axis of the left array (2 elements) to the first axis of the right array (3 elements): try: ary3 + np.array([1, 2]) except ValueError as e: print('ValueError:', e) ValueError: operands could not be broadcast together with shapes (2,3) (2,) So, if we want to add the 2-element array to the columns in ary3, the 2-element array must have two elements along its first axis as well: ary3 + np.array([[1], [2]]) array([[ 5, 6, 7], [ 9, 10, 11]]) np.array([[1], [2]]) + ary3 array([[ 5, 6, 7], [ 9, 10, 11]]) In the previous sections, we have used basic indexing and slicing routines. It is important to note that basic integer-based indexing and slicing create so-called views of NumPy arrays in memory. Working with views can be highly desirable since it avoids making unnecessary copies of arrays to save memory resources. To illustrate the concept of memory views, let us walk through a simple example where we access the first row in an array, assign it to a variable, and modify that variable: ary = np.array([[1, 2, 3], [4, 5, 6]]) first_row = ary[0] first_row += 99 ary array([[100, 101, 102], [ 4, 5, 6]]) As we can see in the example above, changing the value of first_row also affected the original array. The reason for this is that ary[0] created a view of the first row in ary, and its elements were then incremented by 99. The same concept applies to slicing operations: ary = np.array([[1, 2, 3], [4, 5, 6]]) first_row = ary[:1] first_row += 99 ary array([[100, 101, 102], [ 4, 5, 6]]) ary = np.array([[1, 2, 3], [4, 5, 6]]) center_col = ary[:, 1] center_col += 99 ary array([[ 1, 101, 3], [ 4, 104, 6]]) If we are working with NumPy arrays, it is always important to be aware that slicing creates views -- sometimes it is desirable since it can speed up our code by avoiding to create unnecessary copies in memory. However, in certain scenarios we want force a copy of an array; we can do this via the copy method as shown below: second_row = ary[1].copy() second_row += 99 ary array([[ 1, 101, 3], [ 4, 104, 6]]) One way to check if two arrays might share memory is to use the may_share_memory function from NumPy. However, be aware that it uses a heuristic and can return false negatives or false positives. The code snippets shows an example of may_share_memory applied to the view ( first_row) and copy ( second_row) of the array elements from ary: ary = np.array([[1, 2, 3], [4, 5, 6]]) first_row = ary[:1] first_row += 99 ary array([[100, 101, 102], [ 4, 5, 6]]) np.may_share_memory(first_row, ary) True second_row = ary[1].copy() second_row += 99 ary array([[100, 101, 102], [ 4, 5, 6]]) np.may_share_memory(second_row, ary) False In addition to basic single-integer indexing and slicing operations, NumPy supports advanced indexing routines called fancy indexing. Via fancy indexing, we can use tuple or list objects of non-contiguous integer indices to return desired array elements. Since fancy indexing can be performed with non-contiguous sequences, it cannot return a view -- a contiguous slice from memory. Thus, fancy indexing always returns a copy of an array -- it is important to keep that in mind. The following code snippets show some fancy indexing examples: ary = np.array([[1, 2, 3], [4, 5, 6]]) ary[:, [0, 2]] # first and and last column array([[1, 3], [4, 6]]) this_is_a_copy = ary[:, [0, 2]] this_is_a_copy += 99 ary array([[1, 2, 3], [4, 5, 6]]) ary[:, [2, 0]] # first and and last column array([[3, 1], [6, 4]]) Finally, we can also use Boolean masks for indexing -- that is, arrays of True and False values. Consider the following example, where we return all values in the array that are greater than 3: ary = np.array([[1, 2, 3], [4, 5, 6]]) greater3_mask = ary > 3 greater3_mask array([[False, False, False], [ True, True, True]], dtype=bool) Using these masks, we can select elements given our desired criteria: ary[greater3_mask] array([4, 5, 6]) We can also chain different selection criteria using the logical and operator '&' or the logical or operator '|'. The example below demonstrates how we can select array elements that are greater than 3 and divisible by 2: ary[(ary > 3) & (ary % 2 == 0)] array([4, 6]) Note that indexing using Boolean arrays is also considered "fancy indexing" and thus returns a copy of the array. In machine learning and deep learning, we often have to generate arrays of random numbers -- for example, the initial values of our model parameters before optimization. NumPy has a random subpackage to create random numbers and samples from a variety of distributions conveniently. Again, I encourage you to browse through the more comprehensive numpy.random documentation for a more comprehensive list of functions for random sampling. To provide a brief overview of the pseudo-random number generators that we will use most commonly, let's start with drawing a random sample from a uniform distribution: np.random.seed(123) np.random.rand(3) array([ 0.69646919, 0.28613933, 0.22685145]) In the code snippet above, we first seeded NumPy's random number generator. Then, we drew three random samples from a uniform distribution via random.rand in the half-open interval [0, 1). I highly recommend the seeding step in practical applications as well as in research projects, since it ensures that our results are reproducible. If we run our code sequentially -- for example, if we execute a Python script -- it should be sufficient to seed the random number generator only once at the beginning to enforce reproducible outcomes between different runs. However, it is often useful to create separate RandomState objects for various parts of our code, so that we can test methods of functions reliably in unit tests. Working with multiple, separate RandomState objects can also be useful if we run our code in non-sequential order -- for example if we are experimenting with our code in interactive sessions or Jupyter Notebook environments. The example below shows how we can use a RandomState object to create the same results that we obtained via np.random.rand in the previous code snippet: rng1 = np.random.RandomState(seed=123) rng1.rand(3) array([ 0.69646919, 0.28613933, 0.22685145]) Another useful function that we will often use in practice is randn, which returns a random sample of floats from a standard normal distribution $N(\mu, \sigma^2)$, where the mean, ($\mu$) is zero and unit variance ($\sigma = 1$). The example below creates a two-dimensional array of such z-scores: rng2 = np.random.RandomState(seed=123) z_scores = rng2.randn(100, 2) NumPy's random functions rand and randn take an arbitrary number of integer arguments, where each integer argument specifies the number of elements along a given axis -- the z_scores array should now refer to an array of 100 rows and two columns. Let us now visualize how our random sample looks like using Matplotlib: %matplotlib inline import matplotlib.pyplot as plt plt.scatter(z_scores[:, 0], z_scores[:, 1]) #plt.savefig('images/numpy-intro/random_1.png', dpi=600) plt.show() If we want to draw a random sample from a non-standard normal distribution, we can simply add a scalar value to the array elements to shift the mean of the sample, and we can multiply the sample by a scalar to change its standard deviation. The following code snippet will change the properties of our random sample as if it has been drawn from a Normal distribution $N(5, 4)$: rng3 = np.random.RandomState(seed=123) scores = 2. * rng3.randn(100, 2) + 5. plt.scatter(scores[:, 0], scores[:, 1]) #plt.savefig('images/numpy-intro/random_2.png', dpi=600) plt.show() Note that in the example above, we multiplied the z-scores by a standard deviation of 2 -- the standard deviation of a sample is the square root of the variance $\sigma^2$. Also, notice that all elements in the array were updated when we multiplied it by a scalar or added a scalar. In the next section, we will discuss NumPy's capabilities regarding such element-wise operations in more detail. In practice, we often run into situations where existing arrays do not have the right shape to perform certain computations. As you might remember from the beginning of this appendix, the size of NumPy arrays is fixed. Fortunately, this does not mean that we have to create new arrays and copy values from the old array to the new one if we want arrays of different shapes -- the size is fixed, but the shape is not. NumPy provides a reshape methods that allow us to obtain a view of an array with a different shape. For example, we can reshape a one-dimensional array into a two-dimensional one using reshape as follows: ary1d = np.array([1, 2, 3, 4, 5, 6]) ary2d_view = ary1d.reshape(2, 3) ary2d_view array([[1, 2, 3], [4, 5, 6]]) np.may_share_memory(ary2d_view, ary1d) True While we need to specify the desired elements along each axis, we need to make sure that the reshaped array has the same number of elements as the original one. However, we do not need to specify the number elements in each axis; NumPy is smart enough to figure out how many elements to put along an axis if only one axis is unspecified (by using the placeholder -1): ary1d.reshape(2, -1) array([[1, 2, 3], [4, 5, 6]]) ary1d.reshape(-1, 2) array([[1, 2], [3, 4], [5, 6]]) We can, of course, also use reshape to flatten an array: ary2d = np.array([[1, 2, 3], [4, 5, 6]]) ary2d.reshape(-1) array([1, 2, 3, 4, 5, 6]) Note that NumPy also has a shorthand for that called ravel: ary2d.ravel() array([1, 2, 3, 4, 5, 6]) A function related to ravel is flatten. In contrast to ravel, flatten returns a copy, though: np.may_share_memory(ary2d.flatten(), ary2d) False np.may_share_memory(ary2d.ravel(), ary2d) True Sometimes, we are interested in merging different arrays. Unfortunately, there is no efficient way to do this without creating a new array, since NumPy arrays have a fixed size. While combining arrays should be avoided if possible -- for reasons of computational efficiency -- it is sometimes necessary. To combine two or more array objects, we can use NumPy's concatenate function as shown in the following examples: ary = np.array([1, 2, 3]) # stack along the first axis np.concatenate((ary, ary)) array([1, 2, 3, 1, 2, 3]) ary = np.array([[1, 2, 3]]) # stack along the first axis (here: rows) np.concatenate((ary, ary), axis=0) array([[1, 2, 3], [1, 2, 3]]) # stack along the second axis (here: column) np.concatenate((ary, ary), axis=1) array([[1, 2, 3, 1, 2, 3]]) In the previous section, we already briefly introduced the concept of Boolean masks in NumPy. Boolean masks are bool-type arrays (storing True and False values) that have the same shape as a certain target array. For example, consider the following 4-element array below. Using comparison operators (such as <, >, <=, and >=), we can create a Boolean mask of that array which consists of True and False elements depending on whether a condition is met in the target array (here: ary): ary = np.array([1, 2, 3, 4]) mask = ary > 2 mask array([False, False, True, True], dtype=bool) One we created such a Boolean mask, we can use it to select certain entries from the target array -- those entries that match the condition upon which the mask was created): ary[mask] array([3, 4]) Beyond the selection of elements from an array, Boolean masks can also come in handy when we want to count how many elements in an array meet a certain condition: mask array([False, False, True, True], dtype=bool) mask.sum() 2 If we are interested in the index positions of array elements that meet a certain condition, we can use the nonzero() method on a mask, as follows: mask.nonzero() (array([2, 3]),) Note that selecting index elements in the way suggested above is a two-step process of creating a mask and then applying the non-zero method: (ary > 2).nonzero() (array([2, 3]),) An alternative approach to the index selection by a condition is using the np.where method: np.where(ary > 2) (array([2, 3]),) While the example above demonstrate the use of np.where with only one input argument provided, np.where is especially useful in the context of re-assigning values to array elements that meet a certain condition. np.where(ary > 2, 1, 0) array([0, 0, 1, 1]) Notice that we use the np.where function with three arguments: np.where(condition, x, y), which is interpreted as When condition is True, yield x, otherwise yield y. Or more concretely, what we have done in the previous example is to assign 1 to all elements greater than 2, and 0 to all other elements. Of course, this can also be achieved by using Boolean masks "manually:" ary = np.array([1, 2, 3, 4]) mask = ary > 2 ary[mask] = 1 ary[~mask] = 0 ary array([0, 0, 1, 1]) The ~ operator in the example above is one of the logical operators in NumPy: &or np.bitwise_and |or np.bitwise_or ^or np.bitwise_xor ~or np.bitwise_not These logical operators allow us to chain an arbitrary number of conditions to create even more "complex" Boolean masks. For example, using the "Or" operator, we can select all elements that are greater than 3 or smaller than 2 as follows: ary = np.array([1, 2, 3, 4]) (ary > 3) | (ary < 2) array([ True, False, False, True], dtype=bool) And, for example, to negate the condition, we can use the ~ operator: ~((ary > 3) | (ary < 2)) array([False, True, True, False], dtype=bool) Most of the operations in machine learning and deep learning are based on concepts from linear algebra. In this section, we will take a look how to perform basic linear algebra operations using NumPy arrays. I want to mention that there is also a special matrix type in NumPy. NumPy matrix objects are analogous to NumPy arrays but are restricted to two dimensions. Also, matrices define certain operations differently than arrays; for instance, the * operator performs matrix multiplication instead of element-wise multiplication. However, NumPy matrix is less popular in the science community compared to the more general array data structure. Since we are also going to work with arrays that have more than two dimensions (for example, when we are working with convolutional neural networks), we will not use NumPy matrix data structures in this book. Intuitively, we can think of one-dimensional NumPy arrays as data structures that represent row vectors: row_vector = np.array([1, 2, 3]) row_vector array([1, 2, 3]) Similarly, we can use two-dimensional arrays to create column vectors: column_vector = np.array([[1, 2, 3]]).reshape(-1, 1) column_vector array([[1], [2], [3]]) Instead of reshaping a one-dimensional array into a two-dimensional one, we can simply add a new axis as shown below: row_vector[:, np.newaxis] array([[1], [2], [3]]) Note that in this context, np.newaxis behaves like None: row_vector[:, None] array([[1], [2], [3]]) All three approaches listed above, using reshape(-1, 1), np.newaxis, or None yield the same results -- all three approaches create views not copies of the row_vector array. As we remember from the Linear Algebra appendix, we can think of a column vector as a matrix consisting only of one column. To perform matrix multiplication between matrices, we learned that number of columns of the left matrix must match the number of rows of the matrix to the right. In NumPy, we can perform matrix multiplication via the matmul function: matrix = np.array([[1, 2, 3], [4, 5, 6]]) np.matmul(matrix, column_vector) array([[14], [32]]) However, if we are working with matrices and vectors, NumPy can be quite forgiving if the dimensions of matrices and one-dimensional arrays do not match exactly -- thanks to broadcasting. The following example yields the same result as the matrix-column vector multiplication, except that it returns a one-dimensional array instead of a two-dimensional one: np.matmul(matrix, row_vector) array([14, 32]) Similarly, we can compute the dot-product between two vectors (here: the vector norm) np.matmul(row_vector, row_vector) 14 np.dot(row_vector, row_vector) 14 np.dot(matrix, row_vector) array([14, 32]) np.dot(matrix, column_vector) array([[14], [32]]) Similar to the examples above we can use matmul or dot to multiply two matrices (here: two-dimensional arrays). In this context, NumPy arrays have a handy transpose method to transpose matrices if necessary: matrix = np.array([[1, 2, 3], [4, 5, 6]]) matrix.transpose() array([[1, 4], [2, 5], [3, 6]]) np.matmul(matrix, matrix.transpose()) array([[14, 32], [32, 77]]) matrix.T array([[1, 4], [2, 5], [3, 6]]) While this section demonstrates some of the basic linear algebra operations carried out on NumPy arrays that we use in practice, you can find an additional function in the documentation of NumPy's submodule for linear algebra: numpy.linalg. If you want to perform a particular linear algebra routine that is not implemented in NumPy, it is also worth consulting the scipy.linalg documentation -- SciPy is a library for scientific computing built on top of NumPy. Appendix B: Algebra Basics introduced the basics behind set theory, which are visually summarized in the following figure, and NumPy implements several functions that allow us to work with sets efficiently so that we are not restricted to Python's built-in functions (and converting back and forth between Python sets and NumPy arrays). Remember that a set is essentially a collection of unique elements. Given an array, we can generate such a "set" using the np.unique function: ary = np.array([1, 1, 2, 3, 1, 5]) ary_set = np.unique(ary) ary_set array([1, 2, 3, 5]) However, we have to keep in mind that unlike Python sets, the output of np.unique is a regular NumPy array, not specialized data structure that does not allow for duplicate entries. The set operations for example, set union ( np.union1d), set difference ( np.setdiff1d), or set intersection ( np.intersect1d) would return the same results whether array elements are unique or not. However, setting their optional assume_unique argument can speed up the computation. ary1 = np.array([1, 2, 3]) ary2 = np.array([3, 4, 5, 6]) np.intersect1d(ary1, ary2, assume_unique=True) array([3]) np.setdiff1d(ary1, ary2, assume_unique=True) array([1, 2]) np.union1d(ary1, ary2) # does not have assume_unique array([1, 2, 3, 4, 5, 6]) Note that NumPy does not have a function for the symmetric set difference, but it can be readily computed by composition: np.union1d(np.setdiff1d(ary1, ary2, assume_unique=True), np.setdiff1d(ary2, ary1, assume_unique=True)) array([1, 2, 4, 5, 6]) In the context of computer science, serialization is a term that refers to storing data or objects in a different format that can be used for reconstruction later. For example, in Python, we can use the pickle library to write Python objects as bytecode (or binary code) to a local drive. NumPy offers a data storage format (NPY) that is especially well-suited (compared to regular pickle files) for storing array data. There are three different functions that can be used for this purpose: np.save np.savez np.savez_compressed Starting with np.save, this function saves a single array to a so-called .npy file: ary1 = np.array([1, 2, 3]) np.save('ary-data.npy', ary1) np.load('ary-data.npy') array([1, 2, 3]) Suffice it to say, the the np.load a universal function for loading data that has been serialized via NumPy back into the current Python session. The np.savez is slightly more powerful than the np.save function as it generates an archive consisting of 1 or more .npy files and thus allows us to save multiple arrays at once. np.savez('ary-data.npz', ary1, ary2) However, note that if the np.load function will wrap the arrays as a NpzFile object from which the individual arrays can be accessed via keys like values in a Python dictionary: d = np.load('ary-data.npz') d.keys() ['arr_0', 'arr_1'] d['arr_0'] array([1, 2, 3]) As demonstrated above, the arrays are numerated in ascending order with an arr_ prefix ( 'arr_0', 'arr_1', etc.). To use a custom naming convention, we can simply provide keyword arguments: kwargs = {'ary1':ary1, 'ary2':ary2} np.savez('ary-data.npz', **kwargs) np.load('ary-data.npz') d = np.load('ary-data.npz') d['ary1'] array([1, 2, 3]) We have covered a lot of material in this appendix. If you are new to NumPy, its functionality can be quite overwhelming at first. Good news is that we do not need to master all the different concepts at once before we can get started using NumPy in our applications. In my opinion, the most useful yet most difficult concepts are NumPy's broadcasting rules and to distinguish between views and copies of arrays. However, with some experimentation, you can quickly get the hang of it and be able to write elegant and efficient NumPy code.
http://nbviewer.jupyter.org/github/rasbt/deep-learning-book/blob/master/code/appendix_f_numpy-intro/appendix_f_numpy-intro.ipynb
CC-MAIN-2018-26
refinedweb
6,108
51.48
XACML Authorization: Decision 'Indeterminate' priya jayaraj Greenhorn Posts: 5 0 We have a Web Service management tool which does Authentication and Authorization for all the incoming WebService request. Authorization is based on the rules that are configured for the appropriate service. We also have XPath specification as part of rule configuration. We have a rule configured as mentioned below TestService authoized to the user of the particular group (TestGroup1) and XPath (\\com9:source[@VendorId='AB']) When we tried accessing the Test Service and received the following response despite giving a valid user (TestUser1 belonging to TestGroup1) and the proper XML element [com9:source VendorId='AB'] in the request. <Response> <Result ResourceID=""> <Decision>Indeterminate</Decision> <Status> <StatusCode Value="urn <StatusMessage>error in XPath: Prefix must resolve to a namespace: com7</StatusMessage> </Status> </Result> </Response> Xacml Authorization is done with the help of sunxacml.jar. API 'PDP.evaluate(RequestCtx)' is invoked and We got the above mentioned response. We came to know that the Decision 'Indeterminate' comes if any exception occurs during authorization. It would be very helpful if we get to know the rootcause of the decision 'Indeterminate' in the above mentioned scenario and the possible scenarios to get 'Indeterminate' decision. Thanks in advance, With regards, Priya. priya jayaraj Greenhorn Posts: 5 priya jayaraj Greenhorn Posts: 5 0 We have a uri that bound to the namespace say com9. Also, we could see in the log that the request element 'VendorId' prefixed with the required namespace com9 com9:source VendorId='AB', just before it is sent for xacml authorization. So we are stuck on what would be the cause and how and where the prefix is lost. The issue is not reproducible consistently as well (when we restart application servers). It would be great if we get any clues on how to proceed further up with the investigation. Thanks in advance, Priya J Thanks in advance, Priya J
http://www.coderanch.com/t/538500/XML/XACML-Authorization-Decision-Indeterminate
CC-MAIN-2016-07
refinedweb
317
51.07
Hi, I have been looking at a few tasks I want to do using a MySQL DB and Python. Therefor I'm spending some time looking at the MySQLdb module for Python and how I can use it. I've worked out a few bits but I want to be able to use user input to enter data instead of having to edit the python script values each time I found a few alternatives on here and have a single very simple version working: import MySQLdb db = MySQLdb.connect("localhost","root","reverend","TESTDB" ) cursor = db.cursor() staff_first = raw_input("What is your first name? ") #staff_last = raw_input("What is your second name? ") sql="""INSERT INTO STAFF(FIRST_NAME) VALUES('%s')""" % staff_first cursor.execute(sql) db.commit() db.close() This is working so far as it is getting the first name in - but I can't seem to be able to edit the script to allow each input to work (I have commented out staff_last for now - but I would like that information to be requested at some point). Can someone give me an example of how I can do this - altering the script to allow more that 1 input per line (even if it's just a hint to get me thinking)? I tried a few different versions altering the values and the field names etc but I keep getting errors when run. I'm still a bit of a beginner when it comes to programming - and so it's taking a while to sift through and understand some of the errors I am getting. Thanks!
https://www.daniweb.com/programming/software-development/threads/430838/user-input-mysqldb-and-python
CC-MAIN-2018-39
refinedweb
263
66.07
20. Functions By Bernd Klein. Last modified: 16 Aug 2021. Syntax The concept of a function is one of the most important in mathematics. A common usage of functions in computer languages is to implement mathematical functions. Such a function is computing one or more results, which are entirely determined by the parameters passed to it. This is mathematics, but we are talking about programming and Python. So what is a function in programming? In the most general sense, a function is a structuring element in programming languages to group a bunch of statements so they can be utilized in a program more than once. The only way to accomplish this without functions would be to reuse code by copying it and adapting it to different contexts, which would be a bad idea. Redundant code - repeating code in this case - should be avoided! Using functions usually enhances the comprehensibility and quality of a program. It also lowers the cost for development and maintenance of the software. Functions are known under various names in programming languages, e.g. as subroutines, routines, procedures, methods, or subprograms. Motivating Example of Functions Let us look at the following code: print("Program starts") print("Hi Peter") print("Nice to see you again!") print("Enjoy our video!") # some lines of codes the_answer = 42 print("Hi Sarah") print("Nice to see you again!") print("Enjoy our video!") width, length = 3, 4 area = width * length print("Hi Dominque") print("Nice to see you again!") print("Enjoy our video!") OUTPUT: Program starts Hi Peter Nice to see you again! Enjoy our video! Hi Sarah Nice to see you again! Enjoy our video! Hi Dominque Nice to see you again! Enjoy our video! Let us have a closer look at the code above: You can see in the code that we are greeting three persons. Every time we use three print calls which are nearly the same. Just the name is different. This is what we call redundant code. We are repeating the code the times. This shouldn't be the case. This is the point where functions can and should be used in Python. We could use wildcards in the code instead of names. In the following diagram we use a piece of the puzzle. We only write the code once and replace the puzzle piece with the corresponding name: Of course, this was no correct Python code. We show how to do this in Python in the following section. Functions in Python The following code uses a function with the name greet. The previous puzzle piece is now a parameter with the name "name": def greet(name): print("Hi " + name) print("Nice to see you again!") print("Enjoy our video!") print("Program starts") greet("Peter") # some lines of codes the_answer = 42 greet("Sarah") width, length = 3, 4 area = width * length greet("Dominque") OUTPUT: Program starts Hi Peter Nice to see you again! Enjoy our video! Hi Sarah Nice to see you again! Enjoy our video! Hi Dominque Nice to see you again! Enjoy our video! We used a function in the previous code. We saw that a function definition starts with the def keyword. The general syntax looks like this: def function-name(Parameter list): statements, i.e. the function body The parameter list consists of none or more parameters. Parameters are called arguments, if the function is called. The function body consists of indented statements. The function body gets executed every time the function is called. We demonstrate this in the following picture: The code from the picture can be seen in the following: def f(x, y): z = 2 * (x + y) return z print("Program starts!") a = 3 res1 = f(a, 2+a) print("Result of function call:", res1) a = 4 b = 7 res2 = f(a, b) print("Result of function call:", res2) OUTPUT: Program starts! Result of function call: 16 Result of function call: 22 We call the function twice in the program. The function has two parameters, which are called x and y. This means that the function f is expecting two values, or I should say "two objects". Firstly, we call this function with f(a, 2+a). This means that a goes to x and the result of 2+a (5) 'goes to' the variable y. The mechanism for assigning arguments to parameters is called argument passing. When we reach the return statement, the object referenced by z will be return, which means that it will be assigned to the variable res1. After leaving the function f, the variable z and the parameters x and y will be deleted automatically. The references to the objects can be seen in the next diagram: The next Python code block contains an example of a function without a return statement. We use the pass statement inside of this function. pass is a null operation. This means that when it is executed, nothing happens. It is useful as a placeholder in situations when a statement is required syntactically, but no code needs to be executed: def doNothing(): pass A more useful function: def fahrenheit(T_in_celsius): """ returns the temperature in degrees Fahrenheit """ return (T_in_celsius * 9 / 5) + 32 for t in (22.6, 25.8, 27.3, 29.8): print(t, ": ", fahrenheit(t)) OUTPUT: 22.6 : 72.68 25.8 : 78.44 27.3 : 81.14 29.8 : 85.64 """ returns the temperature in degrees Fahrenheit """ is the so-called docstring. It is used by the help function: help(fahrenheit) OUTPUT: Help on function fahrenheit in module __main__: fahrenheit(T_in_celsius) returns the temperature in degrees Fahrenheit Our next example could be interesting for the calorie-conscious Python learners. We also had an exercise in the chapter Conditional Statements of our Python tutorial. We will create now a function version of the program. The body mass index (BMI) is a value derived from the mass (w) and height (l) of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed $BMI = {w \over {l ^ 2}}$ The weight is given in kg and the length in metres. def BMI(weight, height): """ calculates the BMI where weight is in kg and height in metres""" return weight / height**2 We like to write a function to evaluate the bmi values according to the following table: The following shows code which is directly calculating the bmi and the evaluation of the bmi, but it is not using functions: height = float(input("What is your height? ")) weight = float(input("What is your weight? ")) bmi = weight / height ** 2 print(bmi) if bmi < 15: print("Very severely underweight") elif bmi < 16: print("Severely underweight") elif bmi < 18.5: print("Underweight") elif bmi < 25: print("Normal (healthy weight)") elif bmi < 30: print("Overweight") elif bmi < 35: print("Obese Class I (Moderately obese)") elif bmi < 40: print("Obese Class II (Severely obese)") else: print("Obese Class III (Very severely obese)") OUTPUT: 23.69576446280992 Normal (healthy weight) Turn the previous code into proper functions and function calls. def BMI(weight, height): """ calculates the BMI where weight is in kg and height in metres""" return weight / height**2 def bmi_evaluate(bmi_value): if bmi_value < 15: result = "Very severely underweight" elif bmi_value < 16: result = "Severely underweight" elif bmi_value < 18.5: result = "Underweight" elif bmi_value < 25: result = "Normal (healthy weight)" elif bmi_value < 30: result = "Overweight" elif bmi_value < 35: result = "Obese Class I (Moderately obese)" elif bmi_value < 40: result = "Obese Class II (Severely obese)" else: result = "Obese Class III (Very severely obese)" return result Let us check these functions: height = float(input("What is your height? ")) weight = float(input("What is your weight? ")) res = BMI(weight, height) print(bmi_evaluate(res)) OUTPUT: Normal (healthy weight) Default arguments in Python When we define a Python function, we can set a default value to a parameter. If the function is called without the argument, this default value will be assigned to the parameter. This makes a parameter optional. To say it in other words: Default parameters are parameters, which don't have to be given, if the function is called. In this case, the default values are used. We will demonstrate the operating principle of default parameters with a simple example. The following function hello, - which isn't very useful, - greets a person. If no name is given, it will greet everybody: def hello(name="everybody"): """ Greets a person """ result = "Hello " + name + "!") hello("Peter") hello() OUTPUT: Hello Peter! Hello everybody! The Defaults Pitfall In the previous section we learned about default parameters. Default parameters are quite simple, but quite often programmers new to Python encounter a horrible and completely unexpected surprise. This surprise arises from the way Python treats the default arguments and the effects steming from mutable objects. Mutable objects are those which can be changed after creation. In Python, dictionaries are examples of mutable objects. Passing mutable lists or dictionaries as default arguments to a function can have unforeseen effects. Programmer who use lists or dictionaries as default arguments to a function, expect the program to create a new list or dictionary every time that the function is called. However, this is not what actually happens. Default values will not be created when a function is called. Default values are created exactly once, when the function is defined, i.e. at compile-time. Let us look at the following Python function "spammer" which is capable of creating a "bag" full of spam: def spammer(bag=[]): bag.append("spam") return bag Calling this function once without an argument, returns the expected result: spammer() OUTPUT: ['spam'] The surprise shows when we call the function again without an argument: spammer() OUTPUT: ['spam', 'spam'] Most programmers will have expected the same result as in the first call, i.e. ['spam'] To understand what is going on, you have to know what happens when the function is defined. The compiler creates an attribute __defaults__: def spammer(bag=[]): bag.append("spam") return bag spammer.__defaults__ OUTPUT: ([],) Whenever we will call the function, the parameter bag will be assigned to the list object referenced by spammer.__defaults__[0]: for i in range(5): print(spammer()) print("spammer.__defaults__", spammer.__defaults__) OUTPUT: ['spam'] ['spam', 'spam'] ['spam', 'spam', 'spam'] ['spam', 'spam', 'spam', 'spam'] ['spam', 'spam', 'spam', 'spam', 'spam'] spammer.__defaults__ (['spam', 'spam', 'spam', 'spam', 'spam'],) Now, you know and understand what is going on, but you may ask yourself how to overcome this problem. The solution consists in using the immutable value None as the default. This way, the function can set bag dynamically (at run-time) to an empty list: def spammer(bag=None): if bag is None: bag = [] bag.append("spam") return bag for i in range(5): print(spammer()) print("spammer.__defaults__", spammer.__defaults__) OUTPUT: ['spam'] ['spam'] ['spam'] ['spam'] ['spam'] spammer.__defaults__ (None,) Docstring The first statement in the body of a function is usually a string statement called a Docstring, which can be accessed with the function_name.__doc__. For example: def hello(name="everybody"): """ Greets a person """ print("Hello " + name + "!") print("The docstring of the function hello: " + hello.__doc__))) OUTPUT: 8 17 Keyword parameters can only be those, which are not used as positional arguments. We can see the benefit in the example. If we hadn't had keyword parameters, the second call to function would have needed all four arguments, even though the c argument needs just the default value: print(sumsub(42,15,0,10)) OUTPUT: 17 Return Values) OUTPUT: None) OUTPUT: None Otherwise the value of the expression following return will be returned. In the next example 9 will be printed: def return_sum(x, y): c = x + y return c res = return_sum(4, 5) print(res) OUTPUT: 9 Let's summarize this behavior: Function bodies can contain one or more return statements.. Returning Multiple Values A. That_interval(x): """ returns the largest fibonacci number smaller than x and the lowest fibonacci number higher than x""" if x < 0: return -1 old, new = 0, 1 while True: if new < x: old, new = new, old+new else: if new == x: new = old + new return (old, new) while True: x = int(input("Your number: ")) if x <= 0: break lub, sup = fib_interval(x) print("Largest Fibonacci Number smaller than x: " + str(lub)) print("Smallest Fibonacci Number larger than x: " + str(sup)) OUTPUT: Largest Fibonacci Number smaller than x: 5 Smallest Fibonacci Number larger than x: 8 Local and Global Variables in Functions Variable names are by default local to the function, in which they get defined. def f(): print(s) # free occurrence of s in f s = "Python" f() OUTPUT: Python def f(): s = "Perl" # now s is local in f print(s) s = "Python" f() print(s) OUTPUT: Perl Python def f(): print(s) # This means a free occurrence, contradiction to bein local s = "Perl" # This makes s local in f print(s) s = "Python" f() print(s) OUTPUT: --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-25-81b2fbbc4d42> in <module> 6 7 s = "Python" ----> 8 f() 9 print(s) <ipython-input-25-81b2fbbc4d42> in f() 1 def f(): ----> 2 print(s) 3 s = "Perl" 4 print(s) 5 UnboundLocalError: local variable 's' referenced before assignment If we execute the previous script, we get the error message: UnboundLocalError: local variable 's' referenced before assignment. The variable s is ambigious in f(), i.e. in the first print in f() the global s could be used with the value "Python". After this we define a local variable s with the assignment s = "Perl". def f(): global s print(s) s = "dog" print(s) s = "cat" f() print(s) OUTPUT: cat dog dog We made the variable s global inside of the script. Therefore anything we do to s inside of the function body of f is done to the global variable s outside of f. def f(): global s print(s) s = "dog" # globally changed print(s) def g(): s = "snake" # local s print(s) s = "cat" f() print(s) g() print(s) OUTPUT: cat dog dog snake dog Arbitrary Number of Parameters There are many situations in programming, in which the exact number of necessary parameters cannot be determined a-priori. An arbitrary parameter number can be accomplished in Python with so-called tuple references. An asterisk "*" is used in front of the last parameter name to denote it as a tuple reference. This asterisk shouldn't be mistaken for the C syntax, where this notation is connected with pointers. Example: def)) OUTPUT:]) OUTPUT: 5.666666666666667 is cumbersome and above all impossible inside of a program, because list can be of arbitrary length. The solution is easy: The star operator. We add a star in front of the x, when we call the function. arithmetic_mean(*x) OUTPUT: 5.666666666666667 This will "unpack" or singularize the list. A practical example for zip and the star or asterisk operator: We have a list of 4, 2-tuple elements: my_list = [('a', 232), ('b', 343), ('c', 543), ('d', 23)] We want to turn this list into the following 2 element, 4-tuple list: [('a', 'b', 'c', 'd'), (232, 343, 543, 23)] This can be done by using the *-operator and the zip function in the following way: list(zip(*my_list)) OUTPUT: [('a', 'b', 'c', 'd'), (232, 343, 543, 23)] Arbitrary Number of Keyword Parameters In the previous chapter we demonstrated how to pass an arbitrary number of positional parameters to a function. It is also possible to pass an arbitrary number of keyword parameters to a function as a dictionary. To this purpose, we have to use the double asterisk "**" def f(**kwargs): print(kwargs) f() OUTPUT: {} f(de="German",en="English",fr="French") OUTPUT: {'de': 'German', 'en': 'English', 'fr': 'French'} One use case is the following: def f(a, b, x, y): print(a, b, x, y) d = {'a':'append', 'b':'block','x':'extract','y':'yes'} f(**d) OUTPUT: append block extract yes Exercises with Functions Exercise 1 Rewrite the "dog age" exercise from chapter Conditional Statements as a function. The rules are: - A one-year-old dog is roughly equivalent to a 14-year-old human being - A dog that is two years old corresponds in development to a 22 year old person. - Each additional dog year is equivalent to five human years. Exercise 2 Write a function which takes a text and encrypts it with a Caesar cipher. This is one of the simplest and most commonly known encryption techniques. Each letter in the text is replaced by a letter some fixed number of positions further in the alphabet. What about decrypting the coded text? The Caesar cipher is a substitution cipher. Exercise 3 We can create another substitution cipher by permutating the alphet and map the letters to the corresponding permutated alphabet. Write a function which takes a text and a dictionary to decrypt or encrypt the given text with a permutated alphabet. Exercise 4 Write a function txt2morse, which translates a text to morse code, i.e. the function returns a string with the morse code. Write another function morse2txt which translates a string in Morse code into a „normal“ string. The Morse character are separated by spaces. Words by three spaces. Exercise 5 Perhaps the first algorithm used for approximating $\sqrt{S}$ is known as the "Babylonian method", named after the Babylonians, or "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first explicit description of the method. If a number $x_n$ is close to the square root of $a$ then $$x_{n+1} = \frac{1}{2}(x_n + \frac{a}{x_n})$$ will be a better approximation. Write a program to calculate the square root of a number by using the Babylonian method. Exercise 6 Write a function which calculates the position of the n-th occurence of a string sub in another string s. If sub doesn't occur in s, -1 shall be returned. Exercise 7 Write a function fuzzy_time which expects a time string in the form hh: mm (e.g. "12:25", "04:56"). The function rounds up or down to a quarter of an hour. Examples: fuzzy_time("12:58") ---> "13 Solutions Solution to Exercise 1 def dog_age2human_age(dog_age): """dog_age2human_age(dog_age)""" if dog_age == 1: human_age = 14 elif dog_age == 2: human_age = 22 else: human_age = 22 + (dog_age-2)*5 return human_age age = int(input("How old is your dog? ")) print(f"This corresponds to {dog_age2human_age(age)} human years!") OUTPUT: This corresponds to 37 human years! Solution to Exercise 2 import string abc = string.ascii_uppercase def caesar(txt, n, coded=False): """ returns the coded or decoded text """ result = "" for char in txt.upper(): if char not in abc: result += char elif coded: result += abc[(abc.find(char) + n) % len(abc)] else: result += abc[(abc.find(char) - n) % len(abc)] return result n = 3 x = caesar("Hello, here I am!", n) print(x) print(caesar(x, n, True)) OUTPUT: EBIIL, EBOB F XJ! HELLO, HERE I AM! In the previous solution we only replace the letters. Every special character is left untouched. The following solution adds some special characters which will be also permutated. Special charcters not in abc will be lost in this solution! import string abc = string.ascii_uppercase + " .,-?!" def caesar(txt, n, coded=False): """ returns the coded or decoded text """ result = "" for char in txt.upper(): if coded: result += abc[(abc.find(char) + n) % len(abc)] else: result += abc[(abc.find(char) - n) % len(abc)] return result n = 3 x = caesar("Hello, here I am!", n) print(x) print(caesar(x, n, True)) x = caesar("abcdefghijkl", n) print(x) OUTPUT: EBIILZXEBOBXFX-J, HELLO, HERE I AM! -?!ABCDEFGHI We will present another way to do it in the following implementation. The advantage is that there will be no calculations like in the previous versions. We do only lookups in the decrypted list 'abc_cipher': import string shift = 3 abc = string.ascii_uppercase + " .,-?!" abc_cipher = abc[-shift:] + abc[:-shift] print(abc_cipher) def caesar (txt, shift): """Encodes the text "txt" to caesar by shifting it 'shift' positions """ new_txt="" for char in txt.upper(): position = abc.find(char) new_txt +=abc_cipher[position] return new_txt n = 3 x = caesar("Hello, here I am!", n) print(x) x = caesar("abcdefghijk", n) print(x) OUTPUT: -?!ABCDEFGHIJKLMNOPQRSTUVWXYZ ., EBIILZXEBOBXFX-J, -?!ABCDEFGH Solution to Exercise 3 import string from random import sample alphabet = string.ascii_letters permutated_alphabet = sample(alphabet, len(alphabet)) encrypt_dict = dict(zip(alphabet, permutated_alphabet)) decrypt_dict = dict(zip(permutated_alphabet, alphabet)) def encrypt(text, edict): """ Every character of the text 'text' is mapped to the value of edict. Characters which are not keys of edict will not change""" res = "" for char in text: res = res + edict.get(char, char) return res # Donald Trump: 5:19 PM, September 9 2014 txt = """Windmills are the greatest threat in the US to both bald and golden eagles. Media claims fictional ‘global warming’ is worse.""" ctext = encrypt(txt, encrypt_dict) print(ctext + "\n") print(encrypt(ctext, decrypt_dict)) OUTPUT: OQlerQGGk yDd xVd nDdyxdkx xVDdyx Ql xVd Fz xo hoxV hyGe yle noGedl dynGdk. gdeQy HGyQrk EQHxQolyG ‘nGohyG MyDrQln’ Qk MoDkd. Windmills are the greatest threat in the US to both bald and golden eagles. Media claims fictional ‘global warming’ is worse. Alternative solution: import string alphabet = string.ascii_lowercase + "äöüß .?!\n" def caesar_code(alphabet, c, text, mode="encoding"): text = text.lower() coded_alphabet = alphabet[-c:] + alphabet[0:-c] if mode == "encoding": encoding_dict = dict(zip(alphabet, coded_alphabet)) elif mode == "decoding": encoding_dict = dict(zip(coded_alphabet, alphabet)) print(encoding_dict) result = "" for char in text: result += encoding_dict.get(char, "") return result txt2 = caesar_code(alphabet, 5, txt) caesar_code(alphabet, 5, txt2, mode="decoding") OUTPUT: {'a': ' ', 'b': '.', 'c': '?', 'd': '!', 'e': '\n', 'f': 'a', 'g': 'b', 'h': 'c', 'i': 'd', 'j': 'e', 'k': 'f', 'l': 'g', 'm': 'h', 'n': 'i', 'o': 'j', 'p': 'k', 'q': 'l', 'r': 'm', 's': 'n', 't': 'o', 'u': 'p', 'v': 'q', 'w': 'r', 'x': 's', 'y': 't', 'z': 'u', 'ä': 'v', 'ö': 'w', 'ü': 'x', 'ß': 'y', ' ': 'z', '.': 'ä', '?': 'ö', '!': 'ü', '\n': 'ß'} {' ': 'a', '.': 'b', '?': 'c', '!': 'd', '\n': 'e', 'a': 'f', 'b': 'g', 'c': 'h', 'd': 'i', 'e': 'j', 'f': 'k', 'g': 'l', 'h': 'm', 'i': 'n', 'j': 'o', 'k': 'p', 'l': 'q', 'm': 'r', 'n': 's', 'o': 't', 'p': 'u', 'q': 'v', 'r': 'w', 's': 'x', 't': 'y', 'u': 'z', 'v': 'ä', 'w': 'ö', 'x': 'ü', 'y': 'ß', 'z': ' ', 'ä': '.', 'ö': '?', 'ü': '!', 'ß': '\n'} 'windmills are the greatest \nthreat in the us to both bald \nand golden eagles. media claims \nfictional global warming is worse.' Solution to Exercise 4 latin2morse_dict = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.','H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'...--', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ',':'--..--', '.':'.-.-.-', '?':'..--..', ';':'-.-.-', ':':'---...', '/':'-..-.', '-':'-....-', '\'':'.----.', '(':'-.--.-', ')':'-.--.-', '[':'-.--.-', ']':'-.--.-', '{':'-.--.-', '}':'-.--.-', '_':'..--.-'} # reversing the dictionary: morse2latin_dict = dict(zip(latin2morse_dict.values(), latin2morse_dict.keys())) print(morse2latin_dict) OUTPUT: {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '.----': '1', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '--..--': ',', '.-.-.-': '.', '..--..': '?', '-.-.-': ';', '---...': ':', '-..-.': '/', '-....-': '-', '.----.': "'", '-.--.-': '}', '..--.-': '_'} def txt2morse(txt, alphabet): morse_code = "" for char in txt.upper(): if char == " ": morse_code += " " else: morse_code += alphabet[char] + " " return morse_code def morse2txt(txt, alphabet): res = "" mwords = txt.split(" ") for mword in mwords: for mchar in mword.split(): res += alphabet[mchar] res += " " return res mstring = txt2morse("So what?", latin2morse_dict) print(mstring) print(morse2txt(mstring, morse2latin_dict)) OUTPUT: ... --- .-- .... .- - ..--.. SO WHAT? Solution to Exercise 5 def heron(a, eps=0.000000001): """ Approximate the square root of a""" previous = 0 new = 1 while abs(new - previous) > eps: previous = new new = (previous + a/previous) / 2 return new print(heron(2)) print(heron(2, 0.001)) OUTPUT: 1.414213562373095 1.4142135623746899 Solution to exercise 6 def findnth(s, sub, n): num = 0 start = -1 while num < n: start = s.find(sub, start+1) if start == -1: break num += 1 return start s = "abc xyz abc jkjkjk abc lkjkjlkj abc jlj" print(findnth(s,"abc", 3)) OUTPUT: 19 def fuzzy_time(time): hours, minutes = time.split(":") minutes = int(minutes) hours = int(hours) minutes = minutes / 60 # Wandlung in Dezimalminutes # Werte in 0.0, 0.25, 0.5, 0.75: minutes = round(minutes * 4, 0) / 4 if minutes == 0: print("About " + str(hours) + " o'clock!") elif minutes == 0.25: print("About a quarter past " + str(hours) + "!") else: if hours == 12: hours = 1 else: hours += 1 if minutes == 0.50: print("About half past " + str(hours) + "!") elif minutes == 0.75: print("About a quarter to " + str(hours) + "!") elif minutes == 1.00: print("About " + str(hours) + " o'clock!") hour = "12" for x in range(0, 60, 3): fuzzy_time(hour +":" + f"{x:02d}") OUTPUT: Ungefähr 12 Uhr! Ungefähr 12 Uhr! Ungefähr 12 Uhr! Ungefähr viertel nach 12! Ungefähr viertel nach 12! Ungefähr viertel nach 12! Ungefähr viertel nach 12! Ungefähr viertel nach 12! Es ist ungefähr halb 1! Es ist ungefähr halb 1! Es ist ungefähr halb 1! Es ist ungefähr halb 1! Es ist ungefähr halb 1 Uhr! Ungefähr 1 Uhr!
https://python-course.eu/python-tutorial/functions.php
CC-MAIN-2022-05
refinedweb
4,130
64.41
This document is also available in these non-normative formats: XML. Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. The specification governing Uniform Resource Identifiers (URIs) [rfc3986] allows URIs to "identify" anything at all, and this unbounded flexibility is exploited in a variety contexts, notably Semantic Web and Linked Data applications. To exercise this freedom and use a URI to "identify" (or more generally "mean") something, an agent (a) selects a URI, (b) provides documentation for the URI in a manner that permits discovery by agents who encounter the URI, and (c) uses the URI. Subsequently other agents may not only understand the URI (by discovering and consulting the documentation) but may also use the URI themselves with the intended meaning. A few widely known methods are in use to help agents provide and discover URI documentation, including RDF fragment identifier resolution and the HTTP 303 'See Other' explore the design space (archive). Desiderata 2 Use case scenarios 2.1 Choosing a URI, providing documentation for the URI, using the URI 2.2 Using a document as URI documentation by reference to its primary topic 3 URI documentation discovery methods in current general use 3.1 Colocate URI documentation and use 3.2 Specifically point (link) to the URI documentation 3.3 Use non-http: URIs and a non-HTTP protocol 3.4 'Hash URI' 3.4.1 Local identifier misspellings go undetected 3.4.2 Local identifiers are easily lost 3.5 Retrieval as equivalent to instance relationship 3.6 Hashless URI with HTTP 303 'See Other' redirect 3.6.1 303 is difficult, sometimes impossible, to deploy 3.6.2 303 leads to too many round trips 3.6.3 303 responses aren't cached 3.6.4 303 makes the URI difficult to bookmark 4 Don't do it: Potential workarounds 4.1 Use something other than a URI 4.2 Express data in terms of named documents (parallel properties) 5 Some potential new discovery methods 5.1 Global rule yielding documentation URI 5.2 Site-specific rule yielding documentation URI 5.3 HTTP response header that links to documentation 5.4 New HTTP request method eliciting documentation 5.5 New HTTP response status code 6 Discovery methods where some retrieval responses carry URI documentation 6.1 Design space overview 6.2 application/rdf+xml response signals URI documentation 6.3 Rely on implicit coercion from a named document its intended subject 7 Summary 8 Glossary 9 Acknowledgments 10 References 11 Change log This is an old issue, and people are tired of it. — Sandro Hawke, January 2003 [disambiguating] In any kind of discourse it is very useful for an agent to be able to provide documentation for a term, in such a way that other agents can discover and use that documentation in order to make sense of utterances that use that term, and to compose new utterances that use it. documented URI documentation URI documentation says or doesn't say about the URI in question, or the particular way in which a URI is used. Our concern is only with the method by which documentation is conveyed, and with meaning only to the extent the method impinges on interpretation. URI documentation is typically carried in documents. No assumptions are made about what else might be in such a document; there could be additional related information, documentation for other URIs, and so on. Nor is it important here that URI documentation be delimited or set off from the other information in the document. As in an encyclopedia, the URI documentation part blurs into the other-information parts of the document. URI documentation discovery methods include, in addition to those already mentioned, network protocols such as HTTP that involve the URI as a protocol element. Henceforth, in a URI documentation discovery scenario, the URI whose URI documentation is to be discovered will be called the probe URI. URI documentation discovery is similar to Web retrieval in that in both cases one can start with a URI and end with a document. The two must not be confused, however, since retrieval often yields information that does not document the URI, is not recognized as doing so, or is not intended to do so. The reason we define URI documentation. No consensus on success criteria has emerged from the discussion of this question. The following properties have been articulated as desirable by various parties to the discussion. Unfortunately they apparently form a mutually inconsistent set. documentation for the URI, i.e. a document that would lead a reader to understand that the URI refers to the earthquake. Bob then learns of Alice's URI and its documentation, and uses the URI in a document of his own. Subsequently Carol encounters Bob's document. Wanting to know what the URI means, she is led somehow to Alice's published URI documentation, which she reads. She is enlightened. Any method for implementing this use case would need to explain: what kind of URI Alice should use (syntactic constraints); where and how should Alice should publish the documentation so that it can be found; and how Carol might come to discover Alice's documentation, documenting Bob's URI. In fact Bob's URI doesn't even occur in it. Rather than look in the document for URI documentation for Bob's URI, Carol must determine the topic of the document and take the topic as the meaning of Bob's URI.) This section describes currently accepted methods for providing and discovering URI documentation. One way to lead someone encountering a URI to documentation for the URI is to make sure that the URI documentation occurs in each document in which the URI occurs. This makes the URI documentation easy to find, since anyone who encounters the URI will already have it in hand. The form of the URI in this case is arbitrary. This method treats URIs similarly to blank nodes in RDF, which have to stay close to their own documentation, since they are scoped to a graph. An example of the application of this approach would be the use of a URI in an OWL ontology file that carries the URI documentation. Criticism: In RDF, this method is fragile in the same way as are blank nodes, because use and documentation can get separated, e.g. when uses of the URI are deposited into a triple store and then retrieved by a query. Carrying documentation around with a reference does not help in the common case where an out-of-context reference is needed (as one would want in, say, a Semantic Web). (Desideratum: [ Uniform ].) When using a URI, provide, again in the document in which the URI occurs, a recognizable reference to a document that carries the URI documentation. This is the approach taken by OWL; the document containing the URI is related to the one from which the URI documentation documentation can get separated, or keeping the documentation link close to the occurrence of the URI may prove to be too difficult for applications. (Desideratum: [ Uniform ].) It is possible to create a new URI scheme or URN namespace equipped with its own URI documentation discovery regime. A recent example is RFC 5870 for URIs documented as naming geographic locations, where the RFC itself constitutes URI documentation for all of its URIs. Another is the URI documentation for the URI about:blank and other about: URIs,. The most fully developed and widely implemented such design is the 'lsid' URN namespace. URIs beginning 'urn:lsid:' are called LSIDs. [lsid] LSIDs have an associated SOAP-based protocol that has separate methods for retrieval , documentation for the LSID. For clients lacking an LSID protocol implementation, HTTP/LSID gateways are available, suggesting the possible applicability of the 5.1 Global rule yielding documentation URI discovery method as an alternative to the LSID protocol. Criticism: The LSID protocol itself is not widely deployed, and LSIDs are not currently processed in any useful way by most Web clients. (Desiderata: [ Retrieval-friendly ], [ Easy to deploy using a current widely deployed protocol stack ], [ Easy to deploy on Web hosting services ].) With this method, the probe URI must be a 'hash URI', i.e. must contain a hash character '#'. The URI documentation is placed in the document on the Web at the stem (where stem URI = the pre-hash prefix of the URI). For historical reasons the part of the URI following '#' is called the 'fragment identifier', even when it is null. We will call these 'local identifiers' in recognition of their uses beyond just references to document fragments. The interpretation of a 'hash URI', say '', depends (according to [rfc3986]) on the media types of representations of the resource on the Web at its stem URI ''. For media type application/rdf+xml, the media type registration defers to the content of the representation — that is, the representation itself of the stem URI gets to document what the probe URI means.[2] Because of the dependence on media type, care must be taken to ensure that content negotiation does not muddy the meaning of the probe URI. Fortunately any of three approaches may be used: (1) avoid content negotiation, (2) make sure that all representations provide the same documentation (following section 3.2.2 of [webarch]), or (3) institute, as a new consensus practice, a priority ordering on media types, so that, say, media type application/rdf+xml deterministically takes priority over text/html (or vice versa). (The latter in turn requires modifications to discovery clients, so this would would be in effect a new discovery method.) Similar considerations apply for competing use of local identifiers as script-defined or as document fragment identifiers: any potential conflicts must be either avoided or resolved. A second caveat around hash URIs is that when a number of hash URIs are formed by combining a fixed namespace prefix (stem) with many different suffixes using hash as a connector, there must be a single underlying document at the stem URI that provides URI documentation for all of the URIs. This leads to a number of annoyances, including inefficiency (repeated retrieval of a large document is an unacceptable performance hit for the server, the network, and the client), analytics imprecision, and unavailability of HTTP methods such as DELETE specific to the particular URI. The answer to this difficulty has been reported a number of times (e.g. [degraauw]) and might be called the "single-hash-URI-per-stem-URI pattern" of use of hash URIs. For a set of namespace members a, b, c, ... instead of using URIs ... use URIs that look like ... where _ is a common suffix of your choice. Criticism: A hashless URI that is misspelled, when submitted to an HTTP server, would normally evoke a 404 Not Found response, alerting a user quickly to a misspelling. A hash URI, on the other hand, isn't sent to an HTTP server. Any misspelling in the local identifier may go undetected for a long time, since it would only be detected as a failure to recover expected information from the content that was supposed to document it. (Desideratum: [ Substitution resistant ].) Response: This is hard to argue with. Mitigations such as use of Javascript for error checking might be possible. Criticism: Harry Halpin [halpin] reports that local identifiers are often lost during document preparation and cut/paste operations. Rumor has it that some MVC-based web frameworks (Django?, Sinatra?) are not good about preserving local identifiers. This needs to be verified. (Desideratum: [ Substitution resistant ].) Response: More information needed; it's not obvious [to the editor] that this should be the case. Concrete scenarios would help. Widely observed convention relating retrieval to meaning is the following: Convention 1: A retrieval-enabled hashless URI refers to the resource on the Web at that URI (see [generic]), independent of anything that the retrieval results (representations) say about what the URI means. In effect, a response to a retrieval request is equivalent, according to Convention 1, to URI documentation that says that the response is an instance of the thing named by the URI. This in turn implies (as explained in [generic]) that the response (or rather its representation payload) may resemble that thing in properties such as title, author, subject, creation date, and so on. The URI is then useful as the subject of a statement of metadata, which is understood as applying to the instance. Criticism: From the fact that a response is an instance of the URI's referent, you learn from this that the referent is of a kind that might have properties characteristic of a retrieval response. But it's not obvious what in particular the response tells you about the referent of the URI, since most relevant properties, such as length, creation date, or even author, can vary among responses. According to the theory in [generic] a property will hold if it holds of all potential responses, but this is a property that would have to be learned through other channels. Initially (around 2000) 'hash URIs' were advanced as the recommended method for URI documentation provision and discovery. In the 2002-2005 time period demand arose for a discovery method applicable to hashless URIs. This led to the invention of a new protocol for use in situations where 'hash URIs' are considered unacceptable. In this approach, one mints an absolute hashless http: URI, puts documentation for it on the Web at a second URI, and then arranges for a GET request of the first (probe) URI to redirect, using a 303 'See Other' status code, to the second URI. The probe URI is not retrieval-enabled, and therefore does not name the resource at that URI according to Convention 1 (since there is none). The probe URI then gets its meaning by interpreting the document on the Web at the second URI, which presumably contains documentation for the first URI. The document may carry documentation carries URI documentation for '', explaining the URI's meaning by providing details about the earthquake (date, location). For the URI '', which will not be retrieval-enabled (since otherwise, it would, by Convention 1, refer to the resource on the Web at that URI [generic], not the earthquake), she arranges that a GET request yields a 303 redirect with a Location: header specifying '' as the redirect target. Those encountering '' will attempt a retrieval, but this will fail, with a 303 redirect delivered instead. The 303 redirect indicates that the document at '' provides documentation of the URI ''. Another pattern is to use a 303 redirect to a document whose primary topic is the intended referent, similar to the Chicago use case (2.2 Using a document as URI documentation by reference to its primary topic). This could, in theory, lead to ambiguities, as the entity to which the URI refers in the document may not be the document's primary topic. Again, a number of objections to this approach have been raised: Criticism: Deploying a 303 redirect requires giving the correct directive to a web server, for example adding a Redirect line to .htaccess in Apache HTTPD. Unfortunately many hosting solutions do not allow this, putting this manner of publishing URI documentation off limits to many who would otherwise like to use it. (Desideratum: [ Easy to deploy on Web hosting services ].) documented would have to have the form..., while the URI for the document carrying the URI documentation could be anything at all. Unfortunately, use of a redirect service makes one dependent on two service providers instead of one, making one's URI documentation more vulnerable than if only one provider were involved. Criticism: To get URI documentation for N URIs by redirecting through 303 responses, you need to do 2N HTTP requests (in the absence of cache hits). This is a frustrating and apparently gratuitous performance hit for those interested in publishing and accessing large numbers of URI documentation-carrying documents. (Desideratum: [ Efficient ].) Response: See 5.1 Global rule yielding documentation URI. Criticism: RFC 2616 [rfc2616] says that 303 responses shouldn't be cached. Some caching software obeys this directive, with negative consequences for the performance of GET/303 exchanges. (Desideratum: [ Efficient ].). Criticism: "The user enters one URI into their browser and ends up at a different one, causing confusion when they want to reuse the URI ... Often they use the document URI by mistake." [davis] ] (Desideratum: [ Substitution resistant ]). Accomplishing this would be a challenge. If issues around 'hash URIs' and 303 redirects render them unacceptable, it is worth considering alternatives. In this section we reconsider ways in which URI documentation the resource on the Web at that URI according to a generic method (see [generic]). documented URIs. In particular, it is possible. The idea here is that you don't need to document a URI if you are willing to use properties that are defined or understood as indirecting through documents. Instead, just use a URI that refers to the document on the Web at that URI, and use it as the subject of such properties. Assume that each named document (i.e. document+name pair) can have an associated entity, which we'll call its "designated subject".[3] Information about the designated subject is expressed using properties whose subject is the document. Suppose that Alice wants to record some information about an earthquake. She publishes URI documentation containing the following so that it's on the Web at the URI '': <> eq:magnitude 6.9. <> eq:epicenter <geo:37.040,-121.877>. Bob then comes along and writes the following metadata about OW@('') in the usual way, i.e. using the URI to refer to that resource, based on what information is accessed via that URI: <> dc:creator "Alice". <> dc:title "Documentation for Loma Prieta earthquake URI". Suppose that Carol encounters both bits of RDF (or either) and needs to make sense of them. She is aware that '' might be used in both kinds of statement - in metadata, with the intent that the metadata is about OW@(''); and also in statements that relate to an eathquake. Instead of defining eq:epicenter to be a property relating an earthquake to its epicenter, one documents eq:epicenter to be a property that relates a document documents, a document.) The members of class Movie are documents whose designated subjects are movies. [is this message on topic?] Criticism: If a property that refers directly to movies also needs to be used, then two properties have to be defined (with distinct URIs), one relating to the movie and one relating to the Movie. This results in clerical overhead and potential user confusion. All rules presented in this section assume that the probe URI is a hashless http: URI. For compatibility with clients that are not aware of new method(s) for hashless URIs, a complete discovery solution should grandfather discovery methods that are currently widely known, such as 303 redirects. A current method should be deployed when possible, redundantly. Lacking this a 404 should be returned, and if the content of the 404 response can be controlled it should provide suitable information such as a link to the URI documentation. Agents would be faced with the problem of which method to attempt first, since if the the new method doesn't yield URI documentation, a retrieval using the probe URI might have to be attempted (in hope of either success or a See Also), resulting in one or two extra retrieval requests. It is the editor's belief that this problem is not insurmountable, but the details would have to be worked out. The network round-trip (303 redirect) used to map the probe URI to the URI of the document that carries its URI documentation can be avoided if we know a general rule that maps the one kind of URI to the other, as such a rule can be applied on the client without server involvement. The "well known URIs" specification [rfc5988] provides a solution to this problem. For any origin (the part of the URI preceding the path part) we can prefix the path of URIs with a fixed string, say, '/.well-known/meta', to obtain the URI documentation URI. For example, if the URI is '', then its URI documentation would be found by retrieval using the URI ''. (There is nothing special about the string 'meta'; it could as easily be, say, 'about' or 'seealso'.) Criticism: Web publishers without the ability to control retrieval results for the /.well-known/meta/... URIs would not be able to take advantage of this method. (Desideratum: [ Easy to deploy on Web hosting services ].) Criticism: Jeni Tennison says: "the disadvantage is that you lose the distinction between status codes for the thing [described] and the document [instantiated]". [But the editor doesn't understand this. Any information that would have been conveyed by the status code from a GET on the probe URI, could be conveyed in the document retrieved by URI documentation discovery?] Considering the transformation rule idea of the previous section, it is probably too much to hope for that a single rule could work uniformly for hosts whose documentation might be sought, but each individual host may have a rule that applies for URIs at that host. To support site-specific rules, a a file containing such rules can be provided [rfc5988] using a well-known path, say '/.well-known/documentation-rule', e.g. ''. To obtain documentation for '', first retrieve (and cache) the documentation-rule document for its host. Then if the rule says to map '{path}' to, say, '{path}.about', documentation for '' can be sought by a retrieval request using ''. When the mapping rule is cached, the number of round trips is one instead of two. Although it would not be difficult to specify a new .well-known path and syntax for the documentation-rule document, it might be possible to use the link-template feature of the host-meta file. There are pros and cons for each approach. This approach is essentially the same as the ARK design, [TBD: reference or something better] which uses as its global URI transformation appending a '?' to the URI. The main differences are that the ARK rule only works when the path begins 'ark:', and that the risk of 'squatting' on part of a domain owner's URI space (not all '?'-ended URIs are for URI documentation discovery) is somewhat higher than in the case of /.well-known/meta/, which would be sanctioned by [rfc5988]. Criticism: Web publishers without the ability to control retrieval results for /.well-known/meta/documentation-rule would not be able to take advantage of this method. (Desideratum: [ Easy to deploy on Web hosting services ].) Criticism: Jeni Tennison says: "in some cases the mapping from thing URI to document URI can be complex or change over time in ways that make it hard to use a documentation documentation-rule file in those circumstances (we would have to solve it by having a simple mapping with some URIs 307 redirecting to others)." The Link: HTTP header [rfc5988] is useful for indicating a metadata source for an information resource (see POWDER spec [citation needed]). (Although well documented by its normative specifications, this method is not listed in this document under "methods in current use" because the editor is not aware of any deployment.) The URI needn't be retrieval-enabled, as Link: could be used in any non-success response for directing a client to documentation for the URI. Criticism: The advantage of Link: over a 303 redirect in the non-retrieval-enabled case is unclear, since a second network round trip would be required either way. (Desideratum: [ Efficient ].) To reduce the number of round trips relative to the 303 redirect, we might have HTTP requests that are somehow understood as signalling a request for URI documentation, as opposed to retrieval of an instance of a resource on the Web at the URI, with the documentation coming back in the HTTP response. Such a request could be distinguished from a retrieval or other request by its method, headers, and/or content. The URIQA specification [uriqa] defines MGET, a new HTTP request method. An MGET request on a URI yields a response containing information about the referent of the URI. If the URI is retrieval-enabled, then (by Convention 1) the URI refers to the resource on the Web at that URI, so the MGET result is metadata for that resource. Otherwise, the MGET result might be documentation for the URI. In that case a GET request should yield a 303 See Other linking to the same URI documentation obtained by MGET, or maybe to a 405 Method Not Allowed response. Criticism: Not possible to deploy on many hosting services. (Desideratum: [ Easy to deploy on Web hosting services ].) In response to GET of a URI, a server might provide documentation for the URI directly in a non-200 response, as opposed to indirectly via a 303 redirect. (The URI documentation can't go in a successful GET response since that would mean that the URI refers to the resource on the Web at the URI.) Possibilities for HTTP response status codes that might signal this situation: 203 Non-Authoritative Information; a new 2xx status (maybe 209); a new 3xx status (maybe 309); or a variety of 4xx codes. Placing the URI documentation. Criticism: Probably impossible for many hosting services. Not clear whether proxies, caches, and Web clients do something reasonable with the proposed status code. (Desiderata: [ Retrieval-friendly ], [ Easy to deploy on Web hosting services ].) A range of discovery method designs involve having clients interpret parts of retrieval (HTTP GET/200 or equivalent) responses, or entire responses, as URI documentation. Depending on design details, any particular response might be treated as carrying URI documentation (or expected to do so), treated as an instance (per Convention 1), both (instance with embedded metadata), or neither. The following illustration diagrams the case where all retrieval responses are treated as carrying URI documentation, i.e. all responses are instances of something different from what the URI refers to that carries URI documentation. These designs have in common that at most a single HTTP round trip is required, when discovery uses the HTTP protocol. After surveying the design choices that have to be made, a few representative method designs are presented. The entire space of possibilities is too broad to cover here. Designs in this space differ in important ways: Regarding the last question, any method that conflicts with Convention 1 makes some URIs unavailable for expressing what the URIs mean according to Convention 1. There are many applications that need a method for writing a reference to the resource at an arbitrary retrieval-enabled hashless URI, including those concerned with metadata (including licensing), provenance, Web site testing, validation, text processing, text annotation, and access control. Therefore any complete discovery solution that includes some a discovery method that preempts Convention 1 for any URI should include a way to write such references. The workaround 4.2 Express data in terms of named documents (parallel properties) described above falls in this design space, but as it can be used immediately with no new consensus, it is not listed here. Criticism: Designs requiring new request or response headers fail desideratum [ Easy to deploy on Web hosting services ]. Designs in which some responses are non-instances fail desideratum [ Compatible with use of URI as metadata subject ] since metadata might be interpreted to be about the URI documentation. Designs in which URI interpretation is context sensitive fail [ Uniform ]. One particular point in the design space is presented in [davis], and because the proposal has been put forth in a careful manner it will be taken as representative. For discovery, do a GET requesting media type application/rdf+xml. If the result is application/rdf+xml, then assume no retrieval response is an instance of the referent (?), and assume the result carries URI documentation for the probe URI. To refer to the URI documentation, use the URI in the Content-location: header of the response. If there is no application/rdf+xml variant then assume the URI refers to what's on the Web at the probe URI. When an instance is sought (application/rdf+xml not requested), and the result is application/rdf+xml, it is not clear [to the editor] how the result should be classified: as both instance and URI documentation, just an instance, or just URI documentation. Criticism: Designs in which some responses are non-instances fail desideratum [ Compatible with use of URI as metadata subject ] since metadata might be interpreted to be about the URI documentation. Criticism: This design does not seem to support other URI documentation formats such as RDFa or Turtle. If one's domain of discourse mixes documents with entities that might be their designated subjects, then maintaining parallel properties (see 4.2 Express data in terms of named documents obvious documentation for Q would be Q(x,y) if and only if P(x,y) OR P(designated-subject(x),y) For example, taking P = dc:creator as defined by the Dublin Core documentation, a document, so it's probably better use a "tie breaking" rule such as Q(x,y) if and only if P(x,y) OR {P(designated-subject(x),y) AND designated-subject(x) is not a document} There may be better tie-breakers than this one; this is just for illustration. All considerations that apply to the subject of a property also apply to the object, making the coercion rules that much more complex. Criticism: Any tie-breaking rule is going to be fragile and will make the "losing" side of the race difficult to express. One can expect many mistakes where the designated subject was the intended subject of some metadata but the tie-breaking rule implicated the other resource. (Desideratum: [ Compatible with use of URI as metadata subject ]) Criticism: This method, by design, creates the illusion that the URI actually refers to the designated subject, not the resource at the URI. If predicates that already possess meaning are being reinterpreted as overloaded properties, there is risk that an agent will draw unsound conclusions. For example, if two URIs u, v refer to distinct resources with the same designated subject, and one then writes <u> owl:sameAs <v> having their designated subjects in mind, then one can incorrectly impute that the two resources are identical. A similar situation holds with functional properties, which induce equations. (Desideratum: [ Compatible with inference ]) The following table summarizes some of the current and proposed URI documentation discovery methods, evaluating each against the desiderata stated in the introduction, as explained in the key below. A complete discovery solution would combine methods in some way, conceivably resulting in an overall approach possessing more or fewer virtues than any of its individual constituent methods. A table entry of '?' means that the answer depends on the details of the method design, while '~' means it depends on the interpretation of the desideratum statement (i.e. the vagueness of the desideratum statement makes it hard to say). Refer to 1.1 Desiderata, as follows, for explanations of each column in the table: This section defines terms that are used in this report. An attempt has been made to avoid gratuitous differences from the way these terms are used elsewhere, but in a few cases choice of terminology has been difficult and words with other meanings are given technical definitions. These definitions are not being proposed for general adoption. [Draft comment: All terminology choices are provisional; for most of them I am testing the waters to see how well the word works, and am prepared to change.] AWWSW Task Group members. Dave Reynolds gave detailed advice the handling of desiderata throughout the document, and other valuable comments. Jeni Tennison and the rest of the TAG gave many helpful comments. Martin J. Dürst clarified the technical meaning of the term "absolute URI".
http://www.w3.org/2001/tag/awwsw/issue57/20120130/
CC-MAIN-2014-49
refinedweb
5,331
52.19
For log tracing inside a for val ll = List(List(1,2),List(1)) for { outer <- ll a = Console.println(outer) // Dummy assignment makes it compile inner <- outer } yield inner a = You could always define your own trace function: def trace[T](x: T) = { println(x) // or your favourite logging framework :) x } Then the for comprehension would look like: for { outer <- ll inner <- trace(outer) } yield inner Alternatively, if you want more information printed, you can define trace as follows: def trace[T](message: String, x: T) = { println(message) x } and the for comprehension would look like: for { outer <- ll inner <- trace("Value: " + outer, outer) } yield inner EDIT: In response to your comment, yes, you can write trace so that it acts to the right of the target! You just have to use a bit of implicit trickery. And actually, it does look much nicer than when applied to the left :). To do this, you have to first define a class which is Traceable and then define an implicit conversion to that class: class Traceable[A](x: A) { def traced = { println(x) x } } implicit def any2Traceable[A](x: A) = new Traceable(x) Then the only thing you have to modify in the code you have provided is to add traced to the end of the value you want to be traced. For example: for { outer <- ll inner <- outer traced } yield inner (this is translated by the Scala compiler into outer.traced)
https://codedump.io/share/ltI9b1h49M2U/1/how-to-add-tracing-within-a-39for39-comprehension
CC-MAIN-2017-04
refinedweb
241
51.35
As promised, here is a follow up tutorial on the node.js/socket.io/backbone.js/express/connect/jade/redis stack that powers nodechat.js. The first nodechat.js tutorial introduced some fancy ideas, like using backbone.js on the server and streaming models over socket.io which is all well and great, but it left some of the more practical questions unanswered. Issues like coordinating authentication between express/connect and socket.io and creating, storing, and retrieving user profiles, are less sexy, but still quite important for real world use. So that is what the next this tutorial will look at. Practical stuff. Besides, everything is more fun when you do it in node, right? I will also sprinkle you with some other neat wisdom nuggets along the way. If you want. Overview First off, nodechat.js has advanced well passed the point that it is clean and clear enough to be used as a tutorial. I have decided to create a new nodechat project that will be used strictly for tutorials. It lives at github also. The code for this tutorial is at the v0.2 tag. nodechat.js and nodechat-tutorial share same underlying design, so if you want to see a demo, come visit nodechat.no.de. There will probably even be someone there to chat with. Our goal for this tutorial is to put nodechat behind a simple login page, provide a way to sign up new accounts, and make sure that socket.io verifies the accounts before accepting traffic. Install Stuff Any good node.js adventure starts off with npm powerups. For this adventure, we will need everything from part one of this tutorial and: - sudo npm install connect-redis - sudo npm install joose - sudo npm install joosex-namespace-depended - sudo npm install hash And just for fun, let’s do: sudo npm update We will be using connect-redis as our connect session store and hash as our hashing library. The joose modules are there because hash requires them. Authentication To authenticate users and retrieve bits of information about them, we will need to: - Create user accounts - Check login information - Retrieve the profile if successful - Kick them out if we are not successful - Do something with the profile information Let’s start with the easy stuff. We will need a login page and an account creation page. Create the following jade template files in the views/ directory: login.jade !!! 5 html(lang="en") head title nodechat login body #heading h1 nodechat login #content p | Please login or go a(href='/signup') here | to create a new account. form(method="post", action="/login") p label Username: input(type='text', name='username') p label Password: input(type='password', name='password') P input(type='submit', value='send') Not much to this page. Just a simple login form with a link to our signup page. !!! 5 html(lang="en") head title nodechat new user body #heading h1 nodechat new user #content p form(method="post", action="/signup") div(style='width:350px; text-align:right') label Username: input(type='text', name='username') br label Password: input(type='text', name='password1') br label Password (again): input(type='text', name='password2') br label Email: input(type='text', name='email') br label Favorite thing about ponies: input(type='text', name='ponies') br input(type='submit', value='signup') Again, pretty simple. Just collect the signup information and whatever special information we may *ahem* require from our users. Routes Now we need to set up routes to serve our new pages. In core.js, after we have set up express, we want to include several routes. app.get('/login', function(req, res){ res.render('login'); }); app.post('/login', function(req, res){ auth.authenticateUser(req.body.username, req.body.password, function(err, user){ if (user) { req.session.regenerate(function(){ req.session.cookie.maxAge = 100 * 24 * 60 * 60 * 1000; //Force longer cookie age req.session.cookie.httpOnly = false; req.session.user = user; res.redirect('/'); }); } else { req.session.error = 'Authentication failed, please check your username and password.'; res.redirect('back'); } }); }); Setup the routes for GET and POST /login. - GET returns the login.jade template - POST calls the authentication module to verify login details. - Failures are redirected back to the login page. *We will cover the authentication module in a minute. For now, just know that it does what it sounds like it might do :) If the authentication module gives us a user object back, we ask connect to regenerate the session and send the client back to index. Note: we specify a long cookie age so users won’t have to log in frequently. We also set the httpOnly flag to false (I know, not so secure) to make the cookie available over Flash Sockets. app.get('/signup', function(req, res){ res.render('signup'); }); app.post('/signup', function(req, res) { auth.createNewUserAccount(req.body.username, req.body.password1, req.body.password2, req.body.email, req.body.ponies, function(err, user){ if ((err) || (!user)) { req.session.error = 'New user failed, please check your username and password.'; res.redirect('back'); } else if(user) { res.redirect('/login'); } }); }); Setup routes for GET and POST ‘/signup’: - GET returns signup.jade - POST calls createNewUserAccount() in the auth module. - Failures redirect to the same page - Success redirects back to /login for the user to formally log in Next ‘/logout’: app.get('/logout', function(req, res){ req.session.destroy(function(){ res.redirect('home'); }); }); This route tells connect to destroy the session, which will cause nodechat to require the user to login again if they access the ‘/’ route. app.get('/*.(js|css)', function(req, res){ res.sendfile('./'+req.url); }); app.get('/', restrictAccess, function(req, res){ res.render('index', { locals: { name: req.session.user.name, hashPass: JSON.stringify(req.session.user.hashPass) } }); }); function restrictAccess(req, res, next) { if (req.session.user) { next(); } else { req.session.error = 'Access denied!'; res.redirect('/login'); } }; These last two routes already exist in nodechat v0.1. The only difference here is the reference to restrictAcess in the ‘/’ route. restrictAccess() is an express route middleware. Control is passed to the middleware function before the route function is called. We use restrictAccess() to verify that we have a valid user key in the session (implying that authentication has succeeded) before we send the client the requested route. If we do not have a valid user object in the session, then we redirect the client to the ‘/login’ route. This effectively locks down our ‘/’ route from unauthenticated access. You could add the restrictAccess() to any route you want to protect. model That covers our new routes. Next we will need a backbone.js model for user accounts (well we don’t need a model, but nodechat is backbone.js on the server right?). Add a simple empty model to our models/models.js: models.User = Backbone.Model.extend({}); That was easy. auth.js Let’s turn our attention to the authentication module touched on earlier. Create a new file, lib/auth.js. This module will handle the creation, verification, and profile loading of user accounts. It exposes two public methods: authenticateUser() and createNewUserAccount(). This will be a CommonJS module so we need to start off with some set up: (function () { if (typeof exports !== 'undefined') { redis = require('redis'); rc = redis.createClient(); models = require('../models/models'); //joose is required to support the hash lib we are using require('joose'); require('joosex-namespace-depended'); require('hash'); } else { throw new Error('auth.js must be loaded as a module.'); } Here we are checking to see if this code is included as a module. If it is, we go ahead and include our dependencies (in this case, our models lib, redis, and hash + friends). If we are not a module, we may as well explode because the rest of the code won’t run without redis and hash. exports.authenticateUser = function(name, pass, fn) { console.log('[authenticate] Starting auth for ' + name + ' with password ' + pass); var rKey = 'user:' + name; rc.get(rKey, function(err, data){ if(err) return fn(new Error('[authenticateUser] SET failed for key: ' + rKey + ' for value: ' + name)); if (!data) { fn(new Error('[authenticateUser] invalid password')); } else { console.log('[authenticateUser] user: ' + name + ' found in store. Verifying password.'); verifyUserAccount(data, pass, fn); } }); }; authenticateUser() takes a name, password, and callback. It checks to see if the user exists in redis. If it does, it calls verifyUserAccount(). CommonJS Modules An aside: if you are unfamiliar with the CommonJS module specification, the basic idea is that you encapsulate your reusable methods and objects in a anonymous function that assigns its “public” methods to the global exports variable. This allows us to have private variables and methods, like verifyUserAccount() below, and to easily reuse our code through require() statements throughout our application. This is a pattern you will see constantly in node.js-world. var verifyUserAccount = function(foundUserName, pass, fn) { var rKey = 'user:' + foundUserName; rc.get(rKey + '.salt', function(err, data){ if(err) return fn(new Error('[verifyUserAccount] GET failed for key: ' + rKey + '.salt')); if(data) { var calculatedHash = Hash.sha512(data + '_' + pass); rc.get(rKey + '.hashPass', function(err, data) { if(err) return fn(new Error('[verifyUserAccount] GET failed for key: ' + rKey + '.hashPass')); if (calculatedHash === data) { console.log('[verifyUserAccount] Auth succeeded for ' + foundUserName + ' with password ' + pass); rc.get(rKey + '.profile', function(err, data) { if(err) return fn(new Error('[verifyUserAccount] GET failed for key: ' + rKey + '.profile' + ' for user profile')); var foundUser = new models.User(); foundUser.mport(data); foundUser.set({'hashPass': calculatedHash}); return fn(null, foundUser); }); } else { return fn(new Error('[verifyUserAccount] invalid password')); } }); } else { return fn(new Error('[verifyUserAccount] salt not found')); } }); } verifyUserAccount() takes the same parameters as authenticateUser(). It assumes the passed in user exists in redis (remember, it is only accessible within the module, so that is a safe assumption to make) and then steps through the process of retrieving the salt, calculating the hash of the passed in password, then comparing it to the stored hash in redis. If the comparison is successful, create a new user model and pass it to the callback. Otherwise, any failure along the way means we callback with an error. exports.createNewUserAccount = function(name, pass1, pass2, email, ponies, fn) { if (pass1 !== pass2) return fn(new Error('[createNewUserAccount] Passwords do not match')); var newUser = new models.User({name: name, email: email, ponies: ponies}); var rKey = 'user:' + name; rc.set(rKey, name, function(err, data){ if(err) return fn(new Error('[createNewUserAccount] SET failed for key: ' + rKey + ' for value: ' + name)); var salt = new Date().getTime(); rc.set(rKey + '.salt', salt, function(err, data) { if(err) return fn(new Error('[createNewUserAccount] SET failed for key: ' + rKey + '.salt' + ' for value: ' + salt)); var hashPass = Hash.sha512(salt + '_' + pass1); rc.set(rKey + '.hashPass', hashPass, function(err, data) { if(err) return fn(new Error('[createNewUserAccount] SET failed for key: ' + rKey + '.hashPass' + ' for value: ' + hashPass)); rc.set(rKey + '.profile', newUser.xport(), function(err, data) { if(err) return fn(new Error('[createNewUserAccount] SET failed for key: ' + rKey + '.profile' + ' for user profile')); newUser.set({'hashPass': hashPass}); return fn(null, newUser); }); }); }); }); } createNewUserAccount() verifies that the two passwords match, then uses the current timestamp to salt a hash of the password. It stores the hashed password and the passed in information about email and ponies in a user model which we will save as a poor man’s profile–if everything succeeds. Any failure along the way means we callback with an error. We are using SHA512 which has to be good, because it was invented by the NSA. })() If you have actually been cutting and pasting, you will need to end your file with this little snippet per the CommonJS spec. Salting and Hashing Another aside: if you are like me, you probably do not often mess around with actually storing usernames and passwords. Most frameworks will handle this for you quite nicely. I had to do some google-fu to figure out a decent way of doing this. Crypto experts: Please don’t email me telling me how the NSA could crack this in 5 minutes. It’s a chat program. I am also aware that there are probably five thousand node modules on npm that will do this for you as well. This is supposed to be fun dammit! Leave me alone. The basic concept behind cryptographic hashing is to take a string of any length, in our case a password, and map it into a fixed length string, using an algorithm. This computation is inexpensive if you know the password up front, but doing the reverse–finding all the possible passwords that can map to the hash value–is computationally very expensive. Since we only store the hash, if our redis instance is ever compromised, an attacker would have to compute an enormous number potential passwords (and try each one) to figure out which one is the real password. Hashing on its own can be susceptible to rainbow tables–precomputed reverse hash values. The attacker simply looks up the hash in the table and finds the list of corresponding possible passwords. The tables can be precomputed in advance and are easily obtained online by those who may be so inclined. This is where the salt comes in. The salt is a randomly generated string (I am just using a timestamp, but close enough) that is attached to the password before the cryptographic hash computation. We store the hash in the database as well; we will need it to verify passwords later on. The salt mitigates the ability of an attacker to pre-compute the hash space. Since each user has a different salt, the attacker would have to compute the entire hash space for each user, and that is assuming the know the salt! If they don’t have the salt, the task becomes insurmountable. nodechat.js uses the following salt/hash algorithm: Account Creation - On account set up, get the current time in milliseconds. This is our salt. - Prepend the salt to the password separated by an underscore: salt_password. - Calculate the SHA512 hash of the salt_password string. This is our password hash. - Store the salt and the password hash for the user. Account Verification - On an attempt to login to an existing account, retrieve the salt for the requested user. - Prepend the salt to the attempted password, separated by an underscore: salt_attemptedpassword. - Calculate the SHA512 hash of the salt_attemptedpassword string. This is our attempted password hash. - Retrieve the stored password hash and compare it to the attempted password hash. If both hash values match, then assume the passwords match. Otherwise, they do not. Enough crypto for today. Back to node stuff. Making it work with socket.io We now have all the pieces in place to lock down our express routes and if we were not using socket.io, we would be done. But we are using socket.io, so we’re not. We need to be able to protect socket.io connections the same way we protect our routes. socket.io is not aware of the session and will not have access to the session store the same way express does, so we have to improvise. Back in core.js we want to add some more code: function disconnectAndRedirectClient(client, fn) { console.log('Disconnecting unauthenticated user'); client.send({ event: 'disconnect' }); client.connection.end(); fn(); return; } First we are going to give socket.io some teeth (get it, meaner socket.io? it bites? yes I am funny). When we have a client that shouldn’t be connected, kick ‘em off!. disconnectAndRedirectClient() takes a client socket.io object and a callback. socket.on('connection', function(client){ client.connectSession = function(fn) { if (!client.request || !client.request.headers || !client.request.headers.cookie) { disconnectAndRedirectClient(client,function() { console.log('Null request/header/cookie!'); }); return; } var match = client.request.headers.cookie.match(/connect\.sid=([^;]+)/); if (!match || match.length < 2) { disconnectAndRedirectClient(client,function() { console.log('Failed to find connect.sid in cookie'); }); return; } var sid = unescape(match[1]); rc.get(sid, function(err, data) { fn(err, JSON.parse(data)); }); }; client.connectSession(function(err, data) { if(err) { console.log('Error on connectionSession: ' + err); return; } client.user = data.user; activeClients += 1; client.on('disconnect', function(){clientDisconnect(client)}); client.on('message', function(msg){chatMessage(client, socket, msg)}); socket.broadcast({ event: 'update', clients: activeClients }); var ponyWelcome = new models.ChatEntry({name: 'PonyBot', text: 'Hello ' + data.user.name + '. I also feel that ponies ' + data.user.ponies + '. Welcome to nodechat.js'}); socket.broadcast({ event: 'chat', data: ponyWelcome.xport() }); }); }); There is a lot going on here, but much of this code is unchanged from v0.1. First, we are defining a helper method, connectSession, that will verify a client’s validity by checking for a cookie in the request header, then, if we find it, pulling their session out of redis! We then use the helper method in the ‘connection’ handler for our socket listener. Now instead of just accepting any old user connection, we are going to check that the client has a valid session (meaning they logged in). If they don’t, give them the boot! If they do, then we store a copy of the session data (yay we have access!) in the client object and then set up the rest of the socket events. Finally, send them a welcome message just to prove that we remembered their profile. connect-redis One last aside: connect-redis by visionmedia (I love his stuff!) is a connect session store the is backed by redis. It sets a cookie to track the session id, but it stores all other data in redis. This is really nice because a) we don’t have to worry about leaving cookies with critical data on the client, and b) we can grab the session data straight out of redis and give it to socket.io. We still have to parse the cookie to get the session id, but at least that is all we have to worry about. function chatMessage(client, socket, msg){ var chat = new models.ChatEntry(); chat.mport(msg); rc.incr('next.chatentry.id', function(err, newId) { chat.set({id: newId}); nodeChatModel.chats.add(chat); var expandedMsg = chat.get('id') + ' ' + client.user.name + ': ' + chat.get('text'); rc.rpush('chatentries', chat.xport(), redis.print); socket.broadcast({ event: 'chat', data:chat.xport() }); }); } The only material difference in chatMessage() is that we no longer simply believe the client when they tell us their name. Instead we use our newly found session power to tell them what their name is. And prevent fraud and stuff. Oh, and I also removed the call to rc.bgSave(). Because it was crashing during concurrent saves. If you want to persist your chats permanently, use the snapshotting method described by redis here. Wrapping it up That is about it. There may be some minor changes in some of the other files, so it never hurts to get the code from the v0.2 tag at github. I want to close by saying that this method of authentication works and it has worked well enough to run in “production” on nodechat.no.de for several weeks. We do experience some funky issues once clients start falling back to xhr-polling and jsonp-polling, so be warned. This is the bleeding edge folks. Treat it as such. My plan is to follow up with a different take on the authentication issue, one in which we ditch sessions altogether and use a shared key (like the hash) to sign each message over the socket. I’ll write it up if it works. Finally, I want to say thanks to everyone who sent me email, tweets, or stopped by nodechat to… chat. It has been fantastic meeting you all and I look forward to seeing all the cool stuff you guys are cranking out. Follow me on twitter @jdslatts, email me at comments@fzysqr.com, or stop by nodechat.no.de and say hi! -jslatts
http://fzysqr.com/2011/03/27/nodechat-js-continued-authentication-profiles-ponies-and-a-meaner-socket-io/
CC-MAIN-2015-27
refinedweb
3,296
59.5
GraphX API in Apache Spark: An Introductory Guide 1. Objective – Spark GraphX API For graphs and graph-parallel computation, Apache Spark has an additional API, GraphX. In this blog, we will learn the whole concept of GraphX API in Spark. We will also learn how to import Spark and GraphX into the project. Moreover, we will understand the concept of Property Graph. Also, we will cover graph operators and Pregel API in detail. In addition, we will also learn the features of GraphX. Furthermore, we will see the use cases of GraphX API. So, let’s start the Spark GraphX API tutorial. Test how much you know about Spark 2. Introduction to Spark GraphX API For graphs and graph-parallel computation, Apache Spark has an additional API, GraphX. To simplify graph analytics tasks it includes the collection of graph algorithms & builders. In addition, it extends the Spark RDD with a Resilient Distributed Property Graph. Basically, the property graph is a directed multigraph. It has multiple edges in parallel. Here, every vertex and edge have user-defined properties associated with it. Moreover, parallel edges allow multiple relationships between the same vertices. 3. Getting Started with GraphX You first need to import Spark and GraphX into your project, To get started, code as Follows: import org.apache.spark._ import org.apache.spark.graphx._ // To make some of the examples work we will also need RDD import org.apache.spark.rdd.RDD Note: you will also need a SparkContext if you are not using the Spark shell. Let’s discuss Spark Structured Streaming 4. The Property Graph A directed multigraph with user-defined objects attached to each vertex and edge is a property graph. It is a graph with potentially multiple parallel edges. They are also sharing the same source and destination vertex. Where there can be multiple relationships between the same vertices, they are able to support parallel edges. It also simplifies modeling scenarios. By a unique 64-bit long identifier (VertexId) each vertex is keyed. It does not impose any ordering constraints on the vertex identifiers. Hence, edges have corresponding source and destination vertex identifiers. Basically, it is parameterized over the vertex (VD) and edge (ED) types. Ultimately, these are the types of the objects those are associated with each vertex and edge respectively. Some more Insights In addition, it optimizes the representation of vertex and edge types. While they are primitive data types it reduces the in memory footprint. Even by storing them in specialized arrays. As same as RDDs, property graphs are also immutable, distributed, and fault-tolerant. we can produce a new graph with the desired changes by changing the values or structure of the graph. We can reuse substantial parts of the original graph in the new graph. It also reduces the cost of this inherently functional data structure. Using a range of vertex partitioning heuristics, a graph is partitioned across the executors. In the event of a failure, each partition of the graph can be recreated on a different machine. Have a look at Spark machine Learning with R 5. Spark Graph Operators As same as RDDs basic operations like map, filter, property graphs also have a collection of basic operators. Those operators take UDFs (user defined functions) and produce new graphs. Moreover, these are produced with transformed properties and structure. In GraphX, there are some core operators defined that have optimized implementations. While in GraphOps there are some convenient operators that are expressed as compositions of the core operators. Although, Scala operators in GraphOps are automatically available as members of Graph. Example of Spark Graph Operators To compute in-degree of each vertex (defined in GraphOps): val graph1: Graph[(String, String), String] // Use the implicit GraphOps.inDegrees operator val inDegrees1: VertexRDD[Int] = graph.inDegrees1 The only difference between core graph operations and GraphOps is different graph representations. In addition, it is must that each graphical representation provides an implementation of the core operations. We can reuse many of the useful GraphOps operations. There is a set of fundamental operators. For example. Subgraph, joinVertices, and aggregateMessages. Let’s discuss all in detail: a. Structural Operators It supports a simple set of commonly used structural operators. The following is a list of the basic structural operators in Spark.] } i. The reverse operator With all the edge directions reversed, it returns a new graph. when trying to compute the inverse PageRank, this can be very useful. ii. The subgraph operator It returns the graph containing only the vertices, by taking vertex and edge predicates. We can use subgraph operator to restrict the graph to the vertices and edges of interest. Also to eliminate broken links. Have a look at Spark stage iii. The mask operator It constructs a subgraph by returning a graph that contains the vertices and edges that are also found in the input graph. We can use it in conjunction with the subgraph operator to restrict a graph based on the properties in another related graph. iv. The groupEdges operator It merges parallel edges in the multigraph. b. Join Operators Sometimes it is the major requirement to join data from external collections (RDDs) with graphs. Like it is possible that we have extra user properties that we want to merge with an existing graph. Also, we might want to pull vertex properties from one graph into another. Hence, we can accomplish it by using the join operators. In addition, there are two Join operators, joinvertices, and Outerjoinvertices. You must learn Spark executor] } c. Aggregate Messages (aggregateMessages) In GraphX, the core aggregation operation is aggregateMessages. It applies a user-defined sendMsg function to each edge triplet in the graph. Afterwards, it] } 6. Pregel API Since properties of vertices depend on properties of their neighbors, Graphs are inherently recursive data structures. That, in turn, depend on properties of their neighbors. As a matter of fact, many important graph algorithms iteratively recompute the properties of each vertex. It recomputes until it reaches a fixed-point condition. Basically, To express these iterative algorithms it proposes a graph-parallel abstraction. Hence, there is a variant of the Pregel API, exposed by GraphX. 7. Spark GraphX Features The features of Spark GraphX are as follows: a. Flexibility We can work with both graphs and computations with Spark GraphX. It includes exploratory analysis, ETL (Extract, Transform & Load), the iterative graph in 1 system. It is possible to view the same data as both graphs, collections, transform and join graphs with RDDs. Also using the Pregel API it is possible to write custom iterative graph algorithms. b. Speed It offers comparable performance to the fastest specialized graph processing systems. Also comparable with the fastest graph systems. Even while retaining Spark’s flexibility, fault tolerance and ease of use. c. Growing Algorithm Library Spark GraphX offers growing library of graph algorithms. Basically, We can choose from it. For example pagerank, connected components, SVD++, strongly connected components and triangle count. 8. Conclusion – GraphX API in Spark As a result, we have learned the whole concept of GraphX API. Moreover, we have covered the brief introduction of Operators and Variant, Pregel API. Also, we have seen how GraphX API in Apache Spark: An Introductory Guide simplifies graph analytics tasks in Spark. Hence, GraphX API is very useful for graphs and graph-parallel computation in Spark. See also –
https://data-flair.training/blogs/graphx-api-spark/
CC-MAIN-2019-35
refinedweb
1,223
58.99
add the codes below into dolphin / inc / design.inc.php Line133 <pre lang="php" line="1"> / / Members Only - begin if (isMember ()) { header ('Content-type: text / html; charset = utf-8'); $ Echo ($ oTemplate, 'page_'. $ _page [' Apache's default index page is index.html, change into other documents need to modify the httpd.conf file: # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # <IfModule dir_module> DirectoryIndex index.html inde Technical Overview Jump to: Search Advertisement Apps Google Mobile and Android Google Chrome browser, More ... Since we can not limited to a page about our many products and services for all technology development, the following Google products only Transfer: First, the primary key and clustered index is not a one to one match Under normal circumstances we believe that the clustered index and primary key are matched, as long as you SQLServer tab Make sure your navigation is in the form of html links. All pages should be made between a wide range of Internet, if this is not possible, consider creating a site map. In a page so that customers can easily jump to the page you want to visit. So as Commonly used system variables as follows: 1.sy-pagno current page number 2.SY-DATUM current time 3.SY-LINSZ the width of the current report 4.SY-LINCT the length of the current report 5.SPACE null 6.SY-SUBRC implementation status of 0 indicates succ Memory space, Modify or increase the swap partition space innodb_buffer_pool_size To manually add SWAP space Linux system In the SWAP space not enough, how to manually add SWAP space? The following operations must be carried out under the root user: page that page show that the number of each page pagesize conditon that some of the conditions SELECT sql_no_cache * FROM table WHERE id> = (SELECTsql_no_cache id FROM table where conditon ORDER BY id DESC LIMIT 126380,1) limit 20; Optimization of qu Learned friends for the database will not be unfamiliar with the software SQL Server, SQL Server 2005 has been called the developer version of SQL Server 2008 and later SQL Server 2008 R2 features are its rich developer has won approval . In November Framework provided by Swoole WebService class and RestClient class, you can easily achieve Webservice and remote interface calls. Can be used in, the site offers outside API, or a large site within the system call interface between different modules. In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server Compact. In this tutorial you will review and customize the CRUD (create, read, update, delete) code that the MVC scaffold In the previous tutorial you implemented a set of web pages for basic CRUD operations for Student entities. In this tutorial you'll add sorting, filtering, and paging functionality to the Students Index page. You'll also create a page that does simpl Version: CodeIgniter_2.0.1 Hope that CI does not contain the index.php URL application For example: Want to become like This url is more beautiful, perhaps this seo-frien Abstract: The index is the impact of relational database (RDBMS) performance is one important factor. Today's popular relational databases such as SQL Server, Sybase, Oracle, DB2, etc., OR, in the efficiency in the end, and which union all queries quickly. Many voices are saying online union all faster or, in, as or, in will lead to full table scans, they give a lot of examples. But really really fast in the union all or, in? This a OR, in and union all query efficiency which in the end fast. Many voices are saying online union all faster than or, in, as or, in will lead to full table scans, they give a lot of instances. But the union all really really faster than or, in? This a Original sql: select * from ( select a. *, rownum rn from (Select * from product a where company_id =? Order by status) a where rownum <= 20) where rn> 10; Optimization: Optimization principle is to find pages indexed by record net ROWID, then retur Description: Suppose there are two pages, index.html and inner.html. Index.html which has a iframe, the iframe's src points to inner.html. We now have to do is: 1. In index.html called inner.html on a js method 2. In inner.html called index.html on a In the project, we often encountered or used in paging, then the large amount of data (one million or more) under which the efficiency of the best paging algorithm it? We might speak with the facts. Test environment Hardware: CPU Core Duo T5750 Memor Stored within the system has a special system variable structure SYST, one of the most commonly used system variables are: SY-SUBRC: system to perform a command, said the success of the implementation of the variable, '0 'indicates success SY-UNAME: Today, see this piece of code, as follows: Page.clickFunctions = []; Page.click = function(event){ for(var i=0;i<Page.clickFunctions.length;i++){ Page.clickFunctions[i](event); } if(window!=window.parent&&window.parent.Page){ window.parent.Page First, the file structure <br /> site css styles, images, js placement path: WebRoot / res_base / Html Page How to reference: $ {root} is the WebRoot / res_base / path examples: 1 ${root}/fgw/article/css/common.css Place the template path to front: Clustered index key value that is based on data in the table row sort and store the data lines. Each table can have only one clustered index, because the data rows themselves can only be stored in a sequence. To some extent, the clustered index that rails 3 new XXS mechanism, resulting in the output html tags to verify the time, when using the will_paginate have some problems, showed no paging interface, such as: <span> <<Previous </ span> <span> 1 </ span> <a href=&q Click to submit it for print prompt box approach: index page with the js control: # {Hidden_print ("# {url_for (**,: id => **,: pop => true,: print => true )}")} When the jump when the transfer is: destroys_path (: print => params [: Recently made a demo, using HTML + JS + CSS do Android client. Understand that the power lies in WebView Java and javascript can call each other. Java and javascript focus on how to analyze each call. Look at the Activity code: public class WebViewer ExtJs today try to write a page to show, is a big box, no function, when the application for later reference, the page structure is: a tree on the left, right a tabPanel, tabPanel iframe set by a Grid, First index page index page to define a <div> & Yesterday, the host application to add a Codeigniter, but that can only access to the home page, other are shown No Find. Next I realized that godaddy google does not support the URL routing in the $ _SERVER ['PATH_INFO']. About $ _SERVER routing exa First of all talk about the benefits of indexing, a feature these days do, write a stored procedure when the data is 4000, when even run 30 minutes, plus index and after optimization, as long as the 30s a little more, so the index really very importa If you use a mirror and what will happen as a surfboard? Perhaps you will conquer the waves within a short period of time, but you certainly know from the heart, this is not the right choice for surfing. The same applies to PHP programming, although / / Change the index page protected void gv_PageIndexChanging (object sender, GridViewPageEventArgs e) { gv.PageIndex = e.NewPageIndex; gv.DataSource = selectAllTitle (); gv.DataBind (); ) / / When click Edit protected void gv_RowEditing (object send Class prepared to index Book package objectSearcherTest; import org.compass.annotations.Index; import org.compass.annotations.Searchable; import org.compass.annotations.SearchableId; import org.compass.annotations.SearchableProperty; import org.compa 6.4 Function Outlook 6.4.1 use the theme without adding any code, our blog can be themed. In order to use the theme, need to write custom view files in the theme. For example, using a theme called classic, and different page layout, to create a layou Outlook 6.4 features 6.4.1 does not add any code to use the theme of our blog to be themed. In order to use themes, you need to write custom view files in the theme. For example, using a theme called classic, and different page layout, to create a la Almost all of the seam in the document will be presented with plenty of space to describe a session (conversation), because it is the seam of the invention, a unique place to seam. However, to fully understand and apply the conversation is not easy. Django recently with a small thing to do, what the directory structure are set up, and write views.py. Because only a test, so the output of a string that click on it and began: def index(request): return HttpResponse("index page!") def foo(requ Recent crunching codeIgniter, feeling quickly get started, make a second-level domain name rental stations of the recent record of what the problems Local test environment, window server 2003 + appserver 2.5.9 config configuration file is as follows CI in default in the url with index.php, for example Remove the index.php steps: 1. Open the apache configuration file, conf / httpd.conf: LoadModule rewrite_module modules / mod_rewrite.so, to remove th Original Address: [ be easily applied to the Rails in GoogleMap My cartographer plug-in is downloaded here: According the above steps to do next in the rails in the data As we all know, eclipse of the project bulid path can refer to a third party in the library (Figure 1), Figure 1 However, this approach has a drawback: a reference to the library through the absolute path. If you have two computers (office 1 units, h codeigniter learning 1 1 ci of the library and the helper, experience should be called the traditional approach is as follows:, $ This-> load-> library ('pagination'); $ This-> load-> helper ('form'); But often this is trouble, you can system Some time ago introduced jeecms secondary development , but did not specifically say how the second development on the jeecms, today make up. Finishing is very messy, but certainly nothing jeecms secondary development problems. 1, file structure <br Nutch is divided into two parts: the crawler crawler and query searcher. Crawler is mainly used to grab pages from the network and for those pages indexed. Searcher main advantage of these indexes retrieve the user's search keywords to generate searc jboss seam support before loading the page, call the action in page.xml initialization page. For example: To access the page for the index.xhtml, rendering the page you want to call an action before the initialization page. Seam can then write a inde Do seo optimized friends know well by viewing the logs can help yourself website optimization and view your site if there is any hidden dangers. But Pan also found that online search online checked out many explanations are rather vague people to und Create the project is successful, delete the public the following new index_controller index page Add name to "index" of the action Configure routing map.root: controller =>: index Open Service Access Home always prompt error, wondering for a Create the project is successful, delete the public the following new index_controller index page Add name to "index" of the action Configure routing map.root: controller =>: index Open Service Access Home always prompt error, wondering for a I saw a few small projects EXT, They are in the login is successful, redirect to the index page Then once in this index which all of the js are loaded in. This does not not bad? If the project is slightly larger, there may be two 300 js Do not just l SQL when a new table is created when, the system will be allocated in a Yi 8K disk unit of the continuous space, when the field value from memory is written to disk, in this very established space Suiji preserved when an 8K with the When finished, SQ RESTFUL URL RULE -------------------------------------------------- -------------------------------------------------- ----- ACTION URL METHOD meaning of the corresponding VM compatible browser address URL (PUT DELETE) ------------------------------- CodeWeblog.com 版权所有 闽ICP备15018612号 processed in 0.043 (s). 10 q(s)
http://www.codeweblog.com/tag/index-page/
CC-MAIN-2018-17
refinedweb
2,042
59.53
Is it possible? If yes, how? Have you checked wxpython demo? if no Download it and play around with it Not sure if it is possible Yes, I've already seen that, but there's no such thing... I hear it's a windows vista api called dwm. Is there a way to access it from python? I dont know. May be wxpython lists may be best place for the question. Don't forget to be back when you have an answer: Yes there is a way. Use python's ctypes Maybe someone else can give you an example of how to use it. Or maybe you can just look at the documentation (it's not hard). but how do I access that dll, I mean where is it placed. it should be dwm.dll or something (desktop window manager) You don't need to know where the dll is placed (you don't redistribute it). In your python code, you just do: import ctypes.windll.dwmapi as dwm There is no such module Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import ctypes.windll.dwmapi as dwm ImportError: No module named windll.dwmapi There is no such module Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import ctypes.windll.dwmapi as dwm ImportError: No module named windll.dwmapi Yeah that's my bad: import ctypes dwm = ctypes.windll.dwmapi What should I do now? Sorry, I have no clue about ctypes. I don't know :-/. I don't even really know what exactly you're trying to do except that it involves dwmapi. ...
https://www.daniweb.com/programming/software-development/threads/197542/windows-vista-blur-using-wxpython
CC-MAIN-2018-43
refinedweb
272
86.4
Styled-components, what are they? The result of thinking about how to enhance the CSS for component systems styling in React. A JavaScript subset, it mainly provides static classes, interfaces, as well as static typing. One of the most noticeable TypeScript pros is enabling IDEs to provide a richer environment that could see common errors in code typing. It streamlines Java code, which makes reading and debugging so much easier. Use TypeScript with Styled Components It’s great to use styled-components with React, as well as React native. However, it truly shines when using it with VS Code, getting suggestions about the code and errors when writing an error. The components help keep problems regarding the separation of styling and architecture, which makes for a more readable code. In addition, should there be components relying on JavaScript, the components provide control over the states, and then back to CSS, and not using many conditional class names instead. When transitioning most projects to include TypeScript, some things would feel perfect. Consider checking them out. 1. Types Installation Styled components do not ship with types. Rather, you need to install it from the repository called the Definitely Typed. npm i --save-dev @types/styled-components 2. Customized props Using a CSS in a JavaScript solution has one particular major advantage, and this the ability of passing customized props on the runtime, as well as accordingly adapting CSS. const HeaderTitle = styled.h1<{ isActive: boolean }>` color: ${props=>(props.isActive ? 'green' : 'red' )} `; Similar to JSX elements, the generic type could be passed after the component with <>. Now, what you have is a typed styled-component, and thus will become a static element error if unable to pass the active prop. To extend the component, you can use it like this: import Title from './Title' const HeaderTitle = styled(Title)<{ isActive: boolean }>` color: ${props=>(props.isActive ? 'green' : 'red' )} `; Keep in mind however that active as a prop is passed to the Title component even if not explicitly stated so. Later, if someone adds an optional prop to the component, this could be a concern. You can nonetheless refactor to avoid this, such as: const HeaderTitle = styled(({ isActive, ...rest }) => <Title {...rest} />)<{ isActive: boolean; }>` color: ${props => (props.isActive ? 'green' : 'red')}; `; This syntax however obviously is more intricate, and builds additional component. If the mess is worth uncovering an accidental prop, it would be your decision. 3. Typing a Theme With the help of the ThemeProvider, Styled Components could specify a theme. The autocomplete form itself form the theme object is worth doing even if you steer away from everything else. The first thing to do is to build a declarations file. For instance, we shall call it styled.d.ts. // import original module declarations import 'styled-components'; // and extend them! declare module 'styled-components' { export interface DefaultTheme { fontSize:{ body: string; h1: string; h2: string; h3: string; h4: string; h5: string; h6: string; }, colors: { main: string; secondary: string; }; } } Typing the theme manually like this is hard however, mainly due to the fact that every time you add or remove something form the theme object, you have to edit a couple of files. Rather, consider doing this: import {} from 'styled-components'; import myTheme from '../custom-theme'; declare module 'styled-components' { type Theme = typeof myTheme; export interface DefaultTheme extends Theme {} } We make use of the type inference of TypeScript here for the theme object to do it. 4. Using the CSS Prop In the Styled Components documentation, there are a couple of CSS functions. Here specifically is the attribute of CSS that could be utilized on an element when a Babel plugin is enabled. <div css={` display: block; `} > ... </div> Unfortunately, TypeScript does not know about this CSS property, and makes an error. To resolve this, consider the following styled.d.ts: import {} from 'styled-components'; import { CSSProp } from 'styled-components'; declare module 'react' { interface Attributes { css?: CSSProp | CSSObject; } } 5. The Media Templates Specifying media queries from documentation has an easy way. However, while the syntax is user-friendly, the implementation is difficult to reason for TypeScript, and for new users too as it happens. Consider the following seamless option: const customMediaQuery = (maxWidth: number) => `@media (max-width: ${maxWidth}px)`; const media = { custom: customMediaQuery, desktop: customMediaQuery(992), tablet: customMediaQuery(768), phone: customMediaQuery(576), }; const ContentBlock = styled.div` width: 4em; height: 4em; background: white; /* Now we have our methods of raw queries */ ${media.desktop} { background: green; } ${media.tablet} { background: yellow; } ${media.phone} { background: blue; } `; render(<ContentBlock />); The Pros of TypeScript - Helps deal with growing teams - Code scalability - Compliance to ES-next - Awesome tooling and community effort - Types boost agility when refactoring. It’s also better for a compiler to catch errors than having things fail during runtime - Have a proven ability of enhancing the quality and understandability of code. - With typing, it provides a taste of the future of JavaScript - One of the best forms of documentation. - With auto-injection libraries combined, the code-base is truly predictable and maintainable. - The dependency injection opens up a lot of opportunities for cool testing, and make sure that the APIs are controller-based. - The Dependency Injections makes for easy testing. - Supports change and innovation, with safety measures that ensure it won’t entirely go the wrong way. - Helps in the implementation of sturdy design patterns into a language that does not really support it. - Make more readable code, helping developers remember what every code piece is supposed to do fast. - Could compile down to a JavaScript version, which runs on all browsers. - The code completion IntelliSense provides active hints that a code is being added. - Very easily write pure TypeScript object-oriented code with less knowledge. - The static typing feature detects a bug or bugs as a developer is writing the scripts. This enables a developer to write more sturdy code, maintain it, which result in cleaner, better code. - TypeScript tools make refactoring faster and easier. Why Styled Components? 1. Makes less bulky components. There would be plenty of heavy lifting done via the CSS for injecting styling towards a component that’s user-centered. Majority of the methods id render components end up with style objects, which clutter and splits the CSS into two, making the code parsing process difficult. Styled components however keep the element architecture and styling separated, and make more readable components. 2. CSS Function. Props could be used to render CSS conditionally, meaning that there’s no need to render conditional classes names that are props-based. This minimizes components clutter, and maintaining a separation of issues between JavaScript and CSS. 3. ThemeProvider. Severing as the wrapper, it injects props into all the child components. It’s significantly useful when creating a ‘configuration’ page, which is a duplicate page essentially, letting users perform customizations to specific stylistic elements, such as color in particular. 4. Test. Testing of the styled components is painless through building class names that are consistent. Moreover, it also enables asserting certain CSS rules, which could be relevant to the app’s integrity. Conclusion Styled-components overall, have made creating apps with TypeScript more enjoyable. The styles are a neat approach to scoping styles. TypeScript could be leveraged to have a strong-typing in props passed to the styled components. The styled components have over 5.7 million downloads per month from npm, more than 27.8 GitHub stars, as well as hundreds of open source contributors, thus it’s here to stay. Author Profile: V K Chaudhary working as a project manager in a software development company Tatvasoft.com. He is a technical geek and also managing some online campaigns for his.
https://codinginfinite.com/using-typescript-with-styled-components/
CC-MAIN-2020-50
refinedweb
1,265
56.45
commit b450b2007d1975730eb75be5a050591fd00e2024 Author: George Dunlap <george.dunlap@xxxxxxxxxx> AuthorDate: Tue Mar 5 15:14:54 2019 +0100 Commit: Jan Beulich <jbeulich@xxxxxxxx> CommitDate: Tue Mar 5 15:14:54 2019 +0100 xen: Make coherent PV IOMMU discipline In order for a PV domain to set up DMA from a passed-through device to one of its pages, the page must be mapped in the IOMMU. On the other hand, before a PV page may be used as a "special" page type (such as a pagetable or descriptor table), it _must not_ be writable in the IOMMU (otherwise a malicious guest could DMA arbitrary page tables into the memory, bypassing Xen's safety checks); and Xen's current rule is to have such pages not in the IOMMU at all. At the moment, in order to accomplish this, the code borrows HVM domain's "physmap" concept: When a page is assigned to a guest, guess_physmap_add_entry() is called, which for PV guests, will create a writable IOMMU mapping; and when a page is removed, guest_physmap_remove_entry() is called, which will remove the mapping. Additionally, when a page gains the PGT_writable page type, the page will be added into the IOMMU; and when the page changes away from a PGT_writable type, the page will be removed from the IOMMU. Unfortunately, borrowing the "physmap" concept from HVM domains is problematic. HVM domains have a lock on their p2m tables, ensuring synchronization between modifications to the p2m; and all hypercall parameters must first be translated through the p2m before being used. Trying to mix this locked-and-gated approach with PV's lock-free approach leads to several races and inconsistencies: * A race between a page being assigned and it being put into the physmap; for example: - P1: call populate_physmap() { A = allocate_domheap_pages() } - P2: Guess page A's mfn, and call decrease_reservation(A). A is owned by the domain, and so Xen will clear the PGC_allocated bit and free the page - P1: finishes populate_physmap() { guest_physmap_add_entry() } Now the domain has a writable IOMMU mapping to a page it no longer owns. * Pages start out as type PGT_none, but with a writable IOMMU mapping. If a guest uses a page as a page table without ever having created a writable mapping, the IOMMU mapping will not be removed; the guest will have a writable IOMMU mapping to a page it is currently using as a page table. * A newly-allocated page can be DMA'd into with no special actions on the part of the guest; However, if a page is promoted to a non-writable type, the page must be mapped with a writable type before DMA'ing to it again, or the transaction will fail. To fix this, do away with the "PV physmap" concept entirely, and replace it with the following IOMMU discipline for PV guests: - (type == PGT_writable) <=> in iommu (even if type_count == 0) - Upon a final put_page(), check to see if type is PGT_writable; if so, iommu_unmap. In order to achieve that: - Remove PV IOMMU related code from guest_physmap_* - Repurpose cleanup_page_cacheattr() into a general cleanup_page_mappings() function, which will both fix up Xen mappings for pages with special cache attributes, and also check for a PGT_writable type and remove pages if appropriate. - For compatibility with current guests, grab-and-release a PGT_writable_page type for PV guests in guest_physmap_add_entry(). This will cause most "normal" guest pages to start out life with PGT_writable_page type (and thus an IOMMU mapping), but no type count (so that they can be used as special cases at will). Also, note that there is one exception to to the "PGT_writable => in iommu" rule: xenheap pages shared with guests may be given a PGT_writable type with one type reference. This reference prevents the type from changing, which in turn prevents page from gaining an IOMMU mapping in get_page_type(). It's not clear whether this was intentional or not, but it's not something to change in a security update. This is XSA-288. Reported-by: Paul Durrant <paul.durrant@xxxxxxxxxx> Signed-off-by: George Dunlap <george.dunlap@xxxxxxxxxx> Signed-off-by: Jan Beulich <jbeulich@xxxxxxxx> master commit: fe21b78ef99a1b505cfb6d3789ede9591609dd70 master date: 2019-03-05 13:48:32 +0100 --- xen/arch/x86/mm.c | 95 ++++++++++++++++++++++++++++++++++++++++++++++----- xen/arch/x86/mm/p2m.c | 57 ++++++++++++++----------------- 2 files changed, 111 insertions(+), 41 deletions(-) diff --git a/xen/arch/x86/mm.c b/xen/arch/x86/mm.c index 67f6cfc1d5..6cf07763a0 100644 --- a/xen/arch/x86/mm.c +++ b/xen/arch/x86/mm.c @@ -81,6 +81,22 @@ * OS's, which will generally use the WP bit to simplify copy-on-write * implementation (in that case, OS wants a fault when it writes to * an application-supplied buffer). + * + * PV domUs and IOMMUs: + * -------------------- + * For a guest to be able to DMA into a page, that page must be in the + * domain's IOMMU. However, we *must not* allow DMA into 'special' + * pages (such as page table pages, descriptor tables, &c); and we + * must also ensure that mappings are removed from the IOMMU when the + * page is freed. Finally, it is inherently racy to make any changes + * based on a page with a non-zero type count. + * + * To that end, we put the page in the IOMMU only when a page gains + * the PGT_writeable type; and we remove the page when it loses the + * PGT_writeable type (not when the type count goes to zero). This + * effectively protects the IOMMU status update with the type count we + * have just acquired. We must also check for PGT_writable type when + * doing the final put_page(), and remove it from the iommu if so. */ #include <xen/init.h> @@ -2252,19 +2268,79 @@ static int mod_l4_entry(l4_pgentry_t *pl4e, return rc; } -static int cleanup_page_cacheattr(struct page_info *page) +/* + * In the course of a page's use, it may have caused other secondary + * mappings to have changed: + * - Xen's mappings may have been changed to accomodate the requested + * cache attibutes + * - A page may have been put into the IOMMU of a PV guest when it + * gained a writable mapping. + * + * Now that the page is being freed, clean up these mappings if + * appropriate. NB that at this point the page is still "allocated", + * but not "live" (i.e., its refcount is 0), so it's safe to read the + * count_info, owner, and type_info without synchronization. + */ +static int cleanup_page_mappings(struct page_info *page) { unsigned int cacheattr = (page->count_info & PGC_cacheattr_mask) >> PGC_cacheattr_base; + int rc = 0; + unsigned long mfn = mfn_x(page_to_mfn(page)); - if ( likely(cacheattr == 0) ) - return 0; + /* + * If we've modified xen mappings as a result of guest cache + * attributes, restore them to the "normal" state. + */ + if ( unlikely(cacheattr) ) + { + page->count_info &= ~PGC_cacheattr_mask; - page->count_info &= ~PGC_cacheattr_mask; + BUG_ON(is_xen_heap_page(page)); - BUG_ON(is_xen_heap_page(page)); + rc = update_xen_mappings(mfn, 0); + } - return update_xen_mappings(mfn_x(page_to_mfn(page)), 0); + /* + * If this may be in a PV domain's IOMMU, remove it. + * + * NB that writable xenheap pages have their type set and cleared by + * implementation-specific code, rather than by get_page_type(). As such: + * - They aren't expected to have an IOMMU mapping, and + * - We don't necessarily expect the type count to be zero when the final + * put_page happens. + * + * Go ahead and attemp to call iommu_unmap() on xenheap pages anyway, just + * in case; but only ASSERT() that the type count is zero and remove the + * PGT_writable type for non-xenheap pages. + */ + if ( (page->u.inuse.type_info & PGT_type_mask) == PGT_writable_page ) + { + struct domain *d = page_get_owner(page); + + if ( d && is_pv_domain(d) && unlikely(need_iommu(d)) ) + { + int rc2 = iommu_unmap_page(d, mfn); + + if ( !rc ) + rc = rc2; + } + + if ( likely(!is_xen_heap_page(page)) ) + { + ASSERT((page->u.inuse.type_info & + (PGT_type_mask | PGT_count_mask)) == PGT_writable_page); + /* + * Clear the type to record the fact that all writable mappings + * have been removed. But if either operation failed, leave + * type_info alone. + */ + if ( likely(!rc) ) + page->u.inuse.type_info &= ~(PGT_type_mask | PGT_count_mask); + } + } + + return rc; } void put_page(struct page_info *page) @@ -2280,7 +2356,7 @@ void put_page(struct page_info *page) if ( unlikely((nx & PGC_count_mask) == 0) ) { - if ( cleanup_page_cacheattr(page) == 0 ) + if ( !cleanup_page_mappings(page) ) free_domheap_page(page); else gdprintk(XENLOG_WARNING, @@ -3978,9 +4054,10 @@ int steal_page( * NB this is safe even if the page ends up being given back to * the domain, because the count is zero: subsequent mappings will * cause the cache attributes to be re-instated inside - * get_page_from_l1e(). + * get_page_from_l1e(), or the page to be added back to the IOMMU + * upon the type changing to PGT_writeable, as appropriate. */ - if ( (rc = cleanup_page_cacheattr(page)) ) + if ( (rc = cleanup_page_mappings(page)) ) { /* * Couldn't fixup Xen's mappings; put things the way we found diff --git a/xen/arch/x86/mm/p2m.c b/xen/arch/x86/mm/p2m.c index c72a3cdebb..7a52ba993e 100644 --- a/xen/arch/x86/mm/p2m.c +++ b/xen/arch/x86/mm/p2m.c @@ -714,23 +714,9 @@ p2m_remove_page(struct p2m_domain *p2m, unsigned long gfn_l, unsigned long mfn, p2m_type_t t; p2m_access_t a; + /* IOMMU for PV guests is handled in get_page_type() and put_page(). */ if ( !paging_mode_translate(p2m->domain) ) - { - int rc = 0; - - if ( need_iommu(p2m->domain) ) - { - for ( i = 0; i < (1 << page_order); i++ ) - { - int ret = iommu_unmap_page(p2m->domain, mfn + i); - - if ( !rc ) - rc = ret; - } - } - - return rc; - } + return 0; ASSERT(gfn_locked_by_me(p2m, gfn)); P2M_DEBUG("removing gfn=%#lx mfn=%#lx\n", gfn_l, mfn); @@ -775,26 +761,33 @@ guest_physmap_add_entry(struct domain *d, gfn_t gfn, mfn_t mfn, int pod_count = 0; int rc = 0; + /* IOMMU for PV guests is handled in get_page_type() and put_page(). */ if ( !paging_mode_translate(d) ) { - if ( need_iommu(d) && t == p2m_ram_rw ) - { - for ( i = 0; i < (1 << page_order); i++ ) - { - rc = iommu_map_page(d, mfn_x(mfn_add(mfn, i)), - mfn_x(mfn_add(mfn, i)), - IOMMUF_readable|IOMMUF_writable); - if ( rc != 0 ) - { - while ( i-- > 0 ) - /* If statement to satisfy __must_check. */ - if ( iommu_unmap_page(d, mfn_x(mfn_add(mfn, i))) ) - continue; + struct page_info *page = mfn_to_page(mfn); - return rc; - } - } + /* + * Our interface for PV guests wrt IOMMU entries hasn't been very + * clear; but historically, pages have started out with IOMMU mappings, + * and only lose them when changed to a different page type. + * + * Retain this property by grabbing a writable type ref and then + * dropping it immediately. The result will be pages that have a + * writable type (and an IOMMU entry), but a count of 0 (such that + * any guest-requested type changes succeed and remove the IOMMU + * entry). + */ + if ( !need_iommu(d) || t != p2m_ram_rw ) + return 0; + + for ( i = 0; i < (1UL << page_order); ++i, ++page ) + { + if ( get_page_and_type(page, d, PGT_writable_page) ) + put_page_and_type(page); + else + return -EINVAL; } + return 0; } -- generated by git-patchbot for /home/xen/git/xen.git#staging.
https://lists.xenproject.org/archives/html/xen-changelog/2019-03/msg00060.html
CC-MAIN-2022-40
refinedweb
1,695
55.58
NAME CSS::Adaptor::Whitelist -- filter out potentially dangerous CSS SYNOPSIS use CSS use CSS::Adaptor::Whitelist; my $css = CSS->new({ adaptor => 'CSS::Adaptor::Whitelist' }); $css->parse_string( <<EOCSS ); body { margin: 0; background-image: url(javascript:alert("I am an evil hacker")); } #main { background-color: yellow; content-after: '<img src="">'; } EOCSS print $css->output; # prints: # body { # margin: 0; # } # #main { # background-color: yellow; # } # allow the foo selector, but only with value "bar" or "baz" # 1) regex way $CSS::Adaptor::Whitelist::whitelist{foo} = qr/^ba[rz]$/; # 2) hash way $CSS::Adaptor::Whitelist::whitelist{foo} = {bar => 1, baz => 1}; # 3) sub way $CSS::Adaptor::Whitelist::whitelist{foo} = sub { return ($_[0] eq 'bar' or $_[0] eq 'baz') } DESCRIPTION This is a subclass of CSS::Adaptor that paranoidly prunes anything from the input CSS code that it doesn't recognize as standard. It is intended as user-input CSS validation before letting it on your site. The allowed CSS properties and corresponding values were mostly taken from w3schools.com/css . Whitelist The allowed constructs are given in the %CSS::Adaptor::Whitelist::whitelist hash. The keys are the allowed selectors and the values can be 1) regular expressions, 2) code refs and 3) hash refs. Each CSS property is looked up in the whitelist. If it is not found, it is discarded. Each CSS value found is checked. If it passes the test, then it is output in standard indentation, otherwise a message is passed to the log method. In case of regexp, it is checked against the regexp. If it matches, the value passes. In case of subroutine, the value is passed as the only argument to it. If the sub returns a true value, the CSS value passes. In case of hash, if the CSS value is a key in the hash, that is associated with a true value, then it passes. Overriding defaults You are invited to modify the rules, particularly the ones that allow URL's. See set_url_re for a convenient way. Also the font-family (and thus also font) properties are quite generous. Feel free to allow just a list of expected font families: $CSS::Adaptor::Whitelist::whitelist{'font-family'} = qr/^arial|verdana|...$/; Functions - list2hash Simplifies giving values in the hash way. Returns hasref. list2hash('foo', 'bar', 'baz') # returns {foo => 1, bar => 1, baz => 1} - space_sep_res space_sep_res($string, $regex, $regex, ...) # returns 1 or 0 SPACE-SEParated Regular ExpresssionS. Given a string like 1px solid #CCFF55and regular expressions for CSS dimension, border type and CSS color, checks if the string matches piece by piece to these regexps. Will fail if some of the regexp matches too small a chunk, for example: space_sep_res('solid #CCFF55', qr/solid|dotted/, qr/#[A-F\d]{3}|#[A-F\d]{6}/) will return 0 because the latter regexp stops after matching <#CCF>. Also beware that the regular expressions provided MUST NOT contain capturing parentheses, otherwise the function will not work. Use (?: ... )for non-capturing parenthesising. - set_url_re Sets the regular expression that URL's are checked against. Including the url( )wrapper. You are encouraged to use this method to provide a regexp that will only allow URL's to domains you control: CSS::Adaptor::Whitelist::set_url_re(qr{url(https?://example\.com/[\w/]+)}); Notice that the regexp should not be anchored (no ^and $at the edges). It is being used in these properties: cursor background background-image list-style list-style-image - log This is a method that stores messages of things being filtered out in the @CSS::Adaptor::Whitelist::message_logarray. You are encouraged to override or redefine this method to treat the log messages in accordance with your logging habits. AUTHOR Oldrich Kruza <sixtease@cpan.org> This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/release/SIXTEASE/CSS-Adaptor-Whitelist-0.006/lib/CSS/Adaptor/Whitelist.pm
CC-MAIN-2016-44
refinedweb
628
54.73
Introduction There are many developers between us. We write a tons of code every day. Sometime, it is even not a bad code :) Every of us can easily write the simplest code like this: #include <stdio.h> int main() { int x = 10; int y = 100; printf("x + y = %d", x + y); return 0; }.. Yes, must be big difference between Linux 64 bit and DOS 16 bit. So let’s start. Preparation Before we started, we must to prepare some things like As I wrote about, I use Ubuntu (Ubuntu 14.04.1 LTS 64 bit), thus my posts will be for this operating system and architecture. Different CPU supports different set of instructions. I use Intel Core i7 870 processor, and all code will be written processor. Also i will use nasm assembly. You can install it with: $ sudo apt-get install nasm It’s version must be 2.0.0 or greater. I use NASM version 2.10.09 compiled on Dec 29 2013 version. And the last part, you will need in text editor where you will write you assembly code. I use Emacs with nasm-mode.el for this. It is not mandatory, of course you can use your favourite text editor. If you use Emacs as me you can download nasm-mode.el and configure your Emacs like this: (load "~/.emacs.d/lisp/nasm.el") (require 'nasm-mode) (add-to-list 'auto-mode-alist '("\\.\\(asm\\|s\\)$" . nasm-mode)) That’s all we need for this moment. Other tools will be describe in next posts. Syntax of nasm assembly Here I will not describe full assembly syntax, we’ll mention only those parts of the syntax, which we will use in this post. Usually NASM program divided into sections. In this post we’ll meet 2 following sections: - data section - text section The data section is used for declaring constants. This data does not change at runtime. You can declare various math or other constants and etc… The syntax for declaring data section is: section .data The text section is for code. This section must begin with the declaration global _start, which tells the kernel where the program execution begins. section .text global _start _start: ; symbol. Every NASM source code line contains some combination of the following four fields: [label:] instruction [operands] [; comment] Fields which are in square brackets are optional. A basic NASM instruction consists from two parts. The first one is the name of the instruction which is to be executed, and the second are the operands of this command. For example: MOV COUNT, 48 ; Put value 48 in the COUNT variable Hello world Let’s write first program with NASM assembly. And of course it will be traditional Hello world program. Here is the code of it: section .data msg db "hello, world!" section .text global _start _start: mov rax, 1 mov rdi, 1 mov rsi, msg mov rdx, 13 syscall mov rax, 60 mov rdi, 0 syscall Yes, it doesn’t look like printf(“Hello world”). Let’s try to understand what is it and how it works. Take a look 1-2 lines. We defined data section and put there msg constant with Hello world value. Now we can use this constant in our code. Next is declaration text section and entry point of program. Program will start to execute from 7 line. Now starts the most interesting part. We already know what is it mov instruction, it gets 2 operands and put value of second to first. But what is it these rax, rdi and etc… As we can read in the wikipedia: A central processing unit (CPU) is the hardware within a computer that carries out the instructions of a computer program by performing the basic arithmetical, logical, and input/output operations of the system. registers: So when we write mov rax, 1, it means to put 1 to the rax register. Now we know what is it rax, rdi, rbx and etc… But need to know when to use rax but when rsi and etc… rax- temporary register; when we call a syscal, rax must contain syscall number rdx- used to pass 3rd argument to functions rdi- used to pass 1st argument to functions rsi- pointer used to pass 2nd argument to functions In another words we just make a call of sys_write syscall. Take a look on sys_write: size_t sys_write(unsigned int fd, const char * buf, size_t count); It has 3 arguments: fd- file descriptor. Can be 0, 1 and 2 for standard input, standard output and standard error buf- points to a character array, which can be used to store content obtained from the file pointed to by fd. count- specifies the number of bytes to be written from the file into the character array So we know that sys_write msg at rsi register, it will be second buf argument for sys_write. And then we pass the last (third) parameter (length of string) to rdx, it will be third argument of sys_write. Now we have all arguments of the sys_write and we can call it with syscall hello.asm file. Then we need to execute following commands: $ nasm -f elf64 -o hello.o hello.asm $ ld -o hello hello.o After it we will have executable hello file which we can run with ./hello and will see Hello world string in the terminal.
https://0xax.github.io/asm_1/
CC-MAIN-2017-47
refinedweb
896
73.88
An efficient video loader for deep learning with smart shuffling that's super easy to digest Decordis a reverse procedure of Record. It provides convenient video slicing methods based on a thin wrapper on top of hardware accelerated video decoders, e.g. Decordwas designed to handle awkward video shuffling experience in order to provide smooth experiences similar to random image loader for deep learning. Decordis also able to decode audio from both video and audio files. One can slice video and audio together to get a synchronized result; hence providing a one-stop solution for both video and audio decoding. Decord is good at handling random access patterns, which is rather common during neural network training. Simply use pip install decord Supported platforms: Note that only CPU versions are provided with PYPI now. Please build from source to enable GPU acclerator. Install the system packages for building the shared library, for Debian/Ubuntu users, run: # official PPA comes with ffmpeg 2.8, which lacks tons of features, we use ffmpeg 4.0 here sudo add-apt-repository ppa:jonathonf/ffmpeg-4 sudo apt-get update sudo apt-get install -y build-essential python3-dev python3-setuptools make cmake sudo apt-get install -y ffmpeg libavcodec-dev libavfilter-dev libavformat-dev libavutil-dev # note: make sure you have cmake 3.8 or later, you can install from cmake official website if it's too old Clone the repo recursively(important) git clone --recursive Build the shared library in source root directory: cd decord mkdir build && cd build cmake .. -DUSE_CUDA=0 -DCMAKE_BUILD_TYPE=Release make you can specify -DUSE_CUDA=ONor -DUSE_CUDA=/path/to/cudato enable NVDEC hardware accelerated decoding: cmake .. -DUSE_CUDA=ON -DCMAKE_BUILD_TYPE=Release Note that if you encountered the issue(e.g., the offical nvidia docker, see #102) with libnvcuvid.so, it's probably due to the missing link for libnvcuvid.so, you can manually find( ldconfig -p | grep libnvcuvid) and link the library to CUDA_TOOLKIT_ROOT_DIR\lib64to allow decordsmoothly detect and link the correct library. To specify a customized FFMPEG library path, use `-DFFMPEG_DIR=/path/to/ffmpeg". Install python bindings: cd ../python # option 1: add python path to $PYTHONPATH, you will need to install numpy separately pwd=$PWD echo "PYTHONPATH=$PYTHONPATH:$pwd" >> ~/.bashrc source ~/.bashrc # option 2: install with setuptools python3 setup.py install --user Installation on macOS is similar to Linux. But macOS users need to install building tools like clang, GNU Make, cmake first. Tools like clang and GNU Make are packaged in Command Line Tools for macOS. To install: xcode-select --install To install other needed packages like cmake, we recommend first installing Homebrew, which is a popular package manager for macOS. Detailed instructions can be found on its homepage. After installation of Homebrew, install cmake and ffmpeg by: brew install cmake ffmpeg # note: make sure you have cmake 3.8 or later, you can install from cmake official website if it's too old Clone the repo recursively(important) git clone --recursive Then go to root directory build shared library: cd decord mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release make Install python bindings: cd ../python # option 1: add python path to $PYTHONPATH, you will need to install numpy separately pwd=$PWD echo "PYTHONPATH=$PYTHONPATH:$pwd" >> ~/.bash_profile source ~/.bash_profile # option 2: install with setuptools python3 setup.py install --user For windows, you will need CMake and Visual Studio for C++ compilation. git, cmake, ffmpegand python. You can use Chocolatey to manage packages similar to Linux/Mac OS. Visual Studio 2017 Community, this my take some time. When dependencies are ready, open command line prompt: cd your-workspace git clone --recursive cd decord mkdir build cd build cmake -DCMAKE_CXX_FLAGS="/DDECORD_EXPORTS" -DCMAKE_CONFIGURATION_TYPES="Release" -G "Visual Studio 15 2017 Win64" .. # open `decord.sln` and build project Decord provides minimal API set for bootstraping. You can also check out jupyter notebook examples. VideoReader is used to access frames directly from video files. from decord import VideoReader from decord import cpu, gpu vr = VideoReader('examples/flipping_a_pancake.mkv', ctx=cpu(0)) a file like object works as well, for in-memory decoding with open('examples/flipping_a_pancake.mkv', 'rb') as f: vr = VideoReader(f, ctx=cpu(0)) print('video frames:', len(vr)) 1. the simplest way is to directly access frames for i in range(len(vr)): # the video reader will handle seeking and skipping in the most efficient manner frame = vr[i] print(frame.shape) To get multiple frames at once, use get_batch this is the efficient way to obtain a long list of frames frames = vr.get_batch([1, 3, 5, 7, 9]) print(frames.shape) (5, 240, 320, 3) duplicate frame indices will be accepted and handled internally to avoid duplicate decoding frames2 = vr.get_batch([1, 2, 3, 2, 3, 4, 3, 4, 5]).asnumpy() print(frames2.shape) (9, 240, 320, 3) 2. you can do cv2 style reading as well skip 100 frames vr.skip_frames(100) seek to start vr.seek(0) batch = vr.next() print('frame shape:', batch.shape) print('numpy frames:', batch.asnumpy()) VideoLoader is designed for training deep learning models with tons of video files. It provides smart video shuffle techniques in order to provide high random access performance (We know that seeking in video is super slow and redundant). The optimizations are underlying in the C++ code, which are invisible to user. from decord import VideoLoader from decord import cpu, gpu vl = VideoLoader(['1.mp4', '2.avi', '3.mpeg'], ctx=[cpu(0)], shape=(2, 320, 240, 3), interval=1, skip=5, shuffle=1) print('Total batches:', len(vl)) for batch in vl: print(batch.shape) Shuffling video can be tricky, thus we provide various modes: shuffle = -1 # smart shuffle mode, based on video properties, (not implemented yet) shuffle = 0 # all sequential, no seeking, following initial filename order shuffle = 1 # random filename order, no random access for each video, very efficient shuffle = 2 # random order shuffle = 3 # random frame access in each video only AudioReader is used to access samples directly from both video(if there's an audio track) and audio files. from decord import AudioReader from decord import cpu, gpu You can specify the desired sample rate and channel layout For channels there are two options: default to the original layout or mono ar = AudioReader('example.mp3', ctx=cpu(0), sample_rate=44100, mono=False) print('Shape of audio samples: ', ar.shape()) To access the audio samples print('The first sample: ', ar[0]) print('The first five samples: ', ar[0:5]) print('Get a batch of samples: ', ar.get_batch([1,3,5])) AVReader is a wraper for both AudioReader and VideoReader. It enables you to slice the video and audio simultaneously. from decord import AVReader from decord import cpu, gpu av = AVReader('example.mov', ctx=cpu(0)) To access both the video frames and corresponding audio samples audio, video = av[0:20] Each element in audio will be a batch of samples corresponding to a frame of video print('Frame #: ', len(audio)) print('Shape of the audio samples of the first frame: ', audio[0].shape) print('Shape of the first frame: ', video.asnumpy()[0].shape) Similarly, to get a batch audio2, video2 = av.get_batch([1,3,5]) It's important to have a bridge from decord to popular deep learning frameworks for training/inference Using bridges for deep learning frameworks are simple, for example, one can set the default tensor output to mxnet.ndarray: import decord vr = decord.VideoReader('examples/flipping_a_pancake.mkv') print('native output:', type(vr[0]), vr[0].shape) # native output: , (240, 426, 3) # you only need to set the output type once decord.bridge.set_bridge('mxnet') print(type(vr[0], vr[0].shape)) # (240, 426, 3) # or pytorch and tensorflow(>=2.2.0) decord.bridge.set_bridge('torch') decord.bridge.set_bridge('tensorflow') # or back to decord native format decord.bridge.set_bridge('native')
https://xscode.com/dmlc/decord
CC-MAIN-2021-21
refinedweb
1,295
56.35
Any modern web application needs localization! You simply can’t ignore the huge amounts of people who doesn’t speak your language, or whose native language is different from yours. You’re probably using resource files (.resx) in .NET, but how do you go about getting values from your resource files in JavaScript? Rick Strahl wrote a great blog post about an HttpHandler that serves the content of your resource files in JavaScript. You basically add a script tag to your page that points to the HttpHandler, and the HttpHandler will produce the resources in JavaScript as an object with properties on it, like this: [code lang="js"]var localRes = { AreYouSureYouWantToRemoveValue: "Sind Sie sicher dass Sie diesen Wert l\u00F6schen wollen?", BackupComplete: "Der Backup f\u00FChrte erfolgreich durch", BackupFailed: "Der Backup konnte nicht durchgef\u00FChrt werden", BackupNotification: "Diese Operation macht einen Backup von der Lokalisationtabelle. \nM\u00F6chten Sie fortfahren?", Close: "Schliessen", FeatureDisabled: "Diese Funktion ist nicht vorhanden im on-line Demo ", InvalidFileUploaded: "Unzul\u00E4ssige Akten Format hochgeladen.", InvalidResourceId: "Unzul\u00E4ssige ResourceId", LocalizationTableCreated: "Lokalisations Akte wurde erfolgreich erstellt.", LocalizationTableNotCreated: "Die Localizations Akte konnte nicht erstellt werden." };[/code] This is awesome! Now you can access your resource files from JavaScript. Though, I see a single improvement to be made. The thing I don’t like about the HttpHandler approach, is that you don’t get IntelliSense support in Visual Studio. So you have to browse your resource file and copy & paste the resource key to your JavaScript files in order for this to work. Generate static JavaScript files on Post-build Instead of generating dynamic files at runtime, I prefer to generate static JavaScript files and then dynamically include the file of the current language on my pages. I do this by calling a Console Application I’ve written on the Post-build event of my ASP.NET (MVC) project, which you can set in the property pages of your project (By the way, did you know that you can open property pages of a project by double clicking the default Properties folder?): What my JavascriptResxGenerator App does, is quite messy. But the essence of the App is, of course, to take a single (or several) .resx files and do the following: 1. Loop through all keys. 2. Make sure the key is not a JavaScript reserved word. 3. Add the key and value to a dictionary (in JavaScript). 4. Write the file. And for the default culture I generate a –vsdoc file, that I can use for Visual Studio IntelliSense. Using the JavaScript Resx Generator App My App supports a single file approach, and directory approach. Single file: JavascriptResxGenerator.exe C:\Folder\Text.resx C:\Output C:\Output\VsDoc MyApp.Namespace.Resources Directory: JavascriptResxGenerator.exe C:\Folder C:\Output C:\Output\VsDoc MyApp.Namespace.Resources The MyApp.Namespace.Resources value, is the namespace your resource dictionary will get enclosed in. Embedding the file on your pages To include the JavaScript resource file in your page, you simply add a script include tag that points to the correct language. The App will respect the region token used in your Resx files. So if you have a file called Text.da.resx, the JavaScript file generated will include .da.resx at the end. It’s then up to you to add the correct logic to keep hold of the current language and specify the correct region token in order to include the correct JavaScript resource file. Download You can download the App here, as a ZIP file.
http://martinnormark.com/category/internationalization/
CC-MAIN-2014-10
refinedweb
584
66.44
SDKs - iOS 2.0+ - macOS 10.0+ - tvOS 9.0+ - watchOS 2.0+ Framework - Foundation Overview The NSString class and its mutable subclass, NSMutable, provide an extensive set of APIs for working with strings, including methods for comparing, searching, and modifying strings. NSString objects are used throughout Foundation and other Cocoa frameworks, serving as the basis for all textual and linguistic functionality on the platform. NSString is “toll-free bridged” with its Core Foundation counterpart, CFString. See “Toll-Free Bridging” for more information. String Objects An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0. An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL. It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSString. The objects you create using NSString and NSMutable are referred to as string objects (or, when no confusion will result, merely as strings). The term C string refers to the standard char * type. Because of the nature of class clusters, string objects aren’t actual instances of the NSString or NSMutable classes but of one of their private subclasses. Although a string object’s class is private, its interface is public, as declared by these abstract superclasses, NSString and NSMutable. The string classes adopt the NSCopying and NSMutable protocols, making it convenient to convert a string of one type to the other. Understanding Characters A string object presents itself as a sequence of UTF–16 code units. You can determine how many UTF-16 code units a string object contains with the length method and can retrieve a specific UTF-16 code unit with the character(at:) method. These two “primitive” methods provide basic access to a string object. Most use of strings, however, is at a higher level, with the strings being treated as single entities: You compare strings against one another, search them for substrings, combine them into new strings, and so on. If you need to access string objects character by character, you must understand the Unicode character encoding, specifically issues related to composed character sequences. For details see The Unicode Standard, Version 4.0 (The Unicode Consortium, Boston: Addison-Wesley, 2003, ISBN 0-321-18578-1) and the Unicode Consortium web site:. See also Characters and Grapheme Clusters in String Programming Guide. Localized string comparisons are based on the Unicode Collation Algorithm, as tailored for different languages by CLDR (Common Locale Data Repository). Both are projects of the Unicode Consortium. Unicode is a registered trademark of Unicode, Inc. Interpreting UTF-16-Encoded Data When creating an NSString object from a UTF-16-encoded string (or a byte stream interpreted as UTF-16), if the byte order is not otherwise specified, NSString assumes that the UTF-16 characters are big-endian, unless there is a BOM (byte-order mark), in which case the BOM dictates the byte order. When creating an NSString object from an array of unichar values, the returned string is always native-endian, since the array always contains UTF–16 code units in native byte order. Subclassing Notes It is possible to subclass NSString (and NSMutable), but doing so requires providing storage facilities for the string (which is not inherited by subclasses) and implementing two primitive methods. The abstract NSString and NSMutable classes are the public interface of a class cluster consisting mostly of private, concrete classes that create and return a string object appropriate for a given situation. Making your own concrete subclass of this cluster imposes certain requirements (discussed in Methods to Override). Make sure your reasons for subclassing NSString are valid. Instances of your subclass should represent a string and not something else. Thus the only attributes the subclass should have are the length of the character buffer it’s managing and access to individual characters in the buffer. Valid reasons for making a subclass of NSString include providing a different backing store (perhaps for better performance) or implementing some aspect of object behavior differently, such as memory management. If your purpose is to add non-essential attributes or metadata to your subclass of NSString, a better alternative would be object composition (see Alternatives to Subclassing). Cocoa already provides an example of this with the NSAttributed class. Methods to Override Any subclass of NSString must override the primitive instance methods length and character(at:). These methods must operate on the backing store that you provide for the characters of the string. For this backing store you can use a static array, a dynamically allocated buffer, a standard NSString object, or some other data type or mechanism. You may also choose to override, partially or fully, any other NSString method for which you want to provide an alternative implementation. For example, for better performance it is recommended that you override get and give it a faster implementation. You might want to implement an initializer for your subclass that is suited to the backing store that the subclass is managing. The NSString class does not have a designated initializer, so your initializer need only invoke the init() method of super. The NSString class adopts the NSCopying, NSMutable, and NSCoding protocols; if you want instances of your own custom subclass created from copying or coding, override the methods in these protocols. Alternatives to Subclassing Often a better and easier alternative to making a subclass of NSString—or of any other abstract, public class of a class cluster, for that matter—is object composition. This is especially the case when your intent is to add to the subclass metadata or some other attribute that is not essential to a string object. In object composition, you would have an NSString object as one instance variable of your custom class (typically a subclass of NSObject) and one or more instance variables that store the metadata that you want for the custom object. Then just design your subclass interface to include accessor methods for the embedded string object and the metadata. If the behavior you want to add supplements that of the existing class, you could write a category on NSString. Keep in mind, however, that this category will be in effect for all instances of NSString that you use, and this might have unintended consequences.
https://developer.apple.com/documentation/foundation/nsstring
CC-MAIN-2017-43
refinedweb
1,080
51.58
I had an issue where my app would incorrectly report ‘location services’ when attempting to submit for certification. The problem turned out to be two classes in WP7Contrib using the Microsoft.Phone.Controls.Maps and System.Device.Location namespaces. When the capability detection tool runs, it checks for any use of a namespace, not just methods that actually check the user’s location. Unfortunately you can’t override it in the WMAppManifest.xml file – which begs the question of why even have the flags there if all they do is increase the chances of an exception. Anyway, to fix the problem you need to comment out two classes in WP7Contrib.Common. In ‘Serialization’ are ‘SerializeGeoCoordinate’ and ‘SerializeLocationRect’. Comment out these classes in their entirety and re-build both WP7Contrib.Common and your app. Your app should no longer be incorrectly detected as using location services.
http://dan.clarke.name/tag/location-services/
CC-MAIN-2019-39
refinedweb
145
50.63
Home > News & Events > NewsSmith > Fall 2003 You Come in as a Squirrel and Leave as an Owl By Trinity Peacock-Broyles '03 Before she graduated in May, Trinity Peacock-Broyles took a personal interest in Smith history and spent a few afternoons in the College Archives sifting through century-old student handbooks and newspapers. What follows is her idea of the life of a Smith student some 100 years ago. I miss President Seelye's cow. Even though I never met her, I feel a special connection to the cud-chewing pacifist that I've seen in pictures circa 1875–1910. I'd like to return (maybe for a week) to the idyllic days when President Seelye's cow grazed in what was then considered a "neglected area" of campus and is now the Science Quad. Think of how relaxing it would be to walk to class and see a cow peacefully grazing alongside your path. I think that every president should have a cow, as a memento of Smith's noble traditions and a reminder to live simply (while of course acting locally and globally). Maybe the senior class could make a generous gift of a dairy cow to President Christ and forthcoming senior classes could pay for veterinary bills, boarding in the winter and perhaps some hay. Photo courtesy Smith College Archives Speaking of hay at Smith, I am equally fascinated by a picture in "Celebrating a Century: The Botanic Garden of Smith College" that shows three women in long dresses crossing the future Burton Lawn while farmhands pile hay onto a wagon. I would love to be one of those women, for a little while at least. This area was known as the "Back Campus" around 1894 when this photo was taken. Along with the idyllic scene of an open field and a glimpse of a small greenhouse, I examine the structure occupying the "knoll." Instead of seeing Wright Hall, early students (perhaps bearing the names of Teedy, Teddy, Tansy, or Babs, Bunny or Bounce) would have seen the Smith observatory, "devoted to the study of the heavens," as described by the Hampshire Country Journal. Built in 1886, this lovely work of architecture included a dome twenty-one feet in diameter made of iron and fitted with a telescope that "even the slenderest hand among the fair pupils" of Smith could easily turn. I'm sure that most Smith students today would have no trouble swinging it around. As I'm not so much of a science person, instead of spending my week down memory lane studying the heavens, I might prefer to play some basketball. My time travel could take me no further than 1893, when the first women's basketball game in the country was played at Smith. Looking through old local newspapers and photographs, I see that I would need to adjust to having nine players on a team and to competition between classes, not colleges. The bulky and unrevealing uniforms might be ugly and uncomfortable, but it would not matter because no male admirers could attend games. "A woman out of her normal attire was not fit to be seen by a male," according to Senda Berenson, instructor of physical culture at Smith, who introduced the game to women. To play the game I would have to show "good carriage and neatness of appearance," and I could never "snatch" the ball away from another young lady because that would be an infringement of the rules. I would be called "Miss Peacock-Broyles," though it's a mouthful, and I would have to get used to yelling at my teammates, "Hey, Miss Hale, catch!" or "Heads up, Miss Baker!" I'll have to follow many more rules to avoid getting kicked out. As the Smith saying goes, you "come in as a squirrel, and leave as an owl." I wouldn't have wanted to be a "squirrel" in 1918 when the college rules required students to obey "quiet hours" from 9 a.m. to 1 p.m., 2 to 4:30 p.m. and 7:30 to 9:30 p.m. And when the lights were extinguished at 10 p.m., students had to be in their rooms. I would watch out for the Department of Hygiene and Physical Education, which issued "flunk notices" generously, and make sure I didn't "fuss" (entertain men) or become a "grind" (study too much). The social restrictions extended to off-campus behavior as well. I'd make sure to remember that "Rumor is the Patron Saint of Northampton" and to read the Bulletin for facts. I'd watch out for the "Politeness Policemen," an organization whose regulations forbid more than two girls to walk abreast on Northampton sidewalks, and included an injunction against eating while walking on Main Street. I'd keep in mind the popular verse: "The gum-chewing girl and the cud-chewing cow -- The difference? Oh yes, I see it now! It's the thoughtful look on the face of the cow!" And before leaving my room, I'd remember yet another rule: "Don't go below Beckman's [candy store] without a hat. Your reputation will go further below if you do." Despite the rules, there were many ways for Smithies to enjoy themselves. For fun, I could take the trolley to Old Hadley or a carriage ride for 25 cents. I could go to the "libe" and read a book or, if I were feeling especially adventurous, I could become a "grass cop," one of those "stalwart girls" who is privileged to blow loudly on their whistles as a sign for some thoughtless student to get off the grass. I could go bowling in the Alumnae Gym's alley, participate in archery or play golf. If these were to aggravate my "feminine disposition," I could always turn to canoeing, perhaps borrowing one from a student who'd brought her own to school and kept it at the boathouse. I could attend the Junior Frolic dance, decorate Sophia Smith's grave along with the freshmen of Dewey House on Memorial Day or join one of the many senior sings on the steps of the Student's Building. I might win the hoop-rolling contest and be destined to become the first bride, and I could show off my other "stunts" along with my fellow students. I'd be a tired dog at the end of my week of time travel. But come to think of it there's one thing I miss even more than President Seelye's cow -- the Smith College fees in 1923: $200 for tuition, with $250 for board and $100 for a room.
https://web.archive.org/web/20110615080005/http:/www.smith.edu/newssmith/fall2003/100.php
CC-MAIN-2017-30
refinedweb
1,114
66.27
C# Test Builder Pattern: My current thinking I’ve written previously about the test builder pattern in C# and having noticed some different implementations of this pattern I thought it’d be interesting to post my current thinking on how to use it. One thing I’ve noticed is that we often end up just creating methods which effectively act as setters rather than easing the construction of an object. This seems to happen most commonly when the value we want to set is a boolean value. The following is quite typical: public CarBuilder WithSomething(boolean value) { this.something = value; return this; } The usage would be like so: new CarBuilder().WithSomething(true).Build(); It doesn’t read too badly but it seems to be unnecessary typing for the user of the API. If we’re going to use the fluent interface approach then I would prefer to have two methods, defined like so: public CarBuilder WithSomething() { this.something = true; return this; } public CarBuilder WithoutSomething() { this.something = false; return this; } We could then use this like so: new CarBuilder().WithSomething().Build(); ... new CarBuilder().WithoutSomething().Build(); That requires more code but I think it’s a bit more expressive and makes life easier for the user of the API. An alternative approach which my colleague Lu Ning showed me and which I think is actually better is to make use of the object initializer syntax if all we have are setter methods on a builder. We might therefore end up with something like this: public class FooBuilder { public string Something = "DefaultSomething"; public boolean SomethingElse = false; public Foo Build() { return new Foo(Something, SomethingElse); } } new FooBuilder { SomethingElse = true }.Build(); With this approach we end up writing less code and although we use public fields on the builder I don’t think it’s a big deal since it allows us to achieve our goal more quickly. If we need other methods that take out the complexity of construction then we can easily just add those as well. Another thing to note when using this pattern is that we don’t need to override all the object’s attributes on every single test. We only need to override those ones which we are using in our test. The rest of the values can just be defaulted. [Test] public void ShouldDoSomething() { var foo = new FooBuilder { Bar = "myBar", Baz = "myBaz", SomethingElse = "mySE", AndAgain = "..." }.Build(); // and then further on we only check the value of Bar for example Assert.That(someValue, Is.EqualTo("myBar"); } We don’t need to specifically set any of the values except ‘Bar’ because they are irrelevant and create a clutter in the test which means it takes longer to understand what’s going on. This would be preferable: [Test] public void ShouldDoSomething() { var foo = new FooBuilder { Bar = "myBar" }.Build(); // and then further on we only check the value of Bar for example Assert.That(someValue, Is.EqualTo("myBar"); } Something which I’ve been wondering about recently is understanding the best way to describe the case where we don’t want to define a specific value i.e. we want it as null. I’d normally just set it to null like so: new FooBuilder { Bar = null }.Build(); But we could make the API have a specific method and I haven’t really decided whether there’s much value to doing so yet: new FooBuilder().WithNoBar().Build(); About the author Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database.
http://markhneedham.com/blog/2010/01/13/c-test-builder-pattern-my-current-thinking/
CC-MAIN-2018-17
refinedweb
582
59.64
Re: return [expression] -> "unable to continue" Expand Messages - --- In jslint_com@yahoogroups.com, "crlender" <crlender@...> wrote: >I think by "fail" you meant that it succeeded in finding the weakness > The following example causes the JSLint parser to fail: in your code. > return cache = calculate();This is explained in the documentation. When = is used in an > Using extra parentheses works: > > return (cache = calculate()); > > Since parens are not required here (ECMA-262, ed3, 12.9), and JSLint > normally complains about extra parens, I wanted to ask if that's on > purpose or a bug? expression, there is a high likelihood that it is an error caused by mistyping == or ===. From a careful reading of your code, I can't be sure if your code is in error or not. That is not good. You want your code to be more clearly correct. By wrapping the assignment in parens, you are demonstrating that you are doing this deliberately. I recommend avoiding assignment in expressions. I think cache = calculate(); return cache; is cleaner and more bug resistant. - --- In jslint_com@yahoogroups.com, "Douglas Crockford" <douglas@...> wrote: > > The following example causes the JSLint parser to fail:No, I meant "fail" as in "couldn't continue parsing the source". > > I think by "fail" you meant that it succeeded in finding the weakness > in your code. If it finds a weakness, it should issue a warning and move on. > This is explained in the documentation. When = is used in anAh, now I see where this is coming from, and you've got a point. I > expression, there is a high likelihood that it is an error caused by > mistyping == or ===. always use extra parens when an assignment could be misunderstood as a test. Thanks for the explanation. - Conrad Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/jslint_com/conversations/topics/300?xm=1&o=1&m=p&tidx=1
CC-MAIN-2017-26
refinedweb
302
67.15
Serializing ColdFusion Variables Into ColdFusion Code Using WDDX ColdFusion provides us with a number of ways in which to serialized our ColdFusion values - JSON, WDDX, and Binary (as of ColdFusion 9) are all formats that can be generated on the fly. But these formats all require a file read in order to be consumed. What if, rather than serializing a value into a simple data type, we could serialize it into the ColdFusion code that could be used to generate it? In doing so, we could essentially cache values to the template cache rather than to the "file system." Now, of course, CFM files are stored on the file system, just like every other file; but, with ColdFusion features like the template cache and the trusted cache, file access for CFM files is highly optimized. Furthermore, the density of the cache gets managed by ColdFusion in such a way that you can't "overflow" your template cache (it will purge cached templates as needed). Now, I'm not saying that ColdFusion manages the template cache in a very intelligent way - I think it's a time-based queue; but, I am saying that you won't crash your server by filling up your JVM with cached templates. Cache-talk aside, I put together a little proof-of-concept using WDDX. When I first started this, I was going to try and build the code recursively based on the data type; but, ColdFusion's WDDX support is pretty awesome and XML parsing is pretty freaking fast. As such, I didn't see a need to reinvent the wheel (at least not for this exploration). - <cffunction - name="toCode" - access="public" - returntype="string" - output="false" - - <!--- Define arguments. ---> - <cfargument - name="value" - type="any" - required="true" - hint="I am the ColdFusion variable that is being serialized to ColdFusion code (via inline WDDX)." - /> - <cfargument - name="prefix" - type="string" - required="false" - default="data" - hint="I am the variable name prefix to use when generating the ColdFusion code." - /> - <!--- Define the local scope. ---> - <cfset var local = {} /> - <!--- - When converting a value using WDDX, we need two - intermediary values - the content buffer that holds the - actual WDDX data and the intermediary value that holds the - deserialization. Let's create a "Safe" suffix for use in - these values. - ---> - <cfset local.prefixHash = ("toCode" & hash( arguments.prefix )) /> - <!--- Convert the value to WDDX. ---> - <cfwddx - output="local.wddxValue" - action="cfml2wddx" - input="#arguments.value#" - /> - <!--- - Return the value going through the WDDX conversion - life-cycle. We'll need to use an intermediary - CFSaveContent tag to hold the XML. - ---> - <cfreturn ( - "<cfsavecontent variable=""in_#local.prefixHash#"">" & - local.wddxValue & - "</cfsavecontent>" & - (chr( 13 ) & chr( 10 )) & - "<cfwddx " & - "action=""wddx2cfml"" " & - "input=""##in_#local.prefixHash###"" " & - "output=""out_#local.prefixHash#"" " & - "/>" & - (chr( 13 ) & chr( 10 )) & - "<cfset #arguments.prefix# = out_#local.prefixHash# />" - ) /> - </cffunction> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- Create a value that we want to "cache" to code. ---> - <cfset data = {} /> - <cfset data. - <cfset data.tags = [ "Cute", "Adorable" ] /> - <cfset data.collection = queryNew( "" ) /> - <cfset queryAddColumn( - data.collection, - "id", - "cf_sql_integer", - listToArray( "1,2,3" ) - ) /> - <cfset queryAddColumn( - data.collection, - "name", - "cf_sql_varchar", - listToArray( "Jill,Tricia,Katie" ) - ) /> - <!--- Serialize the data value to ColdFusion code. ---> - <cfset code = toCode( data, "newData" ) /> - <!--- Write the ColdFusion code to a CFM file. ---> - <cffile - action="write" - file="#expandPath( './code.cfm' )#" - output="#code#" - /> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- Include the generated code file. ---> - <cfinclude template="code.cfm" /> - <!--- Output the resultant variable. ---> - <cfdump var="#newData#" /> As you can see, the toCode() function takes a variable and returns the ColdFusion code needed to generate it (as close as possible). In the end, this isn't doing much more than creating an inline XML buffer, parsing it, and assigning the result. The value that gets returned is the ColdFusion code needed to generate the original variable. This code can then be written to disk and used as a CFM template. When we run the above code, we get the following CFDump output: As you can see, the ColdFusion variable was serialized into ColdFusion code, which was then used to create a mirrored ColdFusion variable. So, to be honest, I really have no idea if this is a good idea or not. I wouldn't be surprised if the first person to comment told me that this was insane and that if I needed a better cache, I should be using something like CouchDB.... if only my VPS had more memory. This idea just popped into my head the other day and I wanted to try and think it through a bit before I completely discarded Okay . . . so you can scrape serialized data and create CF code from these, but why would you want to do so? This is insane and you need a better cache (there, I said it!). This reminds me of a time when someone I knew wanted a way to put CF code in the database and have it execute by writing a file to disk and then including it (this was way back in the CF5 days). Serializing objects/data to disk and reading them back in is certainly nothing new, but generally it's a good practice to separate the contexts of "data" and "executable code". Turning the data into code is generally not a good idea, and is the reason people harp on the use of CFQUERYPARAM all the time (takes the "data" out of the "code" of the SQL query so it cannot be executed). Granted this is a little more controlled since it's being fully encapsulated into WDDX, so in theory it should work/act exactly the same as if you were putting the WDDX package into the database and reading it from there. I would certainly be exploring options other than generating executable code on-the-fly. It's an interesting proof of concept though. @Lola, I could see this being used for long-term storage for something like basic application settings. For example, the setup process asks for your datasource information and then generates some executable code to set those variables in an included file so they're available for the life of the application on that server. Now that I think back, I recall doing something similar to cache generated page content in places where speed was important and the generated content took a while to produce but didn't change often. This was back in CFMX 6 before the CFCACHE tag could cache parts of a page (it was all or nothing back then). I wrote a CFML custom tag which you could wrap around a piece of content and set a unique name and a time-to-live in seconds. It would execute the code on the first run, then write it to disk as a CFM file in a cache folder, then on subsequent runs if the TTL hadn't expired, it would CFINCLUDE the generated file. The first page load would be slow since it had to execute the code, then the second page load would be faster but still slow because the JVM would have to compile the new CFM file into byte code and cache it before it could be included, but then subsequent page loads would be really quick. It was originally written to speed up the home page on a bunch of floral e-commerce sites I worked on for a while. CF's internal cache mechanisms provide the same functionality now with a lot more flexibility though, so I wouldn't do it again (so I still think it's insane with modern versions of CF. :) @Justin, Ha ha, yeah, maybe it is a bit insane. Here's my situation - I'm on a small VPS with 1 Gig of RAM, a sub-portion of which actually goes to ColdFusion and the JVM. I currently cache things like queries into an object (which is, itself, cached in the Application scope). But, I get nervous that on such a small machine, caching large amounts of database-driven data will quickly soak up the valuable JVM heap space. Disk space, on the other hand, I am dirty with - gigs of it. So, I figured I'd do a little exploration into how one might cache data to disk rather than memory. Now, of course, disk access is really slow. But, I figured the Template Cache would help alleviate that by keeping popular data in the cache and then re-compiling non-popular data as needed. But, cached or in-need of compiling, it's still skipping the database (which I believe is really becoming a bottle-neck on my site). So, anyway, just an exploration. Trying various ways of getting rid of my thousand nightly Error emails and lock-timeouts :D Okay . . . what's causing all those error emails and lock-timeouts? :P @Lola, The CFLocks are around database calls that populate my application cache. As such, I am pretty sure it's my database that is causing the bottleneck. That's why I'm trying to move away from the database and a source of data (at least, to limit the amount that I have to go to it). And, I don't want to cache rendered content because there is still a good amount of logic that I do inside of that content - it is not static. @Lola, I'll go back to the DB and make sure all my indices make sense. @Ben, Ah, the classic computer science exercise of generating code and then executing it. I get what you're saying about CF template cache management not running the JVM out of memory. An alternative (caching already-compiled data structures in the Server scope) can definitely run you out of memory. What you've demonstrated is safer, in terms of memory management. In the early days of CFMX, we had to fight the JDBC problem of cfstoredproc not supporting dbvarname (call-by-name). We had LOTS of cfstoredproc calls that didn't have cfprocparams in the correct order for CFMX's call-by-position. It threatened to keep us from upgrading to CFMX. So I wrote a utility to read the script that defines a stored procedure, parse it and generate a "stored procedure call file", in which the cfprocparams were guaranteed to be in definition order (with the correct datatypes). That way, the call-by-position limitation of CFMX would no longer be a problem. It's what allowed us to go to CFMX. Eventually our stored procedure call files incorporated tons of standardized error recovery, null parameter management, performance logging and other non-CFMX-conversion benefits. And it also allowed us to easily switch between DBMSs (Microsoft SQL Server, Oracle, Sybase), simply by calling a different stored procedure call file targeted to the other DBMS. Recently I've started extracting table column properties as JSON, for use in a general purpose utility that validates whether data can be stored into a database column, based on the table's definition script. Sure, you could call cfdbinfo, but the files to generate data structures from JSON are CFM files, so they can generate a more useful data structure than cfdbinfo and be cached in the template cache (essentially no I/O). So yes, generating code can be a very good idea indeed. @WebManWalking, I've never had to deal with stored procedures before, but that definitely sounds like a great deal of work :) Ultimately, I wish I had some retarded awesome dedicated box where I could just play with different ideas like CouchDB and MongoDB and all that jazz. @Ben, It was a great deal of work back in May, 2003. But ever since, it's been an enormous amount of work saved. Steve Drucker of Fig Leaf Software wrote something he called his "SQL Tool of Justice!" It also generates code from the database, all the way down to input/edit screens. It even honors foreign key constraints and many-to-many relationships. It's Microsoft SQL Server only, because it uses built-in stored procedures such as sp_databases, sp_tables, sp_columns, etc, to find out database information. For a while there, I thought Steve Drucker was trying to put all of us web-to-database types out of our jobs with that tool! @WebManWalking Is this SQL Tool of Justice available anywhere? I suppose there have been more improved code generators since then. @Lola, I just Googled it and found some posts on. Steve Drucker posted a Flash Remoting piece of it and others wanted to see more. But I don't see the tool there. I would've thought there would be something on figleaf.com about it, but I didn't find anything. Sorry. You might be able to contact him directly. He's at their DC office Ben, One idea you might consider to deal with your caching issue would be to use ColdFusion 9's ehcache implementation. You could set the maxElementsInMemory to a relatively low value (to account for your low amount of RAM) and set overflowToDisk="true" so that when the memory cache is filled, ehcache will automatically start caching additional objects/data to disk instead. In general, I would not recommend using a NOSQL database as a cache - mainly because the majority of them cache to disk which is at least an order of magnitude than caching to memory. @Rob, Unfortunately, my VPS is on CF8. And, the amount of memory on it is so low, that I am not sure how easy the upgrade process would be. I have a new sever in the works, using CF9; hopefully, moving to that will help me out a lot! ColdFusion Application Server: "Ride it or miss the joy of power and speed" Hi Ben - How to create a JSON object from a query in coldfusion 5 ? The SerializeJSON is not available there.
http://www.bennadel.com/blog/2141-serializing-coldfusion-variables-into-coldfusion-code-using-wddx.htm
CC-MAIN-2014-49
refinedweb
2,278
61.67
sp-pnp-js 3.0.0 beta Today we are releasing the first beta version of 3.0.0 for sp-pnp-js. This is a breaking change and may require updates to your code. You can see a run down of the changes here, and please remember these changes themselves might change before the final release. Under the hood we have rewritten much of the internals of the library, including the request pipeline and the class inheritance structure. These changes were big, but are our first move down a longer term plan (see below). It is not recommended to upgrade to this beta version for anything going to production as it may change - or simply not work in some way we didn't catch in our testing. Because this is a beta we welcome extra feedback from folks, especially in a few key areas (once you've made any needed updates to your code). You can log an issue in the normal place, but please put "3.0.0-beta" in the title to help us triage. - Any code that was working still works. This is number 1, we can't break folks. - Try out the graph functionality and let us know how things are working - Are all the exports you were using in the global namespace available in the sub namespaces Known Limitations There are some known limitations with this beta release, and would ask that you please not log an issue regarding them - Graph requests only work within SPFx and through the GraphHttpClient and are subject to the same scoping limitations. This is not the end state, we understand folks would like to use the library in node and plain javascript applications - that will come. - Global exports are not available in the distributed pnp.js files. - The dist file sizes are getting bigger, see below for our plan to address this - Graph batching is not yet supported the future When we started this project I did not anticipate how it would grow in both scale and popularity. This is an amazing and humbling problem to have and I want to thank everyone in the community for the support, contributions, and interest in our work. But it means we need to make some changes. 3.0.0 will be the last major release of sp-pnp-js. We will leave the repo in place and continue to patch critical bugs, but we will be moving new development to a new organization within github and a new repo. As part of this move we will completely restructure the library, breaking things up into smaller packages you can combine as needed. This will take a lot of work - but it is the right thing to do to support our long term goals: - Expand our support of O365 services beyond SharePoint - Provide a mix of packages instead of a single library, allowing folks to use only what they need more easily (and help with size) - Create a smooth transition from sp-pnp-js to the new libraries with clear guidance - Updated docs to reflect the changes We'll provide more details as we solidify things and make beta versions available ASAP to get feedback early. While we recognize these changes will be disruptive we believe it is the best way to provide the best service possible to you. As always please share your thoughts. Thanks!
https://blogs.msdn.microsoft.com/patrickrodgers/2017/08/29/sp-pnp-js3-0-0-beta-the-road-ahead/
CC-MAIN-2018-30
refinedweb
564
65.46
The QAxBase class is an abstract class that provides an API to initialize and access a COM object. More... #include <QAxBase> Inherited by: QAxObject and QAxWidget. The QAxBase class is an abstract class that provides an API to initialize and access a COM object.. connect(webBrowser, SIGNAL(TitleChanged(QString)), this, SLOT(setCaption(QString)));. A QMap<QString,QVariant> that can store properties as name:value pairs. This property holds the name of the COM object wrapped by this QAxBase object. Setting this property initializes the COM object. Any COM object previously set is shut down. The most efficient way to set this property is by using the registered component's UUID, e.g. ctrl->setControl("{8E27C92B-1264-101C-8A2F-040224009C02}"); The second fastest way is to use the registered control's class name (with or without version number), e.g. ctrl->setControl("MSCal.Calendar"); The slowest, but easiest way to use is to use the control's full name, e.g. ctrl->setControl("Calendar Control 9.0"); It is also possible to initialize the object from a file, e.g. ctrl->setControl("c:/files/file.doc"); If the component's UUID is used the following patterns can be used to initialize the control on a remote machine, to initialize a licensed control or to connect to a running object: <domain/username>:<password>@server/{8E27C92B-1264-101C-8A2F-040224009C02} {8E27C92B-1264-101C-8A2F-040224009C02}:<LicenseKey> {8E27C92B-1264-101C-8A2F-040224009C02}& The first two patterns can be combined, e.g. to initialize a licensed control on a remote machine: ctrl->setControl("DOMAIN/user:password@server/{8E27C92B-1264-101C-8A2F-040224009C02}:LicenseKey"); The control's read function always returns the control's UUID, if provided including the license key, and the name of the server, but not including the username, the domain or the password. Access functions: Creates a QAxBase object that wraps the COM object iface. If iface is 0 (the default), use setControl() to instantiate a COM object. Shuts down the COM object and destroys the QAxBase object.. Calls&)", "qt.nokia.com"); Alternatively a function can be called passing the parameters embedded in the string, e.g. above function can also be invoked using activeX->dynamicCall("Navigate(\"qt.nokia.com\")"); All parameters are passed as strings; it depends on the control whether they are interpreted correctly, and is slower than using the prototype with correctly typed parameters.(). dynamicCall() can also be used to call objects with a disabled metaobject wrapper, which can improve performance significantely, esp. when calling many different objects of different types during an automation process. ActiveQt will then however not validate parameters.. This is an overloaded function.. This signal is emitted when the COM object throws an exception while called using the OLE automation interface IDispatch. code, source, desc and help provide information about the exception as provided by the COM server and can be used to provide useful feedback to the end user. help includes the help file, and the help context ID in brackets, e.g. "filename [id]". Returns a rich text string with documentation for the wrapped COM object. Dump the string to an HTML-file, or use it in e.g. a QTextBrowser widget.. Connects to an active instance running on the current machine, and returns the IUnknown interface to the running object in ptr. This function returns true if successful, otherwise returns false. This function is called by initialize() if the control string contains the substring "}&". See also initialize().(). Returns true if there is no COM object loaded by this wrapper; otherwise return false.. Returns a pointer to a QAxObject wrapping the COM object provided by the method or property name, passing passing the parameters var1, var1, var2, var3, var4, var5, var6, var7 and var8."); //... } This is an overloaded function. The QVariant objects in vars are updated when the method has out-parameters.(). Sets the property prop to writable if ok is true, otherwise sets prop to be read-only. By default, all properties are writable. Warning: Depending on the control implementation this setting might be ignored for some properties. See also propertyWritable() and propertyChanged(). This generic signal gets emitted when the COM object issues the event name. argc is the number of parameters provided by the event (DISPPARAMS.cArgs), and argv is the pointer to the parameter values (DISPPARAMS.rgvarg). Note that the order of parameter values is turned around, ie. the last element of the array is the first parameter in the function. void Receiver::slot(const QString &name, int argc, void *argv) { VARIANTARG *params = (VARIANTARG*)argv; if (name.startsWith("BeforeNavigate2(")) { IDispatch *pDisp = params[argc-1].pdispVal; VARIANTARG URL = *params[argc-2].pvarVal; VARIANTARG Flags = *params[argc-3].pvarVal; VARIANTARG TargetFrameName = *params[argc-4].pvarVal; VARIANTARG PostData = *params[argc-5].pvarVal; VARIANTARG Headers = *params[argc-6].pvarVal; bool *Cancel = params[argc-7].pboolVal; } } Use this signal if the event has parameters of unsupported data types. Otherwise, connect directly to the signal 4.1.
http://doc.trolltech.com/main-snapshot/qaxbase.html
crawl-003
refinedweb
821
50.53
An interface is a contract, but remember that a contract applies to both parties. Most of the time, when you read an interface, you look at it from the point of view of the client side of the contract, but often it helps to read it from the server side. For example, let's look at the interface for control panel applications. Most of the time, when you're reading this documentation, you are wearing your "I am writing a Control Panel application" hat. So, for example, the documentation says When the controlling application first loads the Control Panel application, it retrieves the address of the CPlApplet function and subsequently uses the address to call the function and pass it messages. With your "I am writing a Control Panel application" hat, this means "Gosh, I had better have a function called CPlApplet and export it so I can receive messages." But if you are instead wearing your "I am hosting a Control Panel application" hat, this means, "Gosh, I had better call GetProcAddress() to get the address of the application's CPlApplet function so I can send it messages." Similarly, under the "Message Processing" section it lists the messages that are sent from the controlling application to the Control Panel application. If you are wearing your "I am writing a Control Panel application" hat, this means "Gosh, I had better be ready to receive these messages in this order." But if you are wearing your "I am hosting a Control Panel application" hat, this means "Gosh, I had better send these messages in the order listed." And finally, when it says "the controlling application release the Control Panel application by calling the FreeLibrary function," your "I am writing a Control Panel application" hat says "I had better be prepared to be unloaded," whereas your "I am hosting a Control Panel application" hat says, "This is where I unload the DLL." So let's try it. As always, start with our scratch program and change the WinMain: #include <cpl.h> int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev, LPSTR lpCmdLine, int nShowCmd) { HWND hwnd; g_hinst = hinst; if (!InitApp()) return 0; if (SUCCEEDED(CoInitialize(NULL))) {/* In case we use COM */ hwnd = CreateWindow( "Scratch", /* Class Name */ "Scratch", /* Title */ WS_OVERLAPPEDWINDOW, /* Style */ CW_USEDEFAULT, CW_USEDEFAULT, /* Position */ CW_USEDEFAULT, CW_USEDEFAULT, /* Size */ NULL, /* Parent */ NULL, /* No menu */ hinst, /* Instance */ 0); /* No special parameters */ if (hwnd) { TCHAR szPath[MAX_PATH]; LPTSTR pszLast; DWORD cch = SearchPath(NULL, TEXT("access.cpl"), NULL, MAX_PATH, szPath, &pszLast); if (cch > 0 && cch < MAX_PATH) { RunControlPanel(hwnd, szPath); } } CoUninitialize(); } return 0; } Instead of showing the window and entering the message loop, we start acting like a Control Panel host. Our victim today is access.cpl, the accessibility control panel. After locating the program on the path, we ask RunControlPanel to do the heavy lifting: void RunControlPanel(HWND hwnd, LPCTSTR pszPath) { // Maybe this control panel application has a custom manifest ACTCTX act = { 0 }; act.cbSize = sizeof(act); act.dwFlags = 0; act.lpSource = pszPath; act.lpResourceName = MAKEINTRESOURCE(123); HANDLE hctx = CreateActCtx(&act); ULONG_PTR ulCookie; if (hctx == INVALID_HANDLE_VALUE || ActivateActCtx(hctx, &ulCookie)) { HINSTANCE hinstCPL = LoadLibrary(pszPath); if (hinstCPL) { APPLET_PROC pfnCPlApplet = (APPLET_PROC) GetProcAddress(hinstCPL, "CPlApplet"); if (pfnCPlApplet) { if (pfnCPlApplet(hwnd, CPL_INIT, 0, 0)) { int cApplets = pfnCPlApplet(hwnd, CPL_GETCOUNT, 0, 0); // We're going to run application zero // (In real life we might show the user a list of them // and let them pick one) if (cApplets > 0) { CPLINFO cpli; pfnCPlApplet(hwnd, CPL_INQUIRE, 0, (LPARAM)&cpli); pfnCPlApplet(hwnd, CPL_DBLCLK, 0, cpli.lData); pfnCPlApplet(hwnd, CPL_STOP, 0, cpli.lData); } } pfnCPlApplet(hwnd, CPL_EXIT, 0, 0); } FreeLibrary(hinstCPL); } if (hctx != INVALID_HANDLE_VALUE) { DeactivateActCtx(0, ulCookie); ReleaseActCtx(hctx); } } } Ignore the red lines for now; we'll discuss them later. All we're doing is following the specification but reading it from the host side. So we load the library, locate its entry point, and call it with CPL_INIT, then CPL_GETCOUNT. If there are any control panel applications inside this CPL file, we inquire after the first one, double-click it (this is where all the interesting stuff happens), then stop it. After all that excitement, we clean up according to the rules set out for the host (namely, by sending a CPL_EXIT message.) So that's all. Well, except for the red parts. What's that about? The red parts are to support Control Panel applications that have a custom manifest. This is something new with Windows XP and is documented in MSDN here. If you go down to the "Using ComCtl32 Version 6 in Control Panel or a DLL That Is Run by RunDll32.exe" section, you'll see that the application provides its manifest to the Control Panel host by attaching it as resource number 123. So that's what the red code does: It loads and activates the manifest, then invites the Control Panel application to do its thing (with its manifest active), then cleans up. If there is no manifest, CreateActCtx will return INVALID_HANDLE_VALUE. We do not treat that as an error, since many programs don't yet provide a manifest. Exercise: What are the security implications of passing NULL as the first parameter to SearchPath? Well, someone could either: Jam a new .cpl in the same dir as the EXE.. Or if they’re on a LUA, they could put a malicious .cpl in their home directory and set it as the current directory before running your program. That would let them run their own code, bypassing policies. "What are the security implications of passing NULL as the first parameter to SearchPath?" A rogue access.cpl file could be placed in the current directory, and SearchPath would find it before the one in the system directory. (?) BTW: Why do some functions (such as this CreateFile and this CreateActCtx) return INVALID_HANDLE_VALUE when they fail while others return zero? Somehow I missed Jack’s comment. Whoops. Sorry bout that. Lost during editing. Why does INVALID_HANDLE_VALUE even exist? When CreateFile() fails to open a file, its return value can be either 0 or -1. The only reliable way to check is to ignore the MSDN Library and just test the result for <= 0. Believe it or not, that’s a topic I already had planned out for a future entry. INVALID_HANDLE_VALUE is -1 cast to the data type HANDLE. HANDLE is either ULONG_PTR or PVOID depending if STRICT is defined at compile time (always is for C++, optional for C). In either case, the test <= 0 is wrong because ((HANDLE)-200) is not an error (it is a real handle in some functions) and because ((ULONG_PTR)-1) > 0 . Anyway, INVALID_HANDLE_VALUE exists just for the benefit of people porting code from the POSIX/UNIX/C functions that return -1 on error rather then NULL, such as creat(), open() lseek() etc. I have never heard of CreateFile returning NULL, but then my code routinly does: if (h == INVALID_HANDLE_VALUE) h = NULL; if (!h) ItFailed! Oh and INVALID_HANDLE_VALUE is a valid handle to the current process (at least on ntoskrnl.exe based operating systems). It is the success return value from GetCurrentProcess().
https://blogs.msdn.microsoft.com/oldnewthing/20031226-00/?p=41343
CC-MAIN-2017-43
refinedweb
1,170
54.12
#include <SimpleArp.h> Inherits BasicModule. Inheritance diagram for SimpleArp: This class takes the network layer id as the network layer address and the mac layer id as the mac layer address ARP implementations are divers, it does not make sense to start from a common class. Their main purpose is to translate layer 2 into layer 3 addresses. However, these addresses can be very different. Here, simple integers are sufficient, but for hardware-in-the-loop simulations more complex ones are appropriate. In contrast to this ARP, others may want to cache entries. This adds another set of basic operations that may or may not make sense for ARPs.
http://mobility-fw.sourceforge.net/api/classSimpleArp.html
CC-MAIN-2018-05
refinedweb
109
56.25
<< Bugzilla::DB - Database access routines, using DBI # Obtain db handle use Bugzilla::DB; my $dbh = Bugzilla->dbh; # prepare a query using DB methods my $sth = $dbh->prepare("SELECT " . $dbh->sql_date_format("creation_ts", "%Y%m%d") . " FROM bugs WHERE bug_status != 'RESOLVED' " . $dbh->sql_limit(1)); # Execute the query $sth->execute; # Get the results my @result = $sth->fetchrow_array; # Schema Modification $dbh->bz_add_column($table, $name, \%definition, $init_value); $dbh->bz_add_index($table, $name, $definition); $dbh->bz_add_table($name); $dbh->bz_drop_index($table, $name); $dbh->bz_drop_table($name); $dbh->bz_alter_column($table, $name, \%new_def, $set_nulls_to); $dbh->bz_drop_column($table, $column); $dbh->bz_rename_column($table, $old_name, $new_name); # Schema Information my $column = $dbh->bz_column_info($table, $column); my $index = $dbh->bz_index_info($table, $index); Functions in this module allows creation of a database handle to connect to the Bugzilla database. This should never be done directly; all users should use the Bugzilla module to access the current dbh instead. This module also contains methods extending the returned handle with functionality which is different between databases allowing for easy customization for particular database via inheritance. These methods should be always preffered over hard-coding SQL commands. Subclasses of Bugzilla::DB are required to define certain constants. These constants are required to be subroutines or "use constant" variables. BLOB_TYPE The \%attr argument that must be passed to bind_param in order to correctly escape a LONGBLOB type. ISOLATION_LEVEL The argument that this database should send to SET TRANSACTION ISOLATION LEVEL when starting a transaction. If you override this in a subclass, the isolation level you choose should be as strict as or more strict than the default isolation level defined in Bugzilla::DB. A new database handle to the required database can be created using this module. This is normally done by the Bugzilla module, and so these routines should not be called from anywhere else. connect_main Function to connect to the main database, returning a new database handle. $no_db_name(optional) - If true, connect to the database server, but don't connect to a specific database. This is only used when creating a database. After you create the database, you should re-create a new Bugzilla::DB object without using this parameter. New instance of the DB class connect_shadow Function to connect to the shadow database, returning a new database handle. This routine dies if no shadow database is configured. A new instance of the DB class bz_check_requirements Checks to make sure that you have the correct DBD and database version installed for the database that Bugzilla will be using. Prints a message and exits if you don't pass the requirements. If $db_check is false (from localconfig), we won't check the database version. $output- trueif the function should display informational output about what it's doing, such as versions found. bz_create_database Creates an empty database with the name $db_name, if that database doesn't already exist. Prints an error message and exits if we can't create the database. _connect Internal function, creates and returns a new, connected instance of the correct DB class. This routine dies if no driver is specified. $driver- name of the database driver to use $host- host running the database we are connecting to $dbname- name of the database to connect to $port- port the database is listening on $sock- socket the database is listening on $user- username used to log in to the database $pass- password used to log in to the database A new instance of the DB class _handle_error Function passed to the DBI::connect call for error handling. It shortens the error for printing. import Overrides the standard import method to check that derived class implements all required abstract methods. Also calls original implementation in its super class. Note: Methods which can be implemented generically for all DBs are implemented in this module. If needed, they can be overridden with DB specific code. Methods which do not have standard implementation are abstract and must be implemented for all supported databases separately. To avoid confusion with standard DBI methods, all methods returning string with formatted SQL command have prefix sql_. All other methods have prefix bz_. new Constructor. Abstract method, should be overridden by database specific code. $user- username used to log in to the database $pass- password used to log in to the database $host- host running the database we are connecting to $dbname- name of the database to connect to $port- port the database is listening on $sock- socket the database is listening on A new instance of the DB class The constructor should create a DSN from the parameters provided and then call db_new() method of its super class to create a new class instance. See db_new description in this module. As per DBI documentation, all class variables must be prefixed with "private_". See DBI. sql_regexp Outputs SQL regular expression operator for POSIX regex searches (case insensitive) in format suitable for a given database. Abstract method, should be overridden by database specific code. $expr- SQL expression for the text to be searched (scalar) $pattern- the regular expression to search for (scalar) $nocheck- true if the pattern should not be tested; false otherwise (boolean) $real_pattern- the real regular expression to search for. This argument is used when $patternis a placeholder ('?'). Formatted SQL for regular expression search (e.g. REGEXP) (scalar) sql_not_regexp Outputs SQL regular expression operator for negative POSIX regex searches (case insensitive) in format suitable for a given database. Abstract method, should be overridden by database specific code. Same as "sql_regexp". Formatted SQL for negative regular expression search (e.g. NOT REGEXP) (scalar) sql_limit Returns SQL syntax for limiting results to some number of rows with optional offset if not starting from the begining. Abstract method, should be overridden by database specific code. $limit- number of rows to return from query (scalar) $offset- number of rows to skip before counting (scalar) Formatted SQL for limiting number of rows returned from query with optional offset (e.g. LIMIT 1, 1) (scalar) sql_from_days Outputs SQL syntax for converting Julian days to date. Abstract method, should be overridden by database specific code. $days- days to convert to date Formatted SQL for returning Julian days in dates. (scalar) sql_to_days Outputs SQL syntax for converting date to Julian days. Abstract method, should be overridden by database specific code. $date- date to convert to days Formatted SQL for returning date fields in Julian days. (scalar) sql_date_format Outputs SQL syntax for formatting dates. Abstract method, should be overridden by database specific code. $date- date or name of date type column (scalar) $format- format string for date output (scalar) ( %Y= year, four digits, %y= year, two digits, %m= month, %d= day, %a= weekday name, 3 letters, %H= hour 00-23, %i= minute, %s= second) Formatted SQL for date formatting (scalar) sql_date_math Outputs proper SQL syntax for adding some amount of time to a date. Abstract method, should be overridden by database specific code. $date string The date being added to or subtracted from. $operator string Either - or +, depending on whether you're subtracting or adding. $interval integer The time interval you're adding or subtracting (e.g. 30) $units string the units the interval is in (e.g. 'MINUTE') Formatted SQL for adding or subtracting a date and some amount of time (scalar) sql_position Outputs proper SQL syntax determining position of a substring (fragment) withing a string (text). Note: if the substring or text are string constants, they must be properly quoted (e.g. "'pattern'"). It searches for the string in a case-sensitive manner. If you want to do a case-insensitive search, use "sql_iposition". $fragment- the string fragment we are searching for (scalar) $text- the text to search (scalar) Formatted SQL for substring search (scalar) sql_iposition Just like "sql_position", but case-insensitive. sql_group_by Outputs proper SQL syntax for grouping the result of a query. For ANSI SQL databases, we need to group by all columns we are querying for (except for columns used in aggregate functions). Some databases require (or even allow) to specify only one or few columns if the result is uniquely defined. For those databases, the default implementation needs to be overloaded. $needed_columns- string with comma separated list of columns we need to group by to get expected result (scalar) $optional_columns- string with comma separated list of all other columns we are querying for, but which are not in the required list. Formatted SQL for row grouping (scalar) sql_string_concat Returns SQL syntax for concatenating multiple strings (constants or values from table columns) together. @params- array of column names or strings to concatenate Formatted SQL for concatenating specified strings sql_string_until Returns SQL for truncating a string at the first occurrence of a certain substring. Note that both parameters need to be sql-quoted. $stringThe string we're truncating $substringThe substring we're truncating at. sql_fulltext_search Returns one or two SQL expressions for performing a full text search for specified text on a given column. If one value is returned, it is a numeric expression that indicates a match with a positive value and a non-match with zero. In this case, the DB must support casting numeric expresions to booleans. If two values are returned, then the first value is a boolean expression that indicates the presence of a match, and the second value is a numeric expression that can be used for ranking. There is a ANSI SQL version of this method implemented using LIKE operator, but it's not a real full text search. DB specific modules should override this, as this generic implementation will be always much slower. This generic implementation returns 'relevance' as 0 for no match, or 1 for a match. $column- name of column to search (scalar) $text- text to search for (scalar) Formatted SQL for full text search sql_istrcmp Returns SQL for a case-insensitive string comparison. $left- What should be on the left-hand-side of the operation. $right- What should be on the right-hand-side of the operation. $op(optional) - What the operation is. Should be a valid ANSI SQL comparison operator, such as =, <, LIKE, etc. Defaults to =if not specified. A SQL statement that will run the comparison in a case-insensitive fashion. Uses "sql_istring", so it has the same performance concerns. Try to avoid using this function unless absolutely necessary. Subclass Implementors: Override sql_istring instead of this function, most of the time (this function uses sql_istring). sql_istring Returns SQL syntax "preparing" a string or text column for case-insensitive comparison. $string- string to convert (scalar) Formatted SQL making the string case insensitive. The default implementation simply calls LOWER on the parameter. If this is used to search on a text column with index, the index will not be usually used unless it was created as LOWER(column). sql_in Returns SQL syntax for the IN () operator. Only necessary where an IN clause can have more than 1000 items. $column_name- Column name (e.g. bug_id) $in_list_ref- an arrayref containing values for IN () Formatted SQL for the IN operator. These methods are implemented in Bugzilla::DB, and only need to be implemented in subclasses if you need to override them for database-compatibility reasons. These methods return information about data in the database. bz_last_key Returns the last serial number, usually from a previous INSERT. Must be executed directly following the relevant INSERT. This base implementation uses "last_insert_id" in DBI. If the DBD supports it, it is the preffered way to obtain the last serial index. If it is not supported, the DB-specific code needs to override this function. $table- name of table containing serial column (scalar) $column- name of column containing serial data type (scalar) Last inserted ID (scalar) These methods are used by the Bugzilla installation programs to set up the database. bz_populate_enum_tables For an upgrade or an initial installation, populates the tables that hold the legal values for the old "enum" fields: bug_severity, resolution, etc. Prints out information if it inserts anything into the DB. These methods modify the current Bugzilla Schema. Where a parameter says "Abstract index/column definition", it returns/takes information in the formats defined for indexes and columns in Bugzilla::DB::Schema::ABSTRACT_SCHEMA. bz_add_column Adds a new column to a table in the database. Prints out a brief statement that it did so, to stdout. Note that you cannot add a NOT NULL column that has no default -- the database won't know what to set all the NULL values to. $table- the table where the column is being added $name- the name of the new column \%definition- Abstract column definition for the new column $init_value(optional) - An initial value to set the column to. Required if your column is NOT NULL and has no DEFAULT set. bz_add_index Adds a new index to a table in the database. Prints out a brief statement that it did so, to stdout. If the index already exists, we will do nothing. $table- The table the new index is on. $name- A name for the new index. $definition- An abstract index definition. Either a hashref or an arrayref. bz_add_table Creates a new table in the database, based on the definition for that table in the abstract schema. Note that unlike the other 'add' functions, this does not take a definition, but always creates the table as it exists in "ABSTRACT_SCHEMA" in Bugzilla::DB::Schema. If a table with that name already exists, then this function returns silently. $name- The name of the table you want to create. bz_drop_index Removes an index from the database. Prints out a brief statement that it did so, to stdout. If the index doesn't exist, we do nothing. $table- The table that the index is on. $name- The name of the index that you want to drop. bz_drop_table Drops a table from the database. If the table doesn't exist, we just return silently. $name- The name of the table to drop. bz_alter_column Changes the data type of a column in a table. Prints out the changes being made to stdout. If the new type is the same as the old type, the function returns without changing anything. $table- the table where the column is $name- the name of the column you want to change \%new_def- An abstract column definition for the new data type of the columm $set_nulls_to(Optional) - If you are changing the column to be NOT NULL, you probably also want to set any existing NULL columns to a particular value. Specify that value here. NOTE: The value should not already be SQL-quoted. bz_drop_column Removes a column from a database table. If the column doesn't exist, we return without doing anything. If we do anything, we print a short message to stdout about the change. $table- The table where the column is $column- The name of the column you want to drop bz_rename_column Renames a column in a database table. If the $old_name column doesn't exist, we return without doing anything. If $old_name and $new_name both already exist in the table specified, we fail. $table- The name of the table containing the column that you want to rename $old_name- The current name of the column that you want to rename $new_name- The new name of the column bz_rename_table Renames a table in the database. Does nothing if the table doesn't exist. Throws an error if the old table exists and there is already a table with the new name. $old_name- The current name of the table. $new_name- What you're renaming the table to. These methods return information about the current Bugzilla database schema, as it currently exists on the disk. Where a parameter says "Abstract index/column definition", it returns/takes information in the formats defined for indexes and columns for "ABSTRACT_SCHEMA" in Bugzilla::DB::Schema. bz_column_info Get abstract column definition. $table- The name of the table the column is in. $column- The name of the column. An abstract column definition for that column. If the table or column does not exist, we return undef. bz_index_info Get abstract index definition. $table- The table the index is on. $index- The name of the index. An abstract index definition for that index, always in hashref format. The hashref will always contain the TYPE element, but it will be an empty string if it's just a normal index. If the index does not exist, we return undef. These methods deal with the starting and stopping of transactions in the database. bz_in_transaction Returns 1 if we are currently in the middle of an uncommitted transaction, 0 otherwise. bz_start_transaction Starts a transaction. It is OK to call bz_start_transaction when you are already inside of a transaction. However, you must call "bz_commit_transaction" as many times as you called bz_start_transaction, in order for your transaction to actually commit. Bugzilla uses REPEATABLE READ transactions. Returns nothing and takes no parameters. bz_commit_transaction Ends a transaction, commiting all changes. Returns nothing and takes no parameters. bz_rollback_transaction Ends a transaction, rolling back all changes. Returns nothing and takes no parameters. Methods in this class are intended to be used by subclasses to help them with their functions. db_new Constructor $dsn- database connection string $user- username used to log in to the database $pass- password used to log in to the database \%override_attrs- set of attributes for DB connection (optional). You only have to set attributes that you want to be different from the default attributes set inside of db_new. A new instance of the DB class The name of this constructor is not new, as that would make our check for implementation of new by derived class useless. DBI "DB_MODULE" in Bugzilla::Constants <<
https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/DB.html
CC-MAIN-2018-47
refinedweb
2,917
56.15
In the previous notebook, we studied a few basic ciphers together with Diffie-Hellman key exchange. The Vigenère cipher we studied uses a secret key for encrypting and decrypting messages. The same key is used for both encryption and decryption, so we say it is a symmetric key cipher. In order for two parties to share the same secret key, we studied the Diffie-Hellman protocol, whose security rests on the difficulty of the discrete logarithm problem. Although this represents progress towards secure communication, it is particularly vulnerable to problems of authentication. For example, imagine a "man-in-the-middle attack": Alice and Bob wish to communicate securely, and begin the Diffie-Hellman protocol over an insecure line. But Eve has intercepted the line. To Alice, she pretends to be Bob, and to Bob, she pretends to be Alice. She goes through the Diffie-Hellman protocol with each, obtaining two secret keys, and decrypting/encrypting messages as they pass through her computer. In this way, Alice and Bob think they are talking to each other, but Eve is just passing (and understanding) their messages the whole time! To thwart such an attack, we need some type of authentication. We need something asymmetric -- something one person can do that no other person can do, like a verifiable signature, so that we can be sure we're communicating with the intended person. For such a purpose, we introduce the RSA cryptosystem. Computationally based on modular exponentiation, its security rests on the difficulty of factoring large numbers. The material in this notebook complements Chapter 7 of An Illustrated Theory of Numbers. Recall Fermat's Little Theorem: if $p$ is prime and $GCD(a,p) = 1$, then $a^{p-1} \equiv 1$ mod $p$. This is a special case of Euler's theorem, which holds for any modulus $m$. Euler's theorem states: if $m$ is a positive integer and $GCD(a,m) = 1$, then $a^{\phi(m)} \equiv 1$ mod $m$. Here $\phi(m)$ denotes the totient of $m$, which is the number of elements of $\{ 1,...,m \}$ which are coprime to $m$. We give a brute force implementation of the totient first, using our old Euclidean algorithm code for the GCD. def GCD(a,b): while b: # Recall that != means "not equal to". a, b = b, a % b return abs(a) def totient(m): tot = 0 # The running total. j = 0 while j < m: # We go up to m, because the totient of 1 is 1 by convention. j = j + 1 # Last step of while loop: j = m-1, and then j = j+1, so j = m. if GCD(j,m) == 1: tot = tot + 1 return tot totient(17) # The totient of a prime p should be p-1. totient(1000) totient(1) # Check a borderline case, to make sure we didn't make an off-by-one error. 17**totient(1000) % 1000 # Let's demonstrate Euler's theorem. Note GCD(17,1000) = 1. pow(17,totient(1000),1000) # A more efficient version, using the pow command. %timeit totient(123456) The totient is a multiplicative function, meaning that if $GCD(a,b) = 1$, then $\phi(ab) = \phi(a) \phi(b)$. Therefore, the totient of number can be found quickly from the totient of the prime powers within its decomposition. We can re-implement the totient using our functions for prime decomposition and multiplicative functions from Notebook 4. When $p^e$ is a prime power, the numbers among $1, \ldots, p^e$ are coprime to $p^e$ precisely when they are not multiples of $p$. Therefore, the totient of a prime power is pretty easy to compute: $$\phi(p^e) = p^e - p^{e-1} = p^{e-1} (p-1).$$ We implement this, and use the multiplicative function code to complete the implementation of the totient. def totient_pp(p,e): return (p**(e-1)) * (p-1) Note that for efficiency, the computation of $p^{e-1}(p-1)$ is probably faster than the computation of $p^e - p^{e-1}$ (which relies on two exponents). totient = mult_function(totient_pp) totient(1000) %timeit totient(123456) This should be much faster than the previous brute-force computation of the totient. A consequence of Euler's theorem is that -- depending on the modulus -- some exponentiation can be "reversed" by another exponentiation, a form of taking a "root" in modular arithmetic. For example, if we work modulo $100$, and $GCD(a,100) = 1$, then Euler's theorem states that $$a^{40} \equiv 1 \text{ mod } 100.$$ It follows that $a^{80} \equiv 1$ and $a^{81} \equiv a$, modulo $100$. Expanding this, we find $$a \equiv a^{81} = a^{3 \cdot 27} = (a^3)^{27} \text{ mod } 100.$$ What all this computation shows is that "raising to the 27th power" is like "taking the cube root", modulo 100 (and with appropriate bases). for b in range(20): b_cubed = pow(b,3,100) bb = pow(b_cubed,27,100) print b, b_cubed, bb, GCD(b,100) == 1 In every line ending with True, the first and third numbers should match. This will happen in some False lines too, but not reliably since Euler's theorem does not apply there. We found the exponent 27 -- reversing the cubing operation -- by an ad hoc sort of procedure. The relationship between 27 and 3, which made things work, is that $$3 \cdot 27 \equiv 1 \text{ mod } 40.$$ In other words, $3 \cdot 27 = 1 + 40k$ for some (positive, in fact) integer $k$. Recalling that $40 = \phi(100)$, this relationship and Euler's theorem imply that $$a^{3 \cdot 27} = a^{1 + 40k} \equiv a^1 = a \text{ mod } 100.$$ By this argument, we have the following consequence of Euler's theorem. If $GCD(a,m) = 1$, and $ef \equiv 1$ mod $\phi(m)$, then $$a^{ef} \equiv a \text{ mod } \phi(m).$$ In this way, "raising to the $f$ power" is like "taking the $e$-th root", modulo $m$. If we are given $f$, then $e$ is a multiplicative inverse of $f$ modulo $\phi(m)$. In particular, such a multiplicative inverse exists if and only if $GCD(e,\phi(m)) = 1$. The following function computes a multiplicative inverse, by adapting the solve_LDE function from Notebook 2. After all, solving $ex \equiv 1$ mod $m$ is equivalent to solving the linear Diophantine equation $ex + my = 1$ (and only caring about the $x$-value). def mult_inverse(a,m): ''' Finds the multiplicative inverse of a, mod m. If GCD(a,m) = 1, this is returned via its natural representative. Otherwise, None is returned. ''' u = a # We use u instead of dividend. v = m # We use v instead of divisor. u_hops, u_skips = 1,0 # u is built from one hop (a) and no skips. v_hops, v_skips = 0,1 # v is built from no hops and one skip (b). while v != 0: # We could just write while v: q = u // v # q stands for quotient. r = u % v # r stands for remainder. So u = q(v) + r. r_hops = u_hops - q * v_hops # Tally hops r_skips = u_skips - q * v_skips # Tally skips u,v = v,r # The new dividend,divisor is the old divisor,remainder. u_hops, v_hops = v_hops, r_hops # The new u_hops, v_hops is the old v_hops, r_hops u_skips, v_skips = v_skips, r_skips # The new u_skips, v_skips is the old v_skips, r_skips g = u # The variable g now describes the GCD of a and b. if g == 1: return u_hops % m else: # When GCD(a,m) is not 1... return None mult_inverse(3,40) # 3 times what is congruent to 1, mod 40? mult_inverse(5,40) # None should be returned. Let's test this out on some bigger numbers. from random import randint while True: m = randint(1000000, 9999999) # a random 7-digit number e = randint(100,999) # a random 3-digit number a = randint(10,99) # a random 2-digit number if GCD(a,m) == 1: tot = totient(m) if GCD(e,tot) == 1: f = mult_inverse(e,tot) test_number = pow(a, e*f, m) print "Success!" print "%d ^ (%d * %d) = %d, mod %d"%(a,e,f,test_number,m) break # Escapes the loop once an example is found! What is the largest integer whose totient is 100? Study this by a brute force search, i.e., looping through the integers up to 10000 For which integers $n$ is it true that $\phi(n) = n/2$? Study this by a brute force search in order to make a conjecture. Then prove it if you can. Compute the totient of the numbers from 1 to 10000, and analyze the results. The totient $\phi(n)$ is always less than $n$ when $n > 1$, but how does the ratio $\phi(n) / n$ behave? Create a graph. What is the average value of the ratio? If $a^{323} \equiv 802931$, mod $5342481$, and $GCD(a, 5342481) = 1$, and $0 < a < 5342481$, then what is $a$? Challenge: Create a function superpow(x,y,z,m) which computes $x^{y^z}$ modulo $m$ efficiently, when $GCD(x,m) = 1$ and $m$ is small enough to factor. Like Diffie-Hellman, the RSA protocol involves a series of computations in modular arithmetic, taking care to keep some numbers private while making others public. RSA was published two years after Diffie-Hellman, in 1978 by Rivest, Shamir, and Adelman (hence its name). The great advance of the RSA protocol was its asymmetry. While Diffie-Hellman is used for symmetric key cryptography (using the same key to encrypt and decrypt), the RSA protocol has two keys: a public key that can be used by anyone for encryption and a private key that can be used by its owner for decryption. In this way, if Alice publishes her public key online, anyone can send her an encrypted message. But as long as she keeps her private key private, only Alice can decrypt the messages sent to her. Such an asymmetry allows RSA to be used for authentication -- if the owner of a private key has an ability nobody else has, then this ability can be used to prove the owner's identity. In practice, this is one of the most common applications of RSA, guaranteeing that we are communicating with the intended person. In the RSA protocol, the private key is a pair of large (e.g. 512 bit) prime numbers, called $p$ and $q$. The public key is the pair $(N, e)$, where $N$ is defined to be the product $N = pq$ and $e$ is an auxiliary number called the exponent. The number $e$ is often (for computational efficiency and other reasons) taken to be 65537 -- the same number $e$ can be used over and over by different people. But it is absolutely crucial that the same private keys $p$ and $q$ are not used by different individuals. Individuals must create and safely keep their own private key. We begin with the creation of a private key $(p,q)$. We use the SystemRandom function (see the previous Python Notebook) to cook up cryptographically secure random numbers, and the Miller-Rabin test to certify primality. from random import SystemRandom, randint random_prime(bitlength): while True: p = SystemRandom().getrandbits(bitlength) # A cryptographically secure random number. if is_prime(p): return p random_prime(100) # A random 100-bit prime random_prime(512) # A random 512-bit prime. Should be quick, thanks to Miller-Rabin! %timeit random_prime(1024) # Even 1024-bit primes should be quick! def RSA_privatekey(bitlength): ''' Create private key for RSA, with given bitlength. Just a pair of big primes! ''' p = random_prime(bitlength) q = random_prime(bitlength) return p,q # Returns both values, as a "tuple" type(RSA_privatekey(8)) # When a function returns multiple values, the type is "tuple". p,q = RSA_privatekey(512) # If a function outputs two values, you can assign them to two variables. print p print q def RSA_publickey(p,q, e = 65537): ''' Makes the RSA public key out of two prime numbers p,q (the private key), and an auxiliary exponent e. By default, e = 65537. ''' N = p*q return N,e N,e = RSA_publickey(p,q) # No value of e is input, so it will default to 65537 print N # A big number! print e Now we explain how the public key $(N,e)$ and the private key $(p,q)$ are used to encrypt and decrypt a (numerical) message $m$. If you wish to encrypt/decrypt a text message, one case use a numerical scheme like ASCII, of course. The message should be significantly shorter than the modulus, $m < N$ (ideally, shorter than the private key primes), but big enough so that $m^e$ is much bigger than $N$ (not usually a problem if $e = 65537$). The encryption procedure is simple -- it requires just one line of Python code, using the message and public key. The ciphertext $c$ is given by the formula $$c = m^e \text{ mod } N,$$ where here we mean the "natural representative" of $m^e$ modulo $N$. def RSA_encrypt(message, N, e): ''' Encrypts message, using the public keys N,e. ''' return pow(message, e, N) c = RSA_encrypt(17,N,e) # c is the ciphertext. print c # A very long number! To decrypt the ciphertext, we need to "undo" the operation of raising to the $e$-th power modulo $N$. We must, effectively, take the $e$-th root of the ciphertext, modulo $N$. This is what we studied earlier in this notebook. Namely, if $c \equiv m^e \text{ mod } N$ is the ciphertext, and $ef \equiv 1$ modulo $\phi(N)$, then $$c^f \equiv m^{ef} \equiv m \text{ mod } N.$$ So we must raise the ciphertext to the $f$ power, where $f$ is the multiplicative inverse of $e$ modulo $\phi(N)$. Given a giant number $N$, it is difficult to compute the totient $\phi(N)$. But, with the private key $p$ and $q$ (primes), the fact that $N = pq$ implies $$\phi(N) = (p-1) \cdot (q-1) = pq - p - q + 1 = N - p - q + 1.$$ Armed with the private key (and the public key, which everyone has), we can decrypt a message in just a few lines of Python code. def RSA_decrypt(ciphertext, p,q,N,e): ''' Decrypts message, using the private key (p,q) and the public key (N,e). We allow the public key N as an input parameter, to avoid recomputing it. ''' tot = N - (p+q) + 1 f = mult_inverse(e,tot) # This uses the Euclidean algorithm... very quick! return pow(ciphertext,f,N) RSA_decrypt(c, p,q,N,e) # We decrypt the ciphertext... what is the result? That's the entire process of encryption and decryption. Encryption requires just the public key $(N,e)$ and decryption requires the private key $(p,q)$ too. Everything else is modular arithmetic, using Euler's theorem and the Euclidean algorithm to find modular multiplicative inverses. From a practical standpoint, there are many challenges, and we just mention a few here. Key generation: The person who constructs the private key $(p,q)$ needs to be careful. The primes $p$ and $q$ need to be pretty large (512 bits, or 1024 bits perhaps), which is not so difficult. They also need to be constructed randomly. For imagine that Alice comes up with her private key $(p,q)$ and Anne comes up with her private key $(q,r)$, with the same prime $q$ in common. Their public keys will include the numbers $N = pq$ and $M = qr$. If someone like Arjen comes along and starts taking GCDs of all the public keys in a database, that person will stumble upon the fact that $GCD(N,M) = q$, from which the private keys $(p,q)$ and $(q,r)$ can be derived. And this sort of disaster has happened! Poorly generated keys were stored in a database, and discovered by Arjen Lenstra et al.. Security by difficulty of factoring: The security of RSA is based on the difficulty of obtaining the private key $(p,q)$ from the public key $(N,e)$. Since $N = pq$, this is precisely the difficulty of factoring a large number $N$ into two primes (given the knowledge that it is the product of two primes). Currently it seems very difficult to factor large numbers. The RSA factoring challenges give monetary rewards for factoring such large $N$. The record (2017) is factoring a 768-bit (232 digit) number, RSA-768. For this reason, we may consider a 1024-bit number secure for now (i.e. $p$ and $q$ are 512-bit primes), or use a 2048-bit number if we are paranoid. If quantum computers develop sufficiently, they could make factoring large numbers easy, and RSA will have to be replaced by a quantum-secure protocol. Web of Trust: Trust needs to begin somewhere. Every time Alice and Bob communicate, Alice should not come up with a new private key, and give Bob the new public key. For if they are far apart, how does Bob know he's receiving Alice's public key and not talking to an eavesdropper Eve? Instead, it is better for Alice to register (in person, perhaps) her public key at some time. She can create her private key $(p,q)$ and register the resulting public key $(N,e)$ with some "key authority" who checks her identity at the time. The key authority then stores everyone's public keys -- effectively they say "if you want to send a secure message to Alice, use the following public key: (..., ...)" Then Bob can consult the key authority when he wishes to communicate securely to Alice, and this private/public key combination can be used for years. But, as one might guess, this kicks the trust question to another layer. How does Bob know he's communicating with the key authority? The key authorities need to have their own authentication mechanism, etc.. One way to avoid going down a rabbithole of mistrust is to distribute trust across a network of persons. Instead of a centralized "key authority", one can distribute one's public keys across an entire network of communicators (read about openPGP). Then Bob, if he wishes, can double-check Alice's public keys against the records of numerous members of the network -- assuming that hackers haven't gotten to all of them! In practice, some implementations of RSA use a more centralized authority and others rely on a web of trust. Cryptography requires a clever application of modular arithmetic (in Diffie-Hellman, RSA, and many other systems), but also a meticulous approach to implementation. Often the challenges of implementation introduce new problems in number theory. A variant of RSA is used to "digitally sign" a document. Not worrying about keeping a message private for now, suppose that Alice wants to send Bob a message and sign the message in such a way that Bob can be confident it was sent by Alice. Alice can digitally sign her message by first hashing the message and then encrypting the hash using her private key (previously the public key was used for encryption -- this is different!). Hashing a message is an irreversible process that turns a message of possibly long length into a nonsense-message of typically fixed length, in such a way that the original message cannot be recovered from the nonsense-message. There is a science to secure hashing, which we don't touch on here. Instead, we import the sha512 hashing function from the Python standard package hashlib. The input to sha512 is a string of arbitrary length, and the output is a sequence of 512 bits. One can convert those 512 bits into 64 bytes (512/8 = 64) which can be viewed as a 64-character string via ASCII. This 64-byte string is called the digest of the hash. Note that many of the characters won't display very nicely, since they are out of the code range 32-126! from hashlib import sha512 print sha512("I like sweet potato hash.").digest() # A 64-character string of hash. Hashes are designed to be irreversible. Nobody should be able to reverse the hashing process and recover the original string ('I like sweet potato hash') from the output of sha512. Moreover, hashes should avoid collisions -- although different input strings can yield the same hashed result, such "collisions" should be exceedingly rare in practice. You can read more about SHA-512 and others at Wikipedia. Now, if Alice wishes to sign a message m, and send it to Bob, she goes through the following steps (in the RSA signature protocol). Alice hashes her message using a method such as SHA-512. Let h be the resulting hash. Alice encrypts the hash by computing $s = h^f$ modulo $N$. Here $f$ is the multiplicative inverse of $e$ modulo $\phi(N)$, just as it was in RSA encryption. Note that this step requires knowledge of the private key $(p,q)$ to compute $\phi(N)$ to compute $f$. Hence only Alice can encrypt the has in this way. Alice sends this encrypted hash along with her message to Bob, along with a note that she signed it using SHA-512 and her RSA key (without revealing her private keys, of course!). When Bob receives the (plaintext) message $m$ and signature $s$, he carries out the following authentication process. Bob computes $s^e$ modulo $N$. Since $s^e = h^{fe} = h$ modulo $N$, Bob now has the hash of the message $h$. Bob also computes the SHA-512 hash of the received message $m$, and compares it to the has he computed in step 1. If they match, then Alice indeed signed the message he received. We leave implementation of this process to the exercises. Why might the exponent $e = 65537$ be a computationally convenient choice? Consider Pingala's algorithm. What would happen if the message $m$ encrypted by RSA were equal to one of these primes of the private key? How might such an occurrence be avoided, and is this something to be concerned about in practice? Look at the technical document on OpenPGP, and try to figure out how RSA and/or other cryptosystems are being used and implemented in practice. Write a 1-2 paragraph nontechnical summary of your findings. Suppose that you choose $M$ prime numbers at random between $2^{b-1}$ and $2^{b}$. Assuming that prime numbers near $x$ have a density $1 / \log(x)$, estimate the probability that there is a "collision" -- that at least two of the $M$ prime numbers are the same. What is this probability when $b = 512$ and $M$ is two billion? (E.g., if a billion people use a pair of 512-bit private keys). Look up the "Birthday Problem" for some hints if you haven't seen this before. Create a function sign(message, p,q,N,e) to carry out the RSA signature protocol described above, based on a private key $(p,q)$ with public key $(N,e)$. Create a function verify(message, signature, N, e) to verify a signed message. Use the SHA-512 algorithm throughout, and check that your functions work.
https://nbviewer.jupyter.org/github/MartyWeissman/Python-for-number-theory/blob/master/PwNT%20Notebook%207.ipynb
CC-MAIN-2019-43
refinedweb
3,814
63.39
TinyOS is a compact operating system (OS) designed to support small wireless platforms like 8-bit ZigBeebased microcontroller solutions. It's an open-source project that was first developed at U.C. Berkeley by the likes of David Culler, now chairman, co-founder, and CTO of Arch Rock. The company announced its ZigBee support at the 2006 Sensors and Expo Conference in Chicago, where the company also showed off its TinyOS 2.0. Arch Rock also supports a range of wireless solutions including support for IEEE 802.15.4 and IEEE 802.11. TinyOS can be used as a general OS, but it targets wireless sensing mesh networks that incorporate thousands of devices. The concept is also called smartdust, and the devices are often referred to as motes. The idea is that motes would be so inexpensive that they could be embedded everywhere, providing details such as stress information within a build-ing s structure. TinyOS already runs on a range of processors, including ARM processors and DSPs. TinyOS is designed to be simple but flexible. Its default scheduler has a non-preemptive FIFO policy. The system supports commands (function calls) and events (callback functions). A close relationship with the hardware can be had with a split-phase approach where a command starts an operation and an event is used for complete it. Functions are divided into synchronous (sync) and asynchronous (async) groups. Async functions can only call other async functions. Events are always sync. Another major difference compared to other platforms is that applications are built from components that are designed to be wired together with connections between component interfaces. Wiring can be parameterized or combined. Pass-through wiring allows efficient implementation of shims. Interestingly, the environment uses only local namespaces instead of the global namespace normally found in Java or C++. A local namespace means the developer must define functions that are called via an interface, as well as functions that will be exported by the application through its interfaces. A new programming language called nesC was developed to build TinyOS and its applications. It is a variant of C that implements the TinyOS concurrency model and interfaces. Tools like ncc, the nesC compiler, are available on most PC platforms such as Windows and Linux. Two items often found on a TinyOS system are TinyDB and Maté. TinyDB is a compact, distributed database that runs on TinyOS. Maté is a virtual machine with a Forth-like architecture that runs capsules, which are small collections of byte codes. Applications can consist of one or more capsules. Capsules are easy to broadcast through a mesh network because of their small size. The chips and OS may be tiny, but they may have huge implications for the future.
http://electronicdesign.com/Articles/ArticleID/12927/12927.html
crawl-002
refinedweb
457
56.96
Note: This assignment is optional. I will be happy to comment on your efforts, or answer any questions. Follow the easy install directions for Radim Rehurek's gensim module, which implements word2vec, the Deep Learning inspried word embedding component. Those directions are here. The discussion here is based on Rehurek's Word2vec tutorial Run the following code (which will take some time): from gensim.models import Word2Vec from nltk.corpus import brown, movie_reviews, treebank b = Word2Vec(brown.sents()) mr = Word2Vec(movie_reviews.sents()) t = Word2Vec(treebank.sents()) You built 3 word2vec models on very small amounts of data, one on Brown, one on Treebank data, and one on movie reviews. They won't be very good, but they still have useful information. Let's find the 5 nearest neighbors of the word man, based on the data in the Movie Review corpus: >>> mr_man_nns = mr.most_similar('man', topn=5) [(u'woman', 0.8220334053039551), (u'girl', 0.6817629933357239), (u'boy', 0.6774479150772095), (u'doctor', 0.6448361873626709), (u'calculating', 0.605032205581665)] >>> mr.similarity('man','woman') 0.8220334001723657 What you get is mr_man_nns is a list of five things, each is a nearest neighbor together with its similarity to man. These are the five words most similar to man according to the model. To find the similarity score of any two words, you use similarity as shown. To complete analogies like woman:king::man::??, you do the following: >>> mr.most_similar(positive=['woman', 'king'], negative=['man']) [(u'ark', 0.7656992077827454), ... ]A variant proposed in Levy and Goldberg (2014): >>> mr.most_similar_cosmul(positive=['woman', 'king'], negative=['man']) [(u'ark', 1.0164012908935547), ... ]This is a pretty weird answer. Of course if you were using the Wikipedia trained model described in Rehurek's tutorial and Mikolov et al. (2013), you would instead get this as the completion of the analogy: [('queen', 0.50882536), ...] You can also use the model to find outlier words that don't fit in a group of words: For this, we find the centroid of the word vectors and choose the one with greatest distance from the centroid as the odd vector out: >>> mr.doesnt_match("breakfast cereal dinner lunch".split()) 'cereal' Models can be significantly improved by finding bigram words ("New York", "Press Secretary"): bigram_transformer = gensim.models.Phrases(sentences) mr = Word2Vec(movie_reviews.sents()) Using a word vector model's implicit co-occurrence probabilities, it can also be used find the probability of a sentence: mr.score(["Colorless green ideas sleep furiously".split()])In other words, the model goes through each word and computes the probability of the other words occurring as neighbors, returning an overall likelihood score. Finally, you can just look at a vector, which by default has 100 dimensions. It's an array with 100 floating point numbers. >>> mvec = mr['man'] >>> len(mvec) 100 >>> mvec array([-0.10986061, -0.12899914, -0.01356757, 0.09450436, -0.04457339, 0.1201788 , 0.07375111, 0.00555919, -0.27961457, -0.04920399, 0.21768376, -0.15391812, -0.07826918, 0.2606242 , -0.12305038, -0.0137245 , 0.02650702, -0.01748919, -0.12054206, -0.13024689, -0.06372885, -0.23327361, 0.33404183, 0.22624712, -0.22911069, -0.12921527, 0.28556904, -0.23052499, -0.19462241, 0.26367468, 0.25053203, 0.03706881, 0.12325867, -0.33901975, -0.02694192, -0.05358029, -0.00767274, -0.13719793, 0.00530363, -0.20839927, -0.03976608, 0.0351226 , 0.18464074, -0.24369034, 0.15803961, -0.0514226 , -0.13602231, 0.25484481, -0.08208569, 0.06340741, 0.21154985, 0.09053291, 0.13411717, -0.24650463, 0.2090898 , -0.14951023, -0.02048201, -0.22660583, 0.04167137, 0.06884803, 0.31761509, -0.1049979 , 0.11771846, 0.11075541, -0.05071831, 0.21371891, 0.12598746, -0.2079615 , -0.13616957, -0.01921517, -0.16636346, 0.1169065 , 0.23653744, 0.31624255, 0.11505274, -0.09718218, -0.06874531, 0.10780501, -0.01663529, -0.10346226, -0.30455628, 0.00246542, -0.15952916, -0.01670113, -0.08883165, 0.13546473, -0.39362314, 0.27298909, -0.08167259, -0.1424706 , 0.12223504, 0.18078147, 0.08870253, 0.15700033, 0.17984635, 0.13593708, -0.43276551, 0.03234629, -0.16896026, -0.12703048], dtype=float32) mr.score(["Colorless green ideas sleep furiously".split()]) from gensim.models import Phrases Phraser = Phrases(movie_reviews.sents()) mrs_phrased = Phraser[mrs] mr_p = Word2Vec(mrs_phrased) Compare the top 25 most similar words to great in this new model with the top 25 most similar words to great in mr model. Report on any effects that having phrases included has had. Are all the results good?
https://gawron.sdsu.edu/compling/course_core/assignments/word2Vec_assignment.html
CC-MAIN-2018-09
refinedweb
727
67.45
" Vim syntax file " Language: WEB Changes " Maintainer: Andreas Scherer <andreas.scherer@pobox.com> " Last Change: April 25, 2001 " Details of the change mechanism of the WEB and CWEB languages can be found " in the articles by Donald E. Knuth and Silvio Levy cited in "web.vim" and " "cweb.vim" respectively. " For version 5.x: Clear all syntax items " For version 6.x: Quit when a syntax file was already loaded if version < 600 syn clear elseif exists("b:current_syntax") finish endif " We distinguish two groups of material, (a) stuff between @x..@y, and " (b) stuff between @y..@z. WEB/CWEB ignore everything else in a change file. syn region changeFromMaterial start="^@x.*$"ms=e+1 end="^@y.*$"me=s-1 syn region changeToMaterial start="^@y.*$"ms=e+1 end="^@z.*$"me=s-1 " Define the default highlighting. " For version 5.7 and earlier: only when not done already " For version 5.8 and later: only when an item doesn't have highlighting yet if version >= 508 || !exists("did_change_syntax_inits") if version < 508 let did_change_syntax_inits = 1 command -nargs=+ HiLink hi link <args> else command -nargs=+ HiLink hi def link <args> endif HiLink changeFromMaterial String HiLink changeToMaterial Statement delcommand HiLink endif let b:current_syntax = "change" " vim: ts=8
http://opensource.apple.com/source/vim/vim-44/runtime/syntax/change.vim
CC-MAIN-2015-40
refinedweb
205
60.61
PCPIntro man page PCPIntro — introduction to the Performance Co-Pilot (PCP) libraries Introduction Performance Co-Pilot (PCP) is a toolkit set of PCP archives. - (c) A bad result data structure passed to pmStore(3). -. -_FAULT QA fault injected Used only for PCP Quality Assurance (QA) testing. -. - set of PCP archives. - PM_ERR_PMID_LOG Metric not defined in the PCP archive log A PCP client has requested information about a metric, and there is no corresponding information in the set of PCP archives. set of PCP archives. If the client is using metric descriptors from the set of archives set of PCP archives. If the client is using instance names from the instance domain in the set of archives . -.. Namespace Errors These errors may occur in the processing of PCP namespace operations. A PCP namespace, see pmns explicitly loaded. - PM_ERR_NOPMNS PMNS not accessible Only occurs when an ASCII namespace is explicitly loaded.merr(1), PMAPI(3), pmErrStr(3), pmGetConfig(3), pcp.conf(5) and pcp.env(5). Referenced By pcp.conf(5), pcp.env(5), PMAPI(3), pmiErrStr(3), pmns(5), PMWEBAPI(3).
https://www.mankier.com/3/PCPIntro
CC-MAIN-2018-05
refinedweb
180
60.61
Help! I have a problem with lists! Hello! I am a real beginner in Sage, I have just started th use it. In fact this is my first programing language, so I have some difficulties with it... Now I needed a command, which determins all the k-element subset of [1,2,...,N]. Since I don't found a command like this, I decided to write a program... :-) And now I simple don't understand while my program doesn't work corrrectly! Could you explain me? It is a bit longish, so sorry for this. def eve(A,N): """ the largest elem in the list A which can be increased by 1, such that the resulting list contains only different elements less than N. Originally A should contain different elements in increasing order. """ ev = len(A)-1 while A[ev] == ev+N-len(A): ev=ev-1 return ev def rakovetkezo(A,N): """ Increases the eve(A,N)nt element by 1, and all the other elements after this element are succesive natural numbers """ Q=A ev=eve(Q,N) x=Q[ev] for i in range(ev,len(Q)): Q[i]=x+i-ev+1 return Q def reszhalmazok(N,k): """ It should (but it doesn't) return the k-element subset of [1,2,...,N] """ X=range(k) B=[range(k)] ev=eve(X,N) while ev != -1: X=rakovetkezo(X,N) B.append(X) ev = eve(X,N) return B Now reszhalmazok(5,3) should return [[0,1,2], [0,1,3],...] but it returns something completely different, aaand I don't see why, and how could be improve it? Katika
https://ask.sagemath.org/question/7727/help-i-have-a-problem-with-lists/?answer=11731
CC-MAIN-2021-49
refinedweb
274
74.08
Posting Technical problems/solutions through out my personal experience A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported. C# Code // Get the physical Path of the file(test.doc) string filepath = Server.MapPath("test.doc"); // Create New instance of FileInfo class to get the properties of the file being downloaded FileInfo file = new FileInfo(filepath); // Checking if file exists if (file.Exists) { // Clear the content of the response Response.ClearContent(); // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); // Add the file size into the response header Response.AddHeader("Content-Length", file.Length.ToString()); // Set the ContentType Response.ContentType = ReturnExtension(file.Extension.ToLower()); // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead) Response.TransmitFile(file.FullName); // End the response Response.End(); }";} N.B:, Response.End() calls Response.Flush(). Therefore, you only need to call Response.End Also, you better clear the headers or you will never be able to open the file in IE6 without saving it first! Thank you for your advice. I tried your code and I could be able to download a file to my local PC. However, when I try to open the file instead of saving it, I could see that it is downloading. After the downloading is done, the MS Word popped up an error message saying: The file could not be found. Try one or more of the following: * Check the spelling of the name of the document. * Try a different file name. (C:\...\test[1].doc) Would you help me to solve this issue? Thank you very much. Hello Jtang, Please send me your code to my email to check it out Best Regards, HC Thanks for this code. i was stuct in my project for this problem since yesterday. thank u very much Thank u for ur help, this will help me out only for single file to downlod. i want n number of selected files to download at a time. how can i? tHANKING YOU IN ADVANCE mail me the code to vinod.vbv@gmail.com Hi Haissam, Did you have any luck solving Jtang's problem? I'm having the same trouble, and I was hoping you could publish a fix for me and anyone else with the same problem. Thanks very much! Neil. Can you send your project to my inbox to test what is going on and how to fix it! haissam@dotnetslackers.com hi all. plz give me solution on following problem. how to execute code or display any message after comlete downloading file. hi this code is working in a simple web from but this code throw error when u try that code in Model Dialog from(popup) in case of target ="_self". plz advice Varun which type of error you are facing!! just email me the project and your problem... Thank you, I have tested the code, for saving file, it works ok. But for opening (in IE6), the word editor doesn't show up, only the xml scripts are displayed in IE. Here's my code: string fileName = @"D:\rptTest\AspNet_Html\WordInHtml\WordInHtml\output\report.xml"; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment;filename=new.xml"); Response.ContentType = "application/ms-word"; Response.WriteFile(fileName); //Response.Flush(); Response.End(); i have a project, i make a intranet webpage i use c# in my script, i page for uploading a file, then i want to view the file that i upload and download it can u help with the script . can you help me. yo can reply me in email add jhd_nightfire@yahoo.com Hi, I'm new to C# and I just wanted to know what a response is? Thank you! navinsukhdeo@gmail.com Hello, Is there a way to make this code work for files located in a network drive? This would be for a web application that runs only in the intranet. Hi, I'm also facing the same problem (ie) (C:\...\Sample[1].doc) Please let me know the solution. A note on Response.End() versus Response.Flush(). The Microsoft documentation says that Response.End() calls Response.Flush() if Response.Buffer =is set to true. E.g., Response.Buffer = true; Response.End(); Also, newbies (like me) who wish to convert the code Haissam graciously provided into a C# class, may need to add the following two lines to the C# class code file: using System.Collections; using System.IO; Visual Studio adds these to a code behind file, in my version (VWDE 2008 beta) did not automatically add them to the class file in the App_Code folder. Chicago_lar your comment is appreciated.... Your code is help to me Thanks Wonderful post Helped a lot ! Thanks Worked for me. I'd also like to add that if you want to delete the file after it has downloaded, then change response.end to response.close then do a delete response.close(); file.delete(); Hi, I would like to know how to download files if I know the directory, but not the filename? best It is working but while downloading it converts " " into "_" it is not requirement At last!! Posted code that works!! I just dont get what application/ms-word is for? I can save pdf and exe files. Anyway, thanx a lot! Christo We assign "application/ms-word" to the response content type property to tell the browser that the content is a microsoft word. Ok, but why does it still work, even if it is not a .doc file? very good article ,it helped me a lot ,thanks for the same. hi, i would like to download multiple file. may i know how can i do that? Very Good article. It solved my problem instantly.. Thanks for such a helpful article. You can add them into a zip or rar and just download that. Or use a download manager that can download multiple files. No other help, sorry The code above works perfectly however for best practices i recommend to use Response.TransmitFile instead of Response.WriteFile. The only difference between these two is 1- Response.WriteFile: Buffers the file to the server memory before being sent to the client 2- Response.TransmitFile: send the file to the client without buffering. thanks, ur code was very helpfull, but there is one question, i am able to save a file but not able to open it in browser, can u help me in this . I m getting error as file is corrupted. Hey thank you.......Thanks for the code.I was worried how to do and to my luck i found it and that too without much difficulty you delivered the code. Keep going. hi Haissam! im making a project in which a user can download file which i have saved in my database table. how can i? the method is very nice but I would like to know how to do a download without using the Response object.THKS a Lot Ruchir Please send me by email the code you are working and on which file type this error is generated Haissam, I reviewed the code you posted and had a couple questions that stem from a problem I found. The problem was non-existent in IE7 but when using IE6 when I click on the "Save" button on the save file dialog it said the file was missing. I noticed at the top a gentlemen named JoshStodola said the header needs to be cleared. I call Response.Clear() but wasn't sure if that included clearing the header as well. I now added Response.ClearHeaders() along with Response.ClearContent(). I'm wondering what the intricacies of this are in terms of whether it is the solution I'm looking for and also what it is that causes this different behavior in IE6. anisia you could use the WebClient class to download the file msdn2.microsoft.com/.../system.net.webclient.aspx how do you do when you do not know the content type of file. My website allow users to upload any type of file and then a link is created to download those files. So how do I configure the contenttype in this case? You can set a predefined list of the popular content types. you get the file extension and using a switch statement u set the content type. It is a basic idea, i will try to find a more generic way. your code for bypassing Open/Save/Cancel dailog box does not work on IE7.. got idea?..thanks thank you for your code. i think it will help me a lot. Hi Haissam, Your code is working perfectly when i am running the application from Dotnet, but the same pdf when i am trying to open from my Localhost (i.e from IIS) i am getting the following error: Adobe Reader could not open '2_21_2008doc[1].pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded). Please suggest some solution for this problem!! I have same problem ['test[1].pdf' because it is either not a supported file type or because the file has been damaged] when i try to delete the file after WriteFile method. I couldn't delete file even by Async call. Here is part of my code : delegate void BeginWriteFile(string filename); private void SendFile() { ..... BeginWriteFile writeasync = new BeginWriteFile(context.Response.WriteFile); writeasync.BeginInvoke(path, delegate(IAsyncResult result) { if(result.IsCompleted)System.IO.File.Delete(path); }, null); } Thanks. would changing the content type to "application/octet-stream" make it more general purpose? application/octet-stream is a general content type which is Binary. thanks it excellent code , it works with me. I am novice programmer, it helps too much for my day to day tasks. keep on writing. thanks Can you translate this code to VB? Haissam, thanks for the code and hint. What I actually wanted was to be able to splash the MS Word document into a browser without. What I am getting from your code is the ability to programatically open or save a word document after being prompted to do so. The reason I am asking for this functionality is because I do not want to tamper with the application everytime the contents of a document changes. Do you have code that can accomplish that? Thanks, Wango Michael, There are some online tools you can use to convert codes between c# and VB.NET. below is a good link labs.developerfusion.co.uk/.../csharp-to-vb.aspx haissam, was I was looking for is code that can grab an MS Word document or any other document and splash it on the browser while retaining the format! If an MS Word doc contains the following: Company News We'll add some news later. Company Events We'll add company events later. I would like to lay my hands on code that would grab that file and produce the same results as the code caption below would produce: <h1>Company News</h1> <p>We'll add some news later.</p> <h1>Company Events</h1> <p>We'll add company events later.</p> In other words, I want to avoid writing HTML tags as above. Wango. Wango, Please email me the code you are using and the exact details of what you are trying to achieve in order to be able to help. Regards, I am getting error while trying to open the file as: File could not be found. Check the spelling of the file name... But surprisingly if i save the file there are no issues. Please help. Here is my sample code: FileInfo file = new FileInfo(fileCompletePath); HttpResponse response = HttpContext.Current.Response; response.ClearContent(); response.ClearHeaders(); response.AppendHeader("Content-Disposition:", "attachment; filename =" + file.Name); response.AppendHeader("Content-Length:", file.Length.ToString()); response.ContentType = "application/vnd.ms-excel"; response.TransmitFile(fileCompletePath); response.Flush(); response.End(); Thanks for this article - it really helped me understand a couple of issues that I did not manage to resolve before. But, if I want my web application to download a file (Xml - zipped) from another server (so the zip file is located at a URI). So basically downloading from a URL to some directory in my hosting web server file structure. Can you maybe give me a couple of idea's/pointers? Jan Hi haissam, Excelent Article. Ravi @janleroux In your case, you should be using the WebClient class to download the file to the server. For more information check link msdn.microsoft.com/.../system.net.webclient(VS.80).aspx Thanks so much for the code. It solved 99% of the issues that I had. I was wondering if you could answer two questions for me. 1. When I used the following line of code: ms-word documents displayed my login page as a word document instead of the actual document that I wanted to display. I have no idea why (I am using Forms Authentication if that makes any difference). The only way that I could solve this problem was to replace that line of code with this line of code: Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 2. For some reason when using excel files still prompt for the file open(pdf's work fine). Any help would be much appreciated. Thanks again for the great article. hi how can i download file which i have saved in my database table. how to download text files using c# source code For the benefit of others: I was receiving the error below others were receiving above when attempting to open the file and not save it to disk first. I experienced this only in Internet Explorer. The resolution for me was unchecking the "do not save encrypted pages to disk" setting under security settings in Internet Explorer. "The file could not be found. (C:\...\test[1].doc)" Seems to be working quite well for me. Thanks. For the mime types, I'm going to store those in a mimetypes configuration section instead. Good getmimetype() function : Huge thanks man, really you like solved a huge chunk of my problem, that blog straight to favorites, peace. Does anyone have an ideas on how to solve the problems I posted on 19 March, 2009? I am stumped. This code was awesome. Exactly what i needed. Thank you so much. Just wanted to say thank you! for all the great info found on your blog, even helped me with my work recently :) keep it up! Will you please tell me how to convert an aspx page into a ppt. i.e , If I click a button in an aspx page, I want that particular page to open in a ppt. TIA. hi all.. its gr8 article, but still i have problem.. the problem is , when diolog comes with open, save and cancel button, then user(visitors of the site) has clicked, then which button and accordingly which action has occured how do we know programatically ? this code saved my ass, thanx buddy I got an error, how can i solve? -- Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; CMDTDF; InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0) Timestamp: Tue, 30 Mar 2010 09:28:55 ''. Line: 976 Char: 13 Code: 0 URI: 146.51.221.245/.../ScriptResource.axd thanks... pls reply Hi, I got an error... message is like this thanks for reply Link to us All material is copyrighted by its respective authors. Site design and layout is copyrighted by DotNetSlackers. Advertising Software by Ban Man Pro
http://dotnetslackers.com/Community/blogs/haissam/archive/2007/04/03/Downloading-Files-C_2300_.aspx
CC-MAIN-2015-11
refinedweb
2,716
67.55
In the spring of 2005, Google introduced a browser plug-in called Google Web Accelerator (GWA), which set off heated discussions in the Rails community. The reason is that GWA worked by pre-fetching links. Upon loading a page, GWA would scan it for links and load them before they were even clickedso when the user did click, the next page would already be cached and load much faster. The problem was that many Rails applications (including Basecamp, the original Rails application) used regular links for destructive actions, such as "delete this post." So if you installed GWA and then visited your Basecamp account, the plug-in triggered a wave of data loss. Users and developers alike were understandably quite upset by the unintended consequences. Google quickly cancelled the product in response to the uproar. But technically, the plug-in wasn't doing anything wrong (besides being wasteful with bandwidth). GWA was only creating HTTP GET requests, which, according the spec, are supposed to be safe for intermediaries like GWA to use. The real problem was that Rails developers had adopted the bad habit of using GET to trigger deletes. The lesson was hard-learned, but important. Today, Rails is leading the charge among web frameworks to support the full vocabulary of HTTP methods, beyond just GET and POST. With most helpers, the fix is as simple as providing a :method option. For example, to create a proper delete link: <%= link_to 'Delete Contact', contact_url(:id => contact), :method => :delete %> Instead of creating a standard link, this helper will create a JavaScript linkone that looks just the same, but has a script in the onclick attribute. The script jumps through the necessary hoops to send the right request. Because browsers generally don't support the DELETE method, Rails piggybacks on the POST method by sending an extra parameter (_method) along with the request. It's not ideal, but it's an acceptable stopgap solution until browsers support more methods. The output of the above helper is this: <a href="/contacts/1" onclick= Contact</a> Upon clicking the link, the JavaScript actually creates a new hidden form and input field and submits it. The effect is totally transparent to the end user, but as far as Rails is concerned, the incoming request is a full-fledged HTTP DELETE request. This brings us to the second half of the equation, the server side. Employing JavaScript to use the correct request method is nice, but if your destroy action still responds to GET, you're still vulnerable. There are several ways to tackle the problem. From within an action, the request object represents all that's known about the current request. So to find out the request method, you'd use (shockingly) request.method. The value will be one of five symbols: :get, :post, :put, :delete, and :head. The request object also provides corresponding Boolean "question-mark" methods, such as request.get? and request.post?. For example, consider account confirmation, a common feature of web applications. In order to deter spammers, new users are emailed a confirmation link, which they're supposed to click before the account is activated. Most implementations of this pattern are flawed, because they use GET requests to change state on the server. A better approach is to check the request method and show a confirmation form if the incoming request is a GET. That kind of conditional processing is made easy by request.post? and friends: def confirm @user = User.find_by_token params[:id] if request.post? @user.update_attributes :confirmed => true redirect_to home_url else render :inline => %Q(<%= start_form_tag %> <%= submit_tag "Confirm Account" %> <%= end_form_tag %>) end end Alternatively, verify, a specialized kind of before_filter, can be used to limit which request methods are allowed for each action. Options provided to verify will determine what happens if the conditions aren't met, such as redirecting and adding a flash. For example: class UsersController < ApplicationController verify :only => :confirm, :method => :post, :add_flash => { "notice" => "Please confirm your account." }, :redirect_to => :confirm_form def confirm_form render :inline => %Q(<%= start_form_tag %> <%= submit_tag "Confirm" %> <%= end_form_tag %>) end # only POSTS will be able to reach this action def confirm @user = User.find_by_token params[:id] @user.update_attributes :confirmed => true redirect_to home_url end end Another solution is to use routes. For example: # only matches if the request method is GET map.connect "/confirm/:id", :controller => "users", :action => "confirm_form", :conditions => { :method => :get } # only matches if the request method is POST map.connect "/confirm/:id", :controller => "users", :action => "confirm", :conditions => { :method => :post } In many cases, you can automatically get the benefits of the :conditions option by using map.resources. For example: ActionController::Routing::Routes.draw do |map| map.resources :products map.connect ':controller/:action/:id' end The resources method generates a whole slew of named routes, and it uses :conditions to direct the same path to multiple actions, depending on the HTTP method. Table 8-1 shows all of the routes generated by map.resources :products. products /products/ index, create GET, POST formatted_products /products.:format/ new_product /products/new/ new GET formatted_new_product /products/new.:format product /products/:id/ show, update, destroy GET, PUT, DELETE formatted_product /products/:id.:format/ show edit_product /products/:id;edit/ edit formatted_edit_product /products/:id.:format;edit
https://flylib.com/books/en/4.386.1.50/1/
CC-MAIN-2021-43
refinedweb
858
55.54
FIN350 In Class Work No. 2 ( Risk & Returns, part 1) Please also go over lecture slides. 1. The stand alone risk of a stock is measured by (a) the stock price (b) stock returns (c) the volatility of the stock return (standard deviation) (d) the mean of the stock price (e) none of the above The risk of a stock is measured by the variance or standard deviation of stock returns. Standard deviation is also called volatility. 2. Which of the following statement is NOT true for a portfolio made up of several stocks? a. The expected return = weighted average of each stock’s expected return. b. The portfolio standard deviation is >= the weighted average of each stock’s standard deviation. c. The portfolio beta is the weighted average of each stock’s beta d. The portfolio standard deviation is <= the weighted average of each stock’s standard deviation. 3. Which of the following statements is correct? a. lower beta stocks have a higher required return. b. Two securities with the same stand-alone risk must have same betas. c. Company-specific risk can be diversified away. d. The market risk premium is not affected by investors’ attitudes about risk. e. All above statements are correct. 4. Inflation, recession, and high interest rates are economic events that are characterized as a. Company-specific risk that can be diversified away. b. Market risk. c. Systematic risk that can be diversified away. d. Diversifiable risk. e. Unsystematic risk that can be diversified away. 5.The risk that remains in a well-diversified stock portfolio is (a) systematic risk (also called market risk) (b) firm-level risk (c) idiosyncratic risk (d) unique risk (e) none of the above 1 View Full Document This preview has intentionally blurred sections. Firm-level risk (also called idiosyncratic risk or unique risk) can be diversified away in a well-diversified portfolio. 6 A portfolio is__________________________________. A) a group of assets, such as stocks and bonds, held collectively by an investor B) the expected return on a risky asset C) the expected return on a collection of risky assets that are in the same industry D) the variance of returns for a risky asset - Spring '07 - Chen - Capital Asset Pricing Model, Volatility, Risk in finance Click to edit the document details
https://www.coursehero.com/file/6452155/350i2-capm1p/
CC-MAIN-2018-09
refinedweb
383
55.13
Handling Categorical Data in Python If you are familiar with machine learning, you will probably have encountered categorical features in many datasets. These generally include different categories or levels associated with the observation, which are non-numerical and thus need to be converted so the computer can process them. In this tutorial, you’ll learn the common tricks to handle this type of data and preprocess it to build machine learning models with them. More specifically, you will learn: This tutorial covers the operations you have perform on categorical data before it can be used in an ML algorithm. But there is more to it. You will also have to clean your data. If you would like to know more about this process, be sure to take a look at DataCamp's Cleaning Data in Python course. Identifying Categorical Data: Nominal, Ordinal and Continuous Categorical features can only take on a limited, and usually fixed, number of possible values. For example, if a dataset is about information related to users, then you will typically find features like country, gender, age group, etc. Alternatively, if the data you're working with is related to products, you will find features like product type, manufacturer, seller and so on. These are all categorical features in your dataset. These features are typically stored as text values which represent various traits of the observations. For example, gender is described as Male (M) or Female (F), product type could be described as electronics, apparels, food etc. Note that these type of features where the categories are only labeled without any order of precedence are called nominal features. Features which have some order associated with them are called ordinal features. For example, a feature like economic status, with three categories: low, medium and high, which have an order associated with them. There are also continuous features. These are numeric variables that have an infinite number of values between any two values. A continuous variable can be numeric or a date/time. Regardless of what the value is used for, the challenge is determining how to use this data in the analysis because of the following constraints: - Categorical features may have a very large number of levels, known as high cardinality, (for example, cities or URLs), where most of the levels appear in a relatively small number of instances. - Many machine learning models, such as regression or SVM, are algebraic. This means that their input must be numerical. To use these models, categories must be transformed into numbers first, before you can apply the learning algorithm on them. - While some ML packages or libraries might transform categorical data to numeric automatically based on some default embedding method, many other ML packages don’t support such inputs. - For the machine, categorical data doesn’t contain the same context or information that humans can easily associate and understand. For example, when looking at a feature called Citywith three cities New York, New Jerseyand New Delhi, humans can infer that New York is closely related to New Jersey as they are. You therefore are faced with the challenge of figuring out how to turn these text values into numerical values for further processing and unmask lots of interesting information which these features might hide. Typically, any standard work-flow in feature engineering involves some form of transformation of these categorical values into numeric labels and then applying some encoding scheme on these values. General Exploration steps for Categorical Data In this section, you'll focus on dealing with categorical features in the pnwflights14 dataset, but you can apply the same procedure to all kinds of datasets. pnwflights14 is a modified version of Hadley Wickham's nycflights13 dataset and contains information about all flights that departed from the two major airports of the Pacific Northwest (PNW), SEA in Seattle and PDX in Portland, in 2014: 162,049 flights in total. To help understand what causes delays, it also includes a number of other useful datasets: weather: the hourly meterological data for each airport planes: constructor information about each plane airports: airport names and locations airlines: translation between two letter carrier codes and names The datasets can be found here. Since it's always a good idea to understand before starting working on it, you'll briefly explore the data! To do this, you will first import the basic libraries that you will be using throughout the tutorial, namely pandas, numpy and copy. Also make sure that you set Matplotlib to plot inline, which means that the outputted plot will appear immediately under each code cell. import pandas as pd import numpy as np import copy %matplotlib inline Next you will read the flights dataset in a pandas DataFrame with read_csv() and check the contents with the .head() method. df_flights = pd.read_csv('') df_flights.head() As you will probably notice, the DataFrame above contains all kinds of information about flights like year, departure delay, arrival time, carrier, destination, etc. Note if you are reading the RDS file formats you can do so by installing rpy2 library. Checkout this link to install the library on your system. The simplest way to install the library is using pip install rpy2 command on command line terminal. Running the following code would read the flights.RDS file and load it in a pandas DataFrame. Remember that you already imported pandas earlier. import rpy2.robjects as robjects from rpy2.robjects import pandas2ri pandas2ri.activate() readRDS = robjects.r['readRDS'] RDSlocation = 'Downloads/datasets/nyc_flights/flights.RDS' #location of the file df_rds = readRDS(RDSlocation) df_rds = pandas2ri.ri2py(df_rds) df_rds.head(2) The same rpy2 library can also be used to read rda file formats. The code below reads and loads flights.rda into a pandas DataFrame: from rpy2.robjects import r import rpy2.robjects.pandas2ri as pandas2ri file="~/Downloads/datasets/nyc_flights/flights.rda" #location of the file rf=r['load'](file) df_rda=pandas2ri.ri2py_dataframe(r[rf[0]]) df_rda.head(2) The next step is to gather some information about different column in your DataFrame. You can do so by using .info(), which basically gives you information about the number of rows, columns, column data types, memory usage, etc. print(df_flights.info()) <class 'pandas.core.frame.DataFrame'> RangeIndex: 162049 entries, 0 to 162048 Data columns (total 16 columns): year 162049 non-null int64 month 162049 non-null int64 day 162049 non-null int64 dep_time 161192 non-null float64 dep_delay 161192 non-null float64 arr_time 161061 non-null float64 arr_delay 160748 non-null float64 carrier 162049 non-null object tailnum 161801 non-null object flight 162049 non-null int64 origin 162049 non-null object dest 162049 non-null object air_time 160748 non-null float64 distance 162049 non-null int64 hour 161192 non-null float64 minute 161192 non-null float64 dtypes: float64(7), int64(5), object(4) memory usage: 19.8+ MB None As you can see, columns like year, month and day are read as integers, and dep_time, dep_delay etc. are read as floats. The columns with object dtype are the possible categorical features in your dataset. The reason why you would say that these categorical features are 'possible' is because you shouldn't not completely rely on .info() to get the real data type of the values of a feature, as some missing values that are represented as strings in a continuous feature can coerce it to read them as object dtypes. That's why it's always a good idea to investigate your raw dataset thoroughly and then think about cleaning it. One of the most common ways to analyze the relationship between a categorical feature and a continuous feature is to plot a boxplot. The boxplot is a simple way of representing statistical data on a plot in which a rectangle is drawn to represent the second and third quartiles, usually with a vertical line inside to indicate the median value. The lower and upper quartiles are shown as horizontal lines at either side of the rectangle. You can plot a boxplot by invoking .boxplot() on your DataFrame. Here, you will plot a boxplot of the dep_time column with respect to the two origin of the flights from PDX and SEA. df_flights.boxplot('dep_time','origin',rot = 30,figsize=(5,6)) <matplotlib.axes._subplots.AxesSubplot at 0x7f32ee10f550> As you will only be dealing with categorical features in this tutorial, it's better to filter them out. You can create a separate DataFrame consisting of only these features by running the following command. The method .copy() is used here so that any changes made in new DataFrame don't get reflected in the original one. cat_df_flights = df_flights.select_dtypes(include=['object']).copy() Again, use the .head() method to check if you have filtered the required columns. cat_df_flights.head() One of the most common data pre-processing steps is to check for null values in the dataset. You can get the total number of missing values in the DataFrame by the following one liner code: print(cat_df_flights.isnull().values.sum()) 248 Let's also check the column-wise distribution of null values: print(cat_df_flights.isnull().sum()) carrier 0 tailnum 248 origin 0 dest 0 dtype: int64 It seems that only the tailnum column has null values. You can do a mode imputation for those null values. The function fillna() is handy for such operations. Note the chaining of method .value_counts() in the code below. This returns the frequency distribution of each category in the feature, and then selecting the top category, which is the mode, with the .index attribute. cat_df_flights = cat_df_flights.fillna(cat_df_flights['tailnum'].value_counts().index[0]) Tip: read more about method chaining with pandas here. Let's check the number of null values after imputation should result in a zero count. print(cat_df_flights.isnull().values.sum()) 0 Another Exploratory Data Analysis (EDA) step that you might want to do on categorical features is the frequency distribution of categories within the feature, which can be done with the .value_counts() method as described earlier. print(cat_df_flights['carrier'].value_counts()) AS 62460 WN 23355 OO 18710 DL 16716 UA 16671 AA 7586 US 5946 B6 3540 VX 3272 F9 2698 HA 1095 Name: carrier, dtype: int64 To know the count of distinct categories within the feature you can chain the previous code with the .count() method: print(cat_df_flights['carrier'].value_counts().count()) 11 Visual exploration is the most effective way to extract information between variables. Below is a basic template to plot a barplot of the frequency distribution of a categorical feature using the seaborn package, which shows the frequency distribution of the carrier column. You can play with different arguments to change the look of the plot. If you want to learn more about seaborn, you can take a look at this tutorial. %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt carrier_count = cat_df_flights['carrier'].value_counts() sns.set(style="darkgrid") sns.barplot(carrier_count.index, carrier_count.values, alpha=0.9) plt.title('Frequency Distribution of Carriers') plt.ylabel('Number of Occurrences', fontsize=12) plt.xlabel('Carrier', fontsize=12) plt.show() Similarly, you could plot a pie chart with the matplotlib library to get the same information. The labels list below holds the category names from the carrier column: labels = cat_df_flights['carrier'].astype('category').cat.categories.tolist() counts = cat_df_flights['carrier'].value_counts() sizes = [counts[var_cat] for var_cat in labels] fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True) #autopct is show the % on plot ax1.axis('equal') plt.show() Encoding Categorical Data You will now learn different techniques to encode the categorical features to numeric quantities. To keep it simple, you will apply these encoding methods only on the carrier column. However, the same approach can be extended to all columns. The techniques that you'll cover are the following: - Replacing values - Encoding labels - One-Hot encoding - Binary encoding - Backward difference encoding - Miscellaneous features Replace Values Let's start with the most basic method, which is just replacing the categories with the desired numbers. This can be achieved with the help of the replace() function in pandas. The idea is that you have the liberty to choose whatever numbers you want to assign to the categories according to the business use case. You will now create a dictionary which contains mapping numbers for each category in the carrier column: replace_map = {'carrier': {'AA': 1, 'AS': 2, 'B6': 3, 'DL': 4, 'F9': 5, 'HA': 6, 'OO': 7 , 'UA': 8 , 'US': 9,'VX': 10,'WN': 11}} Note that defining a mapping via a hard coded dictionary is easy when the number of categories is low, like in this case which is 11. You can achieve the same mapping with the help of dictionary comprehensions as shown below. This will be useful when the categories count is high and you don't want to type out each mapping. You will store the category names in a list called labels and then zip it to a seqeunce of numbers and iterate over it. labels = cat_df_flights['carrier'].astype('category').cat.categories.tolist() replace_map_comp = {'carrier' : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}} print(replace_map_comp) {'carrier': {'AA': 1, 'OO': 7, 'DL': 4, 'F9': 5, 'B6': 3, 'US': 9, 'AS': 2, 'WN': 11, 'VX': 10, 'HA': 6, 'UA': 8}} Throughout this tutorial, you will be making a copy of the dataset via the .copy() method to practice each encoding technique to ensure that the original DataFrame stays intact and whatever changes you are doing happen only in the copied one. cat_df_flights_replace = cat_df_flights.copy() Use the replace() function on the DataFrame by passing the mapping dictionary as argument: cat_df_flights_replace.replace(replace_map_comp, inplace=True) print(cat_df_flights_replace.head()) As you can observe, you have encoded the categories with the mapped numbers in your DataFrame. You can also check the dtype of the newly encoded column, which is now converted to integers. print(cat_df_flights_replace['carrier'].dtypes) int64 Tip: in Python, it's a good practice to typecast categorical features to a category dtype because they make the operations on such columns much faster than the object dtype. You can do the typecasting by using .astype() method on your columns like shown below: cat_df_flights_lc = cat_df_flights.copy() cat_df_flights_lc['carrier'] = cat_df_flights_lc['carrier'].astype('category') cat_df_flights_lc['origin'] = cat_df_flights_lc['origin'].astype('category') print(cat_df_flights_lc.dtypes) carrier category tailnum object origin category dest object dtype: object You can validate the faster operation of the category dtype by timing the execution time of the same operation done on a DataFrame with columns as category dtype and object dtype by using the time library. Let's say you want to calculate the number of flights for each carrier from each origin places, you can use the .groupby() and .count() methods on your DataFrame to do so. import time %timeit cat_df_flights.groupby(['origin','carrier']).count() #DataFrame with object dtype columns 10 loops, best of 3: 28.6 ms per loop %timeit cat_df_flights_lc.groupby(['origin','carrier']).count() #DataFrame with category dtype columns 10 loops, best of 3: 20.1 ms per loop Note that the DataFrame with category dtype is much faster. Label Encoding Another approach is to encode categorical values with a technique called "label encoding", which allows you to convert each value in a column to a number. Numerical labels are always between 0 and n_categories-1. You can do label encoding via attributes .cat.codes on your DataFrame's column. cat_df_flights_lc['carrier'] = cat_df_flights_lc['carrier'].cat.codes cat_df_flights_lc.head() #alphabetically labeled from 0 to 10 Sometimes, you might just want to encode a bunch of categories within a feature to some numeric value and encode all the other categories to some other numeric value. You could do this by using numpy's where() function like shown below. You will encode all the US carrier flights to value 1 and other carriers to value 0. This will create a new column in your DataFrame with the encodings. Later, if you want to drop the original column, you can do so by using the drop() function in pandas. cat_df_flights_specific = cat_df_flights.copy() cat_df_flights_specific['US_code'] = np.where(cat_df_flights_specific['carrier'].str.contains('US'), 1, 0) cat_df_flights_specific.head() You can achieve the same label encoding using scikit-learn's LabelEncoder: cat_df_flights_sklearn = cat_df_flights.copy() from sklearn.preprocessing import LabelEncoder lb_make = LabelEncoder() cat_df_flights_sklearn['carrier_code'] = lb_make.fit_transform(cat_df_flights['carrier']) cat_df_flights_sklearn.head() #Results in appending a new column to df Label encoding is pretty much intuitive and straight-forward and may give you a good performance from your learning algorithm, but it has as disadvantage that the numerical values can be misinterpreted by the algorithm. Should the carrier US (encoded to 8) be given 8x more weight than the carrier AS (encoded to 1) ? To solve this issue there is another popular way to encode the categories via something called one-hot encoding. One-Hot encoding The basic strategy is to convert each category value into a new column and assign a 1 or 0 (True/False) value to the column. This has the benefit of not weighting a value improperly. There are many libraries out there that support one-hot encoding but the simplest one is using pandas' .get_dummies() method. This function is named this way because it creates dummy/indicator variables (1 or 0). There are mainly three arguments important here, the first one is the DataFrame you want to encode on, second being the columns argument which lets you specify the columns you want to do encoding on, and third, the prefix argument which lets you specify the prefix for the new columns that will be created after encoding. cat_df_flights_onehot = cat_df_flights.copy() cat_df_flights_onehot = pd.get_dummies(cat_df_flights_onehot, columns=['carrier'], prefix = ['carrier']) print(cat_df_flights_onehot.head()) As you can see, the column carrier_AS gets value 1 at the 0th and 4th observation points as those points had the AS category labeled in the original DataFrame. Likewise for other columns also. scikit-learn also supports one hot encoding via LabelBinarizer and OneHotEncoder in its preprocessing module (check out the details here). Just for the sake of practicing you will do the same encoding via LabelBinarizer: cat_df_flights_onehot_sklearn = cat_df_flights.copy() from sklearn.preprocessing import LabelBinarizer lb = LabelBinarizer() lb_results = lb.fit_transform(cat_df_flights_onehot_sklearn['carrier']) lb_results_df = pd.DataFrame(lb_results, columns=lb.classes_) print(lb_results_df.head()) Note that this lb_results_df resulted in a new DataFrame with only the one hot encodings for the feature carrier. This needs to be concatenated back with the original DataFrame, which can be done via pandas' .concat() method. The axis argument is set to 1 as you want to merge on columns. result_df = pd.concat([cat_df_flights_onehot_sklearn, lb_results_df], axis=1) print(result_df.head()) While one-hot encoding solves the problem of unequal weights given to categories within a feature, it is not very useful when there are many categories, as that will result in formation of as many new columns, which can result in the curse of dimensionality. The concept of the “curse of dimensionality” discusses that in high-dimensional spaces some things just stop working properly. Binary Encoding This technique is not as intuitive as the previous ones. In this technique, first the categories are encoded as ordinal, then those integers are converted into binary code, then the digits from that binary string are split into separate columns. This encodes the data in fewer dimensions than one-hot. You can do binary encoding via a number of ways but the simplest one is using the category_encoders library. You can install category_encoders via pip install category_encoders on cmd or just download and extract the .tar.gz file from the site. You have to first import the category_encoders library after installing it. Invoke the BinaryEncoder function by specifying the columns you want to encode and then call the .fit_transform() method on it with the DataFrame as the argument. cat_df_flights_ce = cat_df_flights.copy() import category_encoders as ce encoder = ce.BinaryEncoder(cols=['carrier']) df_binary = encoder.fit_transform(cat_df_flights_ce) df_binary.head() Notice that four new columns are created in place of the carrier column with binary encoding for each category in the feature. Note that category_encoders is a very useful library for encoding categorical columns. Not only does it support one-hot, binary and label encoding, but also other advanced encoding methods like Helmert contrast, polynomial contrast, backward difference, etc. 5. Backward Difference Encoding This technique falls under the contrast coding system for categorical features. A feature of K categories, or levels, usually enters a regression as a sequence of K-1 dummy variables. In backward difference coding, the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. This type of coding may be useful for a nominal or an ordinal variable. If you want to learn other contrast coding methods you can check out this resource. The code structure is pretty much the same as any method in the category_encoders library, just this time you will call BackwardDifferenceEncoder from it: encoder = ce.BackwardDifferenceEncoder(cols=['carrier']) df_bd = encoder.fit_transform(cat_df_flights_ce) df_bd.head() The interesting thing here is that you can see that the results are not the standard 1’s and 0’s you saw in the dummy encoding examples but rather regressed continuous values. Miscellaneous Features Sometimes you may encounter categorical feature columns which specify the ranges of values for observation points, for example, the age column might be described in the form of categories like 0-20, 20-40 and so on. While there can be a lot of ways to deal with such features, the most common ones are either split these ranges into two separate columns or replace them with some measure like the mean of that range. You will first create a dummy DataFrame which has just one feature age with ranges specified using the pandas DataFrame function. Then you will split the column on the delimeter - into two columns start and end using split() with a lambda() function. If you want to learn more about lambda functions, check out this tutorial. dummy_df_age = pd.DataFrame({'age': ['0-20', '20-40', '40-60','60-80']}) dummy_df_age['start'], dummy_df_age['end'] = zip(*dummy_df_age['age'].map(lambda x: x.split('-'))) dummy_df_age.head() To replace the range with its mean, you will write a split_mean() function which basically takes one range at a time, splits it, then calculates the mean and returns it. To apply a certain function to all the entities of a column you will use the .apply() method: dummy_df_age = pd.DataFrame({'age': ['0-20', '20-40', '40-60','60-80']}) def split_mean(x): split_list = x.split('-') mean = (float(split_list[0])+float(split_list[1]))/2 return mean dummy_df_age['age_mean'] = dummy_df_age['age'].apply(lambda x: split_mean(x)) dummy_df_age.head() Dealing with Categorical Features in Big Data with Spark Now you will learn how to read a dataset in Spark and encode categorical variables in Apache Spark's Python API, Pyspark. But before that it's good to brush up on some basic knowledge about Spark. Spark is a platform for cluster computing. It lets you spread data and computations over clusters with multiple nodes. computations are performed in parallel over the nodes in the cluster. Deciding whether or not Spark is the best solution for your problem takes some experience, but you can consider questions like: - Is my data too big to work with on a single machine? - Can my calculations be easily parallelized? The first step in using Spark is connecting to a cluster. In practice, the cluster will be hosted on a remote machine that's connected to all other nodes. There will be one computer, called the master that manages splitting up the data and the computations. The master is connected to the rest of the computers in the cluster, which are called slaves. The master sends the slaves data and calculations to run, and they send their results back to the master. When you're just getting started with Spark, it's simpler to just run a cluster locally. If you wish to run Spark on a cluster and use Jupyter Notebook, you can check out this blog. If you wish to learn more about Spark, check out this great tutorial which covers almost everything about it, or DataCamp's Introduction to PySpark course. The first step in Spark programming is to create a SparkContext. SparkContext is required when you want to execute operations in a cluster. SparkContext tells Spark how and where to access a cluster. You'll start by importing SparkContext. from pyspark import SparkContext sc = SparkContext() Note that if you are working on Spark's interactive shell then you don't have to import SparkContext as it will already be in your environment as sc. To start working with Spark DataFrames, you first have to create a SparkSession object from your SparkContext. You can think of the SparkContext as your connection to the cluster and the SparkSession as your interface with that connection. Note that if you are working in Spark's interactive shell you'll have a SparkSession called spark available in your workspace! from pyspark.sql import SparkSession as spark Once you've created a SparkSession, you can start poking around to see what data is in your cluster. Your SparkSession has an attribute called catalog which lists all the data inside the cluster. This attribute has a few methods for extracting different pieces of information. One of the most useful is the .listTables() method, which returns the names of all the tables in your cluster as a list. print(spark.catalog.listTables()) [] Your catalog is currently empty! You will now load the flights dataset in the Spark DataFrame. To read a .csv file and create a Spark DataFrame you can use the .read attribute of your SparkSession object. Here, apart from reading the csv file, you have to additionally specify the headers option to be True, since you have column names in the dataset. Also, the inferSchema argument is set to True, which basically peeks at the first row of the data to determine the fields' names and types. spark_flights = spark.read.format("csv").option('header',True).load('Downloads/datasets/nyc_flights/flights.csv',inferSchema=True) To check the contents of your DataFrame you can run the .show() method on the DataFrame. spark_flights.show(3) +----+-----+---+--------+---------+--------+---------+-------+-------+------+------+----+--------+--------+----+------+ |year|month|day|dep_time|dep_delay|arr_time|arr_delay|carrier|tailnum|flight|origin|dest|air_time|distance|hour|minute| +----+-----+---+--------+---------+--------+---------+-------+-------+------+------+----+--------+--------+----+------+ |2014| 1| 1| 1| 96| 235| 70| AS| N508AS| 145| PDX| ANC| 194| 1542| 0| 1| |2014| 1| 1| 4| -6| 738| -23| US| N195UW| 1830| SEA| CLT| 252| 2279| 0| 4| |2014| 1| 1| 8| 13| 548| -4| UA| N37422| 1609| PDX| IAH| 201| 1825| 0| 8| +----+-----+---+--------+---------+--------+---------+-------+-------+------+------+----+--------+--------+----+------+ only showing top 3 rows If you wish to convert a pandas DataFrame to a Spark DataFrame, use the .createDataFrame() method on your SparkSession object with the DataFrame's name as argument. To have a look at the schema of the DataFrame you can invoke .printSchema() as follows: spark_flights.printSchema() root |-- year: integer (nullable = true) |-- month: integer (nullable = true) |-- day: integer (nullable = true) |-- dep_time: string (nullable = true) |-- dep_delay: string (nullable = true) |-- arr_time: string (nullable = true) |-- arr_delay: string (nullable = true) |-- carrier: string (nullable = true) |-- tailnum: string (nullable = true) |-- flight: integer (nullable = true) |-- origin: string (nullable = true) |-- dest: string (nullable = true) |-- air_time: string (nullable = true) |-- distance: integer (nullable = true) |-- hour: string (nullable = true) |-- minute: string (nullable = true) Note that Spark doesn't always guess the data type of the columns right and you can see that some of the columns ( arr_delay, air_time, etc.) which seem to have numeric values are read as strings rather than integers or floats, due to the presence of missing values. At this point, if you check the data in your cluster using the .catalog attribute and the .listTables() method like you did before, you will find it's still empty. This is because you DataFrame is currently stored locally, not in the SparkSession catalog. To access the data in this way, you have to save it as a temporary table. You can do so by using the .createOrReplaceTempView() method. This method registers the DataFrame as a table in the catalog, but as this table is temporary, it can only be accessed from the specific SparkSession used to create the Spark DataFrame. spark_flights.createOrReplaceTempView("flights_temp") Print the tables in catalog again: print(spark.catalog.listTables()) [Table(name=u'flights_temp', database=None, description=None, tableType=u'TEMPORARY', isTemporary=True)] Now you have registered the flight_temp table as a temporary table in your catalog. Now that you have gotten your hands dirty with a little bit of PySpark code, it's time to see how to encode categorical features. To keep things neat, you will create a new DataFrame which consists of only the carrier column by using the .select() method. carrier_df = spark_flights.select("carrier") carrier_df.show(5) +-------+ |carrier| +-------+ | AS| | US| | UA| | US| | AS| +-------+ only showing top 5 rows The two most common ways to encode categorical features in Spark are using StringIndexer and OneHotEncoder. StringIndexerencodes a string column of labels to a column of label indices. The indices are in [0, numLabels] ordered by label frequencies, so the most frequent label gets index 0. This is similar to label encoding in pandas. You will start by importing the StringIndexer class from the pyspark.ml.feature module. The main arguments inside StringIndexer are inputCol and outputCol, which are self-explanatory. After you create the StringIndex object you call the .fit() and .transform() methods with the DataFrame as the argument passed as shown: from pyspark.ml.feature import StringIndexer carr_indexer = StringIndexer(inputCol="carrier",outputCol="carrier_index") carr_indexed = carr_indexer.fit(carrier_df).transform(carrier_df) carr_indexed.show(7) +-------+-------------+ |carrier|carrier_index| +-------+-------------+ | AS| 0.0| | US| 6.0| | UA| 4.0| | US| 6.0| | AS| 0.0| | DL| 3.0| | UA| 4.0| +-------+-------------+ only showing top 7 rows Since AS was the most frequent category in the carrier column, it got the index 0.0. - OneHotEncoder: as you already read before, one-hot encoding maps a categorical feature, represented as a label index, to a binary vector with at most a single one-value indicating the presence of a specific feature value from among the set of all feature values. For example, with 5 categories, an input value of 2.0 would map to an output vector of [0.0, 0.0, 1.0, 0.0]. The last category is not included by default (configurable via OneHotEncoder .dropLast because it makes the vector entries sum up to one, and hence linearly dependent. That means that an input value of 4.0 would map to [0.0, 0.0, 0.0, 0.0]. Note that this is different from scikit-learn's OneHotEncoder, which keeps all categories. The output vectors are sparse. For a string type like in this case, it is common to encode features using StringIndexer first, here carrier_index. Then pass that column to the OneHotEncoder class. The code is shown below. carrier_df_onehot = spark_flights.select("carrier") from pyspark.ml.feature import OneHotEncoder, StringIndexer stringIndexer = StringIndexer(inputCol="carrier", outputCol="carrier_index") model = stringIndexer.fit(carrier_df_onehot) indexed = model.transform(carrier_df_onehot) encoder = OneHotEncoder(dropLast=False, inputCol="carrier_index", outputCol="carrier_vec") encoded = encoder.transform(indexed) encoded.show(7) +-------+-------------+--------------+ |carrier|carrier_index| carrier_vec| +-------+-------------+--------------+ | AS| 0.0|(11,[0],[1.0])| | US| 6.0|(11,[6],[1.0])| | UA| 4.0|(11,[4],[1.0])| | US| 6.0|(11,[6],[1.0])| | AS| 0.0|(11,[0],[1.0])| | DL| 3.0|(11,[3],[1.0])| | UA| 4.0|(11,[4],[1.0])| +-------+-------------+--------------+ only showing top 7 rows Note that OneHotEncoder has created a vector for each category which can then be processed further by your machine learning pipeline. There are some more methods available in Spark like VectorIndexer, but you have already mastered the most popular ones. If you wish to explore more, check out Spark's fantastic documentation. Conclusion Hurray!! You have come a long way! You have explored most of the bits and pieces which are out there about dealing with categorical features in the machine learning realm. You started with basic EDA in pandas and then you practiced the different encoding methods available. You also learned a bit about Spark's architecture and moved to encoding categorical data in PySpark. That's a lot, but there is always so much more to learn. You will also have to make sure that you data is properly cleaned. To learn how to do so, take a look at our Cleaning Data in Python course. Happy exploring!!
https://www.datacamp.com/community/tutorials/categorical-data
CC-MAIN-2020-10
refinedweb
5,377
55.54
When you need to process Excel files in batches at work, are you still processing them manually one by one? Learn the following automatic batch processing methods and bid farewell to the mechanical and inefficient work! 01 OS library introduction OS (Operation System) refers to the operating system. In Python, the OS library mainly provides some functions to interact with the operating system, that is, the computer system. Many automation operations rely on the functions of the library. 02 Basic operations of OS Library 1 get current working path In Chapter 2 of the book compare Excel and easily learn Python report automation, we introduced how to install Anaconda and how to write code using Jupyter Notebook. But do you know where the code written in the Jupiter notebook is stored on the computer? Do many readers not know? It's easy to know. Just enter the following code in Jupyter Notebook and run it. import os os.getcwd() Running the above code will get the following results. 'C:\\Users\\zhangjunhong\\python library\\Python Report automation' The above file path is the path where the Notebook code file is located. Under which file path your code is stored, you will get the corresponding results. 2 get all file names under a folder We often import local computer files into Python for processing. We need to know the storage path and file name of the file before importing. If there are only one or two files, you can manually enter the file name and file path, but sometimes there are many files to import. Manual input efficiency will be relatively low, and code is needed to improve efficiency. There are four Excel files in the folder shown in Figure 1. Figure 1 We can use os.listdir(path) to get all the file names under the path. The specific implementation code is as follows. import os os.listdir('D:/Data-Science/share/data/test') Running the above code will get the following results. ['3 Monthly performance-Ming Ming Zhang.xlsx', 'Li Dan's performance in March.xlsx', 'Wang Yueyue-3 Monthly performance.xlsx', 'Chen Kai's performance in March.xlsx'] 3 rename the file Renaming files is a high-frequency requirement. We can use os.rename('old_name','new_name ') to rename files. old_ Name is the old file name, new_ Name is the new file name. Let's first create a new folder called test under the test folder_ Old file, and then use the following code to put test_ Change the old file name to test_new. os.rename('D:/Data-Science/share/data/test/test_old.xlsx' ,'D:/Data-Science/share/data/test/test_new.xlsx') After running the above code, go to the test folder to see test_ The old file no longer exists, only test_new. 4 create a folder When we want to create a new folder under the specified path, we can choose to create a new folder manually or by using os.mkdir(path). We only need to specify the specific path. When the following code is run, it means that a new folder named test11 is created under the D: / Data Science / share / data path. The effect is shown in Figure 2. os.mkdir('D:/Data-Science/share/data/test11') Figure 2 5 delete a folder Deleting a folder corresponds to creating a folder. Of course, we can also choose to delete a folder manually, or use OS. Removediers (path) to delete, indicating the path to delete. When the following code is run, it means that the test11 folder just created is deleted. os.removedirs('D:/Data-Science/share/data/test11') 6 delete a file Deleting a file is to delete a specific file, while deleting a folder is to delete the entire folder, including all files in the folder. os.remove(path) is used to delete the file, indicating the path where the file is located. When we run the following code, it means that we will test in the test folder_ The new file was deleted. os.remove('D:/Data-Science/share/data/test/test_new.xlsx') 03 Batch operation 1. Batch read multiple files under a folder Sometimes a folder contains multiple similar files, such as the performance files of different people in a department. We need to read these files into Python in batch and then process them. We learned earlier how to read a file with load_work(), or read_excel(), no matter which method is adopted, you only need to indicate the path of the file to be read. How to batch read? First get all the file names under the folder, and then traverse and read each file. The specific) print('{}Read complete!'.format(i)) If you want to operate on the data of the read file, you only need to place the specific operation implementation code after the read code. For example, we need to delete duplicate values for each read in file. The) df = df.drop_duplicates() #Delete duplicate value processing print('{}Read complete!'.format(i)) 2 create folders in batch Sometimes we need to create specific folders according to specific topics, such as 12 folders according to months. We described how to create a single folder earlier. If you want to create multiple folders in batch, you only need to traverse and execute the statements of a single folder. The specific implementation code is as follows. month_num = ['1 month','2 month','3 month','4 month','5 month','6 month','7 month','8 month','9 month','10 month','11 month','12 month'] for i in month_num: os.mkdir('D:/Data-Science/share/data/' + i) print('{}Creation completed!'.format(i)) After running the above code, 12 folders will be created under the file path, as shown in Figure 3. Figure 3 3 batch rename files Sometimes we have many files with the same subject, but the file names of these files are confused. For example, the file shown in Figure 4 is the performance of each employee in March, but the naming format is different. We should unify it into the format of "name + performance in March". To achieve this effect, you can rename files through the operations you learned earlier. Previously, we only introduced the operations on a single file. How can you batch operate multiple files at the same time? Figure 4 The specific implementation code is as follows. import os #Gets all file names under the specified folder old_name = os.listdir('D:/Data-Science/share/data/test') name = ["Ming Ming Zhang","Li Dan"," Yue Wang Yue ","Kai Chen"] #Traverse each name for n in name: #Traverse each old file name for o in old_name: #Determine whether the old file name contains a specific name #Rename if included if n in o: os.rename('D:/Data-Science/share/data/test/' + o, 'D:/Data-Science/ share/data/test/' + n +"3 Monthly performance.xlsx") After running the above code, you can see that all the original file names under the folder have been renamed, as shown in Figure 5. Figure 5 04 Other batch operations 1 batch merge multiple files Under the folder shown in Figure 6, there are monthly sales daily reports from January to June. It is known that the structure of these daily reports is the same, with only two columns of "date" and "sales volume". Now we want to combine these daily reports of different months into one. Figure 6 The specific implementation code of merging monthly sales daily reports into one document is as follows. import os import pandas as pd #Gets all file names under the specified file name_list = os.listdir('D:/Data-Science/share/data/sale_data') #Create an empty DataFrame with the same structure df_o = pd.DataFrame({'date':[],'sales volume':[]}) #Traverse and read each file for i in name_list: df = pd.read_excel(r'D:/Data-Science/share/data/sale_data/' + i) #Longitudinal splicing df_v = pd.concat([df_o,df]) #Assign the spliced result to df_o df_o = df_v df_o Run the above code and you will get the merged file df_o. As shown in Figure 7. Figure 7 2 split a document into multiple documents according to the specified column The above describes how to merge multiple files in batch. We also have the inverse requirement of merging multiple files, that is, splitting a file into multiple files according to the specified column. As for the above data set, let's assume that we have obtained a document from January to June. In addition to the columns of "date" and "sales volume", this document also has a column of "month". What you need to do now is to split this file into multiple files according to the "month" column, and store each month as a separate file. The specific implementation code is as follows. #Generate a new month column df_o['month'] = df_o['date'].apply(lambda x:x.month) #Traverse each month value for m in df_o['month'].unique(): #Filter the data of specific month values df_month = df_o[df_o['month'] == m] #Save the filtered data df_month.to_csv(r'D:/Data-Science/share/data/split_data/' + str (m) + 'Monthly sales daily_After splitting.csv') By running the above code, you can see multiple split files in the target path, as shown in Figure 8. Figure 8 *This article is excerpted from the book "compare Excel and easily learn Python report automation". For more information about report automation using python, welcome to read this book!
https://programmer.group/this-article-teaches-you-to-batch-operate-excel-files-with-python.html
CC-MAIN-2021-49
refinedweb
1,560
65.32
#include <nsDeque.h> MODULE NOTES: The Deque is a very small, very efficient container object than can hold elements of type void*, offering the following features: Its interface supports pushing and popping of elements. It can iterate (via an interator class) its elements. When full, it can efficiently resize dynamically. NOTE: The only bit of trickery here is that this deque is built upon a ring-buffer. Like all ring buffers, the first element may not be at index[0]. The mOrigin member determines where the first child is. This point is quietly hidden from customers of this class. The nsDequeFunctor class is used when you want to create callbacks between the deque and your generic code. Use these objects in a call to ForEach();
http://doxygen.db48x.net/comm-central/html/classnsDequeFunctor.html
CC-MAIN-2019-09
refinedweb
125
66.13
Indexing of ndarrays can be done using the standard python x[obj] syntax, where x is the array and obj the selection. There are three kinds of indexing available − What kind of indexing will be there depends on obj. In this section, we are going to mainly concentrate on basic slicing & advanced indexing. We can divide advanced indexing into two parts − Python basic concept of slicing is extended in basic slicing to n dimensions. As with python slice object which is constructed by giving a start, stop & step parameters to slice function. To get specific output, the slice object is passed to the array to extract a part of an array. import numpy as np arr = np.arange(25) s = slice(2, 21, 4) print (arr[s]) [ 2 6 10 14 18] In the above example, we first created a ndarray object (arr) using arange() function. Then a slice object is created by assigning start, stop and step value to it (s). When we passed the slice object to the ndarray, we get part (slice) of the array starting with index 2 up to 21 with a step of 4. Another way to write the above program, # Another way to write above program import numpy as np arr = np.arange(25) s = arr[2:21:4] print (s) [ 2 6 10 14 18] #Slice single item from an array import numpy as np arr = np.arange(10) s = arr[9] print(s) 9 #slice item starting from index import numpy as np arr = np.arange(10) s = arr[3:] print(s) [3 4 5 6 7 8 9] #slice item between indexes import numpy as np arr = np.arange(10) s = arr[3: 7] print(s) [3 4 5 6] Above two methods will be applied to multi-dimensional ndarray too, like below − #slice item between indexes import numpy as np arr = np.array([[[1],[2],[3]], [[4],[5],[6]], [[7], [8], [9]]]) s = arr[1:] print(s) [[[4] [5] [6]] [[7] [8] [9]]] Integer array indexing: Let’s create a simple array with integers arr=np.array([[1,2],[3,4],[5,6]]) print(arr) [[1 2] [3 4] [5 6]] Let’s try to select a specific element from the array, like elements with row index [0, 1, 2] and column index [1, 0, 1] from the multidimensional ndarray. import numpy as np arr=np.array([[1,2],[3,4],[5,6]]) s = arr[[0, 1, 2],[1, 0, 1]] print(s) [2 3 6] Selecting with 0 indexes will give you first row − >>> arr=np.array([[1,2],[3,4],[5,6]]) >>> print(arr[0]) [1 2] Similarly, we can select a single item from the array, for example- select the 1 as row index and 1 as the column index element which gives an array value of 4. >>> print(arr[[1], [1]]) [4] We can arithmetic operation like addition and returns the value of a particular index after performing the addition. >>> print(arr[[1], [1]]+ 1) [5] As we can see the index value is incremented by 1 but the actual array remains the same. >>> arr array([[1, 2], [3, 4], [5, 6]]) But we can change the values of the array and returns the new copy of an array. >>> arr[[1], [1]] +=1 >>> arr array([[1, 2], [3, 5], [5, 6]]) We used boolean indexing when the result is going to be the outcome of boolean operations. >>> arr=np.array([[0,1,2], [3,4,5], [6,7,8], [9,10,11]]) >>> arr array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) Returns the values which are 1. >>> arr[arr == 1] array([1]) Returns the values which are even numbers >>> arr[arr %2 == 0] array([ 0, 2, 4, 6, 8, 10])
https://www.tutorialspoint.com/basic-slicing-and-advanced-indexing-in-numpy-python
CC-MAIN-2020-50
refinedweb
630
67.08
I've been wanting to ask this somehow for a while, but had trouble phrasing it as a non-math question. What follows admittedly isn't really a programming problem. It is proving something very important about Turing machines and complexity. Presumably a lot of you are in college. It's expected that at some point, you have studied complexity and "Big O" notation. The following is pretty basic, but it is a very fundamental truth which is needed for many proofs. In the following code, what is the average complexity of increment(char * binary_string) with respect to the string's length? Code: #include <stdio.h> #include <assert.h> /** * Advance binary_string to the 'next' value. * * binary_string An arbitrary sting of '0' and '1'. * binary_string is N characters long. * binary_string is not all '1's (no overflow) * * What is the expected number of comparisons of this function? */ void increment (char * binary_string) { char * curr_char; // Scan until the first '0', flipping off all the '1' bits. for (curr_char = binary_string; *curr_char == '1'; ++curr_char) *curr_char = '0'; // Flip the 0 bit and return. assert (*curr_char == '0'); *curr_char = '1'; return; } int main (void) { char foo[5]; for (strcpy (foo, "0000"); strcmp (foo, "1111"); increment(foo)) printf ("%s\n", foo); printf ("%s\n", foo); return 0; }
https://cboard.cprogramming.com/tech-board/87772-complexity-problem-printable-thread.html
CC-MAIN-2017-30
refinedweb
208
67.55
- Accessing SQL Server on NetBeans using JDBC, Part 1: Create a connection - Accessing SQL Server on NetBeans using JDBC, Part 2: Perform SQL Operations - Accessing SQL Server on NetBeans using JDBC, Part 3: Troubleshooting Accessing SQL Server on NetBeans using JDBC, Part 3: Troubleshooting This post is the last part which gathers common problems along with solutions about accessing SQL Server using JDBC on NetBeans. By defer posting this a few months, I found many problems that may occur from many people and also solutions. So this post will benefit people who want to develop application to connect a SQL Server using JDBC and have problem with it. There are 3 parts: - Part I : Create a connection This part which you’re reading shows about how to establish a connection between NetBeans and SQL Server. In this example, I use SQL Server 2000 SP4 and NetBeans IDE 5.5 - Part II : Perform SQL Operations This part show how to perform some basic operations from NetBeans with SQL Server. For instance, send querys as SELECT, INSERT, UPDATE to the database. - Part III: Troubleshooting The last part is about problems and how to fix them. Troubleshooting index - Missing the JDBC library - Mistype the connection string - The TCP/IP connection to the host has failed - Login failed for user ‘sa’ - This driver is not configured for integrated authentication Missing the JDBC library Problem You received this error message while compile code in part I. Cause This problem may have many causes as the following: - The JDBC library file is not loaded properly. You may not have add the library file “sqljdbc.jar” to the project. - You haven’t import the needed library to the project Solution - Add the appropriate library to the project. Refer to part I: create a connection. - You need to add following code at the top of thesource code: Mistype the connection string Problem You received this error message while compile code in part I. Cause You may have typed your connection string incorrectly so the JDBC driver couldn’t understand. Solution Recheck your connection string format. The format for SQL authentication mode should be “jdbc:sqlserver://serverName:portNumber;databaseName=DatabaseName;user=UserName;password=Password;” where - serverName is the name of the SQL Server - (Optional) portNumber is the TCP port of SQL Server. Default port is 1433. - (Optional) DatabaseName is the database name on SQL Server. - UserName and Password are username and password for login to SQL Server. This user must be SQL Server authentication mode. The format for Windows authentication mode should be “jdbc:sqlserver://serverName:portNumber;databaseName=DatabaseName;integratedSecurity=true;” where - serverName is the name of the SQL Server - (Optional) portNumber is the TCP port of SQL Server. Default port is 1433. - (Optional) DatabaseName is the database name on SQL Server. Note: Database name is an optional. For more complex connection string, refer to MSDN – Building the Connection URL at Microsoft. In this example, I mistype “jdbc:sqlserver://…” to “jdbc:sqlserver:\\…“. The TCP/IP connection to the host has failed Problem You received this error message while compile code in part I. Cause You try to connect to a SQL Server which has not SQL Server service running or the service refuse to accept remote connections. Solution - Recheck your connection string that you have type server name and port correctly or not. - Check that SQL Server is running. - If SQL Server is on remote host, try to check that you have allow remote connections on the server. To enable remote connections on SQL Server, try visit Enable remote connection to SQL Server 2005 Express. - Check firewall which may block the connection from client to server. Login failed for user ‘sa’ Problem You received this error message while compile code in part I. Cause This error message states clearly that you have provide wrong username or password that connect to SQL Server. Solution Recheck username and password again. This driver is not configured for integrated authentication Problem You need to use Windows authentication mode by using ‘integratedSecurity=true’ instead of specify username and password in the connection string but receive this error message: Cause You need to add ‘sqljdbc_auth.dll’ to the system path. This file can be found in Microsoft SQL Server JDBC Driver. It resides in sqljdbc_1.1\enu\auth\x86 depends on your JDBC driver and system platform (x86 or x64). Solution Copy ‘sqljdbc_auth.dll’ to C:\Windows\System32 or You can set the java.library.path to the directory where ‘sqljdbc_auth.dll’ is. Note: If the path contains any spaces or special characters, you have to use double quotes “” around the value (ex. “your directory”). it proved to be realy healpful, my problem is that im working in netbeans Desktop Application, i hav made a form, and behind the actionListener of it, i wana create connection as wel as perform operations ie; Save, Delete etc… now wat things i hav to do more, how to map the textfields to database? plzzz kindly let mekno ASAP… Have you read Accessing SQL Server on NetBeans using JDBC, Part II: Perform SQL Operations? I think it can be applied to what you want. i’m using sql server 2000, OS winXP, Netbeans 6.1, n try the code above to connect Netbeans to Sql n get error : SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect BUILD SUCCESSFUL (total time: 1 second) i try to telnet port 1433, but result connection failed, although my Sql Service is running… can any one help my problem? i already turn off my Firewall.. n i already check thats my sql active port is 1433.. why i can;t telnet port 1433? Thanks If you can’t telnet to SQL Server on certain port. It may cause from these issues: – The firewall between your computer and SQL Server has blocked telnet protocol. – The SQL Server is running on this port. – The SQL Server service is not running. So you need to check if the firewall on SQL Server or on your network are blocking the telnet protocol or not. You can try to telnet on SQL Server itself to avoid firewall on the network. Next, if you can telnet but still unable to connect in java. Try to remove the port number in the connection string (You can omit the default port). Thank you i am finding soluction this problem your meterial is very nice that is help full me thank you.. my problems are still unsolved, or assuming that it works in your PC, can i have the spesification of the PC such as what is the OS, what is the version of SQL Server (2000 or 2005), and other requirements. So i can try from zero. Thanks alot. Hi, Alex About environment in the tutorial: Windows XP SP2 with NetBeans 5.5 and SQL Server 2000 SP4 on the same computer. I suggest the best way is to develop on the same computer first (connect to SQL Server on the local machine). Hi, Thanks for the nice post. My issue is I can create connection to MS SQL Server 2005 through the runtime window in netbeans 6.5,1, but it doesn’t show any tables nor does running queries help. I need to use hibernate in my project and that requires this connection to work properly. Am I missing something? Thanks Hi, Vikash Is there any error message when you established a connection to the SQL Server? I am getting the following error: The TCP/IP connection to the host has failed. java.net.SocketException: Malformed reply from SOCKS server My connection string is: (0.0.0.0 = is the fake ip address to the server for this post) (***** = is the fake password for this post) jdbc:sqlserver://0.0.0.0:1433;databaseName=ITAssetsDB;user=sa;password=*****; Ok, in Netbeans I have a proxy configured and it could not connect through that proxy. Once I turned the proxy off, it connected just fine. thank you for this very useful content. everything worked fine after doing excatly the way you meant. Kind regards, Serhat from TRNC hi Linglom, i’m using this driver “Microsoft SQL Server JDBC Driver 2.0” to connect to SQL Server 2000 from Netbean 6.7.1 i got this error “Unable to add connection. Cannot establish a connection to jdbc:sqlserver://localhost:1433;databaseName=Northwind using com.microsoft.sqlserver.jdbc.SQLServerDriver (The TCP/IP connection to the host localhost, port 1433 has failed. Error: “connect timed out. Verify the connaction propoerties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.”.).” though that i’ve verifed from Server Network Utility that the TCP/IP protocol is enabled and is listening on port 1433. i can connect to the server through query analyzer though. i wonder what’s wrong? Thank you. Hi, Thesti The error message states that it couldn’t connect to the SQL Server so there must be something wrong. I suggest you try to telnet to port 1433 to re-verify if the SQL Server is accepting request or not. If telnet can connect, then try to change hostname on the connection string to an ip address of your computer. If it still doesn’t solve the problem, can you show your source code? Hi thesti, I had the same problem, that made me waste an entire day looking for a solution. The problem, in my case, was the instance name, using a named instance, like this jdbc:sqlserver://SERVERNAME\INSTANCE:1433;databaseName=TESTDB I changed my instalation, so the server isn’t named, and just accept a connection in the form: jdbc:sqlserver://SERVERNAME:1433;databaseName=TESTDB and I got the connection working. it is really good to see problems and solutions . Really it helps us too much and i m very thankfull to u for providing us such news SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ‘THANKGOD-PC/THANKGOD’ This exactly the problem i have SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException Can someone please hellp me, This is my connection string. String connectionUrl = “jdbc:sqlserver://” + IP + “; databaseName=” + Database + “; User=” + user + “; Password=” + password + “;”; the IP,Database,user and password are strings. when i run the class i got this error com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.SocketException: Malformed reply from SOCKS server Can someone PLEASE HELP ME. Hello Sir, I had made a project in netbeans with DB SQL server2005 . My problem is that when i m running the project through netbeans it is running successfully and also it is successfully connected with the DB. But ,when i run the jar file trough cmd it is showing the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. Please help me out , so i can deliver my project to the client. Thanks. Nice. Very useful! Hello All, My problem is solved. The above error comes due to the package problem. Just i had to move one image from one package to another. i am getting the error as communication link failure. will u pls tell me how to solve this?? Hi, I’m using Netbeans 6.8 and SQL server 2005, sqljdbc driver. I’m trying to insert form elements into databae using javascript as well as php. My problem is that whenever i try to run the program it opens up a jsp page. Can someone help me solve this?? Really helpfull. At least I was able to connect to SQL Express 2008. Thank you for posting these information. I was able to configure even I am using SQL 2005. More power. Thanx it helped!! I have following error when user connection with sql server 2005 init: deps-jar: Compiling 1 source file to C:\Users\Archana\Documents\NetBeansProjects\TestSQL\build\classes compile: run: SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value. BUILD SUCCESSFUL (total time: 0 seconds) i have following error Jul 29, 2011 1:03:43 AM com.microsoft.sqlserver.jdbc.SQLServerConnection SEVERE: Java Runtime Environment (JRE) version 1.6 is not supported by this driver. Use the sqljdbc4.jar class library, which provides support for JDBC 4.0. Exception in thread “main”.(SQLServerConnection.java:238) at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841) at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:207) at database.Database.main(Database.java:36) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds) its really helpful now i connected my application with sql server 2008 but when i checked the database there is no any what will be the problem when i run the following is displayed init: deps-jar: compile-single: run-single: so what is the prob i am trying to connect sql and netbeans but geting error.. plz help me linglom.. 🙁 Eric.. ca u plz breifly descirbe how to connect sql server and net beans using java… sir i m using netbeans ide5.5 and tomact server 5.0 and ms sql server 2005. there is no error in my coding but still cant insert data into database. is there any settings in netbeans and ms sql server after installation or if any error in coding just plzzz help me its my project. import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class NewUserRegister extends HttpServlet { // Dbconnect objCon; Connection con=null; String strName1=null; String strMiddleName=null; String strLastName=null; String strNo=null; String strDob=null; String strAddr=null; String strId=null; String strSex=null; String qury=”INSERT INTO UserRegisteration(FirstName,LastName,MiddleName,PhoneNo,Dob,Sex,Address,EmployeeId) VALUES( ?,?,?,?,?,?,?,? )”; //Read more: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType(“text/html;charset=UTF-8”); ///====================================================================================== ///========================================================================================= // objCon=new Dbconnect(); Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String url=”jdbc:odbc:clss”; con= DriverManager.getConnection(url,””,””); // con=objCon.Connects(); System.out.println(“Connected”);”); HttpSession session = request.getSession(true); session.setAttribute(“nam”,strName1); System.out.println(strName1);System.out.println(strMiddleName);); } getServletConfig().getServletContext().getRequestDispatcher(“/pictureViewer.jsp”).forward(request,response); } public void ParamData(HttpServletRequest request, HttpServletResponse response) { try { // objCon=new Dbconnect(); // con=objCon.Connects();.getMessage()); } }”; } }this si one of ma code plz check it out sir Hi… I got the same problem that user “Modh Farham” with my NetBeans 7.2 trying to connect MsSqlServer 2000, so I tried via ODBC but I got a new error: length of String or buffer invalid. Could anyone help me, please? Thanks! sir i am using net beans 7.4 and ms sql server 2008. i am trying to connect my netbeans with sql server. but it gives error like this… Cannot establish a connection to jdbc:sqlserver://localhost\mysql:1433;databaseName=phonebook using com.microsoft.sqlserver.jdbc.SQLServerDriver (Login failed for user ‘sa’. ClientConnectionId:b2895fd2-4228-48af-93f4-6be4ecfd1a8f) please tell me what will be error there? when i login from management studio by providing user name and password , i successfully login , but facing problem when i try to login via netbeans. i have three server one is default with instance name MSSQLSERVER, 2nd is MYSQL, and third is SQLEXPRESS… the port number for MSQLSERVER is 1433 ,,and for rest two not mention ..please guide me what i do ,,,
https://www.linglom.com/programming/java/accessing-sql-server-on-netbeans-using-jdbc-part-iii-troubleshooting/
CC-MAIN-2020-29
refinedweb
2,589
57.16
On 2010-02-04 11:06 AM, Robert Kern wrote: > On 2010-02-04 10:53 AM, Riccardo-Maria BIANCHI wrote: >> >> Hi, >> >> I have a package structured like this: >> >> >> package/__init__.py >> src/ __init__.py >> mod1.py >> share/__init__.py >> mod2.py >> >> >> Now I can import them as: >> package.src.mod1 >> package.share.mod2 >> >> How can I use Distutils to be able to import both of them under the same >> "package" namespace as: >> >> import package.mod1 >> import package.mod2 >> >> ? >> >> Thanks a lot in advance for your kind help! > > Remove the package/src/__init__.py and package/share/__init__.py . In > your package/__init__.py, append the src/ and share/ directories to the > __path__ list. See this essay for more documentation on this feature: -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco
https://mail.python.org/pipermail/distutils-sig/2010-February/015479.html
CC-MAIN-2016-40
refinedweb
161
67.65
Visual Query Designer supports the following SQL capabilities: For more information on how to use these capabilites in Visual Query Designer, refer to Query Building With Visual Query Designer. Note: You need to have Microsoft Internet Explorer 11 or higher installed on the system to run the Visual Query Designer. See the graphic below to understand how a simple SQL query is generated in the Visual Query Designer. In a Section Report Database View contains the structure of a database including namespaces, tables, views and columns. You can drag and drop or double click the elements in the Database View to add them to the Design tab. Alternatively, you can double click the crossed arrows icon on the right hand side of each element in the Database View to add it to the Design tab. This is the first step in query building through the Visual Query Designer. A SQL query is generated as you add the database elements to the Design tab. The Visual Query Designer provides several tools to generate a query. The Query Tools section is divided into three major areas: Design tab, SQL tab and Toolbar buttons. Design Tab The Design tab is the area of the Visual Query Designer where you set up queries. It provides a visual interface for the SQL query you want to generate. Displays the fields, tables or any other element selected from the Database view. Each field in the Selected Fields panel has its own set of editable options. The Tables and Relationships panel displays a list of all the tables with fields in the Selected Fields panel. In case the Selected Fields panel has fields from multiple tables, a Relations button appears at the bottom of the related table's name to show the relationship between two tables. Tables and Relationships panel provides the following options for each table: SQL Tab The SQL Tab displays the SQL statement for the current query. Users can edit the query directly in the SQL Tab. When you switch to the SQL Tab, the Visual Query Designer automatically formats your query in the correct syntax with highlighted keywords. In the SQL Tab you can: Tool Bar Buttons The Query Tools section also has a dropdown on the top right corner with two options: Displays the result of the query set in the Visual Query Designer. This panel is populated when you click the Execute button on the Visual Query Designer toolbar after adding the required fields or tables in the Selected Fields panel.
https://www.grapecity.com/activereportsnet/docs/v15/online/visual-query-designer-interface.html
CC-MAIN-2021-31
refinedweb
420
59.64
Hey I am new to the whole C programming and I am trying to write simple code that computes the roots of the quadratic equation and prints the coefficients and the roots into a seperate text file, roots.txt. The coefficients are found in a text file input_equations.txt. Here is my text file 1 -3 2 1 0 -4.84 1 0 1 And here is my program, I am getting wacky numbers in the roots.txt file and I cant seem to work it out. It compiles fine, but the output into the roots.txt file is not giving the right coefficients. Any help would be great, I just can't seem to find the bug! Thanks alot!It compiles fine, but the output into the roots.txt file is not giving the right coefficients. Any help would be great, I just can't seem to find the bug! Thanks alot!Code:#include <stdio.h> #include <stdlib.h> #include <math.h> int compute_roots(double a, double b, double c, double *root1, double *root2) { double disc; disc = pow(b,2) - (4.0*a*c); if (disc < 0) { return (0); } if (disc >= 0) { *root1 = (-1.0*b+sqrt(disc))/(2.0*a); *root2 = (-1.0*b-sqrt(disc))/(2.0*a); return (1); } } int main() { double a,b,c,root1,root2; FILE *inp, outp; inp = fopen("input_equations.txt", "r"); outp = fopen("roots.txt", "w"); while (fscanf(inp, "%f %f %f", &a, &b, &c) != EOF) { fprintf(outp, "%f %f %f ", a, b, c); if(compute_roots(a, b, c, &root1, &root2) == 1) fprintf(outp, "root1 = %g root2 = %g\n", root1, root2); else fprintf(outp, "The roots are not real numbers.\n"); } fclose(inp); fclose(outp); return(0); }
https://cboard.cprogramming.com/c-programming/100132-quadratic-equation-input-another-file-help-please.html
CC-MAIN-2017-22
refinedweb
285
77.23
wcsxfrm(3) BSD Library Functions Manual wcsxfrm(3) NAME wcsxfrm, wcsxfrm_l -- transform a wide string under locale LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <wchar.h> size_t wcsxfrm(wchar_t *restrict ws1, const wchar_t *restrict ws2, size_t n); #include <wchar.h> #include <xlocale.h> size_t wcsxfrm_l(wchar_t *restrict ws1, const wchar_t *restrict ws2, size_t n, locale_t loc); DESCRIPTION The wcsxfrm() function transforms a null-terminated wide character string pointed to by ws2, according to the current locale's collation order, then copies the transformed string into ws1. No more than n wide charac- ters are copied into ws1, including the terminating null character. If n is set to 0 (it helps to determine an actual size needed for transforma- tion), ws1 is permitted to be a NULL pointer. Comparing two strings using wcscmp() after wcsxfrm() is equivalent to comparing two original strings with wcscoll(). Although the wcsxfrm() function uses the current locale, the wcsxfrm_l() function may be passed a locale directly. See xlocale(3) for more infor- mation. RETURN VALUES Upon successful completion, wcsxfrm() returns the length of the trans- formed string not including the terminating null character. If this value is n or more, the contents of ws1 are indeterminate. SEE ALSO setlocale(3), strxfrm(3), wcscmp(3), wcscoll(3), xlocale(3) STANDARDS The wcsxfrm() function conforms to ISO/IEC 9899:1999 (``ISO C99''). BUGS ws1, whereas wcscoll() compares characters using both primary and secondary weights. BSD October 4, 2002 BSD Mac OS X 10.6 - Generated Thu Sep 17 20:23:46 CDT 2009
http://www.manpagez.com/man/3/wcsxfrm_l/
CC-MAIN-2017-47
refinedweb
256
55.54
Library tutorials & articles OpenGL and C# - Part 1 - Introduction - An OpenGL Control - Our Cube Class - Summary Introduction I’m glad to be the first one writing about OpenGL at this site. What I want to show you in this article is that it is fairly easy to setup a form that is capable of showing 3D. We will accomplish this with the OpenGLControl. So before we can start we (that means you) have to download CsGL here, or if it isn’t there anymore, from its project page. For this article I used the CsGL version 1.4.0 I think it will run on later versions though. Ok let we start. First thing to do is make a new Windows Application. Which I called SimpelOpenGL but its not important. Ok when that done popup the “Solution explorer” and “add reference” the reference for CsGL must be in "D:\WINDOWS\system32\" which are called csgl.dll and csgl-base.dllnotice that there is .dll called csgl-native.dll but you don’t need it. Ok import the following namespaces System.Threading CsGL.OpenGL
http://www.developerfusion.com/article/3930/opengl-and-c-part-1/
crawl-002
refinedweb
183
76.93
SYNC(2) OpenBSD Programmer's Manual MSYNC(2) NAME msync - synchronize a mapped region SYNOPSIS #include <sys/types.h> #include <sys/mman.h> int msync(void *addr, size_t len, int flags); DESCRIPTION The msync() system call writes all pages with shared modifications in the specified region of the process's address space back to permanent stor- age, opera- tions. BUGS Writes are currently done synchronously even if the MS_ASYNC flag is specified. SEE ALSO madvise(2), mincore(2), minherit(2), mprotect(2), munmap(2) HISTORY The msync() function first appeared in 4.4BSD. It was modified to conform to IEEE Std1003.1b-1993 (``POSIX'') OpenBSD 2.6 October 10, 1997 1
http://www.rocketaware.com/man/man2/msync.2.htm
crawl-002
refinedweb
111
59.7
Ionic and Django: No 'Access-Control-Allow-Origin' header is present I'm building my first app with Ionic and I'm using Django Rest Framework as API. I just want to create a simple page in Ionic that shows a list of categories. I've created the model Category, and the ViewSets for the API. When I go to the Django-rest-framwork viewer () everything works fine. But when I try to get the results (with Ionic) I get this error: XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access. My code: import {Page, Platform, NavController} from 'ionic/ionic'; import {EmployeeDetailsPage} from '../employee-details/employee-details'; import {Http} from 'angular2/http'; @Page({ templateUrl: 'build/pages/getting-started/getting-started.html' }) export class GettingStartedPage { constructor(platform: Platform, nav: NavController, http: Http) { this.platform = platform; this.nav = nav; this.http = http; this.http.get("") .subscribe(data =>{ this.items=JSON.parse(data._body).results;//Bind data to items object },error=>{ console.log(error);// Error getting the data } ); } } Answers You need to send CORS headers to Ionic Framework to let cross-domain ajax work, since your ionic app is hosted on port 8100, and django-server is running on port 3010, this is considered a cross-domain request. For django, install CORS headers app through pip. In your settings, enable 'corsheaders' app, and also add the allowed urls. # this disables Cross domain requests CORS_ORIGIN_ALLOW_ALL = False # this allows cookie being passed cross domain CORS_ALLOW_CREDENTIALS = True # this is the list of allowed origins for cross domain ajax CORS_ORIGIN_WHITELIST = ( 'localhost:8100', ) You may need to install CORS. If you are testing on chrome you might also need to allow cross origin (There is an extension for it) which should get you around the CORS issue. Need Your Help What is the standard procedure used for login-systems in iOS-apps? ios objective-c security authentication encryptionI am creating an app and a website for a project I've got going, but I'm not sure what I should do about login. This is not a "I'm a noob and I want an app with login"-question. I am somewhat exper... Traverse to selectMenu and get id (Javascript \ JQuery) javascript jquery traversalI want to get the selected value of the inputs.
http://www.brokencontrollers.com/faq/36033649.shtml
CC-MAIN-2019-35
refinedweb
387
57.16