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
Servers/admin log/October 2008 From OpenStreetMap Wiki Contents October 30 - 08:45 Firefishy: "resumed" planet export steps after server power outage. October 29 - 14:10 TomH: Restore systems after power outage. October 24 - 16:45 Firefishy: Puff, restarted rails after unexpected system reboot - 20:18 Jburgess: Puff, not responding to web requests, kernel task ata_aux spinning cpu, forced rebooted - 21:50 Firefishy: Wiki, mod_evasive, wiki cache whitelisted. Wiki cache timeouts lowered drastically - abort quicker rather than queue old-requests. PHP APC updated. October 23 - 22:57 Jburgess: Dev, Internal NIC jammed earlier in the day, Firefishy rebooted machine. October 22 - 09:00 Firefishy: Wiki, blocked known bots. Additionally yacybot, tkwsearch October 20 - 21:50 Firefishy: Swapped Dev's disks into Dulcy. Dev's PSU had blown. October 16 - 19:15 Firefishy: Munin added temperatures from Puff, Fuchur. October 15 - 19:25 Firefishy: Puff, Fuchur added HP hw advisory fan leads. Less noise. - 09:40 Firefishy: Restart mysql on dev - 08:47 TomH: Database hung, server restarted. October 13 - 17:55 Firefishy: Wiki, patched Mediawiki to version 1.13.2. October 12 - 02:00 Firefishy: DB, disabled spammer's account 'telephonecalli' and removed diary spam. October 10 - 12:00 Firefishy: Wiki, disabled $wgGenerateThumbnailOnParse and moved to efficient Thumb.php + mod_rewrite. - 04:09 Firefishy: Wiki, enabled search for language namespaces. - 04:00 Firefishy: Puff installed ruby-mysql-2.7.7. TomH has installed on Draco and Sarel. October 9 - 10:25 Firefishy: Norbert - test ruby-mysql-2.7.7 and increase ulimits October 3 - 03:50 Firefishy: wiki implemented DE, FR, ES, IT and NL namespaces. More another time. Some pages require Template Linking Fixes. October 2 - 18:20 Firefishy: db purged mysql binary logs prior to 2008-09-01.
http://wiki.openstreetmap.org/wiki/Servers/admin_log/October_2008
CC-MAIN-2016-50
refinedweb
289
51.95
On Thu, 2 Dec 1999, David Woolley wrote: > > 991121 Thomas Burdick asked: > > > Are there any plans to add support for file uploads in forms? > > > > it's not clear just what you are referring to: > > He means multipart/form-data Your are confusing two issues. "multipart/form-data" has been supported for a long time. What isn't supported[*] is the TYPE=file attribute on INPUT elements. Don't equate those two. [*] Except for some code in the devel code that doesn't work properly afaik. > This produces the following message in 2.7.2 and I suspect still does > in the current version: No. (Not in the current version, at least.) > Enctype multipart/form-data not yet supported! Cannot submit. The only place where this message occurs in the source is surrounded by: #ifdef NOTDEFINED /* We're disabling form inputs instead of using this. - FM */ ..... #endif /* NOTDEFINED */ (The comment is now misleading, since "multipart/form-data" does NOT cause disabling of form inputs.) It has been like that for a long time, longer than since 2.7.2 came out. (Maybe "multipart/form-data" handling was disabled in 2.7.2 for some strange reason, but I don't know a good reason why that would be the case.) The following should work in all recent version: <TITLE>test</TITLE> <FORM ACTION="" METHOD=POST <INPUT NAME=n1 <INPUT NAME=n2 <INPUT TYPE=submit NAME=n3 </FORM> Klaus
http://lists.gnu.org/archive/html/lynx-dev/1999-12/msg00030.html
CC-MAIN-2015-48
refinedweb
237
67.55
NAME acl_cmp — compare two ACLs LIBRARY Linux Access Control Lists library (libacl, -lacl). SYNOPSIS #include <sys/types.h> #include <acl/libacl.h> int acl_cmp(acl_t acl1, acl_t acl2); DESCRIPTION The acl_cmp() function compares the ACLs pointed to by the arguments acl1 and acl2 for equality. The two ACLs are considered equal if for each entry in acl1 there is an entry in acl2 with matching tag type, qualifier, and permissions, and vice versa. RETURN VALUE If successful, the acl_cmp() function returns 0 if the two ACLs acl1 and acl2 are equal, and 1 if they differ. Otherwise, the value -1 is returned and the global variable errno is set to indicate the error. ERRORS If any of the following conditions occur, the acl_cmp() function returns -1 and sets errno to the corresponding value: [EINVAL] The argument acl1 is not a valid pointer to an ACL. The argument acl2 is not a valid pointer to an ACL. STANDARDS This is a non-portable, Linux specific extension to the ACL manipulation functions defined in IEEE Std 1003.1e draft 17 (“POSIX.1e”, abandoned). SEE ALSO acl(5) AUTHOR Written by Andreas Gruenbacher <a.gruenbacher@bestbits.at>.
http://manpages.ubuntu.com/manpages/xenial/en/man3/acl_cmp.3.html
CC-MAIN-2018-30
refinedweb
194
64.51
Source code editor What Is Ajax ↑ Database, table, index, column, and alias names are identifiers. This section describes the allowable syntax for identifiers in MySQL. The following table describes the maximum length for each type of identifier. There are some restrictions on the characters that may appear in identifiers: No identifier can contain ASCII 0 ( 0x00) or a byte with a value of 255. The use of identifier quote characters in identifiers is permitted, although it is best to avoid doing so if possible. Database, table, and column names should not end with space characters. Database names cannot contain ‘ /’, ‘ \’, ‘ .’, or characters that are not allowed in a directory name. Table names cannot contain ‘ /’, ‘ \’, ‘ .’, or characters that are not allowed in a filename. The length of the identifier is in bytes, not characters. If you use multi-byte characters in your identifier names, then the maximum length will depend on the byte count of all the characters used. Identifiers are stored using Unicode (UTF-8). This applies to identifiers in table definitions that are stored in .frm files and to identifiers stored in the grant tables in the mysql database. The sizes of the string columns in the grant tables (and in any other tables) in MySQL 5.0 are given as number of characters. This means that (unlike some earlier versions of MySQL) you can use multi-byte characters without reducing the number of characters allowed for values stored in these columns. An identifier may be quoted or unquoted. If an identifier is a reserved word or contains special characters, you must quote it whenever you refer to it. (Exception: A word that follows a period in a qualified name must be an identifier, so it need not be quoted even if it is reserved.) For a list of reserved words, see Section 9.3, “Reserved Words”. Special characters are those outside the set of alphanumeric characters from the current character set, ‘ _’, and ‘ $’. The identifier quote character is the backtick (‘ `’): mysql> SELECT * FROM `select` WHERE `select`.id > 100; If the ANSI_QUOTES SQL mode is enabled, it is also allowable to quote identifiers within double quotes: mysql> CREATE TABLE "test" (col INT);ERROR 1064: You have an error in your SQL syntax. (...) mysql> SET sql_mode='ANSI_QUOTES';mysql> CREATE TABLE "test" (col INT);Query OK, 0 rows affected (0.00 sec) Note: Because the ANSI_QUOTES mode causes the server to interpret double-quoted strings as identifiers, string literals must be enclosed within single quotes when this mode is enabled. They cannot be enclosed within double quotes. The server SQL mode is controlled as described in Section 5.2.6, “SQL Modes”.` INT); Identifiers may begin with a digit but unless quoted may not consist solely of digits. It is recommended that you do not use names of the form or Me , where Me N M and N are integers. For example, avoid using 1e or 2e2 as identifiers, because an expression such as 1e+3 is ambiguous. Depending on context, it might be interpreted as the expression 1e + 3 or as the number 1e+3. A user variable cannot be used directly in an SQL statement as an identifier or as part of an identifier. See Section 9.4, “User-Defined Variables”, for more information and examples of workarounds. Be careful when using MD5() to produce table names because it can produce names in illegal or ambiguous formats such as those just described. MySQL allows names that consist of a single identifier or multiple identifiers. The components of a multiple-part name should be separated by period (‘ .’) characters. The initial parts of a multiple-part name act as qualifiers that affect the context within which the final identifier is interpreted. In MySQL you can refer to a column using any of the following forms: If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`. A word that follows a period in a qualified name must be an identifier, so it is not necessary to quote it, even if it is a reserved word. The syntax .tbl_name means the table tbl_name in the default database. This syntax is accepted for ODBC compatibility because some ODBC programs prefix table names with a ‘ .’ character. In MySQL, databases correspond to directories within the data directory. Each table within a database corresponds to at least one file within the database directory (and possibly more, depending on the storage engine). Consequently, the case sensitivity of the underlying operating system determines the case sensitivity of database and table names. This means database and table names are case sensitive in most varieties of Unix, and not case sensitive in Windows. One notable exception is Mac OS X, which is Unix-based but uses a default filesystem type (HFS+) that is not case sensitive. However, Mac OS X also supports UFS volumes, which are case sensitive just as on any Unix. See Section 1.9.4, “MySQL Extensions to Standard SQL”. The lower_case_table_names system variable also affects how the server handles identifier case sensitivity, as described later in this section. MySQL Enterprise. lower_case_table_names is just one of the system variables monitored by the MySQL Network Monitoring and Advisory Service. For information about subscribing to this service see,. Note: Although database and table names are not case sensitive on some platforms, you should not refer to a given database or table using different cases within the same statement. The following statement would not work because it refers to a table both as my_table and as MY_TABLE: mysql> SELECT * FROM my_table WHERE MY_TABLE.col=1; Column, index and stored routine names are not case sensitive on any platform, nor are column aliases. Trigger names are case sensitive.. On Unix, the default value of lower_case_table_names is 0. On Windows the default value is 1. On Mac OS X, the default value is 2. If you are using MySQL on only one platform, you don't normally have to change the lower_case_table_names variable. However, you may encounter difficulties if you want to transfer tables between platforms that differ in filesystem case sensitivity. For example, on Unix, you can have two different tables named my_table and MY_TABLE, but on Windows these two names are considered identical. To avoid data transfer problems stemming from lettercase of database or table names, you have two options: Use lower_case_table_names=1 on all systems. The main disadvantage with this is that when you use SHOW TABLES or SHOW DATABASES, you don, you should set lower_case_table_names to 1 on all platforms to force names to be converted to lowercase. Note that if you plan to set the lower_case_table_names system variable to 1 on Unix, you must first convert your old database and table names to lowercase before restarting mysqld with the new variable setting. Object names may be considered duplicates if their uppercase forms are equal according to a binary collation. That is true for names of cursors, conditions, functions, procedures, savepoints, and routine local variables. It is not true for names of columns, constraints, databases, statements prepared with PREPARE, tables, triggers, users, and user-defined variables. MySQL 5.0 supports built-in (native) functions, user-defined functions (UDFs), and stored functions. This section describes how the server recognizes whether the name of a built-in function is used as a function call or as an identifier, and how the server determines which function to use in cases when functions of different types exist with a given name. non-expression reference to an identifier such as a table or column name. For example, in the following statements, the first reference to count is a function call, whereas the second reference is a table name: SELECT COUNT(*) FROM mytable; CREATE TABLE count (i INT); The parser should recognize the name of a built-in function as indicating a function call only when parsing what is expected to be an expression. That is, in non-expression context, function names are permitted as identifiers. However, some built-in functions have special parsing or implementation considerations, so the parser uses the following rules by default to distinguish whether their names are being used as function calls or as identifiers in non-expression context: To use the name as a function call in an expression, there must be no whitespace between the name and the following ‘ (’ parenthesis character. Conversely, to use the function name as an identifier, it must not be followed immediately by a parenthesis. The requirement that function calls be written with no whitespace between the name and the parenthesis applies only to the built-in functions that have special considerations. COUNT is one such name. The exact list of function names for which following whitespace determines their interpretation are those listed in the sql_functions[] array of the sql/lex.h source file. Before MySQL 5.1, they are rather numerous (about 200), so you may find it easiest to treat the no-whitespace requirement as applying to all function calls. In MySQL 5.1, parser improvements reduce to about 30 the number of affected function names. For functions not listed in the sql_functions[]) array, whitespace does not matter. They are interpreted as function calls only when used in expression context and may be used freely as identifiers otherwise. ASCII is one such name. However, for these non-affected function names, interpretation may vary in expression context: is interpreted as a built-in function if there is one; if not, func_name () is interpreted as a user-defined function or stored function if one exists with that name. func_name () The IGNORE_SPACE SQL mode can be used to modify how the parser treats function names that are whitespace-sensitive: With IGNORE_SPACE disabled, the parser interprets the name as a function call when there is no whitespace between the name and the following parenthesis. This occurs even when the function name is used in non-expression context: mysql> CREATE TABLE count(i INT);ERROR 1064 (42000): You have an error in your SQL syntax ... near 'count(i INT)' To eliminate the error and cause the name to be treated as an identifier, either use whitespace following the name or write it as a quoted identifier (or both): CREATE TABLE count (i INT); CREATE TABLE `count`(i INT); CREATE TABLE `count` (i INT); With IGNORE_SPACE enabled, the parser loosens the requirement that there be no whitespace between the function name and the following parenthesis. This provides more flexibility in writing function calls. For example, either of the following function calls are legal: SELECT COUNT(*) FROM mytable; SELECT COUNT (*) FROM mytable; However, enabling IGNORE_SPACE also has the side effect that the parser treats the affected function names as reserved words (see Section 9.3, “Reserved Words”). This means that a space following the name no longer signifies its use as an identifier. The name can be used in function calls with or without following whitespace, but causes a syntax error in non-expression context unless it is quoted. For example, with IGNORE_SPACE enabled, both of the following statements fail with a syntax error because the parser interprets count as a reserved word: CREATE TABLE count(i INT); CREATE TABLE count (i INT); To use the function name in non-expression context, write it as a quoted identifier: CREATE TABLE `count`(i INT); CREATE TABLE `count` (i INT); To enable the IGNORE_SPACE SQL mode, use this statement: SET sql_mode = 'IGNORE_SPACE'; IGNORE_SPACE is also enabled by certain other composite modes such as ANSI that include it in their value: SET sql_mode = 'ANSI'; Check Section 5.2.6, “SQL Modes”, to see which composite modes enable IGNORE_SPACE. To minimize the dependency of SQL code on the IGNORE_SPACE setting, use these guidelines: Avoid creating UDFs or stored functions that have the same name as a built-in function. Avoid using function names in non-expression context. For example, these statements use count (one of the affected function names affected by IGNORE_SPACE), so they fail with or without whitespace following the name if IGNORE_SPACE is enabled: CREATE TABLE count(i INT); CREATE TABLE count (i INT); If you must use a function name in non-expression context, write it as a quoted identifier: CREATE TABLE `count`(i INT); CREATE TABLE `count` (i INT); Function Name Resolution The following rules describe how the server resolves references to function names for function creation and invocation: Built-in functions and user-defined functions A UDF can be created with the same name as a built-in function but the UDF cannot be invoked because the parser resolves invocations of the function to refer to the built-in function. For example, if you create a UDF named ABS, references to ABS() invoke the built-in function. Built-in functions and stored functions It is possible to create a stored function with the same name as a built-in function, but to invoke the stored function it is necessary to qualify it with a database name. For example, if you create a stored function named PI in the test database, you invoke it as test.PI() because the server resolves PI() as a reference to the built-in function. User-defined functions and stored functions User-defined functions and stored functions share the same namespace, so you cannot create a UDF and a stored function with the same name. The preceding function name resolution rules have implications for upgrading to versions of MySQL that implement new built-in functions: If you have already created a user-defined function schema qualifier (that is, use syntax). schema_name. func_name() Source code editor What Is Ajax
http://www.yaldex.com/mysql_manual/ch09s02.html
CC-MAIN-2016-50
refinedweb
2,276
51.99
Code: Select all #include "Arduino.h" #include <usb_serial.h> #include <HardwareSerial.h> int ledPin = LED_BUILTIN; void setup() { //initialize the ledPin as an output: pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); Serial.begin(); //AN3155: stm32 usart boot loader requires even parity Serial1.begin(115200,SERIAL_8E1); } void loop() { if(Serial1.available()) { digitalWrite(ledPin, HIGH); // blink the led for traffic while(Serial1.available()) { char c = Serial1.read(); Serial.write(c); } digitalWrite(ledPin, LOW); } if(Serial.available()) { digitalWrite(ledPin, HIGH); // blink the led for traffic while(Serial.available()) { char c = Serial.read(); Serial1.write(c); } digitalWrite(ledPin, LOW); } delay(1);//sleep for 1ms } i compile the above sketch in eclipse and flashed it with dfu-util, but it could just have been the arduino ide. next get this and i flashed a boot loader on the other maple mini, somehow it isn't perfect and i've to occasionally retry a few times. but otherwise it works for me in linux i'm using USART1 PA9, PA10, so connect them similar to this, swapping the PA9 TX, PA10 RX between 2 devices ... 3cec0dbc86 i found it rather convenient to connect GND - GND between devices and for the maple mini (clone) there is the VIN pin for 5V so i connect VIN to the other VIN then i simply connect the dongle to usb cable and it power up both boards if the other device is separately powered, then the pins needed are simply PA9 TX, PA10 RX (swap between dongle & target) and GND-GND and don't forget, set boot0 (on target) and press reset for maple mini hold the user button (boot0), press and release reset (but don't let go on the user button yet) and then let go the user button, the blinks from the in flash boot loader would not run which tells you that it is in the serial boot loader
http://stm32duino.com/viewtopic.php?f=18&t=2752&sid=9b56c48d412c3a0701613ae17dde831b
CC-MAIN-2018-09
refinedweb
311
61.36
I wrote a program for an assignment that should read data from a file on the computer then display the sum of both the positive integers and negative integers. However, when I run my program it goes into an infinite loop. I need to understand what I am doing wrong. Any help would be greatly appreciated. Code:#include <iostream> #include <fstream> using namespace std; int main() { ifstream inputFile; int even = 0; int odd = 0; int x; inputFile.open("C:....\hw4dataf11.txt"); //I have attached the file to this post if (!inputFile) cout << "Error opening file.\n"; while(!inputFile.eof()){ if(x % 2 == 0){ even += x; cout << "Number of even numbers is: " << even << endl; even++; } else { odd += x; cout << "Number of odd numbers is: " << odd << endl; odd++; } } inputFile.close(); cout << "Program is finished. \n";hw4dataf11.txt return 0; }
http://cboard.cprogramming.com/cplusplus-programming/141912-beginner-problem-loop.html
CC-MAIN-2013-48
refinedweb
137
67.25
In this tutorial we will be going over how to use a Wia Dot One with a Grove Servo Motor to make the servo lift a flag on a mailbox whenever you have a new email. Figure 1 Figure 2 #include <WiFi.h> #include <Wia.h> #include <ESP32_Servo.h> String currentState; String previousState; Wia wiaClient = Wia(); Servo myServo19; void setup() { WiFi.begin(); delay(2500); myServo19.attach(19); currentState = ""; previousState = ""; } void loop() { currentState = (wiaClient.getDeviceState("emailReceived")); delay(1000); if (currentState != previousState) { myServo19.write(180); delay(150000); } myServo19.write(20); previousState = currentState; delay(60000); } We are going to use the Zapier platform with webhooks to detect when you have a new email and this will trigger an event on the Wia Cloud Platform. To start go to Zapier and create an account and once you have reached the page as seen in figure 3 you need to start filling in the options for your Zap For the section Connect this app... enter Gmail and then for the section with this one! enter Webhooks by Zapier. Then for the section When this happens... enter New email or if you want some other option in your email to trigger the email box then select that. Lastly for then do this! select POST and press the Use Zap button! As seen in figure 3! Figure 3 Then follow the instructions to connect your account and press continue and follow the instruction for what types of emails you would like to trigger Zap. Next when you see the Choose and action app search for Webhooks and select Post and Continue as seen in figure 4 and figure 5. Figure 4 Figure 5 Now for the next section we will need to fill in some information from the Wia Platform as explained below and refer to Figure 6 and Figure 7 and Figure 8 if needed. For the URL section put in Leave payload empty. For the Data in the left box put name and in the right box put the name of your event which for this example is emailReceived In Wrap Request Array select no Leave File empty. In Unflatten select yes Leave Basic Auth empty. For the Headers in the the left box put Authorization and in the right box we will need our device ID. You can find your device ID by going to the Wia Dashboard and go into the space where your Dot One is. Then go to the Things tab, select your Dot One and go to the Configuration section and you should see Your Device secret key is: copy that key as seen in Figure 8 in the red box. Now go back to Zapier and in the Headers section in the right box input Bearer (your secret key) thus paste the key you copied so an example would look something like "Bearer d_sk_712yhbbasd8192yesn" if your secret key is "d_sk_712yhbbasd8192yesn". Figure 6 Figure 7 Figure 8 Figure 9 Now that we have Zapier all set up with the webhooks to trigger events on our Dot One we need to set up a flow to recognize that event and tell your Dot One what to do. To start off go to the Wia Dashboard and go to the space with your Dot One and select the Flows tab to Create a Flow. Now once in your new flow drag an Event Created node into the workspace found in Trigger under Wia. Then name the event and select your Dot One from the List. Note: It is very important that you name your event the same as the event name you put in your Webhook on Zapier which for our example was emailReceived as you can see in Figure 10. Figure 10 4. Now drag a Run Function node into the workspace found in Logic under Wia. 5. In this run function copy and paste the following code into the editor: output.body = device.state.emailReceived ? (parseInt(device.state.emailReceived) + 1) : 1; This code takes the current state and increments it by one if the state exists and if not it sets the current state to one. This is used by our code previously to change the state so that the code can check if the state has changed and if it has that means an event was sent from webhooks thus a new email is in your email box! 6. Now we need to update the state so drag an Update State node into the workspace found in Logic under Wia. * In this node we need to fill out some information about the state so select your device and for State put the state we are working with, for our example it is emailReceived and for value put ${input.body} which takes the output of the run function and updates the state with its value. 7. Then connect the nodes as seen in Figure 11 and turn on the flow and you should be all set! Figure 11
https://community.wia.io/d/96-you-ve-got-mail-iot-e-mailbox-with-gmail-notification
CC-MAIN-2021-10
refinedweb
828
77.37
Are you sure? This action might not be possible to undo. Are you sure you want to continue?". Multithreading Benefits The reason multithreading is still used in spite of its challenges is that multithreading can have several benefits. Some of these benefits are: •Better resource utilization. •Simpler program design in some situations. •More responsive programs. Better resource utilization Imagine an application that reads and processes files from the local file system. Lets say that reading af file from disk takes 5 seconds and processing it takes 2 seconds. Processing two files then takes 5 seconds reading file A 2 seconds processing file A 5 seconds reading file B 2 seconds processing file B ----------------------14 seconds total When reading the file from disk most of the CPU time is spent waiting for the disk to read the data. The CPU is pretty much idle during that time. It could be doing something else. By changing the order of the operations, the CPU could be better utilized. Look at this ordering: 5 seconds reading file A 5 seconds reading file B + 2 seconds processing file A 2 seconds processing file B ----------------------12 seconds total The CPU waits for the first file to be read. Then it starts the read of the second file. While the second file is being read, the CPU processes the first file. Remember, while waiting for the file to be read from disk, the CPU is mostly idle. In general, the CPU can be doing other things while waiting for IO. It doesn't have to be disk IO. It can be network IO as well, or input from a user at the machine. Network and disk IO is often a lot slower than CPU's and memory IO. Simpler Program Design If you were to program the above ordering of reading and processing by hand in a singlethreaded application, you would have to keep track of both the read and processing state of each file. Instead you can start two threads that each just reads and processes a single file. Each of these threads will be blocked while waiting for the disk to read its file. While waiting, other threads can use the CPU to process the parts of the file they have already read. The result is, that the disk is kept busy at all times, reading from various files into memory. This results in a better utilization of both the disk and the CPU. It is also easier to program, since each thread only has to keep track of a single file. More responsive programs Another common goal for turning a singlethreaded application into a multithreaded application is to achieve a more responsive application. Imagine a server application that listens on some port for incoming requests. when a request is received, it handles the request and then goes back to listening. The server loop is sketched below: This design is sketched below: while(server is active){ listen for request hand request to worker thread } This way the server thread will be back at listening sooner. then the application will appear unresponsive while the task executes. and return to listening immediatedly. no new clients can send requests to the server for that duration. While the worker thread is busy with the task.while(server is active){ listen for request process request } If the request takes a long time to process. the window thread is free to respond to other user requests. Only while the server is listening can requests be received. Instead the task can be handed off to a worker thread. The same is true for desktop applications. The window thread can then update the application windows with the result of the task. Thus more clients can send requests to the server. The program with the worker thread design will appear more responsive to the user.. When the worker thread is done it signals the window thread. and the thread executing the task is the thread updating the windows. An alternate design would be for the listening thread to pass the request to a worker thread. . The server has become more responsive. buttons etc. The worker thread will process the request and send a reply to the client. If you click a button that starts a long task. Try creating a program that creates 100 threads that does nothing but wait. Errors arising from incorrect thread synchronization can be very hard to detect. try measuring the performance or responsiveness of the application. program pointer etc. You can read more about context switching on Wikipedia:. other parts are more complex. are larger than the costs. More complex design Though some parts of a multithreaded applications is simpler than a singlethreaded application. Don't just multithread-enable an application just because you can. The CPU switches from executing in the context of one thread to executing in the context of another. the CPU needs to save the local data. instead of just guessing.wikipedia. of the current thread. It also has some costs.org/wiki/Context_switch Increased Resource Consumption A thread needs some resources from the computer in order to run. of the next thread to execute.Costs of Multithreading Going from a singlethreaded to a multithreaded application doesn't just provide benefits. and see how much memory the application takes when running. When in doubt. It may also take up some resources inside the operating system needed to manage the thread. program pointer etc. and load the local data. Besides CPU time a thread needs some memory to keep its local stack. Code executed by multiple threads accessing shared data need special attention. Context Switching Overhead When a CPU switches from executing one thread to executing another. reproduce and fix. Threads are instances of . Creating and Starting Java Threads Java threads are objects like any other Java objects. You don't want to switch between threads more than necessary. This switch is called a "context switch". Thread interaction is far from always simple. Context switching isn't cheap. You should have a good idea that the benefits gained by doing so. Here is an example: public class MyThread extends Thread { public void run(){ System. like this: thread. The second method is to pass an object that implements Runnable to the Thread constructor. } } To create and start the above thread you can do like this: .println("MyThread running").out. The run() method is what is executed by the thread after you call start(). This example doesn't specify any code for the thread to execute. There are two ways to specify what code the thread should execute. is to create a subclass of Thread and override the run() method.start().Thread. The first is to create a subclass of Thread and override the run() method. Both methods are covered below. To start the thread you will call its start() method.lang. or instances of subclasses of this class. It will stop again right away. Creating a thread in Java is done like this: Thread thread = new Thread().class java. Thread Subclass The first way to specify what code a thread is to run. Runnable.println("Thread Running"). It will not wait until the run() method is done.start().lang.out. You can also create an anonymous subclass of Thread like this: Thread thread = new Thread(){ public void run(){ System. Here is how it looks: public class MyRunnable implements Runnable { public void run(){ . myTread.MyThread myThread = new MyThread(). This example will print out the text "Thread running" once the run() method is executed by the new thread. The Runnable object can be executed by a Thread.start(). Runnable implemention The second way to specify what code a thread should run is by creating a class that implements java. The start() call will return as soon as the thread is started. } } thread. When the run() method executes it will print out the text "MyThread running". The run() method will execute as if executed by a different CPU. start().System.start(). pass an instance of MyRunnable to a Thread in its constructor. } } To have the run() method executed by a thread. Here is how that is done: Thread thread = new Thread(new MyRunnable()). thread. The above example would print out the text "MyRunnable running". You can also create an anonymous implementation of Runnable.out.out.println("Runnable running"). like this: Runnable myRunnable = new Runnable(){ public void run(){ System. Both . When the thread is started it will call the run() method of the MyRunnable instance instead of executing it's own run() method. } } Thread thread = new Thread(myRunnable). thread.println("MyRunnable running"). Subclass or Runnable? There are no rules about which of the two methods that is the best. Sometimes you may have to implement Runnable as well as subclass Thread. like this: Thread newThread = new Thread(MyRunnable()). For instance. you MUST call the newThread. At first you may not notice anything because the Runnable's run() method is executed like you expected. Common Pitfall: Calling run() instead of start() When creating and starting a thread a common mistake is to call the run() method of the Thread instead of start().println("run by: " + getname()). if creating a subclass of Thread that can execute more than one Runnable. The name can help you distinguish different threads from each other. if multiple threads write to System. When having the Runnable's executed by a thread pool it is easy to queue up the Runnable instances until a thread from the pool is idle.out. newThread. In other words. I prefer implementing Runnable. Thread Names When you create a thread you can give it a name.out it can be handy to see which thread wrote the text.run(). This is a little harder to do with Thread subclasses. //should be start(). thread. } . Here is an example: Thread thread = new Thread("New Thread") { public void run(){ System. Personally though. This is typically the case when implementing a thread pool. Instead the run() method is executed by the thread that created the thread.methods works. the thread that executed the above two lines of code.start() method. To have the run() method of the MyRunnable instance called by the new created thread. However. it is NOT executed by the new thread you just created. and handing an instance of the implementation to a Thread instance. For instance. that since the MyRunnable class is not a subclass of Thread.println(thread. First it prints out the name of the thread executing the main() method. The name can be obtained by the Thread's getName() method.}. thread.getName()).start(). System.out. This string is the name of the thread.getName()). This thread is assigned by the JVM. A reference to the currently executing thread can be obtained using the call Thread. "New Thread"). Notice however. and then stops executing. .start().println(thread. You can also pass a name to a Thread when using a Runnable implementation. Thread thread = new Thread(runnable.currentThread(). A Thread Example Here is a small example. Here is how that looks: MyRunnable runnable = new MyRunnable().currentThread(). System. thread. it does not have access to the getName() method of the thread executing it. Notice the string "New Thread" passed as parameter to the Thread constructor. Each thread then prints its name out.getName(). Getting the name of the thread currently executing the code can therefore be done like this: String threadName = Thread. Then it starts up 10 threads and give them all a number as name ("" + i).out. .println("Thread: " + getName() + " running").getName()). or objects). for(int i=0.out.start(). 3 etc.currentThread().out. In fact. For instance the same memory (variables. Race Conditions and Critical Sections Running more than one thread inside the same application does not by itself cause problems.println(Thread. meaning thread 1 may not be the first thread to write its name to System. The problems arise when multiple threads access the same resources. problems only arise if one or more of the threads write to these resources. systems (databases. This is because the threads are in principle executing in parallel and not sequentially. The JVM and/or operating system determines the order in which the threads are executed. It is safe to let multiple threads read the same resources. This order does not have to be the same order in which they were started. as long as the resources do not change. web services etc. } } } Note that even if the threads are started in sequence (1.public class ThreadExample { public static void main(String[] args){ System.) they may not execute sequentially.) or files.out. arrays. i++){ new Thread("" + i){ public void run(){ System. i<10. 2. } }. count into a register (0) reads this. } } Imagine if two threads.count = this. A: B: B: B: A: reads this.Here is a code example that may fail if executed by multiple threads simultanously: public class Counter { protected long count = 0.count now equals 2 adds value 3 to register .count into a register (0) adds value 2 to register writes register value (2) back to memory.count + value. There is no way to know when the operating system switches between the two threads. A and B. this.count = 0. The code is not executed as a single instruction by the Java virtual machine.count from memory into register add value to register write register to memory Observe what happens with the following mixed execution of threads A and B: this. Rather it is executed along the lines of: get this. are executing the add method on the same instance of the Counter class. public void add(long value){ this. Instead of 5. then it contains no race conditions. Race Conditions & Critical Sections The situation where two threads compete for the same resource. Race condition only occur when multiple threads update shared resources. Local Variables Local variables are stored in each thread's own stack. Thus the value should have been 5 after the two threads complete execution. Race conditions can be avoided by proper thread synchronization in critical sections. to the value. Thread Safety and Shared Resources Code that is safe to call by multiple threads simultanously is called thread safe. However. is called race conditions. Without proper thread synchronization mechanisms there is no way to know exactly how the thread execution is interleaved. A code section that leads to race conditions is called a critical section. That means that local variables are never shared between threads. leading to race conditions.count now equals 3 The two threads added the values 2 and 3 to the counter. Therefore it is important to know what resources Java threads share when executing. both threads read the value 0 from memory. since the execution of the two threads is interleaved. the value left in this. this. In the above case it is thread A. In the previous example the method add() is a critical section. 2 and 3. and write the result back to memory. Here is an example of a thread safe local primitive variable: public void someMethod(){ . but it could as well have been thread B. That also means that all local primitive variables are thread safe. Then they add their individual values. If a piece of code is thread safe.count will be the value written by the last thread to write its value. where the sequence in which the resource is accessed is significant.A: writes register value (3) back to memory. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads. } public void method2(LocalObject localObject){ localObject. Here is an example of a thread safe local object: public void someMethod(){ LocalObject localObject = new LocalObject(). } Local Object References Local references to objects are a bit different.long threadSafeInt = 0. The reference itself is not shared. localObject. } The LocalObject instance in this example is not returned from the method. All objects are stored in the shared heap.callMethod(). threadSafeInt++. is not stored in each threads's local stack. If an object created locally never escapes the method it was created in. method2(localObject). The object referenced however.setValue("value"). it is thread safe. nor is it passed to any other objects that are accessible from outside the . .builder. Each thread executing the someMethod() method will create its own LocalObject instance and assign it to the localObject reference. public add(String text){ this.someMethod() method.start(). if two threads call a method on the same object instance and this method updates object members. stores the LocalObject instance in a way that allows access to it from other threads. Object Members Object members are stored on the heap along with the object. the use of it is thread safe. In fact. Therefore the use of the LocalObject here is thread safe. For instance: NotThreadSafe sharedInstance = new NotThreadSafe(). the method is not thread safe. The only exception is of course. Therefore. the whole method someMethod() is thread safe. if one of the methods called with the LocalObject as parameter. or in other classes.append(text). } } If two threads call the add() method simultanously on the same NotThreadSafe instance then it leads to race conditions. Here is an example of a method that is not thread safe: public class NotThreadSafe{ StringBuilder builder = new StringBuilder(). Even if the LocalObject instance is passed as parameter to other methods in the same class. new Thread(new MyRunnable(sharedInstance)). . Now the two threads have each their own instance of NotThreadSafe so their calls to the add method doesn't interfere with each other. but slightly modified: new Thread(new MyRunnable(new NotThreadSafe())). public class MyRunnable implements Runnable{ NotThreadSafe instance = null. even if an object is not thread safe it can still be used in a way that doesn't lead to race condition.start().instance = instance. Therefore. The code does not have race condition anymore. when they call the add() method on the NotThreadSafe instance it leads to race condition.start(). public MyRunnable(NotThreadSafe instance){ this. } public void run(){ this. if two threads call the add() method simultanously on different instancesthen it does not lead to race condition. However.add("some text").instance. new Thread(new MyRunnable(new NotThreadSafe())). Here is the example from before. } } Notice how the two MyRunnable instances share the same NotThreadSafe instance.new Thread(new MyRunnable(sharedInstance)).start(). So. used and disposed within the control of the same thread. so "disposed" means losing or null'ing the reference to the object. For example. socket etc. Result = no Thread 2 checks if record X exists. This is how: Thread 1 checks if record X exists. connection 1 and connection 2. the use of each connection itself is thread safe. But the use of the database the connections point to may not be thread safe. Result = no Thread 1 inserts record X Thread 2 inserts record X . array. the use of that resource is thread safe. if both threads execute code like this: check if record X exists if not. file. if that object points to a shared resource like a file or database. and the record X they are checking for happens to be the same record. if thread 1 and thread 2 each create their own database connections. Resources can be any shared resource like an object. Even if the use of an object is thread safe. your application as a whole may not be thread safe. and never escapes the control of this thread. For instance. In Java you do not always explicitly dispose objects. insert record X If two threads execute this simultanously. there is a risk that both of the threads end up inserting it. database connection.The Thread Control Escape Rule When trying to determine if your code's access of a certain resource is thread safe you can use the thread control escape rule: If a resource is created. We can make sure that objects shared between threads are never updated by any of the threads by making the shared objects immutable.This could also happen with threads operating on files or other shared resources. } } Notice how the value for the ImmutableValue instance is passed in the constructor. If multiple threads read the same resource race conditions do not occur.value. It is immutable. and thereby thread safe.and one or more of the threads write to the resource. } public int getValue(){ return this. Therefore it is important to distinguish between whether an object controlled by a thread is the resource. Once an ImmutableValue instance is created you cannot change its value. public ImmutableValue(int value){ this. You can read it however. Tread Safety and Immutability Race conditions occur only if multiple resources are accessing the same resource.value = value. Here is an example: public class ImmutableValue{ private int value = 0. or if it merely references the resource. using the getValue() method. Notice also how there is no setter method. If you need to perform operations on the ImmutableValue instance you can do so by returning a new instance with the value resulting from the operation. Here is an example of an add operation: . the reference to this object may not be thread safe. public ImmutableValue(int value){ this. Look at this example: . } public ImmutableValue add(int valueToAdd){ return new ImmutableValue(this.public class ImmutableValue{ private int value = 0. that even if an object is immutable and thereby thread safe. The Reference is not Thread Safe! It is important to remember.value. } } Notice how the add() method returns a new ImmutableValue instance with the result of the add operation.value + valueToAdd). rather than adding the value to itself. } public int getValue(){ return this.value = value. currentValue = newValue. } public void add(int newValue){ this. it is not itself immutable.currentValue.add(newValue). and add() methods synchronized. setValue(). This is something to keep in mind when trying to achieve thread safety through immutability. That would have . and therefore not thread safe. } public void setValue(ImmutableValue newValue){ this. To make the Calculator class thread safe you could have declared thegetValue(). In other words: TheImmutableValue class is thread safe. public ImmutableValue getValue(){ return currentValue. } } The Calculator class holds a reference to an ImmutableValue instance. even if the Calculator class uses an immutable object internally. Notice how it is possible to change that reference through both the setValue() and add()methods.public void Calculator{ private ImmutableValue currentValue = null. Therefore. but the use of it is not.currentValue = this. done the trick. Java Synchronized Blocks A Java synchronized block marks a method or a block of code as synchronized.Instance methods 2. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time.Code blocks inside static methods These blocks are synchronized on different objects. Here is a list of the topics covered in this tutorial: • • • • • • The Java synchronized keyword Synchronized instance methods Synchronized static methods Synchronized blocks in instance methods Synchronized blocks in static methods Java Synchronized Example The Java synchronized Keyword Synchronized blocks in Java are marked with the synchronized keyword. . The synchronized keyword can be used to mark four different types of blocks: 1.Code blocks inside instance methods 4.count += value. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. Which type of synchronized block you need depends on the concrete situation. Java synchronized blocks can be used to avoid race conditions.Static methods 3. A synchronized block in Java is synchronized on some object. Synchronized Instance Methods Here is a synchronized instance method: public synchronized void add(int value){ this. If the static synchronized methods are located in different classes. Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. each instance has its synchronized methods synchronized on a different object: the owning instance. Here is a synchronized block of Java code inside an unsynchronized Java . Sometimes it is preferable to synchronize only part of a method. A synchronized instance method in Java is synchronized on the instance (object) owning the method. then one thread at a time can execute inside a synchronized instance method per instance. } Also here the synchronized keyword tells Java that the method is synchronized. One thread per instance. Here is a Java synchronized static method example: public static synchronized void add(int value){ count += value. Since only one class object exists in the Java VM per class. One thread per class regardless of which static synchronized method it calls. Thus. If more than one instance exist. Synchronized Static Methods Static methods are marked as synchronized just like instance methods using thesynchronized keyword. Only one thread can execute inside a synchronized instance method. then one thread can execute inside the static synchronized methods of each class. This tells Java that the method is synchronized.} Notice the use of the synchronized keyword in the method declaration. Java synchronized blocks inside methods makes this possible. Synchronized Blocks in Instance Methods You do not have to synchronize a whole method. only one thread can execute inside a static synchronized method in the same class. String msg2){ log. Notice how the Java synchronized block construct takes an object in parentheses. } } This example uses the Java synchronized block construct to mark a block of code as synchronized.method: public void add(int value){ synchronized(this){ this. The following two examples are both synchronized on the instance they are called on. This code will now execute as if it was a synchronized method. Only one thread can execute inside a Java code block synchronized on the same monitor object. The object taken in the parentheses by the synchronized construct is called a monitor object. In the example "this" is used. A synchronized instance method uses the object it belongs to as monitor object. They are therefore equivalent with respect to synchronization: public class MyClass { public synchronized void log1(String msg1.writeln(msg1). .count += value. The code is said to be synchronized on the monitor object. which is the instance the add method is called on. Synchronized Blocks in Static Methods Here are the same two examples as static methods. log. These methods are synchronized on the class object of the class the methods belong to: public class MyClass { . Had the second synchronized block been synchronized on a different object thanthis.log.writeln(msg2).writeln(msg2). String msg2){ synchronized(this){ log. } public void log2(String msg1. } } } Thus only a single thread can execute inside either of the two synchronized blocks in this example. then one thread at a time had been able to execute inside each method.writeln(msg1). String msg2){ log.class){ log.writeln(msg1).class. then one thread could execute inside each method at the same time. Had the second synchronized block been synchronized on a different object thanMyClass. } } } Only one thread can execute inside any of these two methods at the same time.public static synchronized void log1(String msg1.writeln(msg2). . String msg2){ synchronized(MyClass.writeln(msg1). because the method is synchronized on the instance it belongs to. Only one thread at a time will be able to call the add method on the same instance.writeln(msg2). } public static void log2(String msg1. Java Synchronized Example Here is an example that starts 2 threads and have both of them call the add method on the same instance of Counter. log. log. } .count += value. } public void run() { for(int i=0. public CounterThread(Counter counter){ this. public synchronized void add(long value){ this. i<10. i++){ counter.public class Counter{ long count = 0.add(i). } } public class CounterThread extends Thread{ protected Counter counter = null.counter = counter. Thread Thread threadA = new CounterThread(counter). The same Counter instance is passed to both of them in their constructor. If the two threads had referenced two separate Counter instances. Here is how that could look: . Therefore only one of the threads can call the add() method at a time. The Counter. threadB = new CounterThread(counter).start(). before it can execute the method itself. Therefore the calls would not block. The other thread will wait until the first thread leaves the add() method.start(). so the methods called would also be synchronized on different objects (the object owning the method). The calls would have been to different objects. } } Two threads are created.add() method is synchronized on the instance. because the add method is an instance method. threadB. threadA. there would have been no problems calling the add() methods simultaneously.} } public class Example { public static void main(String[] args){ Counter counter = new Counter(). and marked as synchronized. . Counter counterB = new Counter(). threadA. thread signaling enables threads to wait for signals from other threads. Calling add() on counterA will thus not block a call toadd() on counterB. threadB. threadA and threadB. For instance. no longer reference the same counter instance. a thread B might wait for a signal from thread A indicating that data is ready to be processed. Additionally. threadB = new CounterThread(counterB).public class Example { public static void main(String[] args){ Counter counterA = new Counter(). The add method of counterA and counterB are synchronized on their two owning instances.start().start(). Thread Signaling The purpose of thread signaling is to enable threads to send signals to each other. Thread Thread threadA = new CounterThread(counterA). } } Notice how the two threads. and notifyAll() 4.Missed Signals 5. public synchronized boolean hasDataToProcess(){ return this. } public synchronized void setHasDataToProcess(boolean hasData){ this.Don't call wait() on constant String's or global objects Signaling via Shared Objects A simple way for threads to send signals to each other is by setting the signal values in some shared object variable.wait().hasDataToProcess. also inside a synchronized block.Spurious Wakeups 6. and provide methods to set and check it: public class MySignal{ protected boolean hasDataToProcess = false. Thread A may set the boolean member variable hasDataToProcess to true from inside a synchronized block. notify(). Here is a simple example of an object that can hold such a signal.Busy Wait 3. and thread B may read the hasDataToProcess member variable.Signaling via Shared Objects 2.This text will cover the following topics related to thread signaling in Java: 1.Multiple Threads Waiting for Same Signals 7. .hasDataToProcess = hasData. . The thread is busy while waiting.. they will not detect each others signals. busy waiting } Notice how the while loop keeps executing until hasDataToProcess() returns true. while waiting for this signal: protected MySignal sharedSignal = .. Busy Wait Thread B which is to process the data is waiting for data to become available for processing. If thread A and B has references to different MySignal instance.. In other words. . it is waiting for a signal from thread A which causes hasDataToProcess() to return true.hasDataToProcess()){ //do nothing.. . This is called busy waiting. while(!sharedSignal.. Here is the loop that thread B is running in.} } Thread A and B must have a reference to a shared MySignal instance for the signaling to work. The data to be processed can be located in a shared buffer separate from the MySignal instance. lang.wait(). except if the average waiting time is very small. public class MonitorObject{ } public class MyWaitNotify{ MonitorObject myMonitorObject = new MonitorObject(). the calling thread must call wait() or notify() from inside a synchronized block.Object defines three methods. wait().. Java has a builtin wait mechanism that enable threads to become inactive while waiting for signals. In order to call either wait() or notify the calling thread must first obtain the lock on that object. } catch(InterruptedException e){. A thread that calls wait() on any object becomes inactive until another thread calls notify() on that object. notify()..wait(). Here is a modified version of MySignal called MyWaitNotify that uses wait() and notify(). public void doWait(){ synchronized(myMonitorObject){ try{ myMonitorObject. and notifyAll(). The class java. In other words. notify() and notifyAll() Busy waiting is not a very efficient utilization of the CPU in the computer running the waiting thread. it would be smarter if the waiting thread could somehow sleep or become inactive until it receives the signal it is waiting for. to facilitate this. Else.} . There is also a notifyAll() method that will wake all threads waiting on a given object. In other words: The awakened thread must reobtain the lock on the monitor object before it can exit the wait() call. This allows other threads to call wait() or notify() too. since each thread must obtain the lock on the monitor object in . since these methods must be called from inside a synchronized block. This is mandatory! A thread cannot call wait(). Once a thread calls wait() it releases the lock it holds on the monitor object. But. one of the threads waiting on that object are awakened and allowed to execute. and the notifying thread would call doNotify().. When a thread calls notify() on an object. If multiple threads are awakened using notifyAll() only one awakened thread at a time can exit the wait() method. Once a thread is awakened it cannot exit the wait() call until the thread calling notify() has left its synchronized block. If it does. As you can see both the waiting and notifying thread calls wait() and notify() from within a synchronized block.} } public void doNotify(){ synchronized(myMonitorObject){ myMonitorObject. notify() or notifyAll() without holding the lock on the object the method is called on.notify(). an IllegalMonitorStateException is thrown. because the wait call is nested inside a synchronized block. } } } The waiting thread would call doWait(). } catch(InterruptedException e){. but in some cases this may result in the waiting thread waiting forever. This may or may not be a problem. In the MyWaitNotify example the notify signal should be stored in a member variable inside the MyWaitNotify instance. To avoid losing signals they should be stored inside the signal class. Therefore.. Here is a modified version of MyWaitNotify that does this: public class MyWaitNotify2{ MonitorObject myMonitorObject = new MonitorObject(). if a thread calls notify() before the thread to signal has called wait().wait()..turn before exiting wait(). the signal will be missed by the waiting thread.} } . because the signal to wake up was missed. The notify signal is then just lost. public void doWait(){ synchronized(myMonitorObject){ if(!wasSignalled){ try{ myMonitorObject. never waking up. boolean wasSignalled = false. Missed Signals The methods notify() and notifyAll() do not save the method calls to them in case no threads are waiting when they are called. Also.//clear signal and continue running. myMonitorObject. } } public void doNotify(){ synchronized(myMonitorObject){ wasSignalled = true. In fact it only calls wait() if no signal was received in between the previous doWait() call and this. If a spurious wakeup occurs in the MyWaitNofity2 class's doWait() method the waiting thread may continue processing without having received a proper signal to do so! This could cause serious problems in your application. This is known as spurious wakeups. notice how the doWait() method now checks the wasSignalled variable before calling wait().notify(). } } } Notice how the doNotify() method now sets the wasSignalled variable to true before calling notify(). Wakeups without any reason. wasSignalled = false. Spurious Wakeups For inexplicable reasons it is possible for threads to wake up even if notify() and notifyAll() has not been called. To guard against spurious wakeups the signal member variable is checked . } catch(InterruptedException e){. The thread awakened spins around until the condition in the spin lock (while loop) becomes false. public void doWait(){ synchronized(myMonitorObject){ while(!wasSignalled){ try{ myMonitorObject.. Such a while loop is also called a spin lock. boolean wasSignalled = false.} } //clear signal and continue running. Here is a modified version of MyWaitNotify2 that shows this: public class MyWaitNotify3{ MonitorObject myMonitorObject = new MonitorObject(). } } ..wait(). wasSignalled = false.inside a while loop instead of inside an if-statement. which are all awakened using notifyAll(). this flag was cleared by the first thread waking up. and the while loop will execute once more. Don't call wait() on constant String's or global objects An earlier version of this text had an edition of the MyWaitNotify example class which used a constant string ( "" ) as monitor object. However. causing the awakened thread to go back to waiting. Here is how that example looked: public class MyWaitNotify{ . Multiple Threads Waiting for the Same Signals The while loop is also a nice solution if you have multiple threads waiting.notify(). If the waiting thread wakes up without having received a signal.public void doNotify(){ synchronized(myMonitorObject){ wasSignalled = true. Once this thread then exits the synchronized block in the doWait() method. the other threads can exit the wait() call and check the wasSignalled member variable inside the while loop. the wasSignalled member will still be false. Only one thread at a time will be able to obtain the lock on the monitor object. } } } Notice how the wait() call is now nested inside a while loop instead of an if-statement. myMonitorObject. meaning only one thread can exit the wait() call and clear the wasSignalled flag. until the next signal arrives. but only one of them should be allowed to continue. so the rest of the awakened threads go back to waiting. wasSignalled = false.. } catch(InterruptedException e){.. . public void doWait(){ synchronized(myMonitorObject){ while(!wasSignalled){ try{ myMonitorObject.wait().String myMonitorObject = "". myMonitorObject. boolean wasSignalled = false. } } public void doNotify(){ synchronized(myMonitorObject){ wasSignalled = true.} } //clear signal and continue running.notify(). The situation is sketched in the diagram below: Remember. After all. A doNotify() call on the MyWaitNotify 1 may wake threads waiting in MyWaitNotify 2. that even if you have two different MyWaitNotify instances. . or any other constant string is.} } } The problem with calling wait() and notify() on the empty string. This awakened thread (A or B) will check its signal in the while loop. in which they are waiting. At first this may not seem like a big problem. so the threads go back to waiting. That means. This also means that threads calling doWait() on the first MyWaitNotify instance risk being awakened by doNotify() calls on the second MyWaitNotify instance. and go back to waiting because doNotify() was not called on the first MyWaitNotify instance. that even if the 4 threads call wait() and notify() on the same shared string instance. This situation is equal to a provoked spurious wakeup. But the code can handle this. Thread A or B awakens without having been signaled. but the signal will only be stored in MyWaitNotify 1. the signals from the doWait() and doNotify() calls are stored individually in the two MyWaitNotify instances. if doNotify() is called on the second MyWaitNotify instance all that can really happen is that Thread A and B are awakened by mistake. they both reference the same empty string instance. that the JVM/Compiler internally translates constant strings into the same object. but one of either C or D would have noticed the signal and left the doWait() method call. C and D were sent a signal but fail to respond to it. only one thread is awakened even if 4 threads are waiting on the same string instance (the empty string). For instance. the awakened thread (A or B) will check its signal. In addition. The situation is illustrated below: . neither of them will ever know. Thread 1 can never get B. a deadlock arises. that since the doNotify() call only calls notify() and not notifyAll(). if one of the threads A or B is awakened when really the signal was for C or D. The other of C and D would go back to waiting. Deadlock can occur when multiple threads need the same locks. This situation is equal to the missed signals problem described earlier. You may be tempted then to always call notifyAll() instead notify(). if thread 1 locks A. but obtain them in different order. all waiting threads had been awakened and checked for signals in turn. forever. so the signal is missed. So. A and B. at the same time. for wait() / notify() mechanisms. and go back to waiting. For instance. Thread A and B would have gone back to waiting. Neither C or D wakes up to check the signal they had actually received. and thread 2 has already locked B. and tries to lock B. and tries to lock A. There is no reason to wake up all threads waiting when only one of them can respond to the signal. This situation is a deadlock. and thread 2 can never get A. but this is a bad idea performance wise. Deadlock A deadlock is when two or more threads are blocked waiting to obtain locks that some of the other threads in the deadlock are holding. So: Don't use global objects.The problem is. Use an object that is unique to the construct using it. because the thread discovering the signal clears it on the way out of doWait(). see that no signal was received. each MyWaitNotify3 (example from earlier sections) instance has its own MonitorObject instance rather than using the empty string for wait() / notify() calls. If the doNotify() method had called notifyAll() instead of notify(). string constants etc. They will remain blocked on each their object. waits for B locks B.contains(child)) { this. waits for A Here is an example of a TreeNode class that call synchronized methods in different instances: public class TreeNode { TreeNode parent List = null. } .contains(child){ this.add(child).children.Thread 1 Thread 2 locks A. child.children. public synchronized void addChild(TreeNode child){ if(!this. } } public synchronized void addChildOnly(TreeNode child){ if(!this.children. children = new ArrayList().setParentOnly(this).children.add(child). } public synchronized void setParent(TreeNode parent){ this. Thread 2: child.parent = parent. } public synchronized void setParentOnly(TreeNode parent){ this.parent = parent. a deadlock can occur. } } If a thread (1) calls the parent.addChild(child).addChildOnly(this).addChildOnly() . //locks child --> parent. on the same parent and child instances.addChild(child) method at the same time as another thread (2) calls the child. //locks parent --> child. Here is some pseudo code that illustrates this: Thread 1: parent.setParent(parent) method.setParentOnly(parent). parent.setParent(parent). Thread 2 Thread 3 Thread 4 locks A, waits for B locks B, waits for C locks C, waits for D. Deadlock Prevention In some situations it is possible to prevent deadlocks. I'll describe three techniques in this text: 1.Lock Ordering 2.Lock Timeout 3.Deadlock Detection Lock Ordering Since Thread 1 holds lock A. If a thread does not succeed in taking all necessary locks within the given timeout. This is not always the case. The random amount of time waited serves to give other threads trying to take the same locks a chance to take all locks. neither Thread 2 or Thread 3 can lock C until they have locked A first. Here is an example of two threads trying to take the same two locks in different order. it can only be used if you know about all locks needed ahead of taking any of the locks. However. Thread 2 and 3 must first wait until lock A is unlocked. it will backup. For instance. Then they must succeed in locking A. before they can attempt to lock B or C. wait for a random amount of time and then retry.locks.g. Lock ordering is a simple yet effective deadlock prevention mechanism. Lock Timeout Another deadlock prevention mechanism is to put a timeout on lock attempts meaning a thread trying to obtain a lock will only try for so long before giving up. 257 millis) before retrying. free all locks taken. . and thus let the application continue running without locking.. Then the likeliness of two threads waiting the same time before retrying (or close enough to cause problems) is a lot higher.Thread 2's lock attempt on A times out Thread 2 backs up and releases B as well Thread 2 waits randomly (e. Every time a thread takes a lock it is noted in a data structure (map. whenever a thread requests a lock this is also noted in this data structure. A problem with the lock timeout mechanism is that it is not possible to set a timeout for entering a synchronized block in Java. graph etc. 43 millis) before retrying. that just because a lock times out it does not necessarily mean that the threads had deadlocked. An issue to keep in mind is.util. It could also just mean that the thread holding the lock (causing the other thread to time out) takes a long time to complete its task. Additionally. Additionally. even if timing out and backing up. This may not occur with 2 threads each waiting between 0 and 500 millis before retrying. When Thread 2 finishes.g. Writing custom locks isn't difficult but it is outside the scope of this text. Deadlock Detection Deadlock detection is a heavier deadlock prevention mechanism aimed at cases in which lock ordering isn't possible. the thread can . and lock timeout isn't feasible. if enough threads compete for the same resources they still risk trying to take the threads at the same time again and again. Thread 1 will be able to take both locks too (unless Thread 2 or another thread takes the locks in between). In the above example Thread 2 will retry taking the locks about 200 millis before Thread 1 and will therefore likely succeed at taking both locks.) of threads and locks. You will have to create a custom lock class or use one of the Java 5 concurrency constructs in the java. Thread 1 will then wait already trying to take lock A. When a thread requests a lock but the request is denied.concurrency package. Later texts in the Java concurrency trails will cover custom locks. but with 10 or 20 threads the situation is different. Thread A may wait for Thread B. Thread B waits for Thread C. However. wait a random amount of time and then retry. requesting lock 7. and Thread D waits for Thread A. Thread B having taken lock 7. if a Thread A requests lock 7. C and D). In order for Thread A to detect a deadlock it must transitively examine all requested locks by Thread B. From Thread B's requested locks Thread A will get to Thread C. then Thread A can check if Thread B has requested any of the locks Thread A holds (if any). So what do the threads do if a deadlock is detected? One possible action is to release all locks. If Thread B has requested so. For instance. A data structure like this that can be used to detect deadlocks. B. if a lot of threads are competing for the same locks they may repeatedly end up in a deadlock even if they back up and . Of course a deadlock scenario may be a lot more complicated than two threads holding each others locks. backup. a deadlock has occurred (Thread A having taken lock 1. Thread C waits for Thread D.traverse the lock graph to check for deadlocks. from which it finds one of the locks Thread A itself is holding. and then to Thread D. Then it knows a deadlock has occurred. This is similar to the simpler lock timeout mechanism except threads only backup when a deadlock has actually occurred. requesting lock 1). Below is a graph of locks taken and requested by 4 threads (A. but lock 7 is held by Thread B. Not just because their lock requests timed out. that all threads are fairly granted a chance to execute. the same threads will always be given higher priority. Here is a list of the topics covered in this text. The solution to starvation is called "fairness" .Threads with high priority swallow all CPU time from threads with lower priority. If the priority assigned to the threads is fixed. it is called "starvation".Threads are blocked indefinately waiting to enter a synchronized block. The thread is "starved to death" because other threads are allowed the CPU time instead of it. . To avoid this you may assign the priority randomly whenever a deadlock is detected.Implementing Fairness in Java •Using Locks Instead of Synchronized Blocks •A Fair Lock •A Note on Performance Causes of Starvation in Java The following three common causes can lead to starvation of threads in Java: 1. 1.Causes of Starvation in Java •Threads with high priority swallow all CPU time from threads with lower priority •Threads are blocked indefinately waiting to enter a synchronized block •Threads waiting on an object (called wait() on it) remain waiting indefinately 2. A better option is to determine or assign a priority of the threads so that only one (or a few) thread backs up. Starvation and Fairness f a thread is not granted CPU time because other threads grab it all. The rest of the threads continue taking the locks they need as if no deadlock had occurred. because other threads are constantly allowed access before it. 2.wait. The higher the priority the more CPU time the thread is granted. Implementing Fairness in Java While it is not possible to implement 100% fairness in Java we can still implement our synchronization constructs to increase fairness between threads. This means that there is a theoretical risk that a thread remains blocked forever trying to enter the block. First lets study a simple synchronized code block: public class Synchronizer{ . You can set the priority of threads between 1 and 10. Exactly how this is interpreted depends on the operating system your application is running on. This problem is called "starvation". Threads are blocked indefinately waiting to enter a synchronized block Java's synchronized code blocks can be another cause of starvation. Threads with high priority swallow all CPU time from threads with lower priority You can set the thread priority of each thread individually. Threads waiting on an object (called wait() on it) remain waiting indefinately The notify() method makes no guarantee about what thread is awakened if multiple thread have called wait() on the object notify() is called on. because other threads are constantly granted access before it. Therefore there is a risk that a thread waiting on a certain object is never awakened because other waiting threads are always awakened instead of it. that a thread is "starved to death" by because other threads are allowed the CPU time instead of it.Threads waiting on an object (called wait() on it) remain waiting indefinately because other threads are constantly awakened instead of it.3. Java's synchronized code block makes no guarantee about the sequence in which threads waiting to enter the synchronized block are allowed to enter. It could be any of the threads waiting. For most applications you are better off leaving the priority unchanged. do a lot of work which takes a long time this. Using Locks Instead of Synchronized Blocks To increase the fairness of waiting threads first we will change the code block to be guarded by a lock rather than a synchronized block: public class Synchronizer{ Lock lock = new Lock(). some of them will be blocked until the first thread granted access has left the method.public synchronized void doSynchronized(){ //do a lot of work which takes a long time } } If more than one thread call the doSynchronized() method. If more than one thread are blocked waiting for access there is no guarantee about which thread is granted access next. //critical section.lock. } .unlock().lock().lock. public void doSynchronized() throws InterruptedException{ this. lockingThread = null. } isLocked = true.unlock() calls.currentThread()){ throw new IllegalMonitorStateException( .} Notice how the doSynchronized() method is no longer declared synchronized.currentThread().lockingThread != Thread. Instead the critical section is guarded by the lock. public synchronized void lock() throws InterruptedException{ while(isLocked){ wait(). lockingThread = Thread. } public synchronized void unlock(){ if(this.lock() and lock. A simple implementation of the Lock class could look like this: public class Lock{ private boolean isLocked private Thread = false. This means that the majority of the time waited to be able to lock the lock and enter the critical section is spent waiting in the wait() call inside the lock() method. As stated earlier synchronized blocks makes no guarantees about what thread is being granted access if more than one thread is waiting to enter. lockingThread = null."Calling thread has not locked this lock"). Let us further assume that this code takes long time to execute compared to entering the lock() method and calling wait() because the lock is locked. The current version of the Lock class calls its own wait() method. notify(). } } If you look at the Synchronizer class above and look into this Lock implementation you will notice that threads are now blocked trying to access the lock() method. that the code in between these two calls take a "long" time to execute. The result is that multiple threads can end up having called wait() inside lock(). Nor does wait() make any guarantees about what thread is awakened when notify() is called. the threads are blocked in the wait() call inside the while(isLocked) loop in the lock() method. Second. the current version of the Lock class makes no different guarantees with respect to fairness than synchronized version of doSynchronized(). the Lock class can decide which of these objects to call notify() . not being blocked trying to enter the lock() method. so that only one thread has called wait() on each object. if the lock is locked. So. If instead each thread calls wait() on a separate object. Remember that a thread calling wait() releases the synchronization lock on the Lock instance. If you look back at the doSynchronized() method you will notice that the comment between lock() and unlock() states. so threads waiting to enter lock() can now do so. But we can change that. if more than one thread calls lock() simultanously. } isLocked = false. All other threads are parked waiting until they reach the top of the queue. What is important is. that every thread calling lock() is now queued. isLockedForThisThread = true.add(queueObject). private List<QueueObject> waitingThreads = new ArrayList<QueueObject>(). Exactly how I arrived at this design beginning from the previous Lock class is a longer story involving several incremental design steps. synchronized(this){ waitingThreads. public class FairLock { private boolean private Thread isLocked lockingThread = false. each fixing the problem of the previous step: Nested Monitor Lockout. public void lock() throws InterruptedException{ QueueObject queueObject boolean = new QueueObject(). and Missed Signals. You will notice that the implementation has changed a bit with respect to synchronization and wait() / notify() compared to the Lock class shown earlier. thereby effectively selecting exactly what thread to awaken. . A Fair Lock Below is shown the previous Lock class turned into a fair lock called FairLock. That discussion is left out of this text to keep the text short. if it is unlocked. and only the first thread in the queue is allowed to lock the FairLock instance. but each of the steps are discussed in the appropriate texts on the topic ( see the links above).on. = null. Slipped Conditions. doWait(). lockingThread = Thread. return.currentThread(). waitingThreads. } } try{ queueObject. } } .} while(isLockedForThisThread){ synchronized(this){ isLockedForThisThread = isLocked || waitingThreads.remove(queueObject). } throw e. }catch(InterruptedException e){ synchronized(this) { waitingThreads.remove(queueObject).get(0) != queueObject. if(!isLockedForThisThread){ isLocked = true. size() > 0){ waitingThreads.doNotify(). if(waitingThreads. public synchronized void doWait() throws InterruptedException { while(!isNotified){ .currentThread()){ throw new IllegalMonitorStateException( "Calling thread has not locked this lock").get(0). lockingThread = null.lockingThread != Thread. } } } public class QueueObject { private boolean isNotified = false. } isLocked = false.} public synchronized void unlock(){ if(this. } } First you might notice that the lock() method is no longer declared synchronized. this. to awaken the thread waiting on that object.isNotified = true. } this. This part is what governs the fairness of the FairLock.wait(). } public boolean equals(Object o) { return this == o. Instead only the blocks necessary to synchronize are nested inside synchronizedblocks. rather than all waiting threads. .isNotified = false. FairLock creates a new instance of QueueObject and enqueue it for each thread calling lock(). Notice how the state of the lock is still tested and set within the same synchronized block to avoid slipped conditions. The thread calling unlock() will take the top QueueObject in the queue and call doNotify() on it. } public synchronized void doNotify() { this.this. This way only one waiting thread is awakened at a time.notify(). doWait() call is placed outside the synchronized(this) block to avoid nested monitor lockout. Finally. It does of course also depend on how often this code is called. and we need to dequeue it. by another thread which calls unlock() and therebyqueueObject. the less significant the added overhead of the synchronizer is.catchblock. A nested monitor lockout occurs like this: Thread 1 synchronizes on A Thread 1 synchronizes on B (while synchronized on A) Thread 1 decides to wait for a signal from another thread before continuing Thread 1 calls B. A Note on Performance If you compare the Lock and FairLock classes you will notice that there is somewhat more going on inside the lock() and unlock() in the FairLock class. notice how the queueObject. The queueObject. Thread 2 needs to lock both A and B (in that sequence) . The longer this takes to execute.doWait(). This is done to avoid missed signals caused by a thread being preempted just before callingqueueObject.doWait() is called inside a try . This extra code will cause the FairLock to be a sligtly slower synchronization mechanism thanLock. Nested Monitor Lockout Nested monitor lockout is a problem similar to deadlock.Also notice that the QueueObject is really a semaphore.wait() thereby releasing the lock on B. How much impact this will have on your application depends on how long time the code in the critical section guarded by the FairLock takes to execute. The doWait() anddoNotify() methods store the signal internally in the QueueObject. so another thread can actually call unlock() when no thread is executing inside the synchronized(this)block in lock() method. but not A.doNotify(). In case an InterruptedException is thrown the thread leaves the lock() method. to send Thread 1 the signal. that must be released to make it possible for Thread 2 to send the signal to Thread 1. This may sound like a pretty theoretical situation. but look at the naive Lockimplemenation below: //lock implementation with nested monitor lockout problem public class Lock{ protected MonitorObject monitorObject = new MonitorObject(). Thread 2 remain blocked indefinately waiting for Thread1 to release the lock on A Thread 1 remain blocked indefinately waiting for the signal from Thread 2. since Thread 1 still holds the lock on A. thereby never releasing the lock on A. Thread 2 cannot lock A. public void lock() throws InterruptedException{ synchronized(this){ while(isLocked){ . etc. protected boolean isLocked = false. If isLocked is true however.monitorObject){ this. } } isLocked = true. } } } } Notice how the lock() method first synchronizes on "this".wait().notify(). the thread callinglock() is parked waiting in the monitorObject.wait(). .monitorObject){ this.monitorObject.wait() call.synchronized(this.monitorObject.isLocked = false. synchronized(this. } } public void unlock(){ synchronized(this){ this. If isLocked is false there is no problem. then synchronizes on themonitorObject member. The thread does not call monitorObject. For instance. but rather on the This is probably true.wait() only releases the synchronization monitor on the monitorObject member. private List<QueueObject> waitingThreads = . This result is that any thread calling either lock() or unlock() will become blocked indefinately. But. if you were to implement fairness in a Lock. as it happens in unlock(). Look at this naive implementation of a fair lock: //Fair Lock implementation with nested monitor lockout problem public class FairLock { private boolean private Thread isLocked lockingThread = false. A More Realistic Example You may claim that you would never implement a lock like the one shown earlier.The problem with this is. and a monitorObject. and not the synchronization monitor associated with "this". the thread waiting in lock() needs an unlock() call to execute successfully for it to exit lock() and the synchronized blocks inside it. But there are situations in which designs like the one above may arise. the thread that was just parked waiting is still holding the synchronization lock on "this". = null. no thread can actually execute unlock() until the thread waiting in lock() leaves the outer synchronized block. But the thread waiting in the lock() method will not leave that block until the isLocked is set to false. That you would not call wait() and notify() on an internal monitor object. In other words. so that you can notify the threads one at a time. When the thread that locked the Lock in the first place tries to unlock it by callingunlock() it will be blocked trying to enter the synchronized(this) block in theunlock() method. It will remain blocked until the thread waiting in lock() leaves the synchronized(this) block. When doing so you want each thread to call wait() on each their own queue object. Put shortly. that the call to monitorObject. This is called a nested monitor lockout.notify()is executed. remove(queueObject). } } } waitingThreads. }catch(InterruptedException e){ waitingThreads.add(queueObject). throw e. synchronized(this){ waitingThreads.get(0) != queueObject){ synchronized(queueObject){ try{ queueObject. while(isLocked || waitingThreads. . public void lock() throws InterruptedException{ QueueObject queueObject = new QueueObject().remove(queueObject).new ArrayList<QueueObject>().wait(). } } } } . } } public synchronized void unlock(){ if(this.isLocked = true. lockingThread = null.notify().size() > 0){ QueueObject queueObject = waitingThread. synchronized(queueObject){ queueObject. lockingThread = Thread.currentThread()){ throw new IllegalMonitorStateException( "Calling thread has not locked this lock").get(0).currentThread().lockingThread != Thread. } isLocked = false. if(waitingThreads. wait()it releases the lock on theQueueObject instance. one thread is waiting for a signal.wait(). Thread 2 has locked B. As explained in the text on Deadlock a deadlock occurs when two threads obtain locks in different order. and nested inside that. Notice too. Deadlock The result of nested monitor lockout and deadlock are pretty much the same: The threads involved end up blocked forever waiting for each other. then releases B and waits for a signal from Thread 2. waiting for the waiting thread to release the lock on "this". but notice how the lock() method calls queueObject.public class QueueObject {} At first glance this implementation may look fine. that the unlock() method is declared synchronized which equals asynchronized(this) block. but not the lock associated with "this". When a thread calls queueObject. And so. from inside two synchronized blocks. a nested monitor lockout occurs exactly by two threads taking the locks in the same order. So. waits for B. two threads are waiting for each other to release locks. a block synchronized on the queueObject local variable. The two situations are not equal though. the FairLock implementation from above could lead to nested monitor lockout. since this only happens if a thread succeeds in sending a signal to the waiting thread. Nested Monitor Lockout vs. and now waits for A. Thread 1 locks A. Thread 2 needs both A and B to send Thread 1 the signal. A better implementation of a fair lock is described in the text Starvation and Fairness. However. and another for a lock to be released. One synchronized on "this". As explained in the text onDeadlock Prevention deadlocks can be avoided by always locking the locks in the same order (Lock Ordering). But this will never happen. The difference is summed up here: In deadlock. Thread 1 locks A and B. . All threads calling unlock() will remain blocked indefinately. that if a thread is waiting inside lock() the monitor object associated with "this" will be locked by the waiting thread. This means. and this can only be sent by executing the unlock() method. Thread 2 needs the lock A to send the signal to Thread 1. the condition has been changed by another thread so that it is errornous for the first thread to act. Slipped Conditions Slipped conditions means. that from the time a thread has checked a certain condition until it acts upon it. } catch(InterruptedException e){ //do nothing.In nested monitor lockout. keep waiting . Here is a simple example: public class Lock { private boolean isLocked = true. and waits for a signal from Thread 2. Thread 1 is holding a lock A. public void lock(){ synchronized(this){ while(isLocked){ try{ this.wait(). notify(). } } Notice how the lock() method contains two synchronized blocks. Imagine that isLocked is false. to lock theLock instance for other threads. The first block waits until isLocked is false. } } public synchronized void unlock(){ isLocked = false. If the second thread is now allowed to execute. this. this thread too will see isLocked as false. Now both threads have read the condition as false. The second block sets isLocked to true. If the first thread entering the first synchronized block is preempted right after the first synchronized block. and two threads call lock() at the same time.} } } synchronized(this){ isLocked = true. this thread will have checked isLocked and noted it to be false. and thus enter the first synchronized block. Then both threads will enter the second . In other words.synchronized block.up into the first synchronized block. } catch(InterruptedException e){ //do nothing. public void lock(){ synchronized(this){ while(isLocked){ try{ this. the condition has slipped from the time the condition was checked until the threads change it for subsequent threads.wait(). and continue. setisLocked to true. then exit the synchronized block. To avoid slipped conditions the testing and setting of the conditions must be done atomically by the thread doing it. meaning that no other thread can check the condition in between the testing and setting of the condition by the first thread. right after the while loop. This situation is an example of slipped conditions. Both threads test the condition. keep waiting } . The solution in the example above is simple. before any of the two first threads change the conditions for subsequent threads. thereby allowing other threads to test the condition. Here is how it looks: public class Lock { private boolean isLocked = true. Just move the line isLocked = true. A more realistic example would be during the implementation of a fair lock.notify(). and thus claim slipped conditions to be a rather theoretical problem. } } public synchronized void unlock(){ isLocked = false. } } Now the testing and setting of the isLocked condition is done atomically from inside the same synchronized block.} isLocked = true. If we look at the naive implementation from the text Nested Monitor Lockout. First I'll show the example from the nested monitor lockout text: . A More Realistic Example You may rightfully argue that you would never implement a Lock like the first implementation shown in this text. this. as discussed in the text on Starvation and Fairness. and try to remove the nested monitor lock problem it. it is easy to arrive at an implementation that suffers from slipped conditions. But the first example was kept rather simple to better convey the notion of slipped conditions. public void lock() throws InterruptedException{ QueueObject queueObject = new QueueObject().//Fair Lock implementation with nested monitor lockout problem public class FairLock { private boolean private Thread isLocked lockingThread = false. }catch(InterruptedException e){ . synchronized(this){ waitingThreads. private List<QueueObject> waitingThreads = new ArrayList<QueueObject>(). = null.get(0) != queueObject){ synchronized(queueObject){ try{ queueObject.wait().add(queueObject). while(isLocked || waitingThreads. } } public synchronized void unlock(){ if(this.currentThread()){ throw new IllegalMonitorStateException( "Calling thread has not locked this lock"). } isLocked = false. .remove(queueObject).size() > 0){ QueueObject queueObject = waitingThread. lockingThread = null. lockingThread = Thread.lockingThread != Thread. throw e.waitingThreads. } } } waitingThreads.currentThread(). isLocked = true.remove(queueObject).get(0). if(waitingThreads. Here is how that could look: //Fair Lock implementation with slipped conditions problem public class FairLock { private boolean private Thread isLocked lockingThread = false. resulting in the nested monitor lockout problem.synchronized(queueObject){ queueObject.wait() call is nested inside the synchronized(this) block. To avoid this problem the synchronized(queueObject) block must be moved outside the synchronized(this) block. public void lock() throws InterruptedException{ . private List<QueueObject> waitingThreads = new ArrayList<QueueObject>().notify(). } } } } public class QueueObject {} Notice how the synchronized(queueObject) with its queueObject. = null. synchronized(this){ waitingThreads. }catch(InterruptedException e){ waitingThreads. throw e.wait().get(0) != queueObject.remove(queueObject). . } boolean mustWait = true.QueueObject queueObject = new QueueObject(). while(mustWait){ synchronized(this){ mustWait = isLocked || waitingThreads. } synchronized(queueObject){ if(mustWait){ try{ queueObject.add(queueObject). currentThread(). so the thread exits thesynchronized(queueObject) block right away. First thread 1 will check the isLocked conditition and see it . Notice how the lock() method now contains 3 synchronized blocks. Imagine what will happen if two threads call lock() at the same time when the lock is unlocked.remove(queueObject). The second synchronized(queueObject) block checks if the thread is to wait or not.get(0) != queueObject. Already at this time another thread may have unlocked the lock. since it is the only method I have changed. isLocked = true. The third synchronized(this) block is only executed if mustWait = false. } } } Note: Only the lock() method is shown. but lets forget that for the time being. Let's assume that the lock was unlocked.} } } } synchronized(this){ waitingThreads. and leaves the lock() method. This sets the condition isLocked back to true etc. lockingThread = Thread. The first synchronized(this) block checks the condition by setting mustWait = isLocked || waitingThreads. Here is how it looks: //Fair Lock implementation without nested monitor lockout problem. Then thread 2 will do the same thing. the content of the last synchronized(this) block must be moved up into the first block. public class FairLock { private boolean private Thread isLocked lockingThread = false. = null. //but with missed signals problem. private List<QueueObject> waitingThreads = new ArrayList<QueueObject>(). Removing the Slipped Conditions Problem To remove the slipped conditions problem from the example above.add(queueObject). public void lock() throws InterruptedException{ QueueObject queueObject = new QueueObject(). Then neither of them will wait. . The code will naturally have to be changed a little bit too. to adapt to this move. synchronized(this){ waitingThreads. This is a prime example of slipped conditions. and both will set the state isLocked to true.false. . if(!mustWait){ waitingThreads.get(0) != queueObject.wait(). lockingThread = Thread.remove(queueObject). isLocked = true. while(mustWait){ synchronized(this){ mustWait = isLocked || waitingThreads.} boolean mustWait = true. } } synchronized(queueObject){ if(mustWait){ try{ queueObject.currentThread(). return. remove(queueObject). After the first synchronized(this) block mustWait is true. in thewhile(mustWait) clause. Then imagine that the thread calling lock() is preempted.notify() passes into oblivion. and the thread that locked the lock calls unlock(). you will notice that it calls queueObject.wait(). If you look at the unlock() implementation shown earlier. throw e. But. } } } } } } Notice how the local variable mustWait is tested and set within the same synchronized code block now.notify(). then there is no reason to enter the synchronized(queueObject) block and execute theif(mustWait) clause. When the thread calling lock() right after calls queueObject. It is just a small optimization. A thread that evaluates mustWait to false will atomically also set the internal conditions (isLocked) so that any other thread checking the condition will evaluate it to true. The observant reader will notice that the above implementation of a fair lock still suffers from a missed signal problem.wait() it will remain blocked until some other thread . that even if the mustWait local variable is also checked outside the synchronized(this) code block. The return. the call toqueueObject. the value of the mustWait variable is never changed outside the synchronized(this).}catch(InterruptedException e){ waitingThreads. statement in the synchronized(this) block is not necessary. If the thread must not wait (mustWait == false). The signal is missed. Also notice. Imagine that the FairLock instance is locked when a thread calls lock(). since the thread waiting in lock() has not yet called queueObject. public int inc(){ . and it can still be useful to know the theory behind their implementation.Lock Fairness 4. From Java 5 the package java.locks contains several lock implementations. Locks in Java A lock is a thread synchronization mechanism like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. which may never happen. even if doNotify() is called before doWait().calls unlock(). The missed signals problems is the reason that the FairLock implementation shown in the text Starvation and Fairness has turned the QueueObject class into a semaphore with two methods: doWait() and doNotify().Calling unlock() From a finally-clause A Simple Lock Let's start out by looking at a synchronized block of Java code: public class Counter{ private int count = 0.A Simple Lock 2. But you will still need to know how to use them. Locks (and other more advanced synchronization mechanisms) are created using synchronized blocks. so you may not have to implement your own locks. For more details.Lock Reentrance 3.Lock interface.util. That way the signal is not missed. Here is a list of the topics covered in this text: 1.locks.concurrent. so it is not like we can get totally rid of the synchronized keyword. These methods store and react the signal internally in the QueueObject.util. see my tutorial on thejava.concurrent. . int newCount = ++count. return newCount. lock. } } } Notice the synchronized(this) block in the inc() method. This block makes sure that only one thread can execute the return ++count at a time. The code in the synchronized block could have been more advanced. but the simple + +count suffices to get the point across.unlock(). using a Lock instead of a synchronized block: public class Counter{ private Lock lock = new Lock().synchronized(this){ return ++count.lock(). The Counter class could have been written like this instead. public int inc(){ lock. private int count = 0. . public synchronized void lock() throws InterruptedException{ while(isLocked){ wait(). } isLocked = true. } public synchronized void unlock(){ isLocked = false. Here is a simple Lock implementation: public class Lock{ private boolean isLocked = false.} } The lock() method locks the Lock instance so that all threads calling lock() are blocked until unlock() is executed. notify(). the thread calling lock() is parked waiting in thewait() call. If isLocked is false. and notifies (awakens) one of the threads waiting in thewait() call in the lock() method. the thread exits thewhile(isLocked) loop. that if a Java thread enters a synchronized block of code. This means. the thread calls unlock(). Executing unlock() setsisLocked back to false. the thread can enter other Java code blocks synchronized on the same monitor object. and sets isLocked back to true. if any. } public synchronized inner(){ . Here is an example: public class Reentrant{ public synchronized outer(){ inner(). When the thread is done with the code in the critical section (the code betweenlock() and unlock()). In case the thread should return unexpectedly from the wait() call without having received a notify() call (AKA a Spurious Wakeup) the thread re-checks theisLocked condition to see if it is safe to proceed or not. Spin locks and the methods wait() and notify() are covered in more detail in the text Thread Signaling. to lock the Lock instance for other threads calling lock(). rather than just assume that being awakened means it is safe to proceed. Lock Reentrance Synchronized blocks in Java are reentrant. and thereby take the lock on the monitor object the block is synchronized on. While isLocked is true.} } Notice the while(isLocked) loop. which is also called a "spin lock". which in Java is equivalent to a synchronized(this) block. lock. If a thread calls outer() there is no problem calling inner() from inside outer(). } public synchronized inner(){ .lock(). inner(). public outer(){ lock.unlock().lock()in the inner() method. since both methods (or blocks) are synchronized on the same monitor object ("this"). it has access to all blocks synchronized on the same monitor object. This is called reentrance. If a thread already holds the lock on a monitor object. If we rewrite the Reentrantclass like below. The lock implementation shown earlier is not reentrant. public class Reentrant2{ Lock lock = new Lock().//do something } } Notice how both outer() and inner() are declared synchronized. The thread can reenter any block of code for which it already holds the lock. the thread calling outer() will be blocked inside the lock. Then it will call inner(). Inside the inner() method the thread will again try to lock the Lock instance. The reason the thread will be blocked the second time it calls lock() without having called unlock() in between. //do something lock.lock. } isLocked = true. since the Lock instance was locked already in the outer() method. This will fail (meaning the thread will be blocked). is apparent when we look at the lock()implementation: public class Lock{ boolean isLocked = false. } } A thread calling outer() will first lock the Lock instance.unlock().lock(). public synchronized void lock() throws InterruptedException{ while(isLocked){ wait(). . . public synchronized void lock() throws InterruptedException{ Thread callingThread = Thread. Currently the condition is that isLockedmust be false for this to be allowed. while(isLocked && lockedBy != callingThread){ wait(). Thread int lockedBy = null.} .. To make the Lock class reentrant we need to make a small change: public class Lock{ boolean isLocked = false. } . } It is the condition inside the while loop (spin lock) that determines if a thread is allowed to exit the lock() method or not.currentThread(). lockedCount = 0. regardless of what thread locked it. lockedCount++. } } } . if(lockedCount == 0){ isLocked = false..isLocked = true. lockedBy = callingThread.lockedBy){ lockedCount--. notify(). } public synchronized void unlock(){ if(Thread. } ..curentThread() == this. Notice how the while loop (spin lock) now also takes the thread that locked the Lockinstance into consideration. Therefore. Starvation and fairness are discussed in more detail in the textStarvation and Fairness. there is a risk that one or more of the threads are never granted access . Calling unlock() From a finally-clause When guarding a critical section with a Lock. even if the lock has been locked multiple times. and the thread calling lock() will be allowed to exit the method. Otherwise. they do not guarantee fairness. try{ //do critical section code. This is called starvation. Since theLock implementations shown in this text uses synchronized blocks internally. it is important to call the unlock() method from inside a finally-clause. To avoid this a Lock should be fair. Additionally. which may throw exception } finally { . and the critical section may throw exceptions. Doing so makes sure that the Lock is unlocked so other threads can lock it.that access is always granted to other threads. has executed the same amount of unlock() calls as lock() calls.lock(). a single call to unlock() will unlock the lock. Lock Fairness Java's synchronized blocks makes no guarantees about the sequence in which threads trying to enter them are granted access. we need to count the number of times the lock has been locked by the same thread. Here is an example: lock. If either the lock is unlocked (isLocked = false) or the calling thread is the thread that locked the Lock instance. if many threads are constantly competing for access to the same synchronized block. the while loop will not execute. We don't want the lock to be unloced until the thread that locked it. The Lock class is now reentrant. Read / Write Lock Java Implementation 2. so multiple threads that want to read the resource are granted access at the same time.concurrentpackage.Write to Read Reentrance 7.lock. Even so. it may still be useful to know the theory behind their implementation. but writing it is not done as much as reading it is. you will need a read / write lock. } This little construct makes sure that the Lock is unlocked in case an exception is thrown from the code in the critical section.Calling unlock() from a finally-clause Read / Write Lock Java Implementation First let's summarize the conditions for getting read and write access to the resource: . Java 5 comes with read / write lock implementations in the java. the Lockwould remain locked forever.util. Imagine you have an application that reads and writes some resource. But. causing all threads calling lock() on that Lockinstance to halt indefinately.Fully Reentrant Java Implementation 8. To solve this problem of allowing multiple readers but only one writer.Read to Write Reentrance 6. If unlock() was not called from inside afinally-clause. Here is a list of the topics covered in this text: 1. Two threads reading the same resource does not cause problems for each other. Read / Write Locks in Java A read / write lock is more sophisticated lock than the Lock implementations shown in the text Locks in Java.Read Reentrance 4.Write Reentrance 5. if a single thread wants to write to the resource. overlapping.unlock().Read / Write Lock Reentrance 3. and an exception was thrown from the critical section. no other reads nor writes must be in progress at the same time. If new threads were constantly granted read access the thread waiting for write access would remain blocked indefinately. if reads are what happens most often. = 0. and no threads have requested write access to the resource. public synchronized void lockRead() throws InterruptedException{ while(writers > 0 || writeRequests > 0){ wait(). and we did not up-prioritize writes. With these simple rules in mind we can implement a ReadWriteLock as shown below: public class ReadWriteLock{ private int readers private int writers = 0. Therefore a thread can only be granted read access if no thread has currently locked the ReadWriteLock for writing. Threads requesting write access would be blocked until all readers had unlocked the ReadWriteLock. and no threads have requested write access. A thread that wants write access to the resource can be granted so when no threads are reading nor writing to the resource. By up-prioritizing write-access requests we assume that write requests are more important than read-requests. private int writeRequests = 0.Read Access Write Access If no threads are writing. starvation could occur. If a thread wants to read the resource. } . it is okay as long as no threads are writing to it. Besides. or requested it locked for writing. It doesn't matter how many threads have requested write access or in what sequence. If no threads are reading or writing. unless you want to guarantee fairness between threads requesting write access. resulting in starvation. } writeRequests--. notifyAll(). } public synchronized void lockWrite() throws InterruptedException{ writeRequests++. .readers++. writers++. } public synchronized void unlockWrite() throws InterruptedException{ writers--. } public synchronized void unlockRead(){ readers--. while(readers > 0 || writers > 0){ wait(). By callingnoftifyAll() all waiting threads are awakened and check if they can get the desired access.not one by one. The rules for read access are implemented in the lockRead() method. It is worth noting that both unlockRead() and unlockWrite() calls notifyAll()rather than notify(). and unlockWrite() is called. it would be put back to waiting because there are threads waiting for write access. consider this case: 1. How many threads have requested write access doesn't matter.Thread 2 requests write access but is blocked because there is one . One lock and unlock method for read access and one lock and unlock for write access. However. all threads waiting for read access are granted read access at once . Calling notifyAll() also has another advantage.Thread 1 gets read access. No threads gain neither read nor write access. it will block because there is already one writer itself. or one or more threads have requested write access. imagine the following situation: Inside the ReadWriteLock there are threads waiting for read access.notifyAll(). none of the threads awaiting write access are awakened. } } The ReadWriteLock has two lock methods and two unlock methods. All threads get read access unless there is a thread with write access. The rules for write access are implemented in the lockWrite() method. If a thread awakened by notify() was a read access thread. A thread that wants write access starts out by requesting write access (writeRequests++). To explain why that is. If a thread that has write access requests it again. If multiple threads are waiting for read access and none for write access. 2. Furthermore. and no threads with write access to the resource. so nothing more happens. A thread can get write access if there are no threads with read access to the resource. and threads waiting for write access. Read / Write Lock Reentrance The ReadWriteLock class shown earlier is not reentrant. Then it will check if it can actually get write access. Thread 1 re-requests read access (re-enters the lock). To determine if a thread has read access already a reference to each thread granted read access is kept in a Map along with how many times it has acquired read lock. Here is how the lockRead() and unlockRead()methods looks after that change: public class ReadWriteLock{ private Map<Thread. private int writers private int writeRequests = 0. but is blocked because there is a write request In this situation the previous ReadWriteLock would lock up .reader. 3. Read Reentrance To make the ReadWriteLock reentrant for readers we will first establish the rules for read reentrance: •A thread is granted read reentrance if it can get read access (no writers or write requests). Reentrance for readers and writers will be dealt with separately. Integer> readingThreads = new HashMap<Thread.a situation similar to deadlock. or if it already has read access (regardless of write requests). When determing if read access can be granted this Map will be checked for a reference to the calling thread. = 0. . No threads requesting neither read nor write access would be granted so. To make the ReadWriteLock reentrant it is necessary to make a few changes. Integer>(). int accessCount = getAccessCount(callingThread). (getAccessCount(callingThread) + 1)).currentThread().public synchronized void lockRead() throws InterruptedException{ Thread callingThread = Thread.currentThread(). } else { readingThreads. } readingThreads.remove(callingThread).put(callingThread. while(! canGrantReadAccess(callingThread)){ wait(). if(accessCount == 1){ readingThreads. } . } notifyAll(). (accessCount -1)). } public synchronized void unlockRead(){ Thread callingThread = Thread.put(callingThread. private boolean canGrantReadAccess(Thread callingThread){ if(writers > 0) return false. } private boolean isReader(Thread callingThread){ return readingThreads. Additionally. if(isReader(callingThread) return true.get(callingThread). . } return false. if(accessCount == null) return 0. if the calling thread already has read access this takes precedence over any writeRequests.get(callingThread) != null. private int getReadAccessCount(Thread callingThread){ Integer accessCount = readingThreads.intValue(). } } As you can see read reentrance is only granted if no threads are currently writing to the resource. if(writeRequests > 0) return true. return accessCount. private Thread writingThread = null. Here is how the lockWrite() and unlockWrite() methods look after that change: public class ReadWriteLock{ private Map<Thread. Thread callingThread = Thread. public synchronized void lockWrite() throws InterruptedException{ writeRequests++.Write Reentrance Write reentrance is granted only if the thread has already write access. Integer>(). Integer> readingThreads = new HashMap<Thread. = 0.currentThread(). . private int writeAccesses private int writeRequests = 0. while(! canGrantWriteAccess(callingThread)){ wait(). } writeRequests--. } private boolean canGrantWriteAccess(Thread callingThread){ if(hasReaders()) if(writingThread == null) return false.writeAccesses++. return true. if(!isWriter(callingThread)) return false. } notifyAll(). } public synchronized void unlockWrite() throws InterruptedException{ writeAccesses--. writingThread = callingThread. } private boolean hasReaders(){ . if(writeAccesses == 0){ writingThread = null. return true. return readingThreads. To achieve this thewriteLock() method should be changed a bit. } } Notice how the thread currently holding the write lock is now taken into account when determining if the calling thread can get write access. = 0.size() > 0. Integer>(). Integer> readingThreads = new HashMap<Thread. } private boolean isWriter(Thread callingThread){ return writingThread == callingThread. . Here is what it would look like: public class ReadWriteLock{ private Map<Thread. Read to Write Reentrance Sometimes it is necessary for a thread that have read access to also obtain write access. private int writeAccesses private int writeRequests = 0. For this to be allowed the thread must be the only reader. } . } writeRequests--. writeAccesses++. } public synchronized void unlockWrite() throws InterruptedException{ writeAccesses--. while(! canGrantWriteAccess(callingThread)){ wait(). Thread callingThread = Thread.currentThread(). public synchronized void lockWrite() throws InterruptedException{ writeRequests++. if(writeAccesses == 0){ writingThread = null. writingThread = callingThread.private Thread writingThread = null. } notifyAll(). private boolean canGrantWriteAccess(Thread callingThread){ if(isOnlyReader(callingThread)) if(hasReaders()) if(writingThread == null) if(!isWriter(callingThread)) return true. private boolean hasReaders(){ return readingThreads. } private boolean isOnlyReader(Thread thread){ return readers == 1 && readingThreads. return false. return false. return true. } return true.get(callingThread) != null. } private boolean isWriter(Thread callingThread){ return writingThread == callingThread.size() > 0. } . A writer should always be granted read access if requested.} Now the ReadWriteLock class is read-to-write access reentrant. so it is not dangerous. } return false. return false. If a thread has write access no other threads can have read nor write access. } . return true. if(writingThread != null) if(isReader(callingThread) if(writeRequests > 0) return true. Write to Read Reentrance Sometimes a thread that has write access needs read access too. Here is how thecanGrantReadAccess() method will look with that change: public class ReadWriteLock{ private boolean canGrantReadAccess(Thread callingThread){ if(isWriter(callingThread)) return true. put(callingThread. I have made a few refactorings to the access conditions to make them easier to read. } readingThreads. Integer>().Fully Reentrant ReadWriteLock Below is the fully reentran ReadWriteLock implementation. and thereby easier to convince yourself that they are correct. . while(! canGrantReadAccess(callingThread)){ wait(). private int writeAccesses private int writeRequests = 0. public synchronized void lockRead() throws InterruptedException{ Thread callingThread = Thread. public class ReadWriteLock{ private Map<Thread.currentThread(). = 0. private Thread writingThread = null. Integer> readingThreads = new HashMap<Thread. if(!isReader(callingThread)){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold a read lock on this ReadWriteLock"). if( hasWriter() ) return false. if( isReader(callingThread) ) return true. } private boolean canGrantReadAccess(Thread callingThread){ if( isWriter(callingThread) ) return true. if(accessCount == 1){ readingThreads.currentThread().remove(callingThread). if( hasWriteRequests() return true. } .(getReadAccessCount(callingThread) + 1)). } int accessCount = getReadAccessCount(callingThread). public synchronized void unlockRead(){ Thread callingThread = Thread. } ) return false. writeAccesses++. } public synchronized void unlockWrite() throws InterruptedException{ if(!isWriter(Thread. } . writingThread = callingThread. Thread callingThread = Thread.else { readingThreads. } public synchronized void lockWrite() throws InterruptedException{ writeRequests++. } notifyAll().currentThread()){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold the write lock on this ReadWriteLock"). while(! canGrantWriteAccess(callingThread)){ wait(). } writeRequests--. (accessCount -1)).currentThread().put(callingThread. if(accessCount == null) return 0. return accessCount. . if(writeAccesses == 0){ writingThread = null. } return true. } notifyAll().intValue(). private int getReadAccessCount(Thread callingThread){ Integer accessCount = readingThreads. return false.writeAccesses--. } private boolean canGrantWriteAccess(Thread callingThread){ if(isOnlyReader(callingThread)) if(hasReaders()) if(writingThread == null) if(!isWriter(callingThread)) return true.get(callingThread). return true. return false. } private boolean isOnlyReader(Thread callingThread){ return readingThreads.} private boolean hasReaders(){ return readingThreads.get(callingThread) != null. } private boolean hasWriter(){ return writingThread != null.get(callingThread) != null. } . } private boolean isReader(Thread callingThread){ return readingThreads.size() > 0.size() == 1 && readingThreads. private boolean isWriter(Thread callingThread){ return writingThread == callingThread; } private boolean hasWriteRequests(){ return this.writeRequests > 0; } } Calling unlock() From a finally-clause When guarding a critical section with a ReadWriteLock, and the critical section may throw exceptions, it is important to call the readUnlock() and writeUnlock()methods from inside a finally-clause. Doing so makes sure that theReadWriteLock is unlocked so other threads can lock it. Here is an example: lock.lockWrite(); try{ //do critical section code, which may throw exception } finally { lock.unlockWrite(); } This little construct makes sure that the ReadWriteLock is unlocked in case an exception is thrown from the code in the critical section. If unlockWrite() was not called from inside a finally-clause, and an exception was thrown from the critical section, the ReadWriteLock would remain write locked forever, causing all threads calling lockRead() or lockWrite() on that ReadWriteLock instance to halt indefinately. The only thing that could unlock the ReadWriteLockagain would be if the ReadWriteLock is reentrant, and the thread that had it locked when the exception was thrown, later succeeds in locking it, executing the critical section and callingunlockWrite() again afterwards. That would unlock the ReadWriteLock again. But why wait for that to happen, if it happens? Calling unlockWrite() from a finally-clause is a much more robust solution. Reentrance Lockout Reentrance lockout is a situation similar to deadlock and nested monitor lockout.; util. Whether or not your code is easier to implement with or without lock reentrance must be determined case by case. or to guard a critical section like you would with a lock. but this may not necessary be a problem in your case.util.Use reentrant locks Which of these options suit your project best depends on your concrete situation. A reentrance lockout has occurred. You can read more about it in the java.Using Semaphores as Locks Simple Semaphore Here is a simple Semaphore implementation: . } } If a thread calls lock() twice without calling unlock() in between.Simple Semaphore 2. it can be useful to know the theory behind their implementation and use. Still.concurrent.notify(). Here is a list of the topics covered in this text: 1.Bounded Semaphore 5. To avoid reentrance lockouts you have two options: 1. Java 5 comes with a built-in Semaphore so you don't have to implement your own.Avoid writing code that reenters locks 2. the second call tolock() will block. and they are harder to implement. Reentrant locks often don't perform as well as non-reentrant locks.util. in myjava.Semaphore text. Java 5 comes with semaphore implementations in thejava.Counting Semaphore 4. A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals.concurrent tutorial.concurrent package so you don't have to implement your own semaphores.Using Semaphores for Signaling 3. If the call to take() happens before the call to release() the thread calling release() will still know that take()was called. } } The take() method sends a signal which is stored internally in the Semaphore. The names take() and release() may seem a bit odd when using a semaphore for signaling. This is not the case with wait() and notify(). Using a semaphore like this you can avoid missed signals. } public synchronized void release() throws InterruptedException{ while(!this. because the signal is stored internally in the signal variable. The names origin from the use of semaphores as locks. this. Therelease() method waits for a signal. When received the signal flag is cleared again.public class Semaphore { private boolean signal = false.notify(). public synchronized void take() { this.signal = true. and the release() method exited.signal) wait(). this. You will call take()instead of notify() and release() instead of wait().signal = false. as . start(). receiver.explained later in this text. SendingThread sender = new SendingThread(semaphore). ReceivingThread receiver = new ReceivingThread(semaphore). Using Semaphores for Signaling Here is a simplified example of two threads signaling each other using a Semaphore: Semaphore semaphore = new Semaphore().start().semaphore = semaphore. In that case the names make more sense. sender. public SendingThread(Semaphore semaphore){ this. } public void run(){ . public class SendingThread { Semaphore semaphore = null. } public void run(){ while(true){ this. } } } public class RecevingThread { Semaphore semaphore = null.semaphore. then signal this.release().while(true){ //do something.take().semaphore.semaphore = semaphore. then do something.. public ReceivingThread(Semaphore semaphore){ this. //receive signal.. } } . } } .} Counting Semaphore The Semaphore implementation in the previous section does not count the number of signals sent to it by take() method calls. We can change the Semaphore to do so.notify().signals--. this. public synchronized void take() { this. This is called a counting semaphore. Here is a simple implementation of a counting semaphore: public class CountingSemaphore { private int signals = 0. } public synchronized void release() throws InterruptedException{ while(this. this.signals == 0) wait().signals++. public BoundedSemaphore(int upperBound){ this.bound = upperBound. } public synchronized void take() throws InterruptedException{ while(this. .signals == 0) wait().Bounded Semaphore The CoutingSemaphore has no upper bound on how many signals it can store. private int bound = 0.notify().signals == bound) wait(). } public synchronized void release() throws InterruptedException{ while(this. like this: public class BoundedSemaphore { private int signals = 0. this. this.signals++. We can change the semaphore implementation to have an upper bound. . set the upper bound to 1.notify(). To do so. this. try{ //critical section } finally { . Here is an example: BoundedSemaphore semaphore = new BoundedSemaphore(1). semaphore.take(). Not until a thread has called receive will the thread calling take() be allowed to deliver its signal.this.signals--. Using Semaphores as Locks It is possible to use a bounded semaphore as a lock.. . } } Notice how the take() method now blocks if the number of signals is equal to the upper bound. and have the call to take() and release() guard the critical section. if the BoundedSemaphore has reached its upper signal limit. release(). or you application will fail.semaphore. in the example above. Blocking Queues A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty. or if you try to enqueue items to it and the queue is already full. either by dequeuing one or more items or clearing the queue completely. You can also use a bounded semaphore to limit the number of threads allowed into a section of code. The relase() method is called from inside a finally-block to make sure it is called even if an exception is thrown from the critical section. For instance. that the thread operations do not conflict for these 5 threads. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue. You would have to make sure though. The call torelease() will never block since there has always been a call to take() first. all other threads calling take() will be blocked until release() is called. Since only one thread is allowed to take the semaphore. Here is a diagram showing two threads cooperating via a blocking queue: . what would happen if you set the limit of the BoundedSemaphore to 5? 5 threads would be allowed to enter the critical section at a time. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. } In contrast to the signaling use case the methods take() and release() are now called by the same thread. util. and another thread taking from it.util.BlockingQueuetutorial. it can be useful to know the theory behind their implementation.limit = limit. Blocking Queue Implementation The implementation of a blocking queue looks similar to a Bounded Semaphore. You can read about that class in my java. Here is a simple implementation of a blocking queue: public class BlockingQueue { private List queue = new LinkedList(). public BlockingQueue(int limit){ this. } . private int limit = 10.concurrentpackage. Even if Java 5 comes with a blocking queue implementation. Java 5 comes with blocking queue implementations in the java.A BlockingQueue with one thread putting into it.concurrent. queue. } public synchronized Object dequeue() throws InterruptedException{ while(this.public synchronized void enqueue(Object item) throws InterruptedException { while(this. } .size() == this.size() == this.queue.add(item).size() == 0) { notifyAll(). } this. } if(this.limit) { wait().queue.size() == 0){ wait().queue.queue.limit){ notifyAll(). } if(this. The rest of the idle threads in the pool will be blocked waiting to dequeue tasks. the task can be passed to a thread pool. Internally the tasks are inserted into a Blocking Queuewhich the threads in the pool are dequeuing from.remove(0). there can be no threads waiting to either enqueue or dequeue items. and each thread is also allocated some memory for its stack etc. When a new task is inserted into the queue one of the idle threads will dequeue it successfully and execute it. Instead of starting a new thread for every task to execute concurrently.return this. As soon as the pool has any idle threads the task is assigned to one of them and executed. There is a performance overhead associated with starting a new thread. If the queue size is not equal to either bound when enqueue() or dequeue() is called. A later trail will get into detail about implementing multithreaded servers in Java. The threads in the thread pool will process the requests on the connections concurrently.queue. . Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. } } Notice how notifyAll() is only called from enqueue() and dequeue() if the queue size is equal to the size bounds (0 or limit). Thread Pools Thread Pools are useful when you need to limit the number of threads running in your application at the same time. Thread pools are often used in multi threaded servers. private boolean isStopped = false.start(). } for(PoolThread thread : threads){ thread.ExecutorService.add(new PoolThread(taskQueue)).util. Here is a simple thread pool implementation: public class ThreadPool { private BlockingQueue taskQueue = null. int maxNoOfTasks){ taskQueue = new BlockingQueue(maxNoOfTasks). private List<PoolThread> threads = new ArrayList<PoolThread>().Java 5 comes with built in thread pools in the java. Still it can be useful to know a bit about the implementation of a thread pool anyways. public ThreadPool(int noOfThreads.concurrent. You can read more about it in my text on the java. } } . i<noOfThreads. i++){ threads.util. so you don't have to implement your own thread pool. for(int i=0.concurrent package. stop(). .isStopped) throw new IllegalStateException("ThreadPool is stopped").public void synchronized execute(Runnable task){ if(this. } public synchronized void stop(){ this. } } } public class PoolThread extends Thread { private BlockingQueue taskQueue = null. for(PoolThread thread : threads){ thread.taskQueue. private boolean isStopped = false.isStopped = true.enqueue(task). this. public PoolThread(BlockingQueue queue){ taskQueue = queue. this.dequeue(). . } public void run(){ while(!isStopped()){ try{ Runnable runnable = (Runnable) taskQueue. } } } public synchronized void stop(){ isStopped = true.interrupt(). runnable. //but keep pool thread alive.run(). } catch(Exception e){ //log or otherwise report exception. //break pool thread out of dequeue() call. and a PoolThread class which implements the threads that execute the tasks. } } The thread pool implementation consists of two parts. A ThreadPool class which is the public interface to the thread pool. waiting to be dequeued. Anatomy of a Synchronizer Even if many synchronizers (locks. until stopped. blocking queue etc.run() will exit and the thread dies. You can see this in the PoolThread. and leaves the dequeue() method call with an InterruptedExceptionthrown.run() method.stop(). and then the isStopped variable is checked. The Runnable will be dequeued by an idle PoolThread and executed. This exception is caught in the PoolThread.run() method. thePoolThread. After execution the PoolThread loops and tries to dequeue a task again. Notice how the execute() method will throw anIllegalStateException if execute() is called after stop() has been called. they . The stop called is noted internally in the isStopped member. reported.stop() is called.} public synchronized void isStopped(){ return isStopped.interrupt() call in PoolThread.) are different in function. semaphores.execute(Runnable r) is called with aRunnable implementation as parameter. To stop the ThreadPool the method ThreadPool. To execute a task the method ThreadPool. The Runnable is enqueued in the blocking queue internally.stop(). This makes sure that a thread blocked in a wait() call inside the taskQueue. Since isStopped is now true. Notice thethis. Then each thread in the pool is stopped by calling PoolThread. The threads will stop after finishing any task they are currently executing.dequeue() call breaks out of thewait() call. though not exactly the same. they consist of the same (or similar) basic parts internally.State Changes 4. In a Bounded Semaphore the internal state is kept in a counter (int) and an upper bound (int) which state the current number of "takes" and the maximum number of "takes". Toke Johansen and Lars Bj�rn.State 2. and those that have may not have them exactly as they are described here. I believe. student project at the IT University of Copenhagen in the spring 2004 by Jakob Jenkov. though. Note: The content of this text is a part result of a M. State The state of a synchronizer is used by the access condition to determine if a thread can be granted access.Set Method Not all synchronizers have all of these parts. This book also contains a chapter with the title "Anatomy of a Synchronizer" with content similar to this text. During this project we asked Doug Lea if he knew of similar work.Notification Strategy 5. Here are two code snippets from both Lock and a BoundedSemaphore. Doug Lea's work.are often not that different in their internal design. The state code is marked in bold. . In a Lock the state is kept in a boolean saying whether theLock is locked or not.Test and Set Method 6. It is these parts this text looks closer at. The purpose of most (if not all) synchronizers is to guard some area of the code (critical section) from concurrent access by threads. In a Blocking Queue the state is kept in the List of elements in the queue and the maximum queue size (int) member (if any). Knowing these basic parts can be a great help when designing synchronizers. is described in the book "Java Concurrency in Practice". To do this the following parts are often needed in a synchronizer: 1.Access Condition 3.Sc. In other words. Usually you can find one or more of these parts. Interestingly he had come up with similar conclusions independently of this project during the development of the Java 5 concurrency utilities. } . } public class BoundedSemaphore { //state is kept here private int signals = 0. . public synchronized void lock() throws InterruptedException{ while(isLocked){ wait()..public class Lock{ //state is kept here private boolean isLocked = false. private int bound = 0. } isLocked = true.. bound = upperBound. In a Bounded Semaphore there are actually two access conditions depending on whether you are trying to "take" or "release" the semaphore. The access condition is typically based on the state of the synchronizer. The access condition is typically checked in a while loop to guard against Spurious Wakeups. ..notify(). When the access condition is evaluated it is either true or false.signals == bound) wait(). If a thread tries to take the semaphore the signals variable is checked against the upper bound. In a Lock the access condition simply checks the value of the isLocked member variable. } .public BoundedSemaphore(int upperBound){ this. } Access Condition The access conditions is what determines if a thread calling a test-and-set-state method can be allowed to set the state or not. If a thread tries to release the semaphore the signals variable is checked against 0. this.signal++. } public synchronized void take() throws InterruptedException{ while(this.. this. Here are two code snippets of a Lock and a BoundedSemaphore with the access condition marked in bold. Notice how the conditions is always checked inside a while loop. public class Lock{ private boolean isLocked = false; public synchronized void lock() throws InterruptedException{ //access condition while(isLocked){ wait(); } isLocked = true; } ... } public class BoundedSemaphore { private int signals = 0; private int bound = 0; public BoundedSemaphore(int upperBound){ this.bound = upperBound; } public synchronized void take() throws InterruptedException{ //access condition while(this.signals == bound) wait(); this.signals++; this.notify(); } public synchronized void release() throws InterruptedException{ //access condition while(this.signals == 0) wait(); this.signals--; this.notify(); } } State Changes Once a thread gains access to the critical section it has to change the state of the synchronizer to (possibly) block other threads from entering it. In other words, the state needs to reflect the fact that a thread is now executing inside the critical section. This should affect the access conditions of other threads attempting to gain access. In a Lock the state change is the code setting isLocked = true. In a semaphore it is either the code signals-- or signals++; Here are two code snippets with the state change code marked in bold: public class Lock{ private boolean isLocked = false; public synchronized void lock() throws InterruptedException{ while(isLocked){ wait(); } //state change isLocked = true; } public synchronized void unlock(){ this. } public synchronized void take() throws InterruptedException{ while(this. } } public class BoundedSemaphore { private int signals = 0. notify(). //state change this.//state change isLocked = false. private int bound = 0. } .signals++.notify().signals == bound) wait().bound = upperBound. public BoundedSemaphore(int upperBound){ this. 3.signals == 0) wait().Notify all waiting threads. //state change this.notify(). Notifying all waiting threads is pretty easy. separate object.signals--.Notify 1 specific of N waiting thread. Once a thread want to notify the waiting threads it calls notifyAll() on the object the waiting threads called wait() on. To achive this each waiting thread must call wait() on its own.public synchronized void release() throws InterruptedException{ while(this. Calling notify makes no guarantee about which of the waiting threads will be notified. For instance if you need to guarantee that waiting threads are notified in a specific order. When the notifying thread wants to notify a specific waiting thread it will call notify() on the object this specific thread has called wait() on. this. Notification Strategies typically fall into three categories. Hence the term "random waiting thread". Notifying a single random waiting thread is also pretty easy. or some prioritized order. All waiting threads call wait() on the same object. 1.Notify 1 random of N waiting threads. Just have the notifying thread call notify() on the object the waiting threads have called wait() on. Sometimes you may need to notify a specific rather than a random waiting thread. An example of this can be found in the textStarvation and Fairness. } } Notification Strategy Once a thread has changed the state of a synchronizer it may sometimes need to notify other waiting threads about the state change. . Perhaps this state change might turn the access condition true for other threads. 2. be it the order they called the synchronizer in. } public synchronized void unlock(){ isLocked = false. notify(). public synchronized void lock() throws InterruptedException{ while(isLocked){ //wait strategy .Below is a code snippet with the notification strategy (notify 1 random waiting thread) marked in bold: public class Lock{ private boolean isLocked = false. } isLocked = true.related to notification strategy wait(). //notification strategy } } . . wait 4. If the condition is met the thread sets the internal state of the synchronizer to reflect that the thread has gained access. in a Read . and notify waiting threads if necessary The lockWrite() method of a ReadWriteLock class shown below is an example of a test-and-set method.Test and Set Method Synchronizer most often have two types of methods of which test-and-set is the first type (set is the other). It is imperative that the test-and-set operations are executed atomically meaning no other threads are allowed to execute in the test-and-set method in between the test and the setting of the state. Then it tests the internal state against the access condition in the canGrantWriteAccess() method. Notice that this method does not notify waiting threads. The state transition usually results in the access condition turning false for other threads trying to gain access.Write Lock a thread gaining read access will update the state of the read-write lock to reflect this. Integer> readingThreads = new HashMap<Thread.Test state against access condition 3. For instance. but may not always do so. Integer>(). but other threads requesting read access will also be granted access as long as no threads has requested write access. public class ReadWriteLock{ private Map<Thread.Set state before test if necessary 2. set state. The program flow of a test-and-set method is usually something along the lines of: 1. Threads calling lockWrite() first sets the state before the test (writeRequests++).If access condition is met. Test-and-set means that the thread calling this methodtests the internal state of the synchronizer against the access condition.If access condition is not met. If the test succeeds the internal state is set again before the method is exited. . writeAccesses++.currentThread().private int writeAccesses private int writeRequests = 0. while(! canGrantWriteAccess(callingThread)){ wait(). } writeRequests--. Thread callingThread = Thread.. writingThread = callingThread. public synchronized void lockWrite() throws InterruptedException{ writeRequests++. private Thread writingThread = null... . } . = 0. . public class BoundedSemaphore { private int signals = 0. Both methods test and sets the internal state. public BoundedSemaphore(int upperBound){ this.bound = upperBound.signals++. this.signals == bound) wait(). private int bound = 0. this.} The BoundedSemaphore class shown below has two test-and-set methods: take()and release().notify(). } public synchronized void release() throws InterruptedException{ . } public synchronized void take() throws InterruptedException{ while(this. while(this. A thread holding the lock can always unlock it without having to test if the Lock is unlocked.Notify waiting threads Here is an example unlock() method: public class Lock{ private boolean isLocked = false.signals == 0) wait(). The program flow of a set method is usually along the lines of: 1.notify().signals--. . public synchronized void unlock(){ isLocked = false. } } Set Method The set method is the second type of method that synchronizers often contain. The set method just sets the internal state of the synchronizer without testing it first.Set internal state 2. this. A typical example of a set method is the unlock() method of a Lock class. this. html .com/java-concurrency/ind ex.jenkov.notify(). } } ref:.
https://www.scribd.com/document/141200112/Java-Concurrency
CC-MAIN-2018-17
refinedweb
18,732
60.41
Created on 2020-06-05 09:46 by BTaskaya, last changed 2020-06-06 17:26 by pablogsal. This issue is now closed. import ast t = ast.fix_missing_locations(ast.Expression(ast.Name("True", ast.Load()))) compile(t, "<t>", "eval") compilation of this AST can crash the interpreter for 3.8+ test_constant_as_name (test.test_ast.AST_Tests) ... python: Python/compile.c:3559: compiler_nameop: Assertion `!_PyUnicode_EqualToASCIIString(name, "None") && !_PyUnicode_EqualToASCIIString(name, "True") && !_PyUnicode_EqualToASCIIString(name, "False")' failed. Fatal Python error: Aborted I've encountered this while running test suite of 'pytest' with the current master, so I guess there are some usages related this out there. IMHO we should validate this on the PyAST_Validate step to prevent this kind of crashes. cross-linking pytest issue: New changeset 68874a8502da440a1dc4746cf73262648b870aee by Batuhan Taskaya in branch 'master': bpo-40870: Invalidate usage of some constants with ast.Name (GH-20649) New changeset 90ee51f1cd9e63cfe0f402392612f50fc1bea747 by Miss Islington (bot) in branch '3.9': bpo-40870: Invalidate usage of some constants with ast.Name (GH-20649) New changeset 83a9ba442662c2a030b45955f3dd24ff4b24bb61 by Miss Islington (bot) in branch '3.8': bpo-40870: Invalidate usage of some constants with ast.Name (GH-20649)
https://bugs.python.org/issue40870
CC-MAIN-2021-21
refinedweb
186
52.15
Dry Behaviour aka Protocol Pattern in Ruby Aleksei Matiushkin Nov 14, 2017 Elixir introduced the concept of behaviours. The quote from the official docs: Protocols are a mechanism to achieve polymorphism in Elixir. Dispatching on a protocol is available to any data type as long as it implements the protocol. What is it all about? Well, Elixir entities, aka “terms,” are all immutable. While in ruby we tend to declare methods on objects, that simply mutate the objects, in Elixir it is impossible. Everybody had seen the Animal example explaining the polymorphism in a nutshell for any of so-called OO languages: class Animal def sound raise "I am an abstract animal, I keep silence (and mystery.)" end end class Dog < Animal def sound puts "[LOG] I’m a dog, I bark" "woof" end end class Cat < Animal def sound puts "[LOG] I’m a cat, I am meowing" "meow" end end Now we are safe to call sound method on any animal, without bothering to determine what exact type of animal we are facing. In Elixir, on the other hand, we do not have “methods defined on objects.” The approach to achieve more or less same functionality (the most typical example of where it’s really handy is, for instance, the string interpolation,) would be to declare the protocol. Sidenote: another approach would be to use behaviours, but for the sake of our task we would stick to protocols in this post. The protocol is a pure interface, declared with defprotocol keyword. For the animalistic example above it would be: defprotocol Noisy do @doc "Produces a sound for the animal given" def sound(animal) end The implementation goes into defimpl clause: defimpl Noisy, for: Dog do def sound(animal), do: "woof" end defimpl Noisy, for: Cat do def sound(animal), do: "meow" end Now we can use the protocol, without actual care who the animal we have: ExtrernalSource.animal |> Noisy.sound OK. Why would we want to have this pattern in ruby? We indeed already have polymorphism, right? Yes. And no. The most evident example would be classes, coming from different external third-party sources, but still having something in common. The rails approach, widely spread into ruby world by DHH, would be to monkeypatch everything. The irony here is that I personally love monkeypatching. Yet in some cases I find the protocol approach being more robust. That way, instead of re-opening Integer class for declaring date-aware methods, one might declare the protocol, having to_days method. It in turn might be used as DateGuru.to_days(something) instead of something.to_days. That way all the code, responsible for the date conversions/operations, would be placed together, providing sorta guarantee that there are no conflicts, no accidental unintended monkeypatches etc. I am not advocating this approach is better; it is just different. To try it, we would need to provide some DSL to make it easy to declare protocols in pure ruby. Let’s do it. We are to start with tests. module Protocols::Arithmetics include Dry::Protocol defprotocol do defmethod :add, :this, :other defmethod :subtract, :this, :other defmethod :to_s, :this def multiply(this, other) raise "We can multiply by integers only" unless other.is_a?(Integer) (1...other).inject(this) { |memo,| memo + this } end end defimpl Protocols::Arithmetics, target: String do def add(this, other) this + other end def subtract(this, other) this.gsub /#{other}/, '' end def to_s this end end defimpl target: [Integer, Float], delegate: :to_s, map: { add: :+, subtract: :- } end Let’s dig a bit into the code above. We have declared the protocol Arithmetics, responsible for adding and subtracting values. Once two operations above are implemented for instances of some class, we have multiply method for granted. The usage of this protocol would be Arithmetics.add(42, 3) #⇒ 45. Our DSL support method delegation, mapping and explicit declaration. This contrived example does not make much sense as is, but it provides a good test case for our DSL. Let’s write tests. expect(Protocols::Adder.add(5, 3)).to eq(8) expect(Protocols::Adder.add(5.5, 3)).to eq(8.5) expect(Protocols::Adder.subtract(5, 10)).to eq(-5) expect(Protocols::Adder.multiply(5, 3)).to eq(15) expect do Protocols::Adder.multiply(5, 3.5) end.to raise_error(RuntimeException, "We can multiply by integers only") Yay, it’s time to finally implement this DSL. This is easy. The whole implementation fits one single module. We would call it BlackTie, since it’s all about protocols. In the first place tt will hold the maps of declared protocols to their implementations. module BlackTie class << self def protocols @protocols ||= Hash.new { |h, k| h[k] = h.dup.clear } end def implementations @implementations ||= Hash.new { |h, k| h[k] = h.dup.clear } end end Sidenote: the trick with default_proc in hash declarations ( Hash.new { |h, k| h[k] = h.dup.clear }) produces the hash that has a deep default_proc, returning an empty hash. defmethod is the most trivial method here, it simply stores the declaration under respective name in the global @protocols hash: def defmethod(name, *params) BlackTie.protocols[self][name] = params end Declaration of the protocol is a bit more cumbersome (some details are omitted here for the sake of clarity, see the full code here.) def defprotocol raise if BlackTie.protocols.key?(self) || !block_given? ims = instance_methods(false) class_eval(&Proc.new) (instance_methods(false) - ims).each { |m| class_eval { module_function m } } singleton_class.send :define_method, :method_missing do |method, *args| raise Dry::Protocol::NotImplemented.new(:method, self.inspect, method) end BlackTie.protocols[self].each do |method, *| singleton_class.send :define_method, method do |receiver = nil, *args| impl = receiver.class.ancestors.lazy.map do |c| BlackTie.implementations[self].fetch(c, nil) end.reject(&:nil?).first raise Dry::Protocol::NotImplemented.new(:protocol, self.inspect, receiver.class) \ unless impl impl[method].(*args.unshift(receiver)) end end end Basically, the code above has four block. First of all, we check the conditions the protocol must meet. Then we execute a block given, recording what methods were added by this block, and exposing them with module_function. In the third block we declare the generic method_missing to provide meaningful error messages on erroneous calls. And, lastly, we declare methods, either delegating them to respective implementation (when exists,) or throwing the descriptive exception is there is no implementation for this particular receiver. OK, the only thing left is to declare defimpl DSL. The code below is a bit simplified. def defimpl(protocol = nil, target: nil, delegate: [], map: {}) raise if target.nil? || !block_given? && delegate.empty? && map.empty? # builds the simple map out of both delegates and map mds = normalize_map_delegates(delegate, map) Module.new do mds.each(&DELEGATE_METHOD.curry[singleton_class]) # delegation impl singleton_class.class_eval(&Proc.new) if block_given? # block takes precedence end.tap do |mod| mod.methods(false).tap do |meths| ms = BlackTie.protocols[protocol || self].keys - meths ms.each_with_object(meths) do |m, acc| logger.warn("Implicit delegate #{(protocol || self).inspect}##{m} to #{target}") DELEGATE_METHOD.(mod.singleton_class, [m] * 2) acc << m end end.each do |m| [*target].each do |tgt| BlackTie.implementations[protocol || self][tgt][m] = mod.method(m).to_proc end end end end module_function :defimpl Despite the amount of LOCs, the code above is fairly simple: we create an anonymous module, declare methods on it and supply it as the target of method delegation from the main protocol class methods. Once we have called Arithmetics.add(5, 3), the receiver ( 5) would be used to lookup the respective implementation ( defimpl Arithmetics, target: Integer) and it’s method :+ (because of defimpl target: [Integer, ...], ..., map: { add: :+, ... }, add is mapped to :+) would be called. That’s it. Whether you still think, this is a redundant of-no-practival-use garbage, imagine the Tax protocol. That might be implemented for: ItemToSell, Shipment, Employee, Lunch etc. ❖ dry-behaviour repo. Enjoy! ❖ originally published at rocket-science.ru.
https://dev.to/mudasobwa/dry-behaviour-aka-protocol-pattern-in-ruby-9km
CC-MAIN-2018-09
refinedweb
1,301
51.04
R: Think Bayes Locomotive Problem, or Posterior Probabilities for Different Priors R: Think Bayes Locomotive Problem, or Posterior Probabilities for Different Priors Join the DZone community and get the full member experience.Join For Free In my continued reading of Think Bayes the next problem to tackle is the Locomotive problem which is defined thus: A railroad numbers its locomotives in order 1..N. One day you see a locomotive with the number 60. Estimate how many loco- motives the railroad has. The interesting thing about this question is that it initially seems that we don’t have enough information to come up with any sort of answer. However, we can get an estimate if we come up with a prior to work with. The simplest prior is to assume that there’s one railroad operator with between say 1 and 1000 railroads with an equal probability of each size. We can then write similar code as with the dice problem to update the prior based on the trains we’ve seen. First we’ll create a data frame which captures the product of ‘number of locomotives’ and the observations of locomotives that we’ve seen (in this case we’ve only seen one locomotive with number ’60′:) library(dplyr) possibleValues = 1:1000 observations = c(60) l = list(value = possibleValues, observation = observations) df = expand.grid(l) > df %>% head() value observation 1 1 60 2 2 60 3 3 60 4 4 60 5 5 60 6 6 60 Next we want to add a column which represents the probability that the observed locomotive could have come from a particular fleet. If the number of railroads is less than 60 then we have a 0 probability, otherwise we have 1 / numberOfRailroadsInFleet: prior = 1 / length(possibleValues) df = df %>% mutate(score = ifelse(value < observation, 0, 1/value)) > df %>% sample_n(10) value observation score 179 179 60 0.005586592 1001 1001 60 0.000999001 400 400 60 0.002500000 438 438 60 0.002283105 667 667 60 0.001499250 661 661 60 0.001512859 284 284 60 0.003521127 233 233 60 0.004291845 917 917 60 0.001090513 173 173 60 0.005780347 To find the probability of each fleet size we write the following code: weightedDf = df %>% group_by(value) %>% summarise(aggScore = prior * prod(score)) %>% ungroup() %>% mutate(weighted = aggScore / sum(aggScore)) > weightedDf %>% sample_n(10) Source: local data frame [10 x 3] value aggScore weighted 1 906 1.102650e-06 0.0003909489 2 262 3.812981e-06 0.0013519072 3 994 1.005031e-06 0.0003563377 4 669 1.493275e-06 0.0005294465 5 806 1.239455e-06 0.0004394537 6 673 1.484400e-06 0.0005262997 7 416 2.401445e-06 0.0008514416 8 624 1.600963e-06 0.0005676277 9 40 0.000000e+00 0.0000000000 10 248 4.028230e-06 0.0014282246 Let’s plot the data frame to see how the probability varies for each fleet size: library(ggplot2) ggplot(aes(x = value, y = weighted), data = weightedDf) + geom_line(color="dark blue") The most likely choice is a fleet size of 60 based on this diagram but an alternative would be to find the mean of the posterior which we can do like so: > weightedDf %>% mutate(mean = value * weighted) %>% select(mean) %>% sum() [1] 333.6561 Now let’s create a function with all that code in so we can play around with some different priors and observations: meanOfPosterior = function(values, observations) { l = list(value = values, observation = observations) df = expand.grid(l) %>% mutate(score = ifelse(value < observation, 0, 1/value)) prior = 1 / length(possibleValues) weightedDf = df %>% group_by(value) %>% summarise(aggScore = prior * prod(score)) %>% ungroup() %>% mutate(weighted = aggScore / sum(aggScore)) return (weightedDf %>% mutate(mean = value * weighted) %>% select(mean) %>% sum()) } If we update our observed railroads to have numbers 60, 30 and 90 we’d get the following means of posteriors assuming different priors: > meanOfPosterior(1:500, c(60, 30, 90)) [1] 151.8496 > meanOfPosterior(1:1000, c(60, 30, 90)) [1] 164.3056 > meanOfPosterior(1:2000, c(60, 30, 90)) [1] 171.3382 At the moment the function assumes that we always want to have a uniform prior i.e. every option has an equal opportunity of being chosen, but we might want to vary the prior to see how different assumptions influence the posterior. We can refactor the function to take in values & priors instead of calculating the priors in the function: meanOfPosterior = function(values, priors, observations) { priorDf = data.frame(value = values, prior = priors) l = list(value = priorDf$value, observation = observations) df = merge(expand.grid(l), priorDf, by.x = "value", by.y = "value") %>% mutate(score = ifelse(value < observation, 0, 1 / value)) df %>% group_by(value) %>% summarise(aggScore = max(prior) * prod(score)) %>% ungroup() %>% mutate(weighted = aggScore / sum(aggScore)) %>% mutate(mean = value * weighted) %>% select(mean) %>% sum() } Now let’s check we get the same posterior means for the uniform priors: > meanOfPosterior(1:500, 1/length(1:500), c(60, 30, 90)) [1] 151.8496 > meanOfPosterior(1:1000, 1/length(1:1000), c(60, 30, 90)) [1] 164.3056 > meanOfPosterior(1:2000, 1/length(1:2000), c(60, 30, 90)) [1] 171.3382 Now if instead of a uniform prior let’s use a power law one where the assumption is that smaller fleets are more likely: > meanOfPosterior(1:500, sapply(1:500, function(x) x ** -1), c(60, 30, 90)) [1] 130.7085 > meanOfPosterior(1:1000, sapply(1:1000, function(x) x ** -1), c(60, 30, 90)) [1] 133.2752 > meanOfPosterior(1:2000, sapply(1:2000, function(x) x ** -1), c(60, 30, 90)) [1] 133.9975 > meanOfPosterior(1:5000, sapply(1:5000, function(x) x ** -1), c(60, 30, 90)) [1] 134.212 > meanOfPosterior(1:10000, sapply(1:10000, function(x) x ** -1), c(60, 30, 90)) [1] 134.2435 Now we get very similar posterior means which converge on 134 and so that’s our best prediction. Published at DZone with permission of Mark Needham , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/r-think-bayes-locomotive?fromrel=true
CC-MAIN-2019-35
refinedweb
1,009
55.74
Python – Visualize Google Trends Data in Word Cloud Christmas is just around the corner, the snowfall, beautiful festive lights and joyful songs from the last year still floating in your mind. But this year, things are getting unusual due to the Covid-19. A lot of celebration events are cancelled or suspended and people are advised to avoid gathering and stay at home as much as possible. Although staying at home became new norm, there is still a way that we can get to know what people are thinking about during this festive season since nowadays most of us search a lot from Google every day. With a few lines of Python code, we will be able to extract and visualize the data from Google Trends. Let’s dive into the code examples. Python to get Google trends data To get the search trends from Google, we will need to use a Python package – pytrends. It’s not an official API for Google trends but It provides a convenience way to automatically download Google trends data same as what we can do manually from Google Trends website. You can use the pip command to install the package: pip install --upgrade pytrends And import the necessary modules at the beginning of our code: from pytrends.request import TrendReq To use it, we can initiate the request object by providing the language for searching as well as the time zone information. For instance, I am specifying English as the language and time zone offset as -480 which is UCT + 8 in the below. The default value for this time zone offset is 360 (CST), so you can roughly see how this offset is calculated based on the UCT time zone. pytrend = TrendReq(hl='en-US', tz=-480) To get the search trends for a particular keyword, we shall specify it in a keyword list. For example, we use “christmas” to see what people have searched in Google related to this keyword. There are a few more parameters you need to specify in the build_payload function in order to narrow down the results: cat – The category you are interested in, you can see the full list here. timeframe – The date range when the search happened. You can specify the range as past X hours/days/months/years (the list of available options you can see from Google Trends web page) or even a specific start date and end date. For our case, we use “now 7-d” for the past 7 days. geo – The geolocation which can be two characters country code or leave it empty to see the results from globally gprop – The source which you can leave it as empty for web search, other options can be images, news, youtube, or froogle Let’s build up our query as per below: kw_list = ["christmas"] pytrend.build_payload(kw_list, cat=0, timeframe='now 7-d', geo='SG', gprop='') With all these criteria, we can check what are the related topics people searched in Google from Singapore. The related_queries function will give you a dictionary of both top & rising queries related to the keywords: trends = pytrend.related_queries() If you examine the trends variable, you shall see something similar to below: The dictionary consists of results for both “top” and “rising” results in pandas dataframe objects, and you can access the top queries as per below: df_sg = trends["christmas"]["top"] Examine the first a few records in df_sg, you can see that people in Singapore are still in celebration mood as most of records are related to greetings, light shows or gifts etc. On the other hand, let’s also take a look at the search trends for UK since It has just announced some new restrictions on travelling recently. pytrend.build_payload(kw_list, cat=0, timeframe='now 7-d', geo='GB', gprop='') trends = pytrend.related_queries() df_gb = trends["christmas"]["top"] Examining the df_gb variable, you can see some people started worrying about the new rules and restrictions for this Christmas although majority of the searching results are still around of the festival celebration. Visualize the results in word cloud Since we have all the keywords and popularity that people used for search, the most straightforward to visualize them would be using word cloud to generate a picture. To do so, we will need use another python package – wordcloud which is a pure Python library for generating word cloud image. And you also need to use some supporting packages like PIL and numpy for manipulating the images. You can use pip command to install these packages if you do not have them yet: pip install --upgrade wordcloud pip install Pillow==2.2.2 pip install --upgrade numpy Let’s import all the necessary modules into our code: from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS from PIL import Image import os import numpy as np From previous section, we have already got the search keywords in dataframe. wordcloud supports both text string and words frequencies, for simplicity, let’s convert only keywords into a space separated string and forget about the value (popularity). text = ' '.join(df_sg["query"].to_list()) And as all the keywords contain “christmas”, we shall filter out this word before generating the word cloud. In wordcloud package, it has a list of predefined words to be excluded, and you can append more words to be excluded as per the below: stopwords = set(STOPWORDS) stopwords.add("christmas") Now let’s use this featured image as our background for generating word cloud. We shall load it as a 3-demensional array as the background mask for later use: bg_mask = np.array(Image.open(os.path.join(os.getcwd(), "christmas tree.jpg"))) With all these ready, we can initiate a word cloud object with below parameters. The name of the parameters are quite self-explanatory, so I will not go through them one by one. You can check the official document from here. wc = WordCloud( width = 600, height = 1000, background_color = 'white', colormap = 'rainbow', mask = bg_mask, stopwords = stopwords, max_words = 1000, max_font_size = 150, min_font_size = 15, contour_width = 2, contour_color = 'dodgerblue' ) Then we can supply our words to the generate_from_text function which will process the text and generate the image. Next we can save the output into an image file as per below code: wc.generate_from_text(text) wc.to_file("SG_christmas_cloud.jpg") When opening the output image file, you shall see something like the below. Isn’t that cool? Similarly, when you pass the UK searching result and generate the word cloud, you would see “covid” and “rules” are most concerned by UK people. Note: since we are passing through a text string, the frequency is based on how many times the words repeated rather than the popularity from Google. Conclusion In this article, we have discussed how to use pytrends to automatically get the Google search data for any particular keyword and then use wordcloud to visualize the information. It only covers some basic usage of these two packages, you may check further on their documents to understand what else are provided in these packages. One thing to take note is that pytrends is using some scrapping techniques to get the data from Google Trends, it may break when there is any structural change in the way that Google makes the requests or sends the response. So frequent code upgrade is required by the project team. By the way, they are looking for maintainers, just in case you are interested.
https://www.codeforests.com/2020/12/22/google-trends-data-in-word-cloud/
CC-MAIN-2022-21
refinedweb
1,235
56.08
Introduction why we can still boot into the DOS. We can do that by downloading the zip file attached to this post and then unzipping the archive and adding a new Floppy Controller to the VirtualBox as seen on the picture below: When we boot the Windows XP operating system after doing that, the booting process can be seen on the picture below: We now have the A:\> command prompt, which shows we’ve booted into MSDOS instead of Windows booting normally into the GUI mode. If we enter the dir command, we’ll be listing every file on the A: drive, which is our floppy. The contents of the floppy drive can be seen below: Now, let’s execute the mem command to display the memory details in the MSDOS environment: We can see that MSDOS has a total of 640KB of memory, where 92KB is used and 548KB is still free. Actually, MSDOS uses 20-bit memory addresses, which means it can address at most 1MB of physical memory. MSDOS uses the segmented memory model and all of its registers are 16-bits wide. This means that its programs use 16-bit addresses and the segment register is also 16-bits wide. The segment register contains the base address of the segment in memory, that is 2^16/1024 = 64 KB in size. The logical address is also 16-bits in size. To obtain the actual physical address, we need to add the segment register base and the logical address together to obtain the physical address. But if the segment base address is 16-bits wide and the logical address is also 16-bits wide, this can only address 16-bit address space (let’s forget about what happens if an overflow occurs), so this can’t be right. Earlier, we said that the MSDOS environment has a 20-bit address space, but how can we address it if we’re only using 16-bit addresses? This is possible because of a little trick, where the processor adds an additional zero to the end of the segment register and another zero to the beginning of the logical address. This really doesn’t do anything, because adding zeros to the beginning of hexadecimal digits is just another representation of the same number. By adding an additional zero to the segment base, all of a sudden the segment base address isn’t 16-bits wide any more, but 20-bits wide. An additional zero adds 4 more bits to the address: if 0x00 adds one byte, which is 8-bits, the value 0x0 adds 4-bits to the base segment address. Another interesting fact is that since the logical address can only be 16-bits wide, the segment can also be only 64KB in size, because the logical address is being used as an offset to access a certain value of the segment. Also, real mode doesn’t offer any memory protections that are present in protected mode. This makes MSDOS extremely fault prone, because if one process does something stupid with the memory, it can crash the whole MSDOS system. In protected mode, only that program will crash, but in real mode, the whole system is at risk. The MSDOS Memory Let’s take a look at the detailed MSDOS memory, which we can see by passing some flags to the mem.exe command. We need to execute the “mem.exe /d /p” command, where the /d flag is used for debugging and can display all modules in memory, internal drivers and other information. The /p flag is used to pause the printing of information after each screen, which is useful if we want to view all the data being outputted to the screen. We didn’t present the rest of the output, because it’s the same as the one already presented earlier in the article (the picture about the memory summary). On the pictures above, we can see the interrupt vector table IVT accessible at segment 0x00000 and our program MEM is loaded at segment 0x00EF6 and 0x016E6. We can see a bunch of other loaded device drivers, system data, etc. The MSDOS environment uses six segment registers: CS, DS, SS, ES, FS and GS that are all 16-bits in size. The CS register is a code segment register that holds the base address of the program instructions being executed. The DS segment register is the data segment register that holds the base address to the data of the program. The SS stack segment registers holds the base address of the stack of the program and so on. This means that the program can have at most 6 segments active at any time during execution. Let’s now use the debug.exe 16-bit debugger to debug the mem.exe program. To do so, we must execute the “debug.exe mem.exe” command as can be seen below: After starting the debugging of the program, we’ve inputted the -r command into the debug.exe debugger, which prints the state of all registers. The -r command also prints the next instruction that will be executed when running the program (the instruction where the IP register points to). Notice that the IP register holds the value 0x0010, the CS (code segment) register holds the value 0x2439, and the instruction printed is from the segment 2439 at offset 0010. Introduction to Interrupts An interrupt is an event that triggers some action, which is called Interrupt Service Routine (ISR) or Interrupt Handler. When an interrupt is triggered, it is usually triggered with the specific number that directly corresponds to the ISR routine, because when triggering a specific event, we must know in advance what ISR will get called to handle the event. Various processor architectures use an Interrupt Vector Table (IVT) or Interrupt Description Table (IDT), which is a table of interrupt vectors that is used to call the right interrupt service routine (ISR) based on the interrupt event. When the CPU is interrupted by an event, it looks up the interrupt service routine handler in the IVT, and transfers control to it [1]. Basically the interrupt table stores interrupt descriptions that tell us where the appropriate interrupt service routines are located in memory, so that program control can be transferred there when appropriate. The interrupts must be invisible so that the interrupted program doesn’t even notice that it’s been interrupted. When an interrupt happens, a certain program is being affected in such a way that the CPU state is saved into memory, then the interrupt service routine is called to try to fix the state of the program. After that, the state of the CPU must be restored and the program’s execution can continue as if there was no interrupt at all. The interrupted program doesn’t even notice it’s been interrupted. Types of Interrupts There are three types of interrupts: - hardware interrupts or external interrupts - maskable interrupts (can be ignored or masked) - non-maskable interrupts (must be handled immediately) - software interrupts or programmed exceptions - exceptions (errors that happened while the processor is trying to execute an instruction): - faults (program is restarted before the instruction that generated the fault, such as divide by zero) - traps (program is restarted after the instruction that generated the trap, such as int 3) - aborts (program cannot be restarted) The non-maskable interrupts must be handled as soon as they happen, because they are usually critical, like a hardware failure, division by zero, access to a bad address or something else. Maskable interrupts must be handled sometime in the future; IRQs (Interrupt Requests) can be categorized under the maskable interrupts. An interrupt request is the priority of an interrupt request [2]. We can display all the IRQ numbers currently in use by listing the contents of the /proc/interrupts file, which can be seen below: # cat /proc/interrupts CPU0 CPU1 0: 6944846 7492717 IO-APIC-edge timer 1: 2857 2252 IO-APIC-edge i8042 8: 13 14 IO-APIC-edge rtc0 9: 433 430 IO-APIC-fasteoi acpi 12: 169265 155602 IO-APIC-edge i8042 16: 50 47 IO-APIC-fasteoi uhci_hcd:usb3 17: 16 14 IO-APIC-fasteoi uhci_hcd:usb4 18: 34761 29673 IO-APIC-fasteoi uhci_hcd:usb5, uhci_hcd:usb8 19: 12 11 IO-APIC-fasteoi ehci_hcd:usb1 20: 3 1 IO-APIC-fasteoi ehci_hcd:usb2, uhci_hcd:usb6 22: 4 3 IO-APIC-fasteoi yenta, uhci_hcd:usb7 45: 224863 217010 PCI-MSI-edge ahci 46: 1329799 943403 PCI-MSI-edge snd_hda_intel 47: 11953 12972 PCI-MSI-edge eth0 48: 1158569 1009461 PCI-MSI-edge iwlwifi NMI: 0 0 Non-maskable interrupts LOC: 9125118 9940552 Local timer interrupts SPU: 0 0 Spurious interrupts PMI: 0 0 Performance monitoring interrupts IWI: 0 0 IRQ work interrupts RTR: 0 0 APIC ICR read retries RES: 319540 595551 Rescheduling interrupts CAL: 56 68 Function call interrupts TLB: 67339 65343 TLB shootdowns TRM: 0 0 Thermal event interrupts THR: 0 0 Threshold APIC interrupts MCE: 0 0 Machine check exceptions MCP: 167 167 Machine check polls ERR: 0 MIS: 0 In the first column, we can see the IRQ number. The second column shows how many times the interrupt was called after the last boot of the system. The programmed exception can be triggered with assembler instructions int 3. Interrupt Vector Each interrupt or exception is identified by a number between 0 – 255, which is called an interrupt vector. The interrupt vector numbers are classified as follows: - 0 – 31 : exceptions and non-maskable interrupts (in real mode, the BIOS handles these interrupts) - 32 – 63 : maskable interrupts - 64 – 255 : software interrupts The Linux system often uses software interrupt 0x80, which is used for calling system functions. Interrupt Vector Table (IVT) In the previous part, we’ve seen that the Interrupt Vector Table IVT is allocated in the segment 0x00000 and is 1024 bytes in size. This means that the first 1KB of memory is occupied by the IVT, which holds the pairs of numbers and interrupt service routines (ISR). Each integer number is associated with one ISR. When an interrupt that has a certain number is triggered, it’s corresponding interrupt service routine is called. Because the IVT uses 1024 bytes in total and each interrupt vector takes 4 bytes, the table can hold 1024/4=256 vectors. By the end of the day, it doesn’t really matter whether we’re dealing with maskable or non-maskable interrupts, or software or hardware interrupts. We can imagine this simply with the following sentence: when a system or a process gets into an erroneous state, the CPU immediately tries to fix the problem by executing the right interrupt handler routine, regardless of software or hardware interrupt being triggered. All interrupts and exceptions have an interrupt vector that associates the interrupts with the appropriate functions to be called when an event occurs. The functions that get called are defined in the interrupt descriptor table, which is a linear table of 256 entries. The IDT associates an interrupt handler with an interrupt vector. An Interrupt Example Let’s take a look at the following example where we intentionally divide a number by zero. The source code of the program can be seen below: #include <iostream> using namespace std; int main() { cout << "Result: " << 10/0 << endl; return 0; } We can see that the program is written in C++ and is really simple; it contains just one cout instruction. When the program executes, it should print “Result: ” followed by the result of the 10/0 on the screen. But what happens when we compile and run the program? Below we can see the command that compiles and runs the program and displays the warnings and errors: # g++ main.cpp -o main && ./main main.cpp: In function 'int main()': main.cpp:6:28: warning: division by zero Floating point exception # echo $? 136 So when compiling the program, we get a warning about dividing a number by zero, which is really what we should get. Since this is a warning, we can ignore it (most of the times we ignore warnings), but this time it’s not actually safe to ignore it. When we run the program, we get a floating point exception and the program is terminated with an error 136. This is clearly not a successful return code, so an error must have happened. Conclusion Real mode is important on the IA-32 processor systems, because it’s still being used right after starting our computer: the BIOS itself operates in real mode and it is kind of needed in every computer system. The job of the BIOS is to tell the operating system where it must boot from, or on which partition the boot loaded is located, and a bunch of other stuff that are pretty closely related to hardware components. References: [1] Wikipedia, Interrupt vector table, accessible at. [2] Wikipedia, Interrupt request, accessible at. [3] Interrupt/exception classification,. [4] Interrupt Vector Table,. [5] Interrupt descriptor table,. [6] Protected mode programming tutorial,
http://resources.infosecinstitute.com/the-ia-32-real-mode-and-interrupts/
CC-MAIN-2015-48
refinedweb
2,174
55.58
In this Python programming class, we’ll cover the Python datetime module and understand its functions. Further, you will learn how to get and set the system date-time with the help of the examples. Please note that this module and its functions could come quite handy for recording the events and logs with the timestamp value. Python Datetime Greetings, hope you had a great day. Today, we plan to educate you on how to find the date, day, time, etc. using a module known as the datetime in Python. You should be comfortable with modules in Python before studying the concept of date and time objects in Python. This tutorial uses syntax for Python3 which can get modified for use with Python2. - Pre-requisites - Introduction to Datetime in Python - Implementation - Datetime Examples - Usages of Datetime Module 1. Pre-requisites You need to have some level of experience of using the modules in Python. They provide readymade functions which you can directly call from any program. Read the below tutorial to learn about using the modules quickly. 2. Introduction to Datetime Module Although we can use the time module to find out the current date and time, it lacks features such as the ability to create Date objects for a particular manipulation. To remedy this, Python has the built-in datetime module. Hence, to do any object manipulation regarding date and time, we need to import datetime module. The datetime module is used to modify date and time objects in various ways. It contains five classes to manipulate date and time. They are as follows: - Date: deals with date objects. - Time: deals with time objects. - datetime: deals with date and time object combinations. - timedelta: deals with intervals of time. Used in calculations of past and future date and time objects. - Info: deals with time zone info of local time. We are going to deal with date and time classes. 3. Implementation To create and modify new date and time objects, we need to import the module. We load them by using the following statement. import datetime Or if you want only one of the modules- from datetime import date from datetime import time from datetime import datetime We could create new objects that have different date and time stored for manipulation using the datetime module. The following syntax would do the needful. import datetime datetime.datetime(year_number, month_number, date_number, hours_number, minutes_number, seconds_number) To format the dates into human readable strings, we use strftime() in the datetime module. The timedelta() function allows performing calculations on the date and time objects. It can be useful for time planning and management. The syntax used in invoking timedelta() is as follows: from datetime import timedelta timedelta(days, hours, minutes, seconds, year,...) 4. Python Datetime Examples You can use the commands either in python interpreter or by writing the code in a file and executing it. To display today’s date we use the following code: import datetime print (datetime.date.today()) Or from datetime import date print (date.today()) To view the individual date components, we need: from datetime import date print (datetime.date.today().day) print (datetime.date.today().month) print (datetime.date.today().year) #If you prefer to write in one sentence, write it as print (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year) Since the above code is long, we can rewrite as: from datetime import date now = date.today() print (now.day) print (now.month) print (now.year) #You can also display the previous 3 sentences in one sentence #print (now.day, now.month, now.year) This code is cleaner and compact. Try to write the code in shortest way possible without affecting readability. The below diagram shows the output of the previous commands: You could also use the date class to find out the weekday of the current date: from datetime import date now = date.today() print (now.weekday()) The following image depicts the creation of a date object and time object. See the below output: To format the date and time into human readable strings, we use strftime() in the datetime module. The following example clarifies how to use this function and prints the date/time in a styled manner: Today = datetime.now() print (Today.strftime(“%a, %B, %d, %y”)) In the above the %a stands for the day, %B stands for the month, %d stands for date and %y stands for the year. These are the most common format types use. If we wanted to print local date and time using strftime(), we could use import datetime Today = datetime.now() print (“Today’s date is “ ,Today.strftime(“%c”)) To display only local date, local time separately, we can replace %c with %x and %X, respectively. Programs using timedelta from datetime import date,time,datetime,timedelta Time_gap = timedelta(hours = 23, minutes = 34) #Time_gap is the timedelta object where we can do different calculations on it. print (“Future time is ”, str(datetime.now() + Time_gap)) The output is as follows. Usages of Datetime Module It is a powerful feature that allows us to manipulate system date and time without risking any system changes. We can define a new date object and modify its representation. Arithmetic calculations can be done on the date and time objects for several purposes such as finding the future date, the present year, formatting of date into strings, creating a time management solution, etc.
https://www.techbeamers.com/python-datetime/
CC-MAIN-2019-04
refinedweb
902
66.54
SerialGateway fails to load avr/eeprom.h to Intel Galileo Gen2 - SparkAndHale last edited by SparkAndHale Hi all, I installed Arduino IDE 1.6.3 and copied all the library files over to the Arduino library as shown in this video. (I omited the libs which are already in place). I can upload and run successfully the Arduino Blink sketch to my Intel Galileo Gen2. Good so far. When I load and attempt to upload the MySensors example "SerialGateway", it fails with the following message. In file included from SAHSerialGateway.ino:16:0: C:\Program Files (x86)\Arduino\libraries\MySensors/MySensor.h:19:24: fatal error: avr/eeprom.h: No such file or directory compilation terminated. Error compiling. What is the root folder of where this eeprom.h file should be placed? Apparently the MySensor header file requires it. Any one else is having this problem with a new setup? Does the Intel Galileo platform have something similar as Avr's eeprom library? - SparkAndHale last edited by SparkAndHale Dear @hek, yes it does have 11kb eeprom . If that is similar to AVR, I don't know. Also, this implementation of the eeprom interface is all capital: ``` #include <EEPROM.h> I tried all programmer options in Arduino, like AVR ISP, AVRISP MKII, etc... The Intel Pentium ISA SOC is not a ATMEL AVR-like chip. I assume that is the reason why taking this eeprom.h header file will not work - since the Intel SOC is base on a 32-Bit architecture. @hek shouldn't we try to implement the standard Arduino EEPROM in the mysensors.h header (and pgmspace.h and wdt.h? Or ought we think about a MySensors version for Intel Galileo 32BIT SOC chips? If you look in the development branch the hardware specific code has been moved out of the core library. You could perhaps try to make an Intel Galileo "Hw"-file? - SparkAndHale last edited by
https://forum.mysensors.org/topic/1306/serialgateway-fails-to-load-avr-eeprom-h-to-intel-galileo-gen2/1?lang=en-US
CC-MAIN-2020-29
refinedweb
321
70.09
Introduction to ASE databases¶ ASE has its own database format that can be used for storing and retrieving atoms (and associated data) in a compact and convenient way. In this exercise we will see how to create databases and how to interact with them through python scripts and the command line. Setting up a database¶ To construct a database we first need some atomic structures so let’s quickly create some. As you have seen the ASE command line tool provides many convenient commands and in particular we can use the build command to create some atomic structures. Remember, if you are unsure how to use a particular command you can always append -h to the particular command (ie. ase build -h) to see the help for that particular command. We choose to build silicon, germanium and carbon in the diamond crystal structure for which ASE already knows the lattice constants: $ ase build -x diamond Si $ ase build -x diamond Ge $ ase build -x diamond C This creates three files: Si.json, Ge.json and C.json. If you want to, you can inspect them with ASE’s gui command, however we want to construct a database containing these structures. To do this we can use convert: $ ase convert Si.json C.json Ge.json database.db This has created an ASE database name database.db. Exercise Create your own set of 3 interesting materials either using the ase build command or the techniques from the exercise “Crystals and band structure” and convert them into a ASE database named database.db. You can also build Si, Ge and C like we do here. Inspecting a database¶ We can inspect the database using the db command: $ ase db database.db which will display three entries, one for each structure. From this point it is advised to bring up the help for the db command every time you need it. From the help we can see that it is possible to make selections (queries in database lingo) in the database by: $ ase db database.db Si which will show all structures containing silicon. To see the details of a particular row we can do: $ ase db database.db Si -l From which we can get an overview of the stored data. We can also view all structures in a database using: $ ase gui database.db or if we want to view a single one we can do: $ ase gui database.db@Si where everything after the @ is interpreted as a query. Exercise Create an additional structure by any means and of you choice and add it to the existing ASE database database.db. Hint: Inspect ase db help to figure out how to do this. Opening a database in Python¶ Suppose we want do something more advanced with each row in the database. In this case a Python script would be more suited for our needs. To open a database we can use the ase.database.connect method which returns a database object from which we can make selections: from ase.db import connect db = connect('database.db') for row in db.select(): atoms = row.toatoms() print(atoms) We can make selections in the database using db.select(some_selection) which returns all rows matching some_selection. In this case some_selection was omitted which means that we select all rows in the database. For each row the associated ase.Atoms objects is retrieved by using the row.toatoms() method. Hint A general hint: In order to see the documentation for a particular python function import it and use the help function. For example from ase.db import connect db = connect('database.db') help(db.select) will show the documentation for the select method of the database object. Another useful function is dir which shows all attributes of a python object. For example from ase.db import connect db = connect('database.db') row = db.select(id=1)[0] dir(row) will show all attributes of the row object. Exercise Using a python script, print the formula for each row in your database. Write new entries to a database using Python¶ A new entry in the database can be written using the write() method of a database object. Exercise Loop through all materials, relax them (see exercise “Structure Optimization”) and save the relaxed structure as a new entry in the database with an added column relaxed equal to True that we can use later for selecting only these materials. CAUTION: To relax crystals you have to specify that the cell parameters should be relaxed as well. This is done by wrapping ase.constraints.ExpCellFilter around the atoms object like: filter = ExpCellFilter(atoms) and feeding filter into the optimization routine see help(ExpCellFilter) for more explanation. Adding data to existing database¶ Now we want to calculate some data and include the data in the database which can be done using the update method of the database object. Exercise Loop through all materials in the database and make a self consistent calculation using GPAW in plane wave mode for all materials. Then use the ase.dft.bandgap.bandgap() method to calculate the bandgap of the materials and store it under the bandgap keyword. When you are done with the exercise inspect your database again using the ase db command. To see the new column bandgap you can display all columns using the -c++ option: $ ase db database -c++ Browsing data¶ The database can also be visualized in a browser by using: $ ase database database.db -w $ firefox This opens a local webserver which can be opened in firefox like above. The layout can be customized further than our simple example however this would probably be too much for now. To see a more advanced example of such a web interfaced database in action you can check out the 2D database. Adsorbates on metals¶ When you are done with this introductory exercise we encourage you to follow the online ASE-DB tutorial at. Solutions¶ from pathlib import Path from ase.db import connect from ase.constraints import ExpCellFilter from ase.optimize import BFGS from ase.build import bulk from ase.dft.bandgap import bandgap from gpaw import GPAW, PW if Path('database.db').is_file(): Path('database.db').unlink() structures = ['Si', 'Ge', 'C'] db = connect('database.db') for f in structures: db.write(bulk(f)) for row in db.select(): atoms = row.toatoms() calc = GPAW(mode=PW(400), kpts=(4, 4, 4), txt=f'{row.formula}-gpaw.txt', xc='LDA') atoms.calc = calc atoms.get_stress() filter = ExpCellFilter(atoms) opt = BFGS(filter) opt.run(fmax=0.05) db.write(atoms=atoms, relaxed=True) for row in db.select(relaxed=True): atoms = row.toatoms() calc = GPAW(mode=PW(400), kpts=(4, 4, 4), txt=f'{row.formula}-gpaw.txt', xc='LDA') atoms.calc = calc atoms.get_potential_energy() bg, _, _ = bandgap(calc=atoms.calc) db.update(row.id, bandgap=bg)
https://wiki.fysik.dtu.dk/ase/tutorials/tut06_database/database.html
CC-MAIN-2020-16
refinedweb
1,147
67.15
by Zoran Horvat May 24, 2013 Given an unsorted array containing N integer numbers, write a function which extracts one page from sorted version of the array. Page is a range of elements occupying positions M, M+1, M+2, ... , M+P-1 in the array, where M marks beginning of the page (0 <= M < N) and P is the page size (M+P-1 < N). Function should place elements belonging to the requested page to their dedicated locations, so that the requested page is sorted when function completes. Example: Suppose that array consists of numbers 6, 2, 5, 7, 8, 3, 1, 4, 9. Pages consist of four elements each (except the last one) and we require second page (M=4, P=4). After modifying the array, numbers 5, 6, 7 and 8 should be located starting from position 4. For example, this array content is a legitimate solution: 9, 2, 1, 3, 5, 6, 7, 8, 4. Note that other values in the array are not relevant, as long as the second page is sorted and in place. Keywords: Array, sorting, pagination. This is obviously a sorting problem and it is trivially solved by sorting the whole array. In that case all elements will be in their proper places in the sorted order, and so will be the requested page. But this solution does more than it is asked for. It prepares all other pages as well, pages into which the caller is not really interested. Imagine an array containing millions of numbers and a call made to the function to sort only elements on positions 50-59, inclusive. This would be the sixth page, where each page contains ten elements. There is no point in sorting the remaining 999,990 numbers in the array. One might think that the caller is likely to call the function many times again, asking for all the other pages, so why not sorting the whole array immediately? The answer is that, when things come to large arrays, it often happens that the caller is interested only in a tiny fraction of data contained. As an illustration, consider a problem of querying a search engine with a relatively general query. The engine might detect millions of Web pages that satisfy the query, but only the first couple of them (say, ten links) will be communicated back to the customer. When customer asks for the second page with results, only then will the search engine bother to sort the following ten links. It rarely happens that any Web user walks more than a couple of pages at length before finding the desired document (or modifying the search query). Sorting the whole result set would be a tremendous waste of resources on the server because user is eventually going to leave without looking into anything beyond the leading few pages. The conclusion is that efficient function should focus only on the requested range of elements. Any operation that does not get us nearer to the goal of bounding that range should be avoided. One way to approach the problem is to modify the sorting algorithm so that it only partially sorts the array. Good candidate for this idea is the QUICKSORT algorithm. Its partitioning step could eliminate quite a lot of elements that fall below or above the requested page. The following picture shows how to extract the second page containing three elements from a somewhat longer array than the one in the previous example. In this example we have not fully sorted the array. When deciding whether to sort elements that fall to one specific side from the pivot element (left or right), we check whether elements on that side overlap with requested positions 3, 4 and 5. If not, then there is no point in sorting that range of the array – such discarded elements are shaded gray in the figure above. As process continues, shaded parts of the array grow larger, until only the requested page remains for sorting. Some of the shaded elements are indeed sorted, but that is the pure coincidence. There is no intention to sort anything below or above the page. This solution is efficient because it tends to identify elements that do not belong to the requested page and to discard them completely from further steps. Note that shaded parts of the array are not sorted at the end of the program execution. This is consequence of the fact that they are ignored by the algorithm. Here is the pseudo-code which solves the pagination problem: function Paginate(a, n, m, p) a – unsorted array n – number of elements in the array m – position of the first element in the page p – page size begin PaginateRecursive(a, 0, n – 1, m, p) end function PaginateRecursive(a, left, right, m, p) a – unsorted array left – position of the first element in current scope right – position of the last element in current scope m – position of the first element in the page p – page size begin pivotPos = Partition(a, left, right) -- Partition function from QUICKSORT -- Recursively paginate elements to the left of the pivot -- if left-hand partition overlaps with requested page -- These elements are located between left and pivotPos-1, inclusively if (left < m + p AND pivotPos – 1 >= m AND pivotPos > left) PaginateRecursive(a, left, pivotPos – 1, m, p) -- Recursively paginate elements to the right of the pivot -- if right-hand partition overlaps with requested page -- These elements are located between pivotPos+1 and right, inclusively if (pivotPos + 1 < m + p AND right >= m AND pivotPos < right) PaginateRecursive(a, pivotPos + 1, right, m, p) end The main function is Paginate – it receives the array, its length and information about the page requested. But this function merely delegates the call to the recursive implementation (PaginateRecursive function), which in turn receives the bounds within the array which are currently in scope. This function relies on the Partition function from QUICKSORT algorithm, for which any implementation will suffice. For example, partitioning could be implemented like this: function Partition(a, left, right) a – unsorted array left – index of the first element of the range to partition right – index of the last element of the range to partition begin pivot = a[left] pos = left + 1 while pos <= right begin if a[pos] < pivot then begin a[left] = a[pos] left = left + 1 pos = pos + 1 end else begin tmp = a[right] a[right] = a[pos] a[pos] = tmp right = right - 1 end end a[left] = pivot return left end In this implementation the first element in the range is picked up to be the pivot. After that, all elements that are strictly less than the pivot are moved towards the beginning of the range and all elements greater or equal to the pivot are moved towards the end of the range. Finally, pivot is placed in between and its new position is returned from the function. Note that this implementation of the partitioning function is not very efficient. It may lead to high worst case running time in case when pivot falls to one or the end of the partitioned range. Readers are advised to provide the Partition function implementation with better pivot selection. Anyway, with this function in place, we are ready to provide the complete pagination solution. Below is implementation for the Paginate function and the two helper functions it relies on. void Paginate(int[] a, int m, int p) { PaginateRecursive(a, 0, a.Length - 1, m, p); } void PaginateRecursive(int[] a, int left, int right, int m, int p) { int pivotPos = Partition(a, left, right); if (left < m + p && pivotPos - 1 >= m && pivotPos > left) PaginateRecursive(a, left, pivotPos - 1, m, p); if (pivotPos + 1 < m + p && right >= m && pivotPos < right) PaginateRecursive(a, pivotPos + 1, right, m, p); } int Partition(int[] a, int left, int right) { int pivot = a[left]; int pos = left + 1; while (pos <= right) { if (a[pos] < pivot) { a[left++] = a[pos++]; } else { int tmp = a[right]; a[right] = a[pos]; a[pos] = tmp; right--; } } a[left] = pivot; return left; } In this section we are providing the complete source code of a console application which demonstrates using the Paginate function. using System; namespace Pagination { class Program { private static Random _rnd = new Random(); public static void ShuffleArray(int[] a) { for (int i = a.Length - 1; i > 0; i--) { int index = _rnd.Next(i + 1); int tmp = a[i]; a[i] = a[index]; a[index] = tmp; } } public static int[] GenerateArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = i + 1; ShuffleArray(a); return a; } public static void Paginate(int[] a, int m, int p) { ... } public static void PaginateRecursive(int[] a, int left, int right, int m, int p) { ... } public static int Partition(int[] a, int left, int right) { ... } public static void PrintArray(int[] a, int m, int p) { for (int i = 0; i < a.Length; i++) Console.Write("{0}{1,2}{2}", i == m ? "[" : " ", a[i], i == m + p - 1 ? "]" : " "); if (m + p > a.Length) Console.Write("]"); Console.WriteLine(); } static void Main(string[] args) { while (true) { Console.Write("n="); int n = int.Parse(Console.ReadLine()); if (n <= 0) break; Console.Write("m="); int m = int.Parse(Console.ReadLine()); Console.Write("p="); int p = int.Parse(Console.ReadLine()); int[] a = GenerateArray(n); Paginate(a, m, p); PrintArray(a, m, p); } Console.Write("Press ENTER to continue... "); Console.ReadLine(); } } } When application is run, it produces output like this: n=10 m=3 p=3 1 3 2 [ 4 5 6] 7 8 10 9 n=15 m=8 p=4 4 3 2 1 5 6 7 8 [ 9 10 11 12] 13 15 14 n=20 m=3 p=3 1 3 2 [ 4 5 6] 7 8 9 10 11 12 20 15 16 19 14 17 18 13 n=0 Press ENTER to continue... Readers are advised to modify existing solution and implement a function which sorts next page in a sequence, assuming that all previous pages, i.e. pages with smaller starting positions, are already sorted. Write a function with this signature: void PaginateNext(int[] a, int m, int p) All elements of the array in range 0 to m-1 are already sorted. On output, function should ensure that all elements on positions 0 to m+p-1 are sorted..
http://codinghelmet.com/exercises/array-pagination
CC-MAIN-2019-04
refinedweb
1,721
57.81
Agenda See also: IRC log -> Accepted. -> Accepted. Our Last Call period ends tomorrow! Vojtech gives regrets; Norm at risk, but Henry will chair in his absence. Revisit after looking at the issues. -> Mohamed asked us to review the kinds of nodes that can go through select/match patterns on steps See Norm's proposed changes to p:replace Accepted. Norm's proposed changes to p:wrap -> Richard: I don't have a strong objection, but I'm a bit dubious about having what nodes are ignorable depend on what's on either end. Vojtech: Can it happen that you have a match that matches an element or a text node. Richard: What about two text nodes with a comment between them? You might want to group those. Norm: I see, that would work according to the old rules. Rejected, stick with the status quo. Norm: Then Mohamed and I had a short discussion about p:insert, ending with: -> Norm's proposed changes to p:insert Accepted. Richard: Just a moment. Suppose the match pattern matches a PI before the document element. Norm: Then we could just let the natural failure mode handle that. Richard: If we have an error for producing a document that's not well formed, then we could remove that case--we don't need a special error for it. ... Then we could use error 25 for just the case that doesn't make any sense. Norm: I'm happy with that. Proposal: Adopt Norm's proposal with Richard's change to error 25. Accepted. Vojtech: In p:replace, we say that we can only replace elements. ... Isn't that like p:insert? Norm: Yes, I must have overlooked that one. ... So, we should allow match on p:replace to match elements, comments, PIs, and text nodes? Proposal: Change p:replace as suggested Accepted. Norm: I misunderstood issue 020 last time we talked about it. I thought it was about XML encryption/decryption, effectively a dup of the other one. ... But in fact, it's about text-encrypt, a la gnupg. ... I dont' think we ahve a use case for that, so I'm inclined to reject it. ... If we did add it, it would be a little complicated because it would need to be a wrapper. Richard: Henry suggested we should allow the relevant WGs to invent their own libraries. Alex: Right. We let users create new steps, so they can do it. ... We'll revisit in 1.1 or 2.0 or something. Norm: Yes, but we have an encyption/decryption use case in our requirements document, so I'm a little worried. Richard: Presumably we aren't required to do it if we have a good explanation. Not having the expertise seems like a good reason. Norm: I'm content to leave the *XML* encryption/decryption case open until after we've been able to speak with the XML Security WG. ... This issue is about text encryption. Proposal: Reject this issue. Accepted, no new steps for text encryption/decryption -> Norm summarizes Norm: I've done my best, does anyone have any other or better suggestions? ... Ok, then I'd like to close the issue. Accepted. Norm: I addressed this by changing the definintion in-scope variables in 2.6.2.1. <scribe> ACTION 2008-09-25-01: Norm to make the parallel change in 2.6.1.1 [recorded in] Norm summarizes the changes: defining in-scope variables as being the "specified options" and adding a note about unspecified options. Norm: Does anyone think that that fails to adequately resolve the issue? Proposal: That resolves the issue. Accepted. Norm: The change here is wrt the type of options, variables, and parameters ... I've changed the introductory sections to say that the values "MUST be a string or xs:untypedAtomic" where they used to say "MUST be a string". ... I felt that was necessary for consistency with the actual definitions later on. ... Does anyone have reservations about that change? Proposal: That's fine. Accepted. Norm: Let's go through this one. ... I'm inclined to agree with point 1. No objections. Richard: It's ok as long as none of *our* steps have any implementation-defined ones. ... Do they want XProc implementations to be allowed to have extra pre-defined namespaces, or whether they merely want it to be possible for certain steps to have certain pre-defined namespaces. <scribe> ACTION 2008-09-25-02: Norm to follow-up with the XQuery/XSL WGs on this point. [recorded in] Norm: The only other non-editorial comment is about the XQuery step. I'm inclined to accept comments from the XQuery WG about the p:xquery step. Sounds ok. Norm: I'll try to address these in the next draft and bring back any issues that I see. Norm: I'm inclined to make no change. Proposal: Stick with the status quo Accepted. Vojtech: Someone asked on xproc-dev what the definition of the XSLT match pattern is; is there a clear definition? We should try to clarify that. Norm: I'm happy to point a little more explicitly to the respective definitions of Pattern in XSLT 1.0 and 2.0. <scribe> ACTION 2008-09-25-03: Norm to make the XSLTMatchPattern reference a little more explcit [recorded in] Adjourned.
http://www.w3.org/XML/XProc/2008/09/25-minutes.html
CC-MAIN-2014-41
refinedweb
885
76.11
Multi Conditionals There have been actually several times as I’m writing servers in things like my JDB project and the TridentSDK project in which the following scenario pops up: there is a single thread that manages incoming and outgoing messages. I need to block on an outgoing queue, as well as block until some bytes off the network are read. My situation looks something like the following: BlockingQueue<Message> incoming; BlockingQueue<Message> outgoing; while (true) { if (hasInput()) { // Read into incoming } else if (!outgoing.isEmpty()) { // Write from outgoing } else { // Block, wait for input or output } } boolean hasInput(); Data waitForInput(); void writeToOutput(Message send); Message consumers will block on the incoming queue and wait for input from the socket to be read by the I/O loop in order to process those messages. Given this scenario, how might the I/O loop be implemented in order to block on network input as well as the outgoing queue and wait until either of the two have I/O tasks to execute? Naive Solution: Subsequent take()s A simple, first-thought, although naive solution might look something like the following: while (true) { Message recv = new Message(waitForInput()); incoming.add(recv); Message send = outgoing.take(); writeToOutput(send); } This will not work correctly. Because the loop must wait for input, the second blocking method, outgoing.take(), will not be reached until a message is received. Therefore, a message that is queued to be sent cannot be unless something is received first - and what if the client is written in the same way? There will be a deadlock because the client must depend on input from the server in order to send a message, but the server is in fact also waiting to receive a message that will never come from the waiting client. So it can be seen that this method both does not work as intended and will cause risks with client-server deadlock. Naive Solution: Single lock/Condition A second tempting solution is to protect the incoming queue and the outgoing queue with a single lock/ Condition. Assuming the same context: Lock lock = new ReentrantLock(); Condition cond = lock.newCondition(); while (true) { // Await for a signal from a message producer // adding to the outgoing queue // Spurious wakeup checked by conditions below cond.await(); if (hasInput()) { Message recv = new Message(waitForInput()); if (recv != null) { lock.lock(); try { incoming.add(recv); cond.signal(); // Signal the message consumer } else { lock.unlock(); } } } Message send; lock.lock(); try { send = outgoing.poll(); } finally { lock.unlock(); } if (send != null) { writeToOutput(send); } } However, there still exists several issues with this code. Firstly, cond.await() will block only on the outgoing queue, and ignore network input. This will have the opposite effect as the earlier naive solution in which there requires network input for there to be output; in this case, the I/O thread will, in fact, have to wait for output in order for input to be read. In truth, we can try all different kinds of combinations of switching different Conditions and different mechanisms of all sorts without succeeding, there is simply no way to wait on both the reading from socket and simultaneously the outgoing queue. Further, a thread blocked on network input is not blocked on a lock or Condition or whatever - it remains in RUNNABLE mode, so it might as well be busy waiting for all other observers can care. After exhausting these ideas, I too thought that it would be impossible to act on events rather than having to use a timer and step over the other blocked method in order to check either input or output depending on what is blocked. Fortunately, there is a way. The Solution In order for my I/O thread to correctly handle I/O input, it must be interruptible. Thankfully, by switching to java.nio, this functionality can be achieved with InterruptibleChannel. I was able to override the default interrupt handler and use the following little utility I made to notify the I/O thread: import sun.nio.ch.Interruptible; import java.lang.reflect.Field; import java.nio.channels.SocketChannel; /** * Utility class used to modify {@link SocketChannel}s in * order to override the default behavior and allow for I/O * threads to capture {@link Signal}s passed while waiting * for input. * * <p>Be aware that this is an extremely egregious hack. * For the most part, it is a toy. I don't expect that * anyone would seriously consider using this in production, * but if there is any case where that occurs, I am not * responsible for what happens. Use at your own risk. You * have been warned.</p> * * <p>To add further to the risks associated with this * class, one must <strong>NEVER</strong> call {@link * Thread#interrupt()} on an I/O thread. Doing so may * result in undefined behavior. Capturing a {@link Signal} * also means that the I/O thread must use * {@link Thread#interrupted()} in order to clear the * interrupt state before the next signal. Finally, * {@link Thread#interrupt()} is used in order to propagate * signals to the I/O thread, and therefore, if any methods * that are interruptible must catch the exception and run * {@link Thread#interrupted()}.</p> */ public final class SocketInterruptUtil { /** The cached field used to hack the SocketChannel */ private static final Field INTERRUPTOR; /** The signal used to notify readers */ private static final Signal SIGNAL = new Signal(); static { try { Class<?> cls = Class.forName("java.nio.channels.spi.AbstractInterruptibleChannel"); INTERRUPTOR = cls.getDeclaredField("interruptor"); INTERRUPTOR.setAccessible(true); } catch (NoSuchFieldException e) { System.out.println("No such field: interruptor"); System.out.println("Perhaps not running Oracle HotSpot?"); throw new RuntimeException(e); } catch (ClassNotFoundException e) { System.out.println("No such class: AbstractInterruptibleChannel"); System.out.println("Perhaps not running Oracle HotSpot?"); throw new RuntimeException(e); } } // Suppress instantiation private SocketInterruptUtil() { } /** * Prepares the {@link SocketChannel} to receive * {@link Signal}s dispatched by another thread. This * is required in order for this to work correctly. * * @param ch the channel to prepare */ public static void prepare(SocketChannel ch) { try { INTERRUPTOR.set(ch, (Interruptible) thread -> { throw SIGNAL; }); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * Signals the given I/O thread to unblock from ALL * blocking methods and proceed and throws a * {@link Signal} to be handled by the thread. * * @param thread the thread to unblock */ public static void signal(Thread thread) { try { // Thread probably not blocked on I/O if (thread.getState() != Thread.State.RUNNABLE) { return; } thread.interrupt(); } catch (Signal ignored) { } } /** * A signal dispatched by another thread to a target * I/O thread in order for targets to respond to * notifications. */ public static class Signal extends RuntimeException { private static final long serialVersionUID = -220295899772322553L; } } A correct usage of the class would look something like the following: ServerSocketChannel server = ServerSocketChannel.open(); ... while (true) { SocketChannel ch = server.accept(); SocketInterruptUtil.prepare(ch); while (ch.isOpen()) { try { ByteBuffer buf = ... ch.read(buf); Message msg = new Message(buf); incoming.add(msg); } catch (Signal signal) { Message msg = outgoing.poll(); writeToOutput(msg); Thread.interrupted(); } catch (InterruptedException e) { Thread.interrupted(); } } // Normally you would also need to have another // catch for Signal/InterruptedException here // However, you'd also need to check to make // sure that there is an active connection, so // I can just check to make sure that there is // at least a connected SocketChannel before // signalling and get rid of the try/catch. } And for the outgoing logic: outgoing.add(msg); SocketInterruptUtil.signal(ioThread); Discussion In order for this to work, I made a slightly (OK, really) hacky solution to default InterruptibleChannel functionality. I found that what InterruptibleChannel did was put an interrupt listener before every single blocking call in order to close the socket if either the blocked thread is interrupted or if the socket was closed. I couldn’t put in my own handler because I can only override before or after the blocking method, in which my own handler would be overridden by the interrupt handler provided by the method itself. Therefore, I went one step deeper and overrode the cached instance of the interrupt handler inside of InterruptibleChannel to exit early and throw my own Signal which can be caught by the I/O thread. I haven’t deeply investigated the performance of this method over perhaps timed busy waiting, but from testing, a blocked read can respond to signals in sub-millisecond times even when saturated with messages between “10 nanosecond intervals” on an i3-3240. A while loop probably takes more than 10ns to run which is why I mention that rate in quotes, but again, this time is very impressive even if it’s off by a bit. You wouldn’t want to be waking a thread every 1 millisecond in order to check for the other condition, which is why I say that it’s good in comparison with the alternative. Unfortunately, this technique is risky in many ways, first of all, because it depends on there being the AbstractInterruptibleChannel SPI class being available, as well as the field being available. The field probably won’t be going away because caching is required, but the class itself might. Additionally, the interrupt status of the thread is risky to play around with and requires Thread.interrupted() to be called each time either Signal is thrown or InterruptedException is captured if the signal(Thread) method misses the I/O portion. Otherwise, the thread itself might die. Finally, the only possible way to exit directly out of a blocking read(...) is to throw the exception, but if a read is halfway done, then the behavior may be undefined. I will need to test further in order to determine what happens, but until then, this class still remains a very risky hack. I would highly advise against using it in a production environment, regardless of whatever performance gains may bear fruit through event-driven notifications rather than spurious wakeups. I have included a warning in the class javadoc comment to cover my ass, so please don’t push it :) In the end, even though I have acheived what I was hoping for, even if it isn’t really viable in the real-world, I guess I will just have to keep searching for a better solution. Closing Words Figuring this all out was an interesting use of 3 hours. I’m completely done with this though, I’m not looking to play around anymore with it, but anyone else can feel free to do so themself. My plan is to update the “On Thread Safety” post very soon though, and there is more to come over winter break. Take care everyone!
https://agenttroll.github.io/blog/2017/12/21/multi-conditionals.html
CC-MAIN-2020-29
refinedweb
1,749
53.92
CodePlexProject Hosting for Open Source Software I'm using the updated Orchard.Disqus module (which you can find here) to enable Disqus for my Orchard 1.6 site. The module is installed and appears to be functioning properly, but none of the comments are showing up. The module includes a command ("disqus comments import"), but although Orchard.Disqus is showing up as enabled when I open the command line tool and use: feature list /Summary:true if I try to execute the command, I get the response: 'No command found matching arguments "disqus comments import".' As far as I can tell from checking the source, the command should work, but for some reason Orchard isn't making the command available. Am I missing something about how commands get wired up? If a module is installed properly, and has a command that inherits from DefaultOrchardCommandHandler, what would prevent that command from being available in the CLI? No, that should work. Anything in logs? bertrandleroy wrote: No, that should work. Anything in logs? I checked the logs, but didn't see anything that was obviously related. I tested by renaming the old log, starting a new command line session and attempting to execute the command again. Unfortunately, nothing's showing up in the log when I attempt to execute the command. BTW, the code for the commands is super-simple, and can be viewed here: To clarify...the module code doesn't specifically need to be built with Orchard itself, correct? Any other suggestions for troubleshooting commands? PS - This is a clean install of 1.6, with content imported via the import/export module. I was having some issues with my existing Orchard site, which I had upgraded from an earlier version. I did find the following in the logs, but the time of the exception is way earlier than when I was working with the command line: 2012-12-06 15:24:46,662 [13] Orchard.Exceptions.DefaultExceptionPolicy - An unexpected exception was caught System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Orchard.OrchardCoreException: Recipe execution with id 95699c3296964b21bb1ddcd07f03fb87 was cancelled because the "Feature" step failed to execute. The following exception was thrown: Sequence contains no matching element. Refer to the recipe journal for more information. Could the above be an exception that occurred during installation of the module? Where would I find the recipe journal to look for more information? Is there an OrchardFeature attribute on the command's class? No, but going through the other modules, I noticed that there are several that do not, but whose commands work fine (blog module, themes module, etc.). I tried adding one, like so: [OrchardFeature("Orchard.Disqus")] public class DisqusCommands : DefaultOrchardCommandHandler but it made no difference in the behavior of the command line tool. Still gives me the same error message. Based on this issue filed: it's pretty clear that the wiring up of the command worked for someone, even if they had issues with the actual import process. Other ideas? The only way to sort this out is probably to attach a debugger and step into the code that discovers the commands. Probably best to file a bug in any case. I have the same issue. The module is installed but doesn't seem to work/show or anything!! Please file a bug. Bug filed: And created a clean workflow for a repro. Thanks! Much appreciated. Any news on this ? I just migrated to 6.0 ... having same problem ... Disqus comments enabled, but do not appear .... AND CHECK THIS OUT ... DISQUS COMMENTS WORK WHEN USING WEBMATRIX .... the go back to IIS ... not only does Disqus not show up for posting a new comment ... but the comment does not show up on the blog page ... Bertrand ... No action on this in over a month ??? What's going on ?? I can't go into production without Disqus ... please escalate the priority ... Please note that this bug is scheduled for Orchard 1.7, However if you need help right now are you able to debug? I can tell you where to put break points etc... I have looked at the bug and cannot reproduce. Can someone tell me if I have done anything wrong? - All info on the Issue. @tsaltd: thanks for filing the bug. It will be looked at, but we have close to 900 proposed or active bugs at this time, out of which more than 160 have more votes. This is an open source project, that depends on people like you and me contributing patches. This can take time (a lot of time in some cases). In other words, we have a lot on our hands. If you need a bug fixed urgently, you can do three things: * convince a regular contributor that this bug is more important or blocking than the other 900. This will be the case for example if it's a serious regression affecting a lot of people, if it's a security issue, or if it's causing irreversible data damage. * fix it yourself * find someone who would be willing to fix it, maybe for a fee I hope this helps. doesn't really help ... guess I'll have to go back to 1.4 ... but seriously ... what is the qa process ?? I don't understand why a broken feature that was working in an earlier release isn't caught by tdd ... seems like some process improvement is in order ... Disqus is not a part of your test harness ?? "we have close to 900 proposed or active bugs at this time" - seems to me that backward compatibility bugs deserve to be at the top of the list ... and I didn't "file the bug" ... it was reported in December ... My bad for not checking before I upgraded ... but the Orchard team won my confidence so I didn't think I was taking a risk by investing in the upgrade ... What's the best case for getting this fixed ?? Seems like the problem should be pretty easy to detect since it works with Web Matrix I've migrated to the new menuing features ( nice job ) ... but do have a backup of my 1.4 solution. OP's who have reported this problem ... Pls let the team that this fix deserves priority .... Steve No, Disqus is not part of our test harness. There are almost 500 different modules on the gallery. We can't test them all. I understand that this bug is important to you, but the other bugs are all also important to someone. Some of the other bugs are regressions as well. We don't have a full-time QA team (or a full-time team at all), so we need to rely on people donating part of their time to improve Orchard. We do triage publicly during the podcast recording every Tuesday at 12:00PM Pacific Time on. You are more than welcome to come to the meeting and defend your bug. All constructive suggestions and contributions are welcome as always, including on process. Nick tried to reproduce the problem and was unable to. He also offered to help and collaborate with you in reproducing. I think you should accept that offer. Just saying... wait ... from this thread it seems as if the bug is not yet resolved ... not sure what it means that "nick was unable" ... are you saying that he get Disqus to run under Orchard 1.6 using IIS ? I'm looking for a message from Nick here or on Codeplex .... I do want to contribute but I'm rather specialized on back-end and middle tier - and web services ... most recently WEB API stuff with MVC 4.Web API ... Maybe I could get involved with some TDD / QA tasks ... who is heading that up ? Please let me know of others have been sucessful with Orchard 1.6 / IIS and Disqus -- also have a SQL repository .... Good luck with the other prority stuff. Steve Nick should answer this one, yes. By the way, is this the module you're using? yes tried the oneStop version ... no help ... it did not indicate that it is V 1.0 ... still v .9 .... Frustrating thing is that Disqus runs using the same directory where my IIS Site is installed using Web Matrix ( tho the Disqus icon does not appear in the aside left panel on Dashboard -- so can't configure it --- but it works ... posts comments using Disqus UI on my orchard blogs .. and forwards those posts to Disqus using the Twitter, Facebook, G+, and basic email sign on protocols. But does not work on IIS ... a 1.4 orchard site with Disqus installed shows the "gear" icon in the aside left panel - in no case ... IIS or Web Matrix does it appear in 1.6 I will move the same Orchard and SQL backupa to another Windows Server to see if that may make a difference On IIS all kinds of wierd things happen .... Module gallery tells me I have to upgrade to newer version of Disqus ... have to wait a long time until the hyperlinks to display in browser and after I re-install it still tells me that I need to upgrade .... ( but I did experiment with the oneStop version too ) Still my ? is ... has anyone gotten Disqus to work on IIS 7 with a Orchard 1.6 site ??? From the metrics on the Orchard Disqus site there are a significant number of Disqus downloads / installs ... but there are not many problem reports ?? More later .. Stack Trace: [InvalidOperationException: Sequence contains no matching element] at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate) at Orchard.Environment.Features.FeatureManager.<>c__DisplayClass2d.<EnableFeature>b__20(String fId) in C:\Business\De velopment\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\FeatureManager.cs:line 148 at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext() at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext() at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elemen tSelector, IEqualityComparer`1 comparer) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elemen tSelector) at Orchard.Environment.Features.FeatureManager.<EnableFeature>b__1e(String currentFeatureId, IDictionary`2 featuresSt ate) in C:\Business\Development\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\FeatureManager.cs:l ine 147 at Orchard.Environment.Features.FeatureManager.GetAffectedFeatures(String featureId, IDictionary`2 features, Func`3 g etAffectedDependencies) in C:\Business\Development\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\ FeatureManager.cs:line 195 at Orchard.Environment.Features.FeatureManager.EnableFeature(String featureId, IDictionary`2 availableFeatures, Boole an force) in C:\Business\Development\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\FeatureManager .cs:line 153 at Orchard.Environment.Features.FeatureManager.<>c__DisplayClass9.<EnableFeatures>b__4(String featureId) in C:\Busine ss\Development\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\FeatureManager.cs:line 73 at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Orchard.Environment.Features.FeatureManager.EnableFeatures(IEnumerable`1 featureIds, Boolean force) in C:\Business \Development\Clients\EricaZap\Orchard.Source.1.6\src\Orchard\Environment\Features\FeatureManager.cs:line 72 at Orchard.Modules.Services.ModuleService.EnableFeatures(IEnumerable`1 featureIds, Boolean force) at Orchard.Modules.Commands.FeatureCommands.Enable(String[] featureNames) Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/405905
CC-MAIN-2017-17
refinedweb
1,927
51.85
How could I take input like A=30 B=10 How could I take input like Your query is not so clear that how output is given. 1). if 30 and 10 have a space between them then A,B = [int(x) for x in input().split()] or equal to map(int,input().split()) input().split(’ ‘) splita strings with ’ ’ and int(x) for x or map(int, )convert those strings to integers. extra- input().split(’,’) can be used to take 2,3 input. 2). if 30 and 10 are in different lines then A = int(input()) B = int(input()) go to additional link- Taking multiple inputs from user in Python - GeeksforGeeks Fastest answer (in terms of runtime): import sys a,b = list(map(int, sys.stdin.readline().split())) Naive method: - Read an Entire line as String: line = input() - Read a line containing a Single Integer num = int(input()) - Read a pair of Space separated Integers num1, num2 = map(int, input().split()) - Read a triple of Space separated Integers num1, num2, num3 = map(int, input().split()) - Read a line containing a single, real number f = float(input()) - Read a pair of space separated Real Numbers f1, f2 = map(float, input().split()) - Read a pair of space separated Strings s1, s2 = map(str, input().split()) - Read a list of Integers arr = list(map(int, input().split())) - (Trickier) Read a line containing a string and an Integer s, num = map(str, input().split()) # Consider both of them as Strings num = int(num) # Convert num to int Efficient Method (Recommended for Fast IO): - Declaration part from sys import stdin, stdout read = stdin.readline # read holds the reference to function - Read an Entire line as String: line = read() - Read a line containing a Single Integer num = int(read()) - Read a pair of Space Separated Integers num1, num2 = map(int, read().split()) - Read a list of Space separated Integers arr = list(map(int, read().split())) And so on. If you still need help, feel free to ask. Using a list and then unpacking it into two or more integers would add a very little overhead. The following is little better than the above one. a, b = map(int, stdin.readline().split()) Nice Thanks a,b=input().split() _,a=a.split("=") _,b=b.split("=") After doing this convert both the value in integer using int() I will try to cover various input types. Single input as string- S s = input() Multiple strings on different line- S_{1} S_{2} s1 = input() s2 = input() Multiple space separated strings on same line- S_{1} S_{2} s1, s2 = tuple(input().split()) Single input as integer- N n = int(input()) Multiple integers on different line- N_{1} N_{2} n1 = int(input()) n2 = int(input()) Multiple space separated integers on same line- N_{1} N_{2} n1,n2 = map(int,input().split()) Array of space separated integers - A_{1}\ A_{2}\ A_{3}\ A_{4}\ A_{5}\ \cdots \ A_{N} A = list(map(int,input().split())) Matrix of integers as input-} grid = [list(map(int,input().split())) for i in range m] Something about the split method- It is the method available for string (and so it is applied on strings only) which returns a list of string which are separated on the basis of delimiter(the default argument is whitespace). Map function - We are using map function here because once we have created a list of strings using the split method now we want to change their type. Map takes arguments as function and an iterable (here int is a function and the list of strings is the iterable object). import sys A,B = list(map(int, sys.stdin.readline().split())) print(A, B) alternate solution for different lines of input: A=int(input()) B=int(input()) print(A, B) this might help you
https://discuss.codechef.com/t/python-input/87054
CC-MAIN-2021-49
refinedweb
637
62.38
note almut <p> For PDF to JPG (or any other raster image format like PNG or TIFF), you could use GhostScript to do the conversion: </p> <c> $ gs -q -dBATCH -dNOPAUSE -sDEVICE=jpeg -dJPEGQ88 -r150 -sOutputFile=img%d.jpg input.pdf </c> <p> This would create as many images (<c>img1.jpg</c> to <c>imgN.jpg</c>) as there are pages in the PDF file. <c>-r</c> is the resolution in dpi (150dpi would create an image size of 1240x1754 for A4 paper size), and <c>-dJPEGQ</c> is the quality factor (up to 100). </p> <p>. </p> <p> ImageMagick's <c>convert</c> can be used for the latter. The complete sequence of steps would be: </p> <c> $ gs -q -dBATCH -dNOPAUSE -sDEVICE=jpeg -dJPEGQ88 -r600 -sOutputFile=img%d.jpg input.pdf $ for img in img*.jpg ; do convert $img -filter Lanczos -resize 25% -quality 90 out_$img ; done </c> <p> The resulting anti-aliased images <c>out_img*.jpg</c> would then have 150dpi resolution. </p> <p> In case you have the non-<c>/usr/bin</c>-namespace-polluting sister <i>Graphics</i>Magick installed (instead of ImageMagick), the command would be <c>gm convert ...</c> </p> <p> (Those who hold a degree in Signal Processing - or have come in contact with filter design in some other context - might want to take a look at the [] of filters to choose from — in case of doubt, stick with Lanczos or Kaiser for somewhat sharper, or Gaussian or Cubic for somewhat softer results.) </p> <p> Also, there's documentation - well hidden from daylight - under <c>/usr/share/doc/ghostscript/Devices.htm</c>, which explains what options are available with the individual Ghostscript output devices (you usually need to have another package installed (e.g. <c>ghostscript-doc</c> on Debian/Ubuntu) to have that file). </p> 794904 794904
http://www.perlmonks.org/index.pl?displaytype=xml;node_id=794918
CC-MAIN-2018-09
refinedweb
309
63.59
Stephan T. Lavavej: Core C++, 1 of n - Posted: May 16, 2012 at 7:21 AM - 132,763 Views - 52 Comments Something went wrong getting user information from Channel 9 Something went wrong getting user information from MSDN Something went wrong getting the Visual Studio Achievements Right click “Save as…” In part 1, STL focuses on Name Lookup, which is a surprisingly complex process. Remember Herb Sutter's great GotW post (#30, to be precise) on Name Lookup? Here's the problem from that post, to refresh your memory (Thanks to Herb for providing information like this on GotW!): In the following code, which functions are called? Why? Analyze the implications? namespace A { struct X; struct Y; void f( int ); void g( X ); } namespace B { void f( int i ) { f( i ); // which f()? } void g( A::X x ) { g( x ); // which g()? } void h( A::Y y ) { h( y ); // which h()? } } We recommend you watch this entire episode before playing around with Herb's sample above (and don't read the GotW answer, either! That's cheating. Learn from STL. He's an outstanding teacher, as you know.) Please supply feedback on this thread, especially as it relates to what you'd like STL to focus on in subsequent episodes. For part 2, STL will focus on Template Argument Deduction.! STL. Thank you for new topics that I expect. Awesome. Another c++ series, awesome ! This is great! so cool, I admit these c++ series We welcome you!!! Thanks for beings with us. Cheers. As a C# dev this helped me understand the syntax (:: << etc) more than anything. Most of the rules seem quite similar to the C# rules which is nice. Good work. Thank you for a wonderful presentation. For your next episode on this topic would you cover these topics 0) C/C++ run-time startup functions,lifecycle, ie: initialization, how C/C++ startup function calls your application's entry-point function 1) Virtual functions and the Run time cost of virtual functions & dynamic binding. 2) forward declaration. Forward declaration of template classes 3) difference between template <class T> MyClass template <typename T> MyClass Offtopic: About Chemists and Physicists: Add a vote to Kayvan (1) Virtual functions :-) I also would like to see forward declarations. I'm also curious about typedef and as much as possible about the Preprocessor if that's considered part of the core c++. Thanks. Great video STL Great video STL. Can't wait to watch more episodes. Feel free to just go over each clause in the spec! Outstanding. A lot of STL's topics go over my head, but this is exactly along the lines of what I need. Very happy to see someone so knowledgeable explaining core concepts of the language! Excellent lecture. What I love about C++ is its complexity and that some operations in the language are undefined. This allows you to go even further than just learning C++. You can research C++. I barely managed to watch this episode, but not because STL is bad but because I really dont care that much about language rules, but since STL is so cool I maganed to watch it. @STL 1.Regarding episode 2 dont forgett to mention pointer paradox. I learned about it from a horrible horrible Di Gennaro's TMP book. 2. Do you know why there arent trie_(multi)set and trie_(multi)map in boost or std? To obscure? 3. One of the cool lectures (using TMP) would be solving this problem (if possible) : with TMP 4. Explanation of some Boost TMP magic would be nice... maybe even you can get some cool boost guest lecturer :) 5. Idioms are a cool topic imho. Like I said I dont care that much about lang rules, but I like learning idiomatic way of programming in language X. Another classic. I've been using this language for almost 18 years and Stephan clear up some of the name resolution stuff for me in this video. Looking forward very much to the template resolution stuff. This was a pretty great video, I actually program c++ for 5 years and I was not aware of argument lookup and name space alias syntax thank you STL and I hope this n seris continue to n == infint. I actually have one question when you std::cout something in c++ why don't you include just iostream and you include ostream too I think iosteam will provide the ostream functions and objects too. So I take it that the next standard library is ready to ship (at least the template part)? It's good to have you back, Stephan. Thanks for watching, everyone. I'm always a little nervous when I spend 45 minutes talking to an empty room, because it's hard to tell whether I'm going too fast or too slow, too complicated or too simple. Your feedback really helps when targeting future episodes. LeeCampbell> As a C# dev this helped me understand the syntax (:: << etc) more than anything. I'm glad to hear that. My goal in all of these episodes is to give you a taste and a general overview of the topic, making it easier to understand other videos/articles/books. LeeCampbell> Most of the rules seem quite similar to the C# rules which is nice. "Wow, people in Britain speak a language that's really similar to America's!" :-> kayvan> 0) C/C++ run-time startup functions,lifecycle, ie: initialization, how C/C++ startup function calls your application's entry-point function This is outside my area of expertise (as far as I'm concerned, magic invokes main()), but I bet Charles could ask our CRT maintainer, Mahmoud Saleh, to cover this. kayvan> 1) Virtual functions and the Run time cost of virtual functions & dynamic binding. kayvan> 2) forward declaration. Forward declaration of template classes Got it. I was definitely planning to cover virtual functions (in particular, my favorite NVI idiom), but I had forgotten how important the subject of declarations versus definitions is. I'll cover that at the first available opportunity. kayvan> 3) difference between template <class T> MyClass [and] template <typename T> MyClass There is none! :-> (Only template template parameters care about typename versus class - and that is not a repeated word typo.) I personally prefer "typename", because "class" has confusing connotations (it does NOT restrict T to class types; int remains perfectly acceptable). AceHack> I'm also curious about typedef Cool. I'll see if I can cover this in an episode along with other smaller features. (Unfortunately I can't demonstrate C++11's alias-declarations with the "using" keyword.) There are nontrivial bits here, like typedeffing function pointers. AceHack> and as much as possible about the Preprocessor if that's considered part of the core c++. It is, although the preprocessor is really a primitive text-manipulating language that's applied before C++ itself is compiled. Chris> What I love about C++ is its complexity and that some operations in the language are undefined. Of course, C++ doesn't go out of its way to be complicated. Most of the complexity is there for a reason - usually to support tricky code, sometimes to support backwards compatibility (as obnoxious as it may be, C++'s compatibility with C remains a strength). As for undefined behavior, that usually exists because something is difficult to detect, and leaving it undefined permits significant optimizations. Ivan> I barely managed to watch this episode, but not because STL is bad but because I really dont care that much about language rules Heh. Remember, I'm not really interested in the Core Language as an end in itself. It's just that because it underlies all programming, and as a library developer I deal with very tricky code for a living, having a thorough understanding of Core is invaluable. It lets me write code with a complete understanding of how it's going to behave (users can do lots of things with the Standard Library and we have to be prepared for the crazy stuff they're going to inflict on us). Understanding the Core Language also makes it a lot easier to understand compiler warnings and errors. That speeds up my development cycle, and having no fear allows me to use complicated constructs more extensively. (Some programmers, fearing template errors, avoid templates when they would be a superior solution that would allow them to write cleaner code.) Ivan> 1. Regarding episode 2 dont forgett to mention pointer paradox. I haven't heard of that - perhaps I know it by another name. Ivan> 2. Do you know why there arent trie_(multi)set and trie_(multi)map in boost or std? To obscure? The Boost Graph Library could probably be used to construct tries. Both Boost and the Standard are developed by volunteers, so they consist of things that someone has had the time and motivation to develop/specify. (I got started with C++ by implementing suffix trees, which are a special case of tries.) Ivan> 3. One of the cool lectures (using TMP) would be solving this problem (if possible) : with TMP Interesting - I will see if I can find some time to play around with it (which is how I did my Nurikabe episodes). formally specifies the problem. Ivan> 5. Idioms are a cool topic imho. Like I said I dont care that much about lang rules, but I like learning idiomatic way of programming in language X. I'll definitely cover the Non-Virtual Interface idiom. dot_tom> I've been using this language for almost 18 years and Stephan clear up some of the name resolution stuff for me in this video. Sweet! Guest> I actually have one question when you std::cout something in c++ why don't you include just iostream and you include ostream too I think iosteam will provide the ostream functions and objects too. This is actually an interesting story. In C++98/03, <iostream> provides cout but not endl, which lives in <ostream>. I followed those rules strictly. In C++11, <iostream> is now required to include (or behave as if it includes) <ostream>. I actually just learned this at BoostCon/C++Now! 2012, and one of my todos when I get back to Redmond is to check whether we've implemented this in VC11. Thanks for the video, I am looking forward to the rest of them! As for typename vs class, I just stumbled upon this a few weeks ago => @STL Tnx for the answers... Regarding trie also I guess it is tricky to define what would be a "charachter" for for example int->MyClass map. 8 Bits of the int, Decimal digits of the int... ? Ivan> 1. Regarding episode 2 dont forgett to mention pointer paradox. I haven't heard of that - perhaps I know it by another name. If I remember it correctly : whoAmI(const T& ) { std::cout << "Im a reference" << std::endl; } template <typename T> void whoAmI(const T* ) { std::cout << "Im a ptr" << std::endl; } int *p; whoAmI(p); Hey STL! Nice video as always. Detailed explanations of strict aliasing and alignment would be very appreciated for future episodes. :) Hello I don't really understand the "More episodes in this show" div... if I can't see any next chapter of this, means that there are not ready yet, right? There are other interesting videos but... Btw thanks Stephan yo actually answer your emails! You're great, thanks. @ArmandoMeabe -"this show" is Going Deep, it includes a lot of stuff but this is the first and so far only episode of Core C++ :) Stephan, this question is not related to the lecture, but I hope you can answer it. When you ask for the size of STL containers, do you store it in std::container<T>::size_type or std::size_t? The standard says that for some containers size_type == size_t and for others it's implementation defined. Great job with the video. Can't wait for the next ones. Are they gonna be released on a schedule? Thank you, Vish @Chris Just use std::size_t. It'll be sufficient for all size_types. However, with C++11, why not just using auto? :) @Vish: Well, they'll be released on STL's schedule. which is rather full with shipping VC11 We'll try to get these out as often as possible. We'll have the studio ready for STL when the windows open, for sure. C Ivan: When overloading foo(const T&) and foo(const T *), and calling foo() with int *, what happens is the sequence of steps that I described briefly in this Part 1. Template argument deduction runs, producing the signatures foo(int * const &) and foo(const int *). Then overload resolution runs. The first overload binds the reference parameter directly to the argument, so this is considered an identity conversion (i.e. the best, Exact Match). The second overload converts int * to const int *, which is a qualification conversion, but still considered an Exact Match. Finally, a tiebreaker is applied: the first overload's "identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence" (N3376 13.3.3.2 [over.ics.rank]/3) like the second overload's. Therefore the reference overload wins. It's subtle, but I don't think it's worthy of a name because I don't construct such overload sets. (Part of how I deal with the Core Language's complexity is knowing when and how to sidestep scenarios that will hurt my head.) Dispatching on properties of a type can be tricky, and I prefer to use techniques where I don't have to dig deeply into clause 13 in order to figure out what overload resolution will do. (Template argument deduction is fairly easy to follow, it's overload resolution's rules that can be intricate since it's trying to apply rigid rules in order to produce the fuzzy result of what a human would consider to be the "best" match.) I might actually use this example in Parts 2 and 3. Name> Detailed explanations of strict aliasing and alignment would be very appreciated for future episodes. Alignment might be enough to fill a whole episode. According to my understanding, VC's optimizer doesn't attempt to exploit C++'s strict aliasing rules (whereas GCC does), so I'm not sure what I could demonstrate there. ArmandoMeabe> Btw thanks Stephan yo actually answer your emails! You're great, thanks. I live to serve. :-> (When I'm not on vacation playing Diablo III.) Chris> When you ask for the size of STL containers, do you store it in std::container<T>::size_type or std::size_t? In my own code, size_t. I am comfortable with assuming that the Standard containers will behave sanely. In the STL, however, I would be paranoid and ask for size_type. That would deal with user-defined containers (or user-defined specializations of Standard containers) which may have weird size_types. Vish> Are they gonna be released on a schedule? Like Charles said - remember that I am a dual-use technology ( ) and as much as I'd like to film videos and write blog posts all day, working on the STL itself for as long as they'll let me check in stuff must be my highest priority. I've just returned from BoostCon/C++Now! 2012 and a week of vacation, so a bunch of work has accumulated in my absence. After I deal with that I should be able to find some time to film Part 2. @ STL tnx for the answers Just recently stumbled onto the fact taht u were at boostcon, but github gives error when I try to get your presentation. :( I hope it was similar to your C9 regex lecture. :) @Charles, can you follow STL during future C++Now confs(ofc if he goes), and record his lecture? AFAIK MS is gold sponsor and usually Boostcon video Q is cr*p(sorry Boost people, but you know it is true :) ) Someone else reported that to me too - I've notified C++Now!'s organizer. In the meantime, here are the original slides on my SkyDrive: This is an update of my old TR1 slide deck: @STL Thanks for the answer. Yes, I don't think the VS optimizer takes advantage of that rule, so it would indeed be a little bit hard to show the effects of. Still, I think this is a topic connected with very much confusion. I know for example 3 very experienced C++ programmers, and they all have a different view on 3.10/10. For example: What's with malloc() there? malloc() returns a pointer to void, which obviously has to be converted to be useful. So, if I convert it to pointer to int, store a value, than convert it to pointer to short and read the value - is that undefined or implementation defined? Ah STL, glad to see some new content! I like your videos quite a bit. Thanks for doing this for the community. Name: According to my understanding, reinterpreting directly from int * to short * violates strict aliasing. However, static_casting up to void *, then static_casting down to short *, is a "legitimate" way to view those bits as a short. (Aside from trap representations, which I've never seen in practice.) ChrisL: You'll be happy to hear that I filmed Part 2 yesterday! :-> For impatient STL is on YT: He also makes appearance giving comments in : BTW quality is horrible, so I suggest getting slides and scroll them while watching videos. And again I use this opportunity to beg Charles to go go Boostcon and record at least MS employee presentation. There is a nice one about VS2012, but sound is bad. :( This is simply amazing. I never realized how hard the intellisense and the compiler has to work to resolve the names. Looking forward to more esoteric topics to improve my programming. For some reason, I too smile when you smile. Awesome presentation. Part 2: So by using the rules of ADL it is possible to write code that is shorter and more concise, perhaps. Consider the following examples using the boost::filesystem lib. // a) use fully qualified names boost::filesystem::path p = L"c:\"; if (boost::filesystem::exists(p)) { } // b) use ADL boost::filesystem::path p = L"c:\"; if (exists(p)) { } Both examples compile, but b looks (to me) like an easier code snippet to understand. Are there any pitfalls of using example b? Would one form be preferred over another or is just a matter of style? Thanks again for another great tutorial. (I noticed this by chance; usually I don't look at Part N's comments after Part N+1 is out.) In this case, relying on ADL is fine. Usually I rely on using-directives or using-declarations for even greater convenience, though. (You can't put them at global scope in headers, because that would be enormously polluting, but they can be function-local in headers.) Thank you! This is great stuff. FYI. Koenig did not invent ADL. He himself has said that: Hi I am unable to download this video completely. It always gets struck at 99% I will try one more time using different down loader software. Thanks you do not need a downloader for that, just follow the download posted instructions using 'Right-Click' and then 'Save As' Thanks STL! Your presentation skills and knowledge(of course are impressive. You apparently do template specialization in a different namespace than the namespace of the primary template. It seems msvc10 accepts that, but it's actually ill-formed, so you have a compiler bug there. ;) Stephan, great stuff. Very informative. Keep doing the good job! Stephan , you are my greatest inspiration till date . You are indeed an abundance of knowledge . Thank you for sharing your knowledge. Yes true that you are STL ! I'm with example from 3.4.1 Unqualified name lookup, using VS2012-update2. Compiler complains that [friend] function f() returns a void that cannot be assigned to int. Thoughts? Thank you Mr. STL! Thanks you very much for a wonderful series. I am putting through the excepts/snipped in git so that it is easy to browse and understand. Am I the only one who can not watch this video and get only HTTP 500 instead any of download options? Remove this comment Remove this threadclose
http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-1-of-n
CC-MAIN-2013-48
refinedweb
3,410
64.71
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards The Attribute parser does not consume any input, for this reason it always matches an empty string and always succeeds. It's purpose is to expose its specified parameter as an attribute. // forwards to <boost/spirit/home/qi/auxiliary/attr.hpp> #include <boost/spirit/include/qi_attr.hpp> Also, see Include Structure. Notation a A arbitrary typed constant value, e.g. 0.0, "Hello", or a variable of arbitrary type or a Lazy Argument that evaluates to an arbitrary type. A The type of a or if it is a Lazy Argument, its return type. Semantics of an expression is defined only where it differs from, or is not defined in PrimitiveParser. O(1) The complexity is constant as no input is consumed and no matching is done. Some using declarations: namespace phx = boost::phoenix; using boost::spirit::qi::attr; Using attr with literals: std::string str; test_parser_attr("", attr("boost"), str); std::cout << str << std::endl; // will print 'boost' double d; test_parser_attr("", attr(1.0), d); std::cout << d << std::endl; // will print '1.0' Using attr with Phoenix function objects: d = 0.0; double d1 = 1.2; test_parser_attr("", attr(phx::ref(d1)), d); std::cout << d << std::endl; // will print '1.2'
http://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/reference/auxiliary/attr.html
CC-MAIN-2013-20
refinedweb
225
50.94
There are many variations of this problem, such as 2D packing, linear packing, packing by weight, packing by cost, and so on. They have many applications, such as filling up containers, loading trucks with weight capacity constraints, creating file backups in media and technology mapping in Field-programmable gate array semiconductor chip design. The bin packing problem can also be seen as a special case of the cutting stock problem. When the number of bins is restricted to 1 and each item is characterised by both a volume and a value, the problem of maximising the value of items that can fit in the bin is known as the knapsack problem. Here is source code of the C++ Program to Implement the Bin Packing Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below. #include<iostream> using namespace std; void binPacking(int *a, int size, int n) { int binCount = 1; int s = size; for (int i = 0; i < n; i++) { if (s - *(a + i) > 0) { s -= *(a + i); continue; } else { binCount++; s = size; i--; } } cout << "Number of bins required: " << binCount; } int main(int argc, char **argv) { cout << "BIN - PACKING Algorithm\n"; cout << "Enter the number of items in Set: "; int n; cin >> n; cout << "Enter " << n << " items:"; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; cout << "Enter the bin size: "; int size; cin >> size; binPacking(a, size, n); }.
http://www.sanfoundry.com/cpp-program-implement-bin-packing-algorithm/
CC-MAIN-2017-04
refinedweb
243
58.55
I often got confused about JSON and JSON string. JSON is the code you write in your javascript script to represent an object, so the code is called JavaScript Object Notation. But we can include the piece of code in a string, and the string is called JSON string. Why we need JSON string considering the fact that we can directly write a javascript object with JSON? Well, that is because we can easily transfer a javascript object between client and server by converting the object to a JSON string. If you do not encode the javascript into a JSON string, you have to transfer the binary data of the javascript object, which is not convenient. You can refer to this post about transferring javascript objects over the network. JSON encoding and decoding in javascript(reference) encode a javascript object to a JSON string: var str=JSON.stringify(obj); decode a JSON string to a javascript object: var obj=JSON.parse(str); Store a json string to local storage: localStorage.setItem(“aname”, JSON.stringify(obj)); retrieving a javascript object from local storage: var obj=JSON.parse(localStorage.getItem(“aname”)); JSON Encoding and Decoding in python (reference) encode a python object to a JSON string: import json str=json.dumps(obj); decode a JSON string to a python object: import json obj=json.loads(str); save a python object to a file: import json with open('obj.json', 'w') as f: json.dump(obj,f); read a python object from a file: import json with open('obj.json', 'r') as f: obj=json.load(f); JSON encoding and decoding in php(reference) encode a php object to a JSON string: $str=json_encode($obj); decode a JSON string to a php object: $obj=json_decode($str); We can see almost all programming languages provide functions or a library to encode and parse JSON strings. Converting a string to an object or vice verse is very simple, almost a line of code.
https://myprogrammingnotes.com/json-javascript-python-php.html
CC-MAIN-2019-22
refinedweb
328
64.41
I had not seen a good .NET performance challenge in a while so I figured that I would start one. Obviously the real benefit will come in about two weeks when all of these items are analyzed and discussed (I wager everyone involved will learn something!). If this works out well I will try to run these either bi-weekly or monthly. Let me know your opinion in comments below. Aside from becoming alpha nerd for a few weeks, the winner of this contest will receive a book from the very well known computer scientist Donald E. Knuth. Just to give things an interesting twist the book has absolutely nothing to do with optimizations. The prize is a copy of Things a Computer Scientist Rarely Talks About, it is the transcripts of Knuth’s 1999 lecture series at MIT discussing the relations between faith and science. If you wish to watch the web casts of these lectures you still can here. The runner up will receive a copy of Donald Knuth’s TAOCP V4F3 “Generating all Combinations and Partitions” as this book will help them win a future contest. There will also be a prize TBD for the fastest safe version of the code. I will do a submission but I cannot win a prize. Wc (word count) is an old unix program. One of its main tasks is to go through a set of data and count the number of repetitions of a given word. For instance given the sentence “Hello, yes hello” it would tell you that the word Hello was used twice and that the word yes was used once. While seemingly trivial this problem offers many interesting aspects such as dealing with the trade off of memory usage for large vs small data sets. Hint: since it is a classic problem there is a lot of research on it Here is a naive version of a word counter with a test harness if you can’t beat this you need more optimization J class Program { static Dictionary<string, int> WordCounts = new Dictionary<string, int>(); static void Main(string[] args) { string test = "The quick brown fox jumps over the lazy dog"; Array.ForEach<string>(test.ToUpper().Split(' '), new Action<string>(AddToHash)); foreach (string current in WordCounts.Keys) { Console.WriteLine(current + ":" + WordCounts[current]); } } static void AddToHash(string _Item) { if (!WordCounts.ContainsKey(_Item)) { WordCounts.Add(_Item, 0); WordCounts[_Item] += 1; } Listing 1: Example of a naive word counter Some notes. 1) Capitalization differences do not equate to a difference. 2) You must handle normal punctuation properly there will be no apostrophes/quotes in the test data as they bring up many questions on their own. 3) Code will be run on a 32 bit processor (don’t use 64 bit stuff hoping for a 64 bit processor) 4) My processor is a dual core (hint) 5) You must use the IWordCounter interface 6) You do not need to sort your data before returning 7) If you do not pass unit tests performance tests will not be run. UPDATE: here are some test strings to show ... the quick sample code meets some but not all of these"Hello! Greg" results in Hello 1, Greg 1 "Hello!Greg" results in HelloGreg 1"Hello\nGreg" results in Hello 1, Greg 1 "A.D.D." results in ADD 1 "Wow, how great!" results in Wow 1, how 1, great 1 "wow \n\n\n great" results in wow 1, great 1 "it was a man-eating shark." results in it 1, was 1, a 1, man-eating 1, shark 1 numbers can be a bit odd .. although the data has no numbers in it I will describe the behavior (I will also show how to avoid this in a parser if you wanted to). If you wanted to you could support a special case for numbers but I have NO test data with numbers in it .. this is how they will turn out if you follow the general rule above of ignoring punctuation. 1,000,000 results in 1000000 1 $1,000,000 results in $1000000 1 $ 1,000,000 results in $ 1, 1000000 1 "1.2 1.20 120" results in 12 1, 120 2 Submissions must use the IWordCounter interface provided here, this is to help me by making unit/performance testing a bit easier. using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication39 { struct WordEntry { public string Word; public int Count; interface IWordCounter { WordEntry[] CountWords(string _Text); class WordComparer : IComparer<WordEntry> { public int Compare(WordEntry x, WordEntry y) { return x.Word.CompareTo(y.Word); class WordCounter :IWordCounter { Dictionary<string, int> WordCounts = new Dictionary<string, int>(); private void AddToHash(string _Item) { public WordEntry [] CountWords(string _Text) { List<WordEntry> Words = new List<WordEntry>(); Array.ForEach<string>(_Text.ToUpper().Split(' '), new Action<string>(AddToHash)); WordEntry w; w.Word = current; w.Count = WordCounts[current]; Words.Add(w); return Words.ToArray(); IWordCounter Counter = new WordCounter(); WordEntry [] Counts = Counter.CountWords(test); Array.Sort(Counts, new WordComparer()); Array.ForEach<WordEntry>(Counts, new Action<WordEntry>(PrintEntry)); static void PrintEntry(WordEntry _Entry) { Console.WriteLine(_Entry.Word + " " + _Entry.Count); } Listing 2: Naïve example using required interface Submissions are to be EMAILED to me at Gregory<insertmylastname>1@gmail.com before midnight (EST) on Aug 10th, I will have results ready by the 13th. Do not post your submission in comments or I will be forced to delete it. I will post when I receive entries so you can be sure you entry has actually reached me. Also it is not your best interest to do this as someone could come through and optimize one line of your code to beat you :P I will the day that the contest ends create a post including performance results for all code. I will also post a zip file of all submissions (including my performance harness & unit tests so others can view it). 3 sets of data will be run through the submissions each will be run many times with a new object constructed for each iteration. There will be one very small set of data, one medium set of data and one large set of data. Each of these sections is worth the same number of points. 1. 10 points 2. 8 points 3. 7 points 4. 6 points 5. 5 points The submission with the most combined points from the three sections will win. If there is a point based tie, the entry that did better on section three (the large set) will win. Why three datasets? Optimizations for the largest data set often come at the expense of the smallest, what is sought after is the best all around solution. 1) Only one submission per person to be evaluated, you can submit multiples for discussion if you come across an interesting tidbit that you think is worth sharing 2) Items will be run on the MS 2.0.50727 CLR (there can be no tricks such as adding IL instructions to mono) 3) You may not call out to unmanaged code! 4) You CAN use unsafe code 5) No you can’t know what the data is beforehand. 6) You must pass unit tests in order to be included (what good is fast if it doesn’t work?) If you have any questions, need clarification, or have thoughts on the overall idea of these competitions please post them here. A Strategies Ok. It seems as if the queen is in charge of providing central goals but Borgs are able to achieve these goals by any means they consider appropriate. For now, we recognize that Borgs use communication and interaction, share their knowledge with each other, can interoperate independently as groups but not as individuals, continuously share their knowledge and abilities, strive for common code ownership. don't respond to an enemy soldier until he actually destroys something or attacks somebody. In Q Who, the cube just sat there trying to decide what to do, waiting for so long that the Enterprise's crew was able to hold its own meetings, decide what to do, and then explore the Borg ship! In fact, the only time that we ever saw the Borg react and move quickly was "Descent", when they were not part of a collective. This is due to the inefficiencies of the hive mind and other similar symmetric multi-processing systems. (SMP while being great at some tasksorg? There :) public. public static unsafe string GregsInt32Reverse(string s) { UInt32 Low; UInt32 High;
http://codebetter.com/blogs/gregyoung/archive/2006/07.aspx
crawl-001
refinedweb
1,414
62.58
CodeGuru Forums > Visual C++ & C++ Programming > C++ (Non Visual C++ Issues) > FTP messenger (Windows) PDA Click to See Complete Forum and Search --> : FTP messenger (Windows) nie_wiadomo February 6th, 2008, 02:28 PM Dear programmers, I wanted to have a simple messenger for me to talk with my friend. If I wanted to use IM clients, I would be a member of bigger or smaller group of people communicating this way. I thought I needed something more original. Let me state that I'm not a programmer at all and I would just like to finish this application, not necessarily raise my skills to a new level. Here's my code: #include <iostream> #include <fstream> #include "cstdlib" #include <string> #include <vector> #include "windows.h" //this one is for Sleep, used in other functions using namespace std; // some other functions (like checking, if the other side is already trying to update the file) go here int main() { std::system("del log.dvc"); // delete the files, wget tends not to overwrite std::system("del stat"); // anyone knowing how to avoid deleting please let me know string a; vector<string> s; string sl; //something really unimportant goes here std::system("cls"); std::system("C:/kontakt/wget/wget.exe --quiet --tries=0 --retry-connrefused --wait=3"); //download the log ifstream in("log.dvc"); // open log for reading while(in >> sl) // catch words into a vector s.push_back(sl); for(int i = 0; i< s.size(); i++) // display the words inside vector cout << s[i] << endl; // (log file) while(1) { // here's where problems begin to appear (Help here please) std::system("C:/kontakt/wget/wget.exe --quiet --tries=0 --timestamping --retry-connrefused --wait=3"); //keep the log file updated string sl2; vector<string> s2; // same as with first log file, catch words into a vector ifstream in("log.dvc"); while(in >> sl2) s2.push_back(sl2); if (s.size() != s2.size()) { // if the just-downloaded log file is different than the one printed out std::system("cls"); // clear the screen for(int i = 0; i< s2.size(); i++) // and print the new one cout << s2[i] << endl;}} // now I have my screen updated, but I'd also like my program to catch the messages written from now on on my computer return 0; } The whole problem lies in what is missing by the last line of while(1). I want my program to update the screen with new messages from the other side while still waiting for me to enter mine. Unfortunately, if I tell it to cin or getchar it will wait for me to click enter before updating log file again, and this is fatal for my messenger (this way it would only check log for new messages after me sending a message). My program uses wput and wget (binaries from sourceforge). The final version would connect to a remote ftp server, I just setup a simple one on my computer for quick tests. Thanks a bunch for any tips, good luck with interpreting my terrible code. Michal codeguru.com
http://forums.codeguru.com/archive/index.php/t-445459.html
crawl-003
refinedweb
506
66.67
Command Line User Guide¶ Rasterio’s command line interface (CLI) is a program named “rio” 1. The CLI allows you to build workflows using shell commands, either interactively at the command prompt or with a script. Many common cases are covered by CLI sub-commands and it is often more convenient to use a ready-made command as opposed to implementing similar functionality as a python script. The rio program is developed using the Click framework. Its plugin system allows external modules to share a common namespace and handling of context variables. $ rio --help ⏎ Usage: rio [OPTIONS] COMMAND [ARGS]... Rasterio command line interface. Options: -v, --verbose Increase verbosity. -q, --quiet Decrease verbosity. --aws-profile TEXT Select a profile from the AWS credentials file --aws-no-sign-requests Make requests anonymously --aws-requester-pays Requester pays data transfer costs --version Show the version and exit. --gdal-version --help Show this message and exit. Commands: blocks Write dataset blocks as GeoJSON features. bounds Write bounding boxes to stdout as GeoJSON. calc Raster data calculator. clip Clip a raster to given bounds. convert Copy and convert raster dataset. edit-info Edit dataset metadata. env Print information about the Rasterio environment. gcps Print ground control points as GeoJSON. info Print information about a data file. insp Open a data file and start an interpreter. mask Mask in raster using features. merge Merge a stack of raster datasets. overview Construct overviews in an existing dataset. rasterize Rasterize features. rm Delete a dataset. sample Sample a dataset. shapes Write shapes extracted from bands or masks. stack Stack a number of bands into a multiband dataset. transform Transform coordinates. warp Warp a raster dataset. Commands are shown below. See --help of individual commands for more details. creation options¶ For commands that create new datasets, format specific creation options may also be passed using --co. For example, to tile a new GeoTIFF output file, add the following. --co tiled=true --co blockxsize=256 --co blockysize=256 To compress it using the LZW method, add --co compress=LZW bounds¶ Added in 0.10. The bounds command writes the bounding boxes of raster datasets to GeoJSON for use with, e.g., geojsonio-cli. $ rio bounds tests/data/RGB.byte.tif --indent 2 { "features": [ { "geometry": { "coordinates": [ [ [ -78.898133, 23.564991 ], [ -76.599438, 23.564991 ], [ -76.599438, 25.550874 ], [ -78.898133, 25.550874 ], [ -78.898133, 23.564991 ] ] ], "type": "Polygon" }, "properties": { "id": "0", "title": "tests/data/RGB.byte.tif" }, "type": "Feature" } ], "type": "FeatureCollection" } Shoot the GeoJSON into a Leaflet map using geojsonio-cli by typing rio bounds tests/data/RGB.byte.tif | geojsonio. calc¶ Added in 0.19 The calc command reads files as arrays, evaluates lisp-like expressions in their context, and writes the result as a new file. Members of the numpy module and arithmetic and logical operators are available builtin functions and operators. It is intended for simple calculations; any calculations requiring multiple steps is better done in Python using the Rasterio and Numpy APIs. Input files may have different numbers of bands but should have the same number of rows and columns. The output file will have the same number of rows and columns as the inputs and one band per element of the expression result. An expression involving arithmetic operations on N-D arrays will produce a N-D array and result in an N-band output file. The following produces a 3-band GeoTIFF with all values scaled by 0.95 and incremented by 2. In the expression, (read 1) evaluates to the first input dataset (3 bands) as a 3-D array. $ rio calc "(+ 2 (* 0.95 (read 1)))" tests/data/RGB.byte.tif /tmp/out.tif The following produces a 3-band GeoTIFF in which the first band is copied from the first band of the input and the next two bands are scaled (down) by the ratio of the first band’s mean to their own means. The --name option is used to bind datasets to a name within the expression. (take a 1) gets the first band of the dataset named a as a 2-D array and (asarray ...) collects a sequence of 2-D arrays into a 3-D array for output. $ rio calc "(asarray (take a 1) (* (take a 2) (/ (mean (take a 1)) (mean (take a 2)))) (* (take a 3) (/ (mean (take a 1)) (mean (take a 3)))))" \ > --name a=tests/data/RGB.byte.tif /tmp/out.rgb.tif The command above is also an example of a calculation that is far beyond the design of the calc command and something that could be done much more efficiently in Python. clip¶ Added in 0.27 The clip command clips a raster using bounds input directly or from a template raster. $ rio clip input.tif output.tif --bounds xmin ymin xmax ymax $ rio clip input.tif output.tif --like template.tif If using --bounds, values must be in coordinate reference system of input. If using --like, bounds will automatically be transformed to match the coordinate reference system of the input. It can also be combined to read bounds of a feature dataset using Fiona: $ rio clip input.tif output.tif --bounds $(fio info features.shp --bounds) convert¶ Added in 0.25 The convert command copies and converts raster datasets to other data types and formats (similar to gdal_translate). Data values may be linearly scaled when copying by using the --scale-ratio and --scale-offset options. Destination raster values are calculated as dst = scale_ratio * src + scale_offset For example, to scale uint16 data with an actual range of 0-4095 to 0-255 as uint8: $ rio convert in16.tif out8.tif --dtype uint8 --scale-ratio 0.0625 You can use –rgb as shorthand for –co photometric=rgb. edit-info¶ Added in 0.24 The edit-info command allows you edit a raster dataset’s metadata, namely coordinate reference system affine transformation matrix nodata value color interpretation A TIFF created by spatially-unaware image processing software like Photoshop or Imagemagick can be turned into a GeoTIFF by editing these metadata items. For example, you can set or change a dataset’s coordinate reference system to Web Mercator (EPSG:3857), $ rio edit-info --crs EPSG:3857 example.tif set its affine transformation matrix, $ rio edit-info --transform "[300.0, 0.0, 101985.0, 0.0, -300.0, 2826915.0]" example.tif or set its nodata value to, e.g., 0: $ rio edit-info --nodata 0 example.tif or set its color interpretation to red, green, blue, and alpha: $ rio edit-info --colorinterp 1=red,2=green,3=blue,4=alpha example.tif which can also be expressed as: $ rio edit-info --colorinterp RGBA example.tif See rasterio.enums.ColorInterp for a full list of supported color interpretations and the color docs for more information. info¶ Added in 0.13 The info command prints structured information about a dataset. $ rio info tests/data/RGB.byte.tif --indent 2 { "count": 3, "crs": "EPSG:32618", } More information, such as band statistics, can be had using the --verbose option. $ rio info tests/data/RGB.byte.tif --indent 2 --verbose { "count": 3, "crs": "EPSG:32618", "stats": [ { "max": 255.0, "mean": 44.434478650699106, "min": 1.0 }, { "max": 255.0, "mean": 66.02203484105824, "min": 1.0 }, { "max": 255.0, "mean": 71.39316199120559, "min": 1.0 } ], } insp¶ The insp command opens a dataset and an interpreter. $ rio insp --ipython tests/data/RGB.byte.tif Rasterio 0.32.0 Interactive Inspector (Python 2.7.10) Type "src.meta", "src.read(1)", or "help(src)" for more information. In [1]: print(src.name) /path/rasterio/tests/data/RGB.byte.tif In [2]: print(src.bounds) BoundingBox(left=101985.0, bottom=2611485.0, right=339315.0, top=2826915.0) mask¶ Added in 0.21 The mask command masks in pixels from all bands of a raster using features (masking out all areas not covered by features) and optionally crops the output raster to the extent of the features. Features are assumed to be in the same coordinate reference system as the input raster. A common use case is masking in raster data by political or other boundaries. $ rio mask input.tif output.tif --geojson-mask input.geojson GeoJSON features may be provided using stdin or specified directly as first argument, and output can be cropped to the extent of the features. $ rio mask input.tif output.tif --crop --geojson-mask - < input.geojson The feature mask can be inverted to mask out pixels covered by features and keep pixels not covered by features. $ rio mask input.tif output.tif --invert --geojson-mask input.geojson merge¶ Added in 0.12.1 The merge command can be used to flatten a stack of identically structured datasets. $ rio merge rasterio/tests/data/R*.tif merged.tif overview¶ New in 0.25 The overview command creates overviews stored in the dataset, which can improve performance in some applications. The decimation levels at which to build overviews can be specified as a comma separated list $ rio overview --build 2,4,8,16 or a base and range of exponents. $ rio overview --build 2^1..4 Note that overviews can not currently be removed and are not automatically updated when the dataset’s primary bands are modified. Information about existing overviews can be printed using the –ls option. $ rio overview --ls The block size (tile width and height) used for overviews (internal or external) can be specified by setting the GDAL_TIFF_OVR_BLOCKSIZE environment variable to a power-of-two value between 64 and 4096. The default value is 128. $ GDAL_TIFF_OVR_BLOCKSIZE=256 rio overview --build 2^1..4 rasterize¶ New in 0.18. The rasterize command rasterizes GeoJSON features into a new or existing raster. $ rio rasterize test.tif --res 0.0167 < input.geojson The resulting file will have an upper left coordinate determined by the bounds of the GeoJSON (in EPSG:4326, which is the default), with a pixel size of approximately 30 arc seconds. Pixels whose center is within the polygon or that are selected by Bresenham’s line algorithm will be burned in with a default value of 1. It is possible to rasterize into an existing raster and use an alternative default value: $ rio rasterize existing.tif --default_value 10 < input.geojson It is also possible to rasterize using a template raster, which will be used to determine the transform, dimensions, and coordinate reference system of the output raster: $ rio rasterize test.tif --like tests/data/shade.tif < input.geojson GeoJSON features may be provided using stdin or specified directly as first argument, and dimensions may be provided in place of pixel resolution: $ rio rasterize input.geojson test.tif --dimensions 1024 1024 Other options are available, see: $ rio rasterize --help rm¶ New in 1.0 Invoking the shell’s $ rm <path> on a dataset can be used to delete a dataset referenced by a file path, but it won’t handle deleting side car files. This command is aware of datasets and their sidecar files. sample¶ New in 0.18. The sample command reads x, y positions from stdin and writes the dataset values at that position to stdout. $ cat << EOF | rio sample tests/data/RGB.byte.tif > [220649.99999832606, 2719199.999999095] > EOF [18, 25, 14] The output of the transform command (see below) makes good input for sample. shapes¶ New in 0.11. The shapes command extracts and writes features of a specified dataset band out as GeoJSON. $ rio shapes tests/data/shade.tif --bidx 1 --precision 6 > shade.geojson The resulting file, uploaded to Mapbox, looks like this: sgillies.j1ho338j. Using the --mask option you can write out the shapes of a dataset’s valid data region. $ rio shapes --mask --precision 6 tests/data/RGB.byte.tif | geojsonio See. stack¶ New in 0.15. The stack command stacks a number of bands from one or more input files into a multiband dataset. Input datasets must be of a kind: same data type, dimensions, etc. The output is cloned from the first input. By default, stack will take all bands from each input and write them in same order to the output. Optionally, bands for each input may be specified using the following syntax: --bidx Ntakes the Nth band from the input (first band is 1). --bidx M,N,Otakes bands M, N, and O. --bidx M..Otakes bands M-O, inclusive. --bidx ..Ntakes all bands up to and including N. --bidx N..takes all bands from N to the end. Examples using the Rasterio testing dataset that produce a copy of it. $ rio stack RGB.byte.tif stacked.tif $ rio stack RGB.byte.tif --bidx 1,2,3 stacked.tif $ rio stack RGB.byte.tif --bidx 1..3 stacked.tif $ rio stack RGB.byte.tif --bidx ..2 RGB.byte.tif --bidx 3.. stacked.tif You can use –rgb as shorthand for –co photometric=rgb. transform¶ New in 0.10. The transform command reads a JSON array of coordinates, interleaved, and writes another array of transformed coordinates to stdout. To transform a longitude, latitude point (EPSG:4326 is the default) to another coordinate system with 2 decimal places of output precision, do the following. $ echo "[-78.0, 23.0]" | rio transform - --dst-crs EPSG:32618 --precision 2 [192457.13, 2546667.68] To transform a longitude, latitude bounding box to the coordinate system of a raster dataset, do the following. $ echo "[-78.0, 23.0, -76.0, 25.0]" | rio transform - --dst-crs tests/data/RGB.byte.tif --precision 2 [192457.13, 2546667.68, 399086.97, 2765319.94] warp¶ New in 0.25 The warp command warps (reprojects) a raster based on parameters that can be obtained from a template raster, or input directly. The output is always overwritten. To copy coordinate reference system, transform, and dimensions from a template raster, do the following: $ rio warp input.tif output.tif --like template.tif You can specify an output coordinate system using a PROJ.4 or EPSG:nnnn string, or a JSON text-encoded PROJ.4 object: $ rio warp input.tif output.tif --dst-crs EPSG:4326 $ rio warp input.tif output.tif --dst-crs '+proj=longlat +ellps=WGS84 +datum=WGS84' You can also specify dimensions, which will automatically calculate appropriate resolution based on the relationship between the bounds in the target crs and these dimensions: $ rio warp input.tif output.tif --dst-crs EPSG:4326 --dimensions 100 200 Or provide output bounds (in source crs) and resolution: $ rio warp input.tif output.tif --dst-crs EPSG:4326 --bounds -78 22 -76 24 --res 0.1 Previous command in case of south-up image, -- escapes the next -: $ rio warp input.tif output.tif --dst-crs EPSG:4326 --bounds -78 22 -76 24 --res 0.1 -- -0.1 Other options are available, see: $ rio warp --help Rio Plugins¶ Rio uses click-plugins to provide the ability to create additional subcommands using plugins developed outside rasterio. This is ideal for commands that require additional dependencies beyond those used by rasterio, or that provide functionality beyond the intended scope of rasterio. For example, rio-mbtiles provides a command rio mbtiles to export a raster to an MBTiles file. See click-plugins for more information on how to build these plugins in general. To use these plugins with rio, add the commands to the rasterio.rio_plugins entry point in your setup.py file, as described here and in rasterio/rio/main.py. See the plugin registry for a list of available plugins.
https://rasterio.readthedocs.io/en/latest/cli.html
CC-MAIN-2021-21
refinedweb
2,565
60.31
. Converting strings and numbers using string streams in Open C++ Overview This code snippet shows how to use string streams to convert strings to numbers and vice versa. The sstream library provides a functionality similar to sscanf() and sprintf() in the standard C library. The three main classes of this library are istringstream, ostringstream, and stringstream. An ostringstream object can be used to write to a string, an istringstream object can be used to read from a string, and a stringstream object can be used for both input and output to a string. String streams provide a great help when conversions between strings and numbers are needed. Note: In order to use this code, you need to install the Open C/C++ plug-in. This snippet can be self-signed. MMP file The following libraries are required: LIBRARY libstdcpp.lib LIBRARY libc.lib LIBRARY euser.lib Source file #include <iostream> #include <sstream> #include <string> using namespace std; //template conversion functions that can be used //with different number types template<typename T> T ConvertStringToNumber(const string& str) { istringstream ss(str); T number = 0; ss >> number; if (ss.fail( )) { throw invalid_argument("ConvertStringToNumber:" + str); } return number; } template<typename T> string ConvertNumberToString (const T number) { ostringstream ss; ss << number; return ss.str(); } int main() { // -- converting with stringstream -- int m = 1; int n = 0; string s1 = ""; string s2 = "123"; stringstream ss; //number to string ss << m; s1 = ss.str(); cout << "s1:" << s1 << endl; //s1:1 //clear/reuse stringstream object ss.str(""); //string to number ss << s2; ss >> n; cout << "n:" << n << endl; //n:123 // -- converting with istringstream and ostringstream -- try { string intString = ConvertNumberToString<int>(1234); cout << intString << endl; //1234 string floatString = ConvertNumberToString<float>(1.2); cout << floatString << endl; //1.2 float floatVar = ConvertStringToNumber<float>(floatString); cout << floatVar << endl; //1.2 int intVar = ConvertStringToNumber<int>(intString); cout << intVar << endl; //1234 string exceptionString = "xyz"; intVar = ConvertStringToNumber<int>(exceptionString); //this line is never executed because of exception cout << intVar << endl; } catch (const exception& e) { cout << e.what() << endl; //ConvertStringToNumber:xyz } return 0; } Note: There is a known bug in the current Open C++ plug-in that prevents this code snippet to compile when working with the gcce compiler. To fix this problem, open the file stdapis/stlport/stl/_sstream.c and find and replace the following line: if((_M_str.size() - _M_str._M_stream_pos) >= __n) with if((_M_str.size() - _M_str._M_stream_pos) >= (size_t)__n) Postconditions Different string-to-number and number-to-string conversions have been executed and are displayed as standard output. Exceptions have been caught because of an invalid conversion argument.
http://developer.nokia.com/community/wiki/Converting_strings_and_numbers_using_string_streams_in_Open_C%2B%2B
CC-MAIN-2014-52
refinedweb
422
55.74
Count each bit-position separately over many 64-bit bitmasks, with AVX but not AVX2 (Related: How to quickly count bits into separate bins in a series of ints on Sandy Bridge? is an earlier duplicate of this, with some different answers. Editor's note: the answers here are probably better. Also, an AVX2 version of a similar problem, with many bins for a whole row of bits much wider than one uint64_t: Improve column population count algorithm) I am working on a project in C where I need to go through tens of millions of masks (of type ulong (64-bit)) and update an array (called target) of 64 short integers (uint16) based on a simple rule: // for any given mask, do the following loop for (i = 0; i < 64; i++) { if (mask & (1ull << i)) { target[i]++ } } The problem is that I need do the above loops on tens of millions of masks and I need to finish in less than a second. Wonder if there are any way to speed it up, like using some sort special assembly instruction that represents the above loop. Currently I use gcc 4.8.4 on ubuntu 14.04 (i7-2670QM, supporting AVX, not AVX2) to compile and run the following code and took about 2 seconds. Would love to make it run under 200ms. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/stat.h> double getTS() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } unsigned int target[64]; int main(int argc, char *argv[]) { int i, j; unsigned long x = 123; unsigned long m = 1; char *p = malloc(8 * 10000000); if (!p) { printf("failed to allocate\n"); exit(0); } memset(p, 0xff, 80000000); printf("p=%p\n", p); unsigned long *pLong = (unsigned long*)p; double start = getTS(); for (j = 0; j < 10000000; j++) { m = 1; for (i = 0; i < 64; i++) { if ((pLong[j] & m) == m) { target[i]++; } m = (m << 1); } } printf("took %f secs\n", getTS() - start); return 0; } Thanks in advance! On my system, a 4 year old MacBook (2.7 GHz intel core i5) with clang-900.0.39.2 -O3, your code runs in 500ms. Just changing the inner test to if ((pLong[j] & m) != 0) saves 30%, running in 350ms. Further simplifying the inner part to target[i] += (pLong[j] >> i) & 1; without a test brings it down to 280ms. Further improvements seem to require more advanced techniques such as unpacking the bits into blocks of 8 ulongs and adding those in parallel, handling 255 ulongs at a time. Here is an improved version using this method. it runs in 45ms on my system. #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/stat.h> double getTS() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } int main(int argc, char *argv[]) { unsigned int target[64] = { 0 }; unsigned long *pLong = malloc(sizeof(*pLong) * 10000000); int i, j; if (!pLong) { printf("failed to allocate\n"); exit(1); } memset(pLong, 0xff, sizeof(*pLong) * 10000000); printf("p=%p\n", (void*)pLong); double start = getTS(); uint64_t inflate[256]; for (i = 0; i < 256; i++) { uint64_t x = i; x = (x | (x << 28)); x = (x | (x << 14)); inflate[i] = (x | (x << 7)) & 0x0101010101010101ULL; } for (j = 0; j < 10000000 / 255 * 255; j += 255) { uint64_t b[8] = { 0 }; for (int k = 0; k < 255; k++) { uint64_t u = pLong[j + k]; for (int kk = 0; kk < 8; kk++, u >>= 8) b[kk] += inflate[u & 255]; } for (i = 0; i < 64; i++) target[i] += (b[i / 8] >> ((i % 8) * 8)) & 255; } for (; j < 10000000; j++) { uint64_t m = 1; for (i = 0; i < 64; i++) { target[i] += (pLong[j] >> i) & 1; m <<= 1; } } printf("target = {"); for (i = 0; i < 64; i++) printf(" %d", target[i]); printf(" }\n"); printf("took %f secs\n", getTS() - start); return 0; } The technique for inflating a byte to a 64-bit long are investigated and explained in the answer: . I made the target array a local variable, as well as the inflate array, and I print the results to ensure the compiler will not optimize the computations away. In a production version you would compute the inflate array separately. Using SIMD directly might provide further improvements at the expense of portability and readability. This kind of optimisation is often better left to the compiler as it can generate specific code for the target architecture. Unless performance is critical and benchmarking proves this to be a bottleneck, I would always favor a generic solution. A different solution by njuffa provides similar performance without the need for a precomputed array. Depending on your compiler and hardware specifics, it might be faster. [PDF] x86 Intrinsics Cheat Sheet, Count each bit-position separately over many 64-bit bitmasks, with AVX but not AVX2. 2019 Community Moderator ElectionHow to generate a sse4.2 popcnt� Count each bit-position separately over many 64-bit bitmasks, with AVX but not AVX2 AVX, not AVX2) to compile and run the following code and took about 2 seconds Uncategorized – Branch Free, NOTE: For each element pair cmpord sets the result bits to 1 if both elements are not. NaN, otherwise 0. cmpunord sets bits if at least one is NaN. SSE2. Old Float/ � Count each bit-position separately over many 64-bit bitmasks 6 0 One way of speeding this up significantly, even without AVX, is to split the data into blocks of up to 255 elements, and accumulate the bit counts byte-wise in ordinary uint64_t variables. Since the source data has 64 bits, we need an array of 8 byte-wise accumulators. The first accumulator counts bits in positions 0, 8, 16, ... 56, second accumulator counts bits in positions 1, 9, 17, ... 57; and so on. After we are finished processing a block of data, we transfers the counts form the byte-wise accumulator into the target counts. A function to update the target counts for a block of up to 255 numbers can be coded in a straightforward fashion according to the description above, where BITS is the number of bits in the source data: /* update the counts; } } } The entire ISO-C99 program, which should be able to run on at least Windows and Linux platforms is shown below. It initializes the source data with a PRNG, performs a correctness check against the asker's reference implementation, and benchmarks both the reference code and the accelerated version. On my machine (Intel Xeon E3-1270 v2 @ 3.50 GHz), when compiled with MSVS 2010 at full optimization ( /Ox), the output of the program is: p=0000000000550040 ref took 2.020282 secs, fast took 0.027099 secs where ref refers to the asker's original solution. The speed-up here is about a factor 74x. Different speed-ups will be observed with other (and especially newer) compilers. #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #if defined(_WIN32) #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> double second (void) { LARGE_INTEGER t; static double oofreq; static int checkedForHighResTimer; static BOOL hasHighResTimer; if (!checkedForHighResTimer) { hasHighResTimer = QueryPerformanceFrequency (&t); oofreq = 1.0 / (double)t.QuadPart; checkedForHighResTimer = 1; } if (hasHighResTimer) { QueryPerformanceCounter (&t); return (double)t.QuadPart * oofreq; } else { return (double)GetTickCount() * 1.0e-3; } } #elif defined(__linux__) || defined(__APPLE__) #include <stddef.h> #include <sys/time.h> double second (void) { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (double)tv.tv_usec * 1.0e-6; } #else #error unsupported platform #endif /* From: geo <gmars...@gmail.com> Newsgroups: sci.math,comp.lang.c,comp.lang.fortran Subject: 64-bit KISS RNGs Date: Sat, 28 Feb 2009 04:30:48 -0800 (PST) This 64-bit KISS RNG has three components, each nearly good enough to serve alone. The components are: Multiply-With-Carry (MWC), period (2^121+2^63-1) Xorshift (XSH), period 2^64-1 Congruential (CNG), period 2^64 */ static uint64_t kiss64_x = 1234567890987654321ULL; static uint64_t kiss64_c = 123456123456123456ULL; static uint64_t kiss64_y = 362436362436362436ULL; static uint64_t kiss64_z = 1066149217761810ULL; static uint64_t kiss64_t; #define MWC64 (kiss64_t = (kiss64_x << 58) + kiss64_c, \ kiss64_c = (kiss64_x >> 6), kiss64_x += kiss64_t, \ kiss64_c += (kiss64_x < kiss64_t), kiss64_x) #define XSH64 (kiss64_y ^= (kiss64_y << 13), kiss64_y ^= (kiss64_y >> 17), \ kiss64_y ^= (kiss64_y << 43)) #define CNG64 (kiss64_z = 6906969069ULL * kiss64_z + 1234567ULL) #define KISS64 (MWC64 + XSH64 + CNG64) #define N (10000000) #define BITS (64) #define BLOCK_SIZE (255) /* cupdate the count; } } } int main (void) { double start_ref, stop_ref, start, stop; uint64_t *pLong; unsigned int target_ref [BITS] = {0}; unsigned int target [BITS] = {0}; int i, j; pLong = malloc (sizeof(pLong[0]) * N); if (!pLong) { printf("failed to allocate\n"); return EXIT_FAILURE; } printf("p=%p\n", pLong); /* init data */ for (j = 0; j < N; j++) { pLong[j] = KISS64; } /* count bits slowly */ start_ref = second(); for (j = 0; j < N; j++) { uint64_t m = 1; for (i = 0; i < BITS; i++) { if ((pLong[j] & m) == m) { target_ref[i]++; } m = (m << 1); } } stop_ref = second(); /* count bits fast */ start = second(); for (j = 0; j < N / BLOCK_SIZE; j++) { sum_block (pLong, target, j * BLOCK_SIZE, (j+1) * BLOCK_SIZE); } sum_block (pLong, target, j * BLOCK_SIZE, N); stop = second(); /* check whether result is correct */ for (i = 0; i < BITS; i++) { if (target[i] != target_ref[i]) { printf ("error @ %d: res=%u ref=%u\n", i, target[i], target_ref[i]); } } /* print benchmark results */ printf("ref took %f secs, fast took %f secs\n", stop_ref - start_ref, stop - start); return EXIT_SUCCESS; } [PDF] Faster Population Counts Using AVX2 Instructions, There include, but are not limited to (I told you I don't care about floating point, All the other granularities of shuffle up to a 512-bit size are there in AVX-512 but bytes that many cheap byte->byte transformations that can be done over 8 bits that 512->256->128->64 bits, but the first stage requires two separate 256-> 128� Count each bit-position separately over many 64-bit bitmasks, with AVX but not AVX2 I can't die. Who am I? Locked Away- What am I? Is there a way to make cleveref distinguish two environments with the same counter? Too soon for a plot twist? For starters, the problem of unpacking the bits, because seriously, you do not want to test each bit individually. So just follow the following strategy for unpacking the bits into bytes of a vector: Now that you have padded each bit to 8 bits, you can just do this for blocks of up to 255 bitmasks at a time, and accumulate them all into a single vector register. After that, you would have to expect potential overflows, so you need to transfer. After each block of 255, unpack again to 32bit, and add into the array. (You don't have to do exactly 255, just some convenient number less than 256 to avoid overflow of byte accumulators). At 8 instructions per bitmask (4 per each lower and higher 32-bit with AVX2) - or half that if you have AVX512 available - you should be able to achieve a throughput of about half a billion bitmasks per second and core on an recent CPU. typedef uint64_t T; const size_t bytes = 8; const size_t bits = bytes * 8; const size_t block_size = 128; static inline __m256i expand_bits_to_bytes(uint32_t x) { __m256i xbcast = _mm256_set1_epi32(x); // we only use the low 32bits of each lane, but this is fine with AVX2 // Each byte gets the source byte containing the corresponding bit const __m256i shufmask = _mm256_set_epi64x( 0x0303030303030303, 0x0202020202020202, 0x0101010101010101, 0x0000000000000000); __m256i shuf = _mm256_shuffle_epi8(xbcast, shufmask); const __m256i andmask = _mm256_set1_epi64x(0x8040201008040201); // every 8 bits -> 8 bytes, pattern repeats. __m256i isolated_inverted = _mm256_andnot_si256(shuf, andmask); // this is the extra step: byte == 0 ? 0 : -1 return _mm256_cmpeq_epi8(isolated_inverted, _mm256_setzero_si256()); } void bitcount_vectorized(const T *data, uint32_t accumulator[bits], const size_t count) { for (size_t outer = 0; outer < count - (count % block_size); outer += block_size) { __m256i temp_accumulator[bits / 32] = { _mm256_setzero_si256() }; for (size_t inner = 0; inner < block_size; ++inner) { for (size_t j = 0; j < bits / 32; j++) { const auto unpacked = expand_bits_to_bytes(static_cast<uint32_t>(data[outer + inner] >> (j * 32))); temp_accumulator[j] = _mm256_sub_epi8(temp_accumulator[j], unpacked); } } for (size_t j = 0; j < bits; j++) { accumulator[j] += ((uint8_t*)(&temp_accumulator))[j]; } } for (size_t outer = count - (count % block_size); outer < count; outer++) { for (size_t j = 0; j < bits; j++) { if (data[outer] & (T(1) << j)) { accumulator[j]++; } } } } void bitcount_naive(const T *data, uint32_t accumulator[bits], const size_t count) { for (size_t outer = 0; outer < count; outer++) { for (size_t j = 0; j < bits; j++) { if (data[outer] & (T(1) << j)) { accumulator[j]++; } } } } Depending on the chose compiler, the vectorized form achieved roughly a factor 25 speedup over the naive one. On a Ryzen 5 1600X, the vectorized form roughly achieved the predicted throughput of ~600,000,000 elements per second. Surprisingly, this is actually still 50% slower than the solution proposed by @njuffa. General Setwise Operations, Most processors have dedicated instructions to count the number of ones in a word instructions: popcnt for x64 processors and cnt for the. 64-bit ARM be preferable to dedicated non-SIMD instructions if we are by checking the value of each bit individually by calling count A population count for a 64-bit word would. What should I do when a paper is published similar to my PhD thesis without citation? School performs periodic password audits. Is my pass See Efficient Computation of Positional Population Counts Using SIMD Instructions by Marcus D. R. Klarqvist, Wojciech Muła, Daniel Lemire (7 Nov 2019) Faster Population Counts using AVX2 Instructions by Wojciech Muła, Nathan Kurz, Daniel Lemire (23 Nov 2016). Basically, each full adder compresses 3 inputs to 2 outputs. So one can eliminate an entire 256-bit word for the price of 5 logic instructions. The full adder operation could be repeated until registers become exhausted. Then results in the registers are accumulated (as seen in most of the other answers). Positional popcnt for 16-bit subwords is implemented here: // Carry-Save Full Adder (3:2 compressor) b ^= a; a ^= c; c ^= b; // xor sum b |= a; b ^= c; // carry Note: the accumulate step for positional-popcnt is more expensive than for normal simd popcnt. Which I believe makes it feasible to add a couple of half-adders to the end of the CSU, it might pay to go all the way up to 256 words before accumulating. [PDF] x86 Intrinsics Cheat Sheet, Bitwise boolean operations on 64-bit words are in fact 64 parallel operations on each bit performing one setwise operation without any "side-effects". Square� Count each bit-position separately over many 64-bit bitmasks, with AVX but not AVX2 (5 answers) Closed last month . Update: Please read the code, it is NOT about counting bits in one int Programming, NOTE: For each element pair cmpord sets the result bits to 1 if both elements are not. NaN, otherwise 0. cmpunord sets bits if at least one is NaN. SSE2. Old Float/ � Output : n = 16, Position 5 n = 12, Invalid number n = 128, Position 8. Following is another method for this problem. The idea is to one by one right shift the set bit of given number ‘n’ until ‘n’ becomes 0. Indirect Bit Indexing and Set, Faster Population Counts Using AVX2 Instructions with Daniel Lemire and Nathan Kurz. AVX512 8-bit positional population count procedure [2019-12-31] new Parse multiple decimal integers separated by arbitrary number of delimiters can be really AVX512F is not as powerful as AVX512BW, but base64 is feasible.. [PDF] Intel� Architecture Instruction Set Extensions Programming Reference, Each byte contain 2 independently indices - say upper 3 bits will be Each entry will be also counted (not only) set, but this is not required. Tags: Intel� Advanced Vector Extensions (Intel� AVX) surely it will be much better to notify this more visible. To be short - AVX2 is currently unusable for me. Write an efficient program to count number of 1s in binary representation of an integer. Examples : Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 13 is 1101 and has 3 set bits - using uint16as counters would likely result in overflow - "like using some sort special assembly instruction that represents the above loop." --> a good compiler will see this. Refer to your compiles optimization settings to activate such. - Suggestion: take down question, add a test harness around it to report time and post that code asking for improvements. As is now, question is too broad. - You should fill the buffer with realistic data too. The number of set bits and their pattern affects the performance of this code, accidentally having all zeroes would unfairly benefit branchy code which would perform worse on maximally random bits (50% chance, uncorrelated) - @Gene: no, popcntis a horizontal popcnt that adds up all the bits in one integer. The OP wants separate counts for every bit-position over multiple integers. You want to unpack bit to something wider (e.g. nibbles or bytes), then vertical add (like paddb) as many times as you can without overflow, then expand to wider counters. - It appears that my CPU doesn't perform as well as yours :-) I tried if ((pLong[j] & m) != 0)and it made no difference in time. Tried target[i] += (pLong[j] >> i) & 1;, it is actually worse, since time goes to 2.74 seconds. - @pktCoder and chqrlie: Your numbers are more useful when you specify the CPU model used to run the experiments and the compiler options used to compile the code. - @HadiBrais My CPU is i7-2670QM, mentioned in the post. - @pktCoder: Also note that chqrlie is using clang, which normally unrolls inner loops, while gcc doesn't enable loop unrolling unless you use -fprofile-generate/ run the program / -fprofile-use. Also your gcc4.8 is quite old, barely newer than your CPU. A newer gcc version would optimize better. - @phuclv: Thank you. I added your method in this comparative benchmark: stackoverflow.com/a/55059914/4593267 in the case of this question, it is (only) 30% slower than the lookup table. SIMD approaches would probably squeeze more cpu cycles out. - Thanks @peter-cordes for the writeup. I will have to study it carefully since I believe it's the way to go.
http://thetopsites.net/article/55081525.shtml
CC-MAIN-2020-50
refinedweb
3,009
60.35
28 December 2004 to 04 January 2005. Happy New Year to everyone. 1) Anyone tried to compile Ocaml on .NET? 2) Parser for configuration file 3) recmod 4) OCaml NAE releases Cf-0.5 and Iom-0.1 5) Internships and Post-doctoral Positions at MSR Cambridge 6) MacOS port and file formats 7) Ocaml in String Theory 8) timer ======================================================================== ====== 1) Anyone tried to compile Ocaml on .NET? Archive: ------------------------------------------------------------------------ ------ ** SooHyoung Oh asked: Is there anyone who has ever tried to compile ocaml on .NET environment? I can find lots of infomation from the ocaml-mailing list: Mono project: F#: sml.net: Nemerle: John Goerzen's message: After some test on F#, my feeling is that it's not so good as Ocaml. So I'm looking for Ocaml implementation on .NET environment. (Interoperability is not my concern.) There is a message that because the type system of Ocaml is so complex that it's not easy to make Ocaml.net. But I think it's not so difficult to compile Ocaml on .NET, is it? ** Tom Hirschowitz suggested: What about this work by Raphael Montelatici and others? ** Richard Jones also answered: One possibility is running .NET code on the Mono VM, embedded in an OCaml process. It seems like it should be possible, although the specifics of how the two garbage collectors might behave together is unclear. ======================================================================== ====== 2) Parser for configuration file Archive: ------------------------------------------------------------------------ ------ ** Romildo asked and Jørgen Hermanrud Fjeld suggested: > Is there a library that implements a parser > for configuration files similar to the *.ini > files from windows? For instance: > > [section 1] > key1 = value1 > key2 = value2 > > [section 2] > key3 = value3 > key4 = value4 > key5 = value5 May I suggest ConfigParser from missinglib:... ======================================================================== ====== 3) recmod Archive: ------------------------------------------------------------------------ ------ ** Anastasia Gornostaeva asked and John Skaller answered: > Is it possible to compile such files? > > mod1.ml: > let get a = > if Mod2.mem a then 1 else 2 > > mod2.ml: > let mem a = List.mem a [1;2;3] > let other () = > print_int (Mod1.get 5) No. There is a new experimental feature which provides some support for intra-module recursion, but at present the modules must reside in the same file. The two common workaround for functions are: (a) pass Mod2.get to Mod1.get as an argument (b) create a reference in mod1.ml initialised to fun (x:int) -> raise Not_found; 1 and in mod2.ml store Mod2.get into it, call it in mod1.ml by first dereferencing it. Another technique is to use classes, which automate the late binding more safely. ======================================================================== ====== 4) OCaml NAE releases Cf-0.5 and Iom-0.1 Archive: ------------------------------------------------------------------------ ------ ** James Woodyatt announced: below. ===== OCaml NAE Core Foundation (cf) library ===== ===== Version 0.5 ===== Highlights of the changes: + Many bugs fixed (some critical). + IPv6 socket addresses are now a triple, containing the scope identifier. + Fixed a very bad stack leak problem in the [Cf_gadget] scheduler. --- [Cf_deque] Fix major bug in [fold] that caused a BUS ERROR (ack!), and also fixed [filter] so that it uses the non-recursive [fold] function here instead of going to the extra work of using [Cf_seq.fold]. --- [Cf_rbtree] Fix a bug in [iterate] (found by Craig Falls; thanks Craig!) caused by a stoopid typo. Caused some elements to be iterated twice, and others not at all. --- [Cf_gadget] Moderate surgery on the scheduler to fix a bad stack leak. The new code is probably a tiny bit more efficient too, because I got rid of some unnecessary uses of {Lazy.t} in places, and there is a bit less lifting between monads. I didn't benchmark it, though. --- [Cf_socket] Added a special case for Mac OS X to work around a bug in Apple's network stack that errors in connect(2) on a non-blocking socket do not get in the errno system variable. You have to get them out of the socket with the SO_ERROR socket option. --- [Cf_ip4_addr] Make the network subnet manipulation functions cope with networks that are not unicast networks. (Yes, there are multicast ranges that can be treated like subnets.) --- [Cf_ip6_proto] Add a third element to the socket address type: an int32 for the scope id. --- [Cf_ip6_addr] Fix the [v4compat] and [v4mapped] address type tags so that they are actually polymorphic variants, like they're supposed to be. This was another stoopid typo, but I found it myself. --- [Cf_netif] Fixed the C-language code to call if_nametoindex() with the proper arguments. Again, this was a stoopid typo. --- [Cf_poll] A minor change to the commented bits of debugging code in the middle of the select loop to use [Cf_journal] instead of my [xprintf] hackery. --- {TESTS} Added a test for the [Cf_gadget] scheduler to detect stack leaks. ===== OCaml NAE Reactive I/O Monad (iom) library ===== ===== Version 0.1 ===== Highlights of this release: + Rewrote the [Iom_sock_stream.endpoint] reactor to fix bugs (and hopefully improve performance in some edge cases). + More optional tests coded (but they're still suboptimal, and maybe buggy). --- [Iom_sock_stream] Rewrote the [endpoint] reactor to use less consing, i.e. the state is now a couple of mutable objects derived from [Cf_poll.event]. Events are plumbed around the inside of the reactor in shorter paths. --- [T_iom] Change to be compatible with cf-0.5 notion of IPv6 socket addresses, which now contain an int32 element for the scope identifier. --- {New Tests} Added a couple of new programs which help me work out bugs. I don't think these programs are really done, since they don't quite give me the control I need to be able to adequately test and benchmark the performance of code based on the [Iom] library. I'll probably need to hammer on these for a while before I have something to document. In the meantime, consider them curiosities for your amusement. ======================================================================== ====== 5) Internships and Post-doctoral Positions at MSR Cambridge Archive: ------------------------------------------------------------------------ ------ ** Don Syme announced: On behalf of those at Microsoft Research, Cambridge, I would like to announce that applications for intern positions at our lab for 2005 are now being accepted. Our lab has a number of groups, but of particular interest may be the Distributed Systems group (), the Programming Principles and Tools group () and the Security group () For myself I am particularly interested in applications for projects related to type systems, virtual machines and/or aspects of language design and implementation related to .NET, ML and F# (). Specific interests of other researchers are detailed on their home pages, and in general you should consider discussing potential projects with a specific researcher soon after applying. Cambridge is a great place to work, and Internships normally last 12 weeks and most commonly occur over the summer. Applicants should be graduate students on PhD programs. For summer 2005 Internships, the deadline for complete applications is 28th February 2005, and references have to be received by this date. The admission process is quite competitive, and we encourage applications in good time before the deadline. We aim to notify candidates of the outcome of their applications by the end of April 2005. Full details and application forms can be found at the following link:... In addition, we are always open to applications for a smaller number of post-doctoral positions. Full details can be found at... ======================================================================== ====== 6) MacOS port and file formats Archive: ------------------------------------------------------------------------ ------ ** Mary Fernandez asked and Jacques Garrigue answered: > I have a question regarding the ./configure options for MacOS/Darwin. > > ./configure selects the -bundle option for MKSHAREDLIB, which > has the effect of creating MacOS bundle type files for the dynamically > linked libraries in lib/ocaml/stublibs. I have had trouble linking > these bundle files with the standard dynamically linked libraries > created with the -dynamiclib option. As an experiment, I replaced > -bundle by -dynamiclib and attempted to rebuild the O'Caml compiler, > but got an error deep in compilation of the compiler. Ultimately, > I just made the otherlibs/* libraries by hand with -dynamiclib and was > able to link my application. > > I will admit that I am overwhelmed by the Darwin documentation > that explains how to port a Linux application to MacOS. > Can someone explain why the -bundle option is necessary to the compiler > compilation? > Is it because the O'Caml compiler a full-fledged Mac application? Could you explain exactly what you are trying to do? The dlls in stublibs are only intended to be dynamically loaded by an ocaml application. The reason bundles are used rather than dynamic libraries is that the API for bundles is simpler, and that their explicit intent (plugins) seems close enough to the use of dlls in ocaml. Note that a bundle can depend on dynamic libraries, so this should not induce other limitations. ** Mary Fernandez replied: Thanks for your message. Here is what I am trying to do.. What I have found is that if the dll*.so libraries are Mac bundle files, then I get a linking error of the form "...ld: /Users/mff/ocaml-3.08.2/lib/ocaml/stublibs/libstr.dylib is input for the dynamic link editor, is not relocatable by the static link editor again..." (Note that the default name of dllstr.so is not recognized by the Darwin linker). If I re-compile the otherlibs/ in stublibs/ to be dynamically linked libraries, then I have no problems. Also, if I just use the archive files, that works too -- but I typically use O'Caml with dynamic libs enabled which is how I tripped over this problem. We only create a dynamically linked library, because our Java library call the C library, and the Java JNI requires dynamically linked C libraries. So, in short, I have something that works, but still dont' understand why bundles and dynamically linked libraries caused me trouble. ** Jacques Garrigue answered: >. To be more precise, ocamlmklib produces two kinds of output: a DLL for dynamic loading in bytecode programs, and a static library for custom and native programs. What you seem to want is a dynamic library to link with native programs, which is out of the specification. On most architectures, the DLL can be used as a dynamic library, but this is not true on darwin, and only partly true on windows (you also need a binding library, which is not kept.) If your concern is darwin, then there is a simple answer: you can just get the installed static library, and turn it into a dynamic library, as all C code on darwin is position independent. Just look for the correct linker incantation in the darwin manual. It's better not to try to meddle with the core ocaml compilation, which has different goals in mind. ** Jacques Garrigue then added: In case you could not find it, here is the incantation: ld -dylib -all_load -flat_namespace -undefined suppress /usr/local/lib/ocaml/libunix.a -ldylib1.o -o libunix.dylib You can also link all these libraries directly in your dynamic linked C library, without creating individual dlls (but this works only for platforms such as darwin, where all code is position independent). ======================================================================== ====== 7) Ocaml in String Theory Archive: ------------------------------------------------------------------------ ------ ** Thomas Fischbacher announced: Ladies and Gentlemen, a happy new year to all readers of this list. For a non-mainstream language like Ocaml, it is evidently of great importance to have good answers to the question about its practical relevance. It seems as if we now have another nice application to add to the list: in today's official arxiv.org listing, the following preprint paper (by myself and two colleagues from the Albert Einstein Institute) appeared: Physically speaking, one of the hot topics in string theory today is the conjectured equivalence of certain quantum field theories which neither at the classical level nor as quantum theories have an intrinsic length scale on the one side - so-called conformal field theories - and string theory on a space-time which approaches constant negative curvature at infinity (i.e. anti deSitter space) - see e.g. What we did was to provide further strong evidence that the physical key property of integrability holds, however another important property known as BMN scaling (sorry, I cannot go into details) is violated in quite non-obvious ways. Computationally, what we had to do in order to achieve this result was to develop a fast algorithm which furthermore can be implemented close to the machine level that allows us to sum literally billions of contributions from different planar feynman graphs with four loops in them. Planarity is the key property here that makes this calculation feasible - if we included the non-planar graphs as well, we would have had to deal with an estimated number of contributions of about half a quadrillion. At the much simpler three loop level, our approach is faster than previous ones (using the FORM program which was built explicitly for fast quantum field theoretic calculations) by about a factor of 100. This comes in part from our improved algorithm that singles out planar graphs (and hence scales much better than algorithms which do not), in part from doing term transformations not in an interpreted fashion, but directly at machine code level (via compiled ocaml), furthermore from carefully ensuring not to do unnecessary work when simplifying terms, from evil hacks (such as abusing the FPU to do exact(!) fraction arithmetics for fractions of the form <small numerator>/<small power of 2>), and - quite important - from certain algorithmic tricks from the functional programmer's toolbox such as continuation coding and lazy evaluation. In other words, it would not at all have been possible in anything else but a fast compiled functional language. Nevertheless, we still had to burn 88 000+ CPU-hours on 2 GHz Athlon (and Opteron) hardware to do the largest piece of the calculation and we are very grateful towards our numerical colleagues for providing us with appropriate resources - this is true symbolic supercomputing. While we (the authors) are not yet sure about this, we think to have strong reason to believe that this may be the (presumably by orders of magnitude) largest symbolic algebra calculation performed so far - counting the number of term transformations. (Excluding cypher breaking and prime search attempts, as the underlying questions hardly can be regarded as of symbolic nature.) We know that there have been quite large four-loop QCD calculations before involving something like 50 000 individual graphs that furthermore had to deal with some transformations on integrals (which we do not have, due to a certain kind of reduction we perform in our model) and hence are somewhat more difficult to calculate than our graphs - but certainly not by a factor of 100 000. If anyone knows better and can tell us about an even larger symbolic calculation, we would be glad to hear about it. While our paper is essentially for physicists, it features a self-contained appendix explaining the algorithmic and implementation aspects of our work that should be readable especially for people with a computer science background. Furthermore, one can download (details in the paper) our source. Unfortunately, in order to actually build the program, one needs a somewhat large development environment, as some of the ocaml source and data files are machine generated by perl and CMU Common Lisp. Admittedly, the code could be cleaner, but one should keep in mind here a few external factors (i.e. pressure to publish new physical results) which are different for computer scientists and physicists. Well, it's not as bad as quite a lot of code in physics, and I think I can show it around without having to pull a brown paper bag over my head, but the style is certainly not one I'd like to see in textbooks. Given the time (which I at present do not have), I'd like to clean it up a bit more. ======================================================================== ====== 8) timer Archive: ------------------------------------------------------------------------ ------ ** Anastasia Gornostaeva asked and SooHyoung Oh answered: > Does exist Timer module, that allows me add/reset/remove timed events? > Currently I use Unix.setitimer() for my simple implementation that allows > only adding new events into a queue, but my skills is not enough to implement > reset and remove events from the Timer queue. > And I'm not sure if using Unix.sleep() with setitimer() is safely (without > Threads). I have one at . ======================================================================== ======, just tell me so. ======================================================================== ====== Alan Schmitt Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/117717/
crawl-003
refinedweb
2,699
62.88
Really Simple Syndication By Sam Ruby, September 2, 2002. From Netscape's RDF Site Summary (RSS) 0.9 official DTD, proposed: RSS is an XML/RDF vocabulary for describing metadata about websites, and enabling the display of "channels" on the "My Netscape" website. This document explores the basic concepts behind the various XML grammars which were derived from this base and makes suggestions as to directions for their further evolution. Gentle introduction to RSS Let's start this journey by looking at a humble RSS file. In fact, lets look at mine as produced by two different tools, first Radio, then blosxom. There are some differences (primarily additional elements that few render), but the essential structure is the same, i.e.: Channels have items. Both channels and items have (optionally, it turns out) a title, link, and description. That's pretty all you need to get up and running. Everything else is gravy. You could write one by hand, but the truth of the matter is that the overwhelming majority of RSS feeds are written by programs and for programs. Now lets take a look at a specification. Here's the recently proposed 0.94 spec. It describes a lot more elements than I described above. Here's a summary of the ever growing number of elements defined in the core specifications. RSS 1.0 bucks the trend. Instead of an ever growing number of elements in the core specifications, extensions are provided by modules. In fact, there is even a proposed module capturing the additions made by 0.91. The roadmap for 0.94 indicates that successors to this version may consider a similar approach, but for now, additions continue to be made to the core. The change notes for 0.94 indicate that <image> is now optional. This surprised me. Looking at my RSS feeds, including the one produced by Radio, I don't see an image element. I am not aware of any aggregator having a problem with my Radio newsfeed, so I can only conclude that this element was effectively always optional. A slow but continuous rate of growth. Looking again at the change history for 0.94, it is clear that great pains have been made to ensure that upward compatibility has been maintained. What this means is that if you author (by hand or by program) an RSS feed precisely according to the 0.92 specification, your investment will be protected and can be consumed by any aggregator designed for 0.94. As I said previously, RSS feeds are typically written by programs and for programs. There are a number of programs designed to consume RSS feeds. These programs are known as aggregators. Now, lets take a moment and look at compatibility from the consumer's perspective. RSS 0.91, RSS 0.92, and RSS 0.94 do not make any claims about backwards compatibility. What this means that if you are writing an aggregator (or merely using one), there are no guarantees that your investment will be protected. However, things are not as dire as this may seem. Given the excellent record on upward compatibility, it appears that one can safely assume that the following changes can be expected: required elements may be made optional, limits will be lifted, and new elements will be added. The good news is that if there is an element that you are looking for, it's meaning won't change. Given these observations, it is possible to cope with change after a fashion. Namespaces would be better. And they may be coming, just not now. At least not in 0.94. Now lets look at the version attribute, present at the top of, for example, RSS 0.92 feeds. Who is this data intended for? I have no research to back this up, but it would seem to me that most consumers of RSS feeds would ignore this attribute, for two reasons, both stated previously. First, one can't assume that the data that follows is valid with respect to such specifications. Second, there will in all likelihood be other versions of RSS specifications, perhaps not even written yet, that have to be dealt with by the same aggregator. Now lets look at other differences between RSS 0.9/RSS 1.0 and RSS 0.91/RSS 0.92/RSS 0.94. Comparing the latest of each branch one ends up with the following: - The name of the outermost element are both TLA's starting with the letter 'R'. Just different TLA's. - Both support the essential <channel>, <item>, <title>, <link>, and <description> elements described above. - Both also support <image> and <textInput> elements, which appear largely to be holdovers from 0.9. - <item> elements appear within <channel> elements in 0.94, and appear alongside the <channel> in 1.0. - 1.0 supports namespaces now, successors to 0.94 may do so in the future. - 0.94 defines more elements in the core specification. When you include modules, 1.0 has more elements defined in total. So lets start with a clean slate and describe what I would like to see in an RSS 2.0 if I were made king of the world for a day and were free to make whatever changes I like. Of course, if I were made king of the world for a day, I would probably devote my time to other matters, but let's not digress here too much... Before talking about futures, it helps to establish a framework of values. From the very beginning of my career, I've been indoctrinated into the importance of backwards compatibility. Not just for producers, but also for consumers. As king, I would ensure that the next spec explicitly recognizes the importance of this from this point on. Simplicity. I really L*O*V*E the new name for RSS 0.94. Really Simple Syndication. Unfortunately, this spec attempts to live up to this new name by adding still more attributes to the core, albeit optional ones. Extensibility as described in the RSS 1.0 design goals, and affirmed by the RSS 0.94 roadmap, developers should be able to add modules without interfering with each others work. So this one no longer appears to be controversial. For starters, I would like to see a return to simplicity. Remove from the core all elements except <channel>, <item>, <title>, <link> and <description>. And make every one of them optional except channel. This means that image and textInput would be placed into a "mod_rss09" module. Then add in an 0.91 module, with a key difference. I'd like to see UserLand host the document and have the RSS 2.0 modules list reflect this. This means that every recipient of document containing these elements would provide attribution to UserLand, as well as having the URL where they can find the human readable description for any such elements. This should be repeated for 0.92 and 0.94. Simon Fell can host his own description for 0.93. Of course, every 1.0 module would be a valid 2.0 module. As to whether the items should be in or out of the channel, or the name of the outermost element which acts as a container... I would leave such important decisions to day two. I actually don't want to slow down or derail the current 0.94 work. Let a thousand flowers bloom and all that. But it is helpful occasionally to revisit first principles. In this case, can every feature of 0.92 justify itself? If so, great, otherwise, perhaps at some point in the future it might be worth streamlining the core spec. Meanwhile, RSS has grown considerably from it's original humble beginnings as a "site summary" to a syndication format that enable people to communicate with people without significant investment in infrastructure and across both time and platform boundaries. Everyone involved, particularly Netscape, UserLand, and the RSS-DEV working group deserve our gratitude.
http://www.intertwingly.net/stories/2002/09/02/reallySimpleSyndication.html
CC-MAIN-2017-09
refinedweb
1,333
67.35
A vendor sent us three separate files which need to be merged. 70,000+ records each. They're CSV files, so column position doesn't much matter. The column name (in row 1) is what matters. I looked at three solutions. Two of which are merely OK. The third was some functional programming that was very cool. Option 1 -- OS Sort/Merge To get the files into a consistent order, we need to sort. The Linux sort, however, is biased toward columns that are known positionally. So, we need to exploit the Decorate-Sort-Undecorate design pattern. So we have a shell script something like the following. decorate.py a.csv | sort >a_sorted.csv decorate.py b.csv | sort >b_sorted.csv decorate.py c.csv | sort >c_sorted.csv sort -m a_sorted.csv b_sorted.csv c_sorted.csv | undecorate.py >result.csv This works well because decorate.py and undecorate.py are such simple programs. Here's decorate.py. from __future__ import print_function import csv import sys with open(sys.argv[1],"rb") as source: rdr= csv.DictReader( source ) for row in rdr: print( row['the key'], row ) Undecorate is similar. It uses the str.partition() method to remove the decoration. Note that the initial "decorate" steps can be run concurrently, leading to some time reduction. This scales well. It doesn't use much memory; the OS concurrency management means that it uses every core available. I didn't benchmark this, BTW. Option 2 -- Big In-Memory Dict Since the files aren't insanely big, they do fit in memory. This is pretty simple, also. import csv from collections import defaultdict # build the result set result = defaultdict( dict ) for f in ( 'a.csv', 'b.csv', 'c.csv' ): with open( f, 'rb' ) as source: rdr = csv.DictReader( source ) for row in rdr: result[row['key']].update( row ) # find the column titles keys = set() for row in result: keys |= set( result[row].keys() ) # write the result set with open( 'output.csv', 'wb' ) as target: wtr= csv.DictWriter( target, sorted(keys) ) wtr.writerow( dict(zip(keys,keys)) ) for row in result: wtr.writerow( result[row] ) This isn't too bad. For insanely big files, however, it won't scale well. Elapsed time for the real files (which were zipped, adding processing that's not relevant to this posting) was 218 seconds on my little laptop. Option 3 -- Functional Programming The functional programming approach is a bit more code than option 1. But it's way cool and very extensible. It offers more flexibility without the memory limitation of the big dictionary. Let's start with the end in mind. We're doing a 3-file merge. The algorithm for 2-file merge is really simple. The algorithm for an n-file merge, however, is not so simple. We can easily build up an n-file merge as a composition of n-1 pair-wise merges. Here's how it should look. We're doing merge( merge( s1, s2 ), s3 ) to compose a 3-file merge from 2 2-file merges. And yes, it can be just that simple.We're doing merge( merge( s1, s2 ), s3 ) to compose a 3-file merge from 2 2-file merges. And yes, it can be just that simple.with open('temp.csv','wb') as output: wtr= csv.DictWriter( output, sorted(fieldNames) ) wtr.writerow( dict( zip( fieldNames, fieldNames ))) for row in merge( merge( s1, s2 ), s3 ): wtr.writerow( row ) Composable Sort To be "composable", we must write iterator functions which read and write data of the same type. In our case, since we're using a DictReader, our various functions must work with an iterable over dicts which yields dicts. In order to merge, the input must be sorted. Here's our composable sort. Yes, we need to pre-process the keys, they're not simple text; they're numbers.Yes, we need to pre-process the keys, they're not simple text; they're numbers.def key_sort( source, key='key' ): def get_key( x ): return int(x[key]) for row in sorted(source, key=get_key ): yield row Composable 2-File Merge The composable merge has a similar outline. It's a loop over the inputs and it yields outputs of the same type. def merge( f1, f2, key='key' ): """Merge two sequences of row dictionaries on a key column.""" r1, r2 = None, None try: r1= f1.next() r2= f2.next() while True: if r1[key] == r2[key]: r1.update(r2) yield r1 r1, r2 = None, None r1= f1.next() r2= f2.next() elif r1[key] < r2[key]: yield r1 r1= None r1= f1.next() elif r1[key] > r2[key]: yield r2 r2= None r2= f2.next() else: raise Exception # Yes, this is impossible except StopIteration: pass if r1 is not None: yield r1 for r1 in f1: yield r1 elif r2 is not None: yield r2 for r2 in f2: yield r2 else: pass # Exhausted with an exact match. This runs in 214 seconds. Not a big improvement in time. However, the improvement in flexibility is outstanding. And the elegant simplicity is delightful. Having the multi-way state managed entirely through the Generator Function/Iterator abstraction is amazing. Also, this demonstrates that the bulk of the time is spent reading the zipped CSV files and writing the final CSV output file. The actual merge algorithm doesn't dominate the complexity.
http://slott-softwarearchitect.blogspot.com/2010/05/functional-programming-goodness-python.html
CC-MAIN-2017-43
refinedweb
891
70.09
How to count unique values in a Python list? There are multiple ways and in this tutorial we will go through them as a way for you to practice several Python constructs. The simplest way to count unique values in a Python list is to convert the list to a set considering that all the elements of a set are unique. You can also count unique values in a list using a dictionary, the collections.Counter class, Numpy.unique() or Pandas.unique(). Most of our examples will work on the same list of numbers: numbers = [2, 3, 3, 6, 8, 8, 23, 24, 24, 30, 45, 50, 51, 51] We will implement every approach in its own function so it’s easy to call them from the “main” of our code. Every function takes the numbers list as input and returns the list with unique values. The main of our program will then count the number of unique values using the list len() method. Let’s get started! 1. Using a For Loop to Count Unique Values in a Python List The first approach uses a Python for loop to go through all the elements. def get_unique_values_with_for_loop(values): unique_values = [] for value in values: if value not in unique_values: unique_values.append(value) return unique_values The for loop goes through every element of the list and adds that element to a new list if it’s not already present in the new list. Let’s write a generic code to print the result returned by this function so we can use pretty much the same code to print the result returned by the other functions we will create in the next sections. numbers = [2, 3, 3, 6, 8, 8, 23, 24, 24, 30, 45, 50, 51, 51] unique_values = get_unique_values_with_for_loop(numbers) number_of_unique_values = len(unique_values) print("The list of unique values is: {}".format(unique_values)) print("The number of unique values is: {}".format(number_of_unique_values)) The output is: The list of unique values is: [2, 3, 6, 8, 23, 24, 30, 45, 50, 51] The number of unique values is: 10 The only line we will have to update when calling a different function is the following: unique_values = get_unique_list_with_for_loop(numbers) Everything else in the main of our program will stay the same because it depends on the variable unique_values. 2. Count Unique Values in a Python List Using a Set The set is a data structure that only contains unique elements. We can use this property of the set to get back just unique values. def get_unique_values_with_set(values): return set(values) ... unique_values = get_unique_values_with_set(numbers) ... Notice the curly brackets in the output due to the fact that the function returns a set: The list of unique values is: {2, 3, 6, 8, 45, 50, 51, 23, 24, 30} The number of unique values is: 10 Do you see that the order of the elements has changed compared to the original list? That’s because… The set data type is unordered. The nice thing of this approach is that the code is a lot more concise (just a single line function). 3. Using a Dictionary to Get the Number of Unique Values in a List Could we use the fact that dictionary keys are unique to get unique elements from the original list? We could create a dictionary where the unique elements in the list are the keys of the dictionary. The values of the dictionary are counters that tell us how many time each element appears in the list. def get_unique_values_with_dictionary(values): new_values = {} for value in values: if value in new_values.keys(): new_values[value] += 1 else: new_values[value] = 1 print(new_values) return new_values.keys() ... unique_values = get_unique_values_with_dictionary(numbers) ... At each iteration of the for loop we verify if a specific value already exists as dictionary key. If it doesn’t we add that key to the dictionary and we set the value to 1. Otherwise we increase the value associated to the existing key in the dictionary. I have added a print() statement in the function to show you the dictionary created. {2: 1, 3: 2, 6: 1, 8: 2, 23: 1, 24: 2, 30: 1, 45: 1, 50: 1, 51: 2} The list of unique values is: dict_keys([2, 3, 6, 8, 23, 24, 30, 45, 50, 51]) The number of unique values is: 10 4. Collections.Counter To Count Unique Values in a List The same approach explained in the previous section (using a standard dictionary) can also be implemented using the Counter class of the Collections module. Let’s find out what Counter does exactly: >>> from collections import Counter >>> Counter([1,2,3,3]) Counter({3: 2, 1: 1, 2: 1}) Interesting… It generates a dictionary-like data structure where the keys are the elements of the list and the values indicate the count of each element in the original list. Basically the same thing we have created in the previous section using a standard Python dictionary. Let’s apply it to our list of numbers: >>> from collections import Counter >>> numbers = [2, 3, 3, 6, 8, 8, 23, 24, 24, 30, 45, 50, 51, 51] >>> new_values = Counter(numbers) These are the methods available for the Counter object: >>> new_values. new_values.clear( new_values.get( new_values.pop( new_values.update( new_values.copy( new_values.items( new_values.popitem( new_values.values( new_values.elements( new_values.keys( new_values.setdefault( new_values.fromkeys( new_values.most_common( new_values.subtract( The .keys() method is the one we need to get the unique elements in the original list: >>> new_values.keys() dict_keys([2, 3, 6, 8, 23, 24, 30, 45, 50, 51]) So, we can add the following function to our code: from collections import Counter ... ... def get_unique_values_with_counter(values): return Counter(values).keys() ... unique_values = get_unique_values_with_counter(numbers) ... The output is: The list of unique values is: dict_keys([2, 3, 6, 8, 23, 24, 30, 45, 50, 51]) The number of unique values is: 10 In the same way we have seen when using the set, with this approach we can write a one-line function. 5. Counting Unique Values in a List Using NumPy The NumPy library also provides a way to count unique values in a list (or array). NumPy.unique not only allows to find the unique elements of an array but it also provides the number of times each element is present by using the return_counts parameter. >>> import numpy as np >>> print(np.unique(numbers)) [ 2 3 6 8 23 24 30 45 50 51] >>> print(np.unique(numbers, return_counts=True)) (array([ 2, 3, 6, 8, 23, 24, 30, 45, 50, 51]), array([1, 2, 1, 2, 1, 2, 1, 1, 1, 2])) So, let’s create a new function that uses np.unique(): import numpy as np ... def get_unique_values_with_numpy(values): return np.unique(values) ... unique_values = get_unique_values_with_numpy(numbers) ... And here are the unique elements we get back: The list of unique values is: [ 2 3 6 8 23 24 30 45 50 51] The number of unique values is: 10 6. Using Pandas to Get Unique Values in a List We can also get unique values in a list using Pandas. To do that we will use pandas.unique. It takes as input a one-dimensional array, so let’s write our function: import pandas as pd ... def get_unique_values_with_pandas(values): return pd.unique(pd.Series(values)) ... unique_values = get_unique_values_with_pandas(numbers) ... The output returned by our program is: The list of unique values is: [ 2 3 6 8 23 24 30 45 50 51] The number of unique values is: 10 7. Count Unique Values in a List of Dictionaries Let’s write code to do something a bit more complex. I have a list of dictionaries that all contain the same key and I want to get the count of unique values across all the dictionaries in the list. countries = [{"name": "Italy"}, {"name": "UK"}, {"name": "Germany"}, {"name": "Brazil"}, {"name": "Italy"}, {"name": "UK"}] The first step would be to get a list that contains all the values in each dictionary. To do that we can use a list comprehension. >>> names = [country['name'] for country in countries] >>> print(names) ['Italy', 'UK', 'Germany', 'Brazil', 'Italy', 'UK'] Now we can use one of the approaches already used before. For example we can pass the list to collections.Counter: >>> from collections import Counter >>> Counter(names) Counter({'Italy': 2, 'UK': 2, 'Germany': 1, 'Brazil': 1}) >>> Counter(names).keys() dict_keys(['Italy', 'UK', 'Germany', 'Brazil']) >>> len(Counter(names).keys()) 4 Makes sense? 8. Which One is the Faster Approach to Count Unique List Values? We will complete this tutorial by comparing the performance of all the approaches we have implemented to solve our problem. To do that we will generate a list with random elements and then use the timeit module to measure the execution time for each implementation. We will generate the list of random numbers using the Python random module: >>> import random >>> random_numbers = [random.randrange(10) for i in range(10)] >>> print(random_numbers) [7, 6, 0, 7, 9, 8, 1, 6, 7, 4] This is just an example of list that contains 10 random numbers between 0 and 9. To measure the performance of our function we will use a bigger list with random numbers in a wider range. random_numbers = [random.randrange(100) for i in range(1000000)] Let’s take the first function we have created, the one that uses the for loop. Here is how we can pass it to the timeit.timeit function: import timeit testfunction = ''' def get_unique_values_with_for_loop(values): unique_values = [] for value in values: if value not in unique_values: unique_values.append(value) return unique_values ''' random_numbers = [random.randrange(100) for i in range(1000000)] print(timeit.timeit(testfunction, number=100000000)) The number parameter represents the number of executions. The output is: 5.022220958 To measure the execution time for every function with timeit simply surround a given function with the following two lines in the same way we have done above: testfunction = ''' {function_to_test} ''' Let’s compare the execution time between the six approaches implemented in this tutorial: get_unique_values_with_for_loop: 5.022220958 get_unique_values_with_set: 5.150171875 get_unique_values_with_dictionary: 5.140621958 get_unique_values_with_counter: 5.145550625 get_unique_values_with_numpy: 5.187875792000001 get_unique_values_with_pandas: 5.070051584 The fastest implementation is the first one that uses a Python for loop and most of them have a comparable performance. Conclusion After reading this article you have lots of different ways to count unique values in a Python list. I hope you have found this tutorial useful to see how you can solve the same problem in many different ways using Python. Which one of the solutions we have implemented do you prefer? 🙂 I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
https://codefather.tech/blog/python-count-unique-values-in-list/
CC-MAIN-2021-31
refinedweb
1,768
60.95
Groovy Goodness: Using Builder to Create Fluent API for Other Classes In a previous post we learned about the new @Builder AST transformation introduced in Groovy 2.3. We applied to the annotation to our class files and we got a nice fluent API to set property values. But what if we cannot change the class itself, for example if we want to create a fluent API for classes in an external library. Then we can still use the @Builder AST transformation but we use a different strategy. We can define the builder strategy via a annotation parameter. In the following sample we assume the Message class is from an external library and we cannot or do not want to change the class definition. We create a new Groovy class and set the @Builder annotation on this new class. We use the annotation parameters builderStrategy to indicate the generated code is not for the new class, but for the class set with the annotation parameter forClass. import groovy.transform.builder.Builder import groovy.transform.builder.ExternalStrategy // We don't want to change the definition // of this class to get a fluent API. class Message { String from, to, subject, body } // New builder class for the Message class. @Builder(builderStrategy = ExternalStrategy, forClass = Message) class MessageBuilder {} def message = new MessageBuilder() // Create new instance. .from('mrhaki@mrhaki.com') .to('mail@host.nl') .subject('Groovy 2.3 is released') .body('Groovy rocks!') .build() // Return filled Message instance. assert message.body == 'Groovy rocks!' assert message.from == 'mrhaki@mrhaki.com' assert message.subject == 'Groovy 2.3 is released' We can also customize the prefix for the method names to set property values and we can change the name of the build method. And we can include or exclude properties with the includes and excludes properties: import groovy.transform.builder.Builder import groovy.transform.builder.ExternalStrategy class Message { String from, to, subject, body } @Builder(builderStrategy = ExternalStrategy, forClass = Message, prefix = 'assign', buildMethodName = 'create', includes = 'from,subject') class MessageBuilder {} def message = new MessageBuilder() .assignFrom('mrhaki@mrhaki.com') .assignSubject('Groovy 2.3 is released') .create() assert message.from == 'mrhaki@mrhaki.com' assert message.subject == 'Groovy 2.3 is released' Code written with Groovy 2.3.
https://blog.jdriven.com/2014/05/groovy-goodness-using-builder-create-fluent-api-classes/
CC-MAIN-2021-43
refinedweb
364
50.53
Tag:Add to […] Add instance code of voice input function for textview (integrated iFLYTEK speech recognition)Thank you very much for using your precious time to read my article. Today we bring you a small demo integrating iFLYTEK speech recognition function, adding a voice input function for textview. I believe that in this intelligent trend environment, many people can use this function. If necessary, I hope I can help you. Of […] […] JSP simple add, query function codeThe example of this paper describes the simple add and query function of JSP. Share with you for your reference. The details are as follows: JSP technology: public class ISOtoGb2312 { public static String convert( String str ) { try { byte<> bytesStr=str.getBytes( “ISO-8859-1” ) ; return new String( bytesStr, “gb2312” ) ; } catch( […] Two methods of adding and deleting nodes in mongodb replica set1、 Use rs.reconfig to add and delete nodes 1. Add node Repmore: primary > config = {}id: “repmore”, members: [{}id: 0, host: ‘127.0.0.1:27017’, priority: 2}, {}id: 1, host: ‘127.0.0.1:27018’, priority: 1}]}; // add node Repmore: primary > rs.reconfig (config); // make the configuration effective Repmore: primary > rs.status(); // view node status Node added successfully.Note: […] Explain the link management function of WordPressKeyword Description: function management link can be explained in this add information website This time we’ll talk about WordPress link management. In every WordPress website, users will list some websites they often visit (mostly blogs). WordPress calls this blogroll, which is actually what we call friendship links. In the WordPress management background, blogroll is listed […] Java sample code for adding, modifying and deleting PDF bookmarksWhen reading a long PDF document, in order to facilitate us to quickly locate the last reading position when we read it again, we can insert a bookmark to mark; in addition, for the existing bookmarks in the document, we can also modify or delete them as needed. This article uses Java programming to show […] Summary of common operation methods of JavaScript array [connect, add, delete, de duplicate, sort, etc.]This article describes the common operation methods of JavaScript array. To share with you for your reference, as follows: <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″> < title > array method < / Title > <script> var arr=[1,3,4] var arr1=[“a”,”b”,”c”] var arr2=[“d”,”e”,”f”] var arrNum=[] //1. Add one or more elements to the end of […] Using skills of ckeditor rich text editorThe example of this article describes how to use ckeditor rich text editor to add custom plug-ins. To share with you for your reference, as follows: First, create a new directory qchoice in the plugins directory of ckeditor: The structure of the directory of qchoice is as follows: Then, the images are as follows: The […] Ckeditor 4.4.1 add code highlight plug-in function tutorial [use official recommended code snippet plug-in]This article describes the add code highlight plug-in function of ckeditor 4.4.1. To share with you for your reference, as follows: With the release of ckeditor4.4.1, the previously troubled code highlighting problem has been solved perfectly. In ckeditor4.4, the code snippet plug-in has been officially released, and the code highlighting plug-in can be embedded perfectly. […] WordPress Adding Front Register FunctionThis paper illustrates how WordPress can add the function of foreground registration. Share for your reference. Specific analysis is as follows: WordPress belongs to the open source system of personal blog type. Whether it has the function of foreground registration or not, let me introduce myself to add a member registration function to WordPress. Friends […] Implementation Method of Adding Voice Search Function to WordPressThis paper gives an example of how to add voice search function to WordPress. Share for your reference. Specific analysis is as follows: WordPress can add a voice search function, but this function can only be used in Chrome browser for the time being, because it must use x-webkit-speech, but it is also the API […]
https://developpaper.com/tag/add-to/
CC-MAIN-2020-50
refinedweb
665
53.61
Adding or subtracting a month to a Python datetime.date or datetime.datetime is a little bit of a pain. Here is the code I use for that. These functions return the same datetime type as given. They preserve time of day data (if that is at all important to you). See also: - Recipe 476197: First / Last Day of the Month. - monthdelta module Python, 39 lines There is a much simpler way. For finding the previous month you go to the first, then subtract one day: For finding the next month's first you advance to the next month. By adding 32 days from the first of a month you will always reach the next month. @andreas: Yup, thanks. For some of my use cases, preserving the day of month was important. What about this as an alternative; the range of months is limited by date or datetime, both are supported, and all data (day, and hour/minute/second if it's a datetime) are maintained. The code is also much shorter, and negative numbers are supported for subtracting months. Note: months may be positive, or negative, but must be an integer. def addmonths(date,months): targetmonth=months+date.month try: date.replace(year=date.year+int(targetmonth/12),month=(targetmonth%12)) except: # There is an exception if the day of the month we're in does not exist in the target month # Go to the FIRST of the month AFTER, then go back one day. date.replace(year=date.year+int((targetmonth+1)/12),month=((targetmonth+1)%12),day=1) date+=datetime.timedelta(days=-1) Lets try that again: I think the code of jort.bloom is on the right track, but I believe errors will also always be generated when the target month is a multiple of 12, which returns a modulo remainder of 0. An error in the month will mess up the result. For example, addmonths(12/5/2011, 0) i.e., December 5, 2011 minus no months, will return 12/31/2011, not 12/5/2011, because an error will occur when month=(targetmonth%12) tries to set month=0, not month=12. Also, when the input date is the last day of the month, often I favor using the end of the month of the offset date. So, while 7/31/2012 - 1 month = 6/30/2012 is good, 6/30/2012 - 1 month = 5/30/2012 is bad (I want 5/31/2012). A variable indicating that I want to favor the end of the month should be included so that I can specify if I want an end of the month date to offset to the closest matching day number in a month with more days (i.e, 30 in a 30 day month = 30 in a 31 day month) or to the closest end of the month day in a month with more days (30 in a 30 day month = 31 in a 31 day month). Here is the way I would revise the code to deal with these issues: There was a missing else block in the code I posted. Here it is corrected. Oops. I caught a variable name spelling error. I wish I could edit my previous comments, but since I can't, here is the corrected code again: My own:
https://code.activestate.com/recipes/577274-subtract-or-add-a-month-to-a-datetimedate-or-datet/?in=lang-python
CC-MAIN-2022-05
refinedweb
553
72.46
20 January 2011 18:28 [Source: ICIS news] HOUSTON (ICIS)-- A hefty boost in electricity output helped soak up 243bn cubic feet from ?xml:namespace> The relatively large delivery in the week of 14 January brought total stocks down to 2,716 bcf. The draw was on the high end of market expectations and spurred an increase in the futures market. At noon Natural gas futures prices are an important barometer for the value of chemical commodities, with the fuel’s use as feedstock as well as power production fuel. “Overall electricity output surged by 8.6% to 86,690 gigawatt hours,” Schork said. “That was the largest amount of electrons transmitted since last summer’s heat.” Despite the large withdrawal, current stockpiles are nearly 3% above last year’s levels at the same time, and at a 1.9% surplus to the five-year average. The delivery during 2010’s corresponding week was 248 bcf, according to EIA data. The year-over-year overhang continues to be driven by historically high inventory in the US Gulf coast, which has seen demand in its key market in the northeast wane as production emerges out of shale fields within that region, particularly the Marcellus
http://www.icis.com/Articles/2011/01/20/9428005/strong-electricity-demand-spurs-243-bcf-natural-gas.html
CC-MAIN-2014-10
refinedweb
203
62.38
Abdullah Jassim4,551 Points I didnt understand this video from 3:50 onwards. The following are my specific questions: 1) How does the .pop() function change the list? - my understanding of the .pop() function is that it merely returns either the last item or the indexed item. So how does this change the list? 2) I did not understand the explanation of how it changes in 4:36 - 4:48. - My understanding is that in def DISPLAY_WISHLIST, both DISPLAY_NAME and WISHES are parameters and they are objects. The labels applied to these parameters are Books and books. Correct? After this I still dont understand how .pop changes the list item. 3) How does making a copy of the list not change the list? Thanks in advance. 2 Answers Alex KoumparosPython Web Development Treehouse Moderator 32,445 Points Hi Abdullah, 1) Your understanding of pop() is not quite correct. Let's look at the documentation: list.pop(i) Remove the item at the given position in the list, and return it. It is the removing the item from the given position part that modifies the list. 2) Yes, display_name and wishes are parameters, and they are objects (everything in Python is an object). "Books" and books are the arguments provided for those parameters. The reason that pop() changes the list item is entirely down to the behaviour of the pop method itself, which always changes the list on which the method is called. Example: my_list = ["hello", "there", "abdullah"] word = my_list.pop(0) print(word) # hello print(my_list) # ['there', 'abdullah'] As you can see in this simple example, pop() always does two things: 1: it takes the specified item (or last item if None specified) out of the list and 2: it returns that item. 3) Making a copy of the list is creating an entirely new list and filling it with the items that are in the old list. Consider this simple example: my_list = ["hello", "there", "abdullah"] word = my_list[0] print(word) # hello print(my_list) # ['hello', 'there', 'abdullah'] Hopefully it's clear that just reading a value from a list and putting that value in a variable doesn't modify the original list. We can extend the example slightly: my_list = ["hello", "there", "abdullah"] words = my_list[0:2] print(words) # ['hello', 'there'] print(my_list) # ['hello', 'there', 'abdullah'] Here we've done basically the same thing, but instead of reading one value out of the list, we've read the items from index 0 ('hello') to the last item before index 2 ('there'). Again, we're just reading the values out of the original list, so the original list remains unchanged. Lastly, we can extend the example to copying the whole list: my_list = ["hello", "there", "abdullah"] words = my_list[:] print(words) # ['hello', 'there', 'abdullah'] print(my_list) # ['hello', 'there', 'abdullah'] As you can see, this is exactly the same, except we are telling Python to read all the values from the beginning of the original list to the end of it. Hope that clears everything up for you Cheers Alex Derek Lefler2,608 Points def display_wishlist(display_name, wishes): print(display_name + ":") suggested_gift = wishes.pop(0) print("======>", suggested_gift, "<=======") for item in items: print("* " + item) print() .pop() returns an item from the list and then drops off that item from the list (the last item if not specified). So in the lesson's example, suggested_gift = wishes.pop(0) print("======>", suggested_gift, "<=======") pop(0) returned wishes and then removed the first item from the list. for wish in wishes: print("* " + wishes) So when this part of the function is executed, wishes doesn't include the book "Learning Python..." or the video game "Legend of Zelda...." because pop(0) removed it before. Steven Parker170,248 Points FYI: "pop" removes the last item if not specified. Derek Lefler2,608 Points Steven Parker My mistake, you're correct. Abdullah Jassim4,551 Points Got it now. Thanks for the explanation. Abdullah Jassim4,551 Points Abdullah Jassim4,551 Points Thanks for that detailed explanation. Quick question - in the above example, isnt 2 - 'abdullah'? How come its only capturing till 'there'?
https://teamtreehouse.com/community/i-didnt-understand-this-video-from-350-onwards-the-following-are-my-specific-questions
CC-MAIN-2019-30
refinedweb
675
64.71
You'll need to use a callback function. Basically, a callback function is a function that runs when a piece of code has finished running. In your case, you'd submit the form via the callback function. Have a look at this article. I have a char* data that I casted in order to access it like this I have a char* data that I casted in order to access it like this And that's the source of your problems. It's a contiguous memory block. Write a view facade if you need a different interface, or... My problem is how can I pass "arr" as an argument to a function ? My problem is how can I pass "arr" as an argument to a function ? The easiest way is to avoid using (terrible) low-level primitives left in the language for C compatibility. If you don't know the size at compilation time, use an std::vector. If you do know, use std::array. std::vector std::array but I need to avoid multiplications for speed constraints. but I need to avoid multiplications for speed constraints. Unless you have benchmark data to back that up, I am dismissing that requirement as a premature optimization. Yes, it is possible: #include <stdio.h> void test(char (*foo)[6]) // "declare foo as pointer to array 6 of char" { printf("%zu ", sizeof(*foo)); // mind the asterisk } int main(void) { char foo[6]; test(&foo); // mind the ampersand return 0; } Compare cdecl.org ("C gibberish ↔ English") for char (*foo)[6] char foo[6] char *foo[6] Another option is wrapping the array. But if you don't like referencing/dereferencing, then this solution with an addition member access probably is not what you are looking for, either: #include <stdio.h> typedef struct { char data[6]; } char_6_array_t; void test(char_6_array_t foo) { // prints "6: abcdef" printf("%zu: %.*s ", sizeof(foo.data), (int) sizeof(foo.data), foo.data); } int main(void) { char_6_array_t foo = { {"abcdef"} }; // Depending on the ABI, this prints 6, 8, or possibly 16: printf("%zu ", sizeof(foo)); test(foo); return 0; } This is an example how you can do this. $('.mainnav').find('li').on({ mouseenter: function() { var c = $(this).attr('class'); $('#background-wrap').find('img').attr('src', 'images/' + c + '.jpg'); }, mouseleave: function() { $('#background-wrap').find('img').attr('src', 'images/bg2.jpg'); } }); In the fiddle, even though you can't see the image change. But if you use firebug you can see the source of the image changing. Alternatively, you can have 4 images loaded in the container to begin with. Hide them all with css except for the initial one. Then when you hover the list, you can simply add/remove class for the div to set which image to show and which to hide. This way there is no loading time for all of the images when changing them. But I guess you can also pre-load all the images first You could either define a hitArea () if your image only requires one segment or if you want multiple clickeable areas on one image: Split up the image through using multiple Shapes via beginnBitmapFill (an example for bitmapFill can be found here:) and then put the listeners on the individual shapes. hitArea Shapes beginnBitmapFill
http://bighow.org/questions/16886796/Pass-a-variable-size-value-out-of-Filereader-function-for-seperate-manipulation
CC-MAIN-2017-26
refinedweb
540
65.12
Introduction >>IMAGE alternate source of power , so they can continue to keep track of time while the primary source of power is off. This power source is usually a lithium ion battery. My DS3231 has a CR2032 lithium ion battery. These cells typically produce voltages from 1.5V to about 3.7V. RaspberryPi and the BeagleBone Black do not have a real-time clock which is the reason it is unable to get the current time. You can connect to the internet to get the time from NTP servers. The NTP or the Network Time Protocol is a networking protocol for clock synchronization between computer systems over packet-switched , variable latency data networks ( Confused ? See here : ). The RTC maintains seconds , minutes , hours , day , date , month and year information. You can view the DS3231 datasheet from Here. How Does it Work ? The DS3231 is marketed as an extremely accurate I2C – Integrated TCXO. Let us break it down. The Inter-integrated Circuit or the I2C Protocol is a protocol which allows multiple Slave digital ICs to communicate with one or more Master chips. I will write a whole tutorial on SPI , I2C and other communication protocols. For the time being , you can see the wikipedia page from here. If you look at the backside image of the module ( As shown in the picture ) , it uses two separate ICs on it. The first one is the DS3231 [ the big one ] which is the real-time clock and the second one is the Atmel 24C24N EEPROM which is used by the DS3231 to store the date , time and all other information the clock generates. The DS3231 chip has an internal oscillator. It uses an integrated temperature-compensated crystal oscillator ( TXCO ) and crystal. The chip has 32kHz crystal integrated into the package with a built-in temperature sensor to periodically measure the temperature of the crystal and adjust the frequency so it remains constant to keep it accurate. What is a crystal oscillator or resonator ? TXCO is a form of crystal oscillator widely used in frequency control applications due to its frequency stability and low cost. Crystal oscillators are stable but are affected by temperature. A TXCO adjusts the frequency of the oscillator to compensate for the changes that will occur as a result of temperature changes. Now, let us get the module running. Parts Required Pin Wiring Sensor Pin Arduino Pin VCC 5V GND GND SDA A4 SCL A5 Downloading the Library I’m going ahead with the DS3231 library by Rinky-Dink Electronics which can be downloaded from Here. Add the .zip library from the Arduino IDE to use it ( Go to Sketch > Use Library ). Code #include <DS3231.h> // Include the library DS3231 rtc(SDA, SCL); // SDA and SCL are the data and clock lines void setup() { Serial.begin(115200); // Baud rate : 115200 rtc.begin(); // Initialize the rtc object // Parameters to set rtc.setDOW(SUNDAY); // Set day of the week rtc.setTime(18, 03, 12); // Set the time (24hr format) rtc.setDate(27, 8, 2017); // Set the date/month/year } void loop() { // Send Day-of-Week Serial.print(rtc.getDOWStr()); Serial.print(" "); // Send date Serial.print(rtc.getDateStr()); Serial.print(" -- "); // Send time Serial.println(rtc.getTimeStr()); delay (1000); // 1 sec delay } Output Final Comments Thank you for visiting the website and I would love see your progress and developments with the module. In case of any doubt , feel free to contact me.
http://saumitra.co/ds3231/
CC-MAIN-2019-43
refinedweb
569
57.57
Nothing on serial monitor on MySensor sketches Hello, I am trying to setup a sensor network connected by MQTT Gateway to Open Hab. I started with codebender and was unsuccessful so now I am using the Ardiuno IDE. I have been testing the soil moisture and light level sensors thus far. If I upload the LED Blinking sketch, the LED on my Pro Mini blinks. If I upload the basic Arduino Serial Analog output sketch then on serial monitor I get values that fluctuate depending on light level. If I upload the MySensors light sensor sketch (and change baud rate to 115200) I get nothing on the serial monitor. Similarly if I upload the soil moisture sketch I get no response on the serial monitor. Myconfig.h has #define DEBUG in it. I think my MQTT Gateway is working because I can connect to it from MyMQTT on my Android. OpenHab isn't really giving me any indication it can or cannot connect to the broker. Any thoughts? Right now I am assuming my sensors are the issue but without any output on the serial monitor, I'm unsure. - hooraysimpsons last edited by hooraysimpsons Small update. Plugged the MQTT Controller with MQTT Gateway sketch into the serial monitor and I am getting some information on the monitor. It looks like gibberish which I thought would normally be fized by adjusting the baud rate (started with it on 115200) but trying all the settings gives similar results. However I can publish a message with MyMQTT on android and it does seem to react. So I am still thinking it is my sensors with the issue. Further update: When connecting the monitoring gateway to the serial monitor I see "Started" and if I send a message from MyMQTT on Android I see the message. So the gateway portion and the ethernet portion are working. Cannot confirm radio is working yet. On my light sensor I can build a sketch that doesn't use MySensors and I can read the light level on the serial monitor. When I use MySensors, I get nothing on the serial monitor. Debug is enabled on myconfig. I'm not sure at which point in the process the failure occurs since nothing prints to the serial monitor. I haven't added any capacitors to the radios. I saw that this could help with signal but I'm not sure this is the issue since the two device are 2-4 feet from each other. Is it safe to assume that if the radio connection was the problem, that I would received some kind of feedback about not being able to connect on the serial monitor? Thanks Which light sketch are you using? BH1750FVI or LM393? Have you confirmed communication with just a serial gateway/IDE serial monitor? The sensor is like the LM 393 and it is the analog output sketch. When using the Arduino IDE serial monitor: If I make my own sketch from scratch or use the Arduino example sketch to read analog output, I get a reading from the sensor. If I use the example MySensors sketch and disable all the commands with gw in them, I can get a reading as well. However, when I use the MySensors related commands including gw.begin, I get nothing on the serial monitor. I am having similar issue with a soil moisture monitor. Strange.. IDE version? Serial should be set to 115200 by default. Maybe you could try to lower it in gw.setup() if your USB cable is junk. Ardunio 1.0.6 This code works: #include <SPI.h> #include <MySensor.h> #define CHILD_ID_LIGHT 0 #define LIGHT_SENSOR_ANALOG_PIN 0 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) MySensor gw; MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); int lastLightLevel; void setup() { Serial.begin(9600); // gw.begin(); // Send the sketch version information to the gateway and Controller // gw.sendSketchInfo("Light Sensor", "1.0"); // Register all sensors to gateway (they will be created as child devices) // gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); } void loop() { int lightLevel = (1023-analogRead(LIGHT_SENSOR_ANALOG_PIN))/10.23; Serial.println(lightLevel); if (lightLevel != lastLightLevel) { // gw.send(msg.set(lightLevel)); lastLightLevel = lightLevel; } delay(1000); // gw.sleep(SLEEP_TIME); } with gw.setup I get: LightSensor:18: error: 'class MySensor' has no member named 'setup' If the issue was a bad radio would there still be some kind of output on the serial monitor or would the failure to connect to the gateway cause an issue that prevents the remainder of the code from executing and giving an output? If I replace gw.begin() with the below line of code and continue to comment out the remainder of the gw lines I can get the light output on the serial monitor.); My understanding is the gw.begin() and that line of code should be equivalent. I've coded in the past with Fortran but not for years so I may be missing something obvious here. Sorry meant you could edit begin() (not setup) in MySensor.cpp to lower the serial baudrate above if you have problem with the serial line at high speeds. You should at least get a startup message if you have DEBUG enabled in MyConfig.h. Remve Serial.begin(9600); from your sketch and use the baudrate you use /set in begin(). #define BAUD_RATE 9600 is already placed in mysensors.h. I don't see any reference to baud rate or starting the serial output in the begin function in mysensors.h That is why I added serial.begin(9600) to the sketch to see if that helped. It didn't but I left it in so that it would be started when I commented out the gw.begin Set it here: Which affects this line: I forgot about the .cpp files. Did I tell you I was new to this? So by placing serial.println commands in my mysensors.cpp file I have identified where things seem to get stuck: Within the findparentnode routine: Serial.println("FPN1"); sendWrite(BROADCAST_ADDRESS, msg, true); Serial.println("FPN1"); I'll keep investigating when I get time. Thanks for your help I turned on failure_handling within the rf24 config. Now I get the following messageon my serial output: send: 255-255-255-0 s=255,c=3,t=3,pt=0,l=0,st=fail: as well as: sensor started, id 255 req node id This happens three times before it appears to give up and runs the rest of the parent sketch which starts a serial output of A0. - daulagari Hero Member last edited by send: 255-255-255-0 s=255,c=3,t=3,pt=0,l=0,st=fail: Seems like your node is requesting a id from a controller, see for example I added capacitors to my radios to see if that would help. I'm also testing with a serial gateway without much difference. I tried assigning a node id of 1. Didn't seem to change much. The debug output goes to the serial monitor correct? I'm wondering why I'm not getting any debug messages. Ok. My primary problem was the radios I purchased form Ebay weren't the correct type. I've purchased new ones. Still got some problems to work through but I'll put in a seperate thread. For others reading later: Other references to these radios: And specifically mentioned on the troubleshooting page as well.
https://forum.mysensors.org/topic/615/nothing-on-serial-monitor-on-mysensor-sketches
CC-MAIN-2018-43
refinedweb
1,233
65.83
Interleaved Increasing-Decreasing Sort May 13, 2016 This must be somebody’s homework: Given an array of integers, rearrange the elements of the array so that elements in even-indexed positions are in ascending order and elements in odd-indexed positions are in descending order. For instance, given the input 0123456789, the desired output is 0927456381, with the even-indexed positions in ascending order 02468 and the odd-indexed positions in descending order 97531. Your task is to write a program that performs the indicated rearrangement of its input. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below. Advertisements I want (intend) to implement a sorting algorithm that does this, rather than call sort from a standard library or external library, but I don’t have much energy at the moment (jetlagged). Anyhow, here’s a solution in matlab (haven’t tested Octave). In Python: values = range(10) print “”.join(map(str, [x for t in zip(sorted([x for i,x in enumerate(values) if not i % 2]), sorted([x for i,x in enumerate(values) if i % 2], reverse=True)) for x in t])) And another Python solution: it’s not clear if we are meant to be separately sorting the odd and even positions, or just coming up with any permutation with the odd and even positions sorted as required. The former seems more interesting & involves sorting slices of the original array: it’s nice to do that in place & we can do that, for example, with slices of Python numpy arrays which construct a view onto the original array (slices of Python lists create new lists so aren’t in place). numpy sort only supports ascending order so we construct a reversed slice starting at an appropriate offset from the end of the array: > “I want (intend) to implement a sorting algorithm that does this, rather than call sort from a standard library or external library…” Here’s a Java solution that first sorts the array using quick sort, and then reverses the elements at even indexes (even with respect to 1-based indexing, odd with respect to 0-based indexing). > “I want (intend) to implement a sorting algorithm that does this, rather than call sort from a standard library or external library…” I was jetlagged when I wrote that. I think my actual intent was not to write a normal sorting algorithm, and then re-arrange, but rather to write a sorting algorithm that does the interleaved increasing-decreasing sort at sort-time. Here’s a solution in Java. It’s similar to my solution above, but at sort-time the indexing considers the interleaved increasing-decreasing ordering (using the reidx function). The signature for iidsort should be: I mistakenly left it private since it was based on the original quick sort I wrote, which was private. (the original iidsort method was correctly public). A Haskell version. Unless – in addition to the ascending/descending requirements of the even and odd slots – even numbers are supposed to end up in the even slots (and odd numbers in the odd slots), why would 0123456789 sort to 0927456381? I would think the more natural output would be 0918273645 – i.e. the even slots contain 01234 and the odd slots contain 98765. And if the problem does include this unstated additional requirement, then it raises other questions when one is sorting an input of, say, 0468248820. Or is this just a poorly written problem that is only supposed to work with the one given input? import java.util.*; class Increasing_Decreasing_Sort { static int getLength(int ar[]){ int len =ar.length-1; if(ar.length%2 !=0) return ar.length-2; return len; } public static int[] sortByInc_Dec(int ar[]){ //First Sort the Array, If array is not Sorted Arrays.sort(ar); int len = Increasing_Decreasing_Sort.getLength(ar); for(int i = 0; i < ar.length/2; i++){ if((i%2) != 0){ int temp = ar[i]; ar[i] = ar[len]; ar[len] = temp; len =len-2; } } return ar; } static void print(int ar[]){ for(int i : ar) System.out.print(i+" "); System.out.println(" "); } public static void main(String[] args){ int ar[] = {3,1,2,4,0,5,6,7,8,9}; int ans[] = sortByInc_Dec(ar); print(ans); } }
https://programmingpraxis.com/2016/05/13/interleaved-increasing-decreasing-sort/
CC-MAIN-2017-43
refinedweb
723
58.11
The best answers to the question “PATH issue with pytest 'ImportError: No module named YadaYadaYada'” in the category Dev. QUESTION: I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so: repo/ |--app.py |--settings.py |--models.py |--tests/ |--test_app.py run py.test while in the repo directory, everything behaves as you would expect but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this? ANSWER: conftest solution The least invasive solution is adding an empty file named conftest.py in the repo/ directory: $ touch repo/conftest.py That’s it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn’t belong (using python -m pytest as suggested in Apteryx’s answer is a good solution though!). The project directory afterwards: repo ├── conftest.py ├── app.py ├── settings.py ├── models.py └── tests └── test_app.py Explanation pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path (in this case the repo directory). Other project structures If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example: repo ├── conftest.py ├── spam │ ├── __init__.py │ ├── bacon.py │ └── egg.py ├── eggs │ ├── __init__.py │ └── sausage.py └── tests ├── test_bacon.py └── test_egg.py src layout Although this approach can be used with the src layout (place conftest.py in the src dir): repo ├── src │ ├── conftest.py │ ├── spam │ │ ├── __init__.py │ │ ├── bacon.py │ │ └── egg.py │ └── eggs │ ├── __init__.py │ └── sausage.py └── tests ├── test_bacon.py └── test_egg.py beware that adding src to PYTHONPATH mitigates the meaning and benefits of the src layout! You will end up with testing the code from repository and not the installed package. If you need to do it, maybe you don’t need the src dir at all. Where to go from here Of course, conftest modules are not just some files to help the source code discovery; it’s where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files? ANSWER: I’m not sure why py.test does not add the current directory in the PYTHONPATH itself, but here’s a workaround (to be executed from the root of your repository): python -m pytest tests/ It works because Python adds the current directory in the PYTHONPATH for you. ANSWER: Yes, the source folder is not in Python’s path if you cd to the tests directory. You have 2 choices: Add the path manually to the test files, something like this: import sys, os myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../') Run the tests with the env var PYTHONPATH=../. ANSWER: I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.
https://rotadev.com/path-issue-with-pytest-importerror-no-module-named-yadayadayada-dev/
CC-MAIN-2022-40
refinedweb
607
67.96
What i want to do is calculate the square root of the variance in a statistical program i am creating. Anyways here is some of the code of my program, i have already sorted the data using a sort and have done all the other calculations with other functions that i havent posted in this extract of code but i am having trouble finding the square root of (var). In this case since i havent worked it out properly i have given var a permanently value. Can someone please show me where i am going wrong, i have tried and tried to get it working but i keep getting errors.Can someone please show me where i am going wrong, i have tried and tried to get it working but i keep getting errors.Code: #include <stdio.h> #include <math.h> #define size 29 void doBubbleSort(double [], int); double calTotalNum(double []); double sqrt(double var); main() { double num[] = {15.5, 17.2, 17.4, 15.2, 15.3, 17.8, 17.5, 18,0, 18.1, 19.5, 17.5, 18.0, 19.5, 17.5, 15.9, 20.0, 16.3, 14.5, 20.5, 20.5, 17.3, 15.5, 15.8, 18.3, 16.5, 16.6, 15.5, 16.2, 16.0}; double totalNum, mean, median, lowerQuart, upperQuart, iqr, var, stdDev; int i, n; n=sizeof(num)/sizeof(double); doBubbleSort(num, n); totalNum = calTotalNum(num); mean = totalNum/size; median=(num[(size+1)/2]); lowerQuart=(num[(size+3)/4]); upperQuart=(num[3*size/4]); iqr=((num[3*size/4]-num[(size+3)/4])); var=4.5; stdDev= sqrt(var); printf("\n\n"); printf(" Statistical report of Data%s\n"); printf("------------------------------------------------------\n"); for(i = 1; i<n; ++i) printf("%6.1lf\n", num[i]); printf("mean temperature : %5.2lf.\n", mean); printf("median temperature : %5.2lf.\n", median); printf("lower quartile value : %5.2lf.\n", lowerQuart); printf("upper quartile value : %5.2lf.\n", upperQuart); printf("inter quartile range : %5.2lf.\n", iqr); printf("variance : %5.2lf.\n", var); printf("standard deviation : %5.2lf.\n", stdDev); printf("\n"); }
http://cboard.cprogramming.com/c-programming/44627-finding-square-root-not-working-printable-thread.html
CC-MAIN-2015-14
refinedweb
349
58.08
Building an Internet Router Integrating with the Hardware VNS framework. Your router server software will run on the machine physically connected to the NetFPGA board and communicate with the board using a driver. In order to make your router run in “cpu” mode, you will have to recompile it using the -D_CPUMODE_ flag (currently commented out in the Makefile). On startup, a router in cpu mode will expect a hardware information file, cpuhw, in the current directory. This file provides the interface information for the router, instead of receiving it from VNS. The provided base code reads cpuhw and calls your sr_integ_add_interface(…) for every interface it finds. An entry in this file should list the interface name, IP address, mask and MAC: eth0 192.168.0.1 255.255.255.255 00:ba:d0:ca:fe:00 eth1 192.168.1.1 255.255.255.255 00:ba:d0:ca:fe:01 eth2 192.168.2.1 255.255.255.255 00:ba:d0:ca:fe:02 eth3 192.168.3.1 255.255.255.255 00:ba:d0:ca:fe:03 You will want to supply a static routing table file (details below). A connection to the board may look something like: $ ./sr -r my_rtable Once connected, you should be able to access the hardware registers and if implemented correctly, send and receive packets as before. In a nutshell, the hardware supports eight packet channels. Four channels for the Ethernet ports (e-ports) and four matching CPU channels (c-ports). An incoming packet on an e-port will be routed to any one of the eight channels, according to the entries in the routing table. If it is routed to a c-port, the software will be able to read it in. To send a packet out from software, write it to the appropriate c-port and it will automatically be forwarded to the matching e-port and sent out. The static rtable file should either be empty, or contain a single default gateway entry, ie: $ cat rtable 0.0.0.0 192.168.0.100 0.0.0.0 eth0 Note that in this example, eth0 corresponds to port 0 on the NetFPGA. Instead of sending and receiving packets through VNS, you will be responsible for reading them from raw sockets. Below is some starter code to help you bind to the sockets. After binding you are responsible for reading and writing packets to the sockets using your choice of methods. #include <sys/ioctl.h> #include <sys/socket.h> #include <linux/netdevice.h> #include <linux/sockios.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> char iface_name[32] = "nf2c"; int i; for (i = 0; i < 4; ++i) { sprintf(&(iface_name[4]), "%i", base+i); int s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); struct ifreq ifr; bzero(&ifr, sizeof(struct ifreq)); strncpy(ifr.ifr_ifrn.ifrn_name, iface_name, IFNAMSIZ); if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) { perror("ioctl SIOCGIFINDEX"); exit(1); } struct sockaddr_ll saddr; bzero(&saddr, sizeof(struct sockaddr_ll)); saddr.sll_family = AF_PACKET; saddr.sll_protocol = htons(ETH_P_ALL); saddr.sll_ifindex = ifr.ifr_ifru.ifru_ivalue; if (bind(s, (struct sockaddr*)(&saddr), sizeof(saddr)) < 0) { perror("bind error"); exit(1); } // Do something with s here!! } are specified in reg_defines.h. you first start the software you will want to empty all the hardware tables and registers on the card so you start from a clean slate. You can execute the command: writeReg(&your_netfpga_struct, CPCI_REG_CTRL, 0x00010100); which will trigger the reset signal on the card. It is also a good idea to sleep for a small period of time after the reset before sending commands to the card (eg. usleep(2000)). CPCI_REG_CTRL is defined in nf2.h. -.
http://www.cl.cam.ac.uk/teaching/1011/P33/sw/integrating-with-the-hardware/
CC-MAIN-2018-05
refinedweb
609
66.74
This page shows you how to resolve issues with Cloud Run. Deployment errors This section lists issues that you might encounter with deployment and provides suggestions for how to fix each of them. Container failed to start The following error occurs when you try to deploy: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. To resolve this issue, rule out the following potential causes: Verify that you can run your container image locally. If your container image cannot run locally, you need to diagnose and fix the issue locally first. Check if your container is listening for requests on the expected port as documented in the container runtime contract. Your container must listen for incoming requests on the port that is defined by Cloud Run and provided in the PORTenvironment variable. See Configuring containers for instructions on how to specify the port. Check if your container is listening on all network interfaces, commonly denoted as 0.0.0.0. Verify that your container image is compiled for 64-bit Linux as required by the container runtime contract. Use Cloud Logging to look for application errors in stdoutor stderrlogs. You can also look for crashes captured in Error Reporting. You might need to update your code or your revision settings to fix errors or crashes. You can also troubleshoot your service locally. Internal error, resource readiness deadline exceeded The following error occurs when you try to deploy or try to call another Google Cloud API: The server has encountered an internal error. Please try again later. Resource readiness deadline exceeded. This issue might occur when the Cloud Run service agent does not exist, or when it does not have the Cloud Run Service Agent ( roles/run.serviceAgent) role. To verify that the Cloud Run service agent exists in your Cloud project and has the necessary role, perform the following steps: Open the Cloud Console: Go to the Permissions page In the upper-right corner of the Permissions page, select the Include Google-provided role grants checkbox. In the Principals list, locate the ID of the Cloud Run service agent, which uses the ID service-PROJECT_NUMBER@serverless-robot-prod.iam.gserviceaccount.com. Verify that the service agent has the Cloud Run Service Agent role. If the service agent does not have the role, grant it. Default Compute Engine service account is deleted The following error occurs when you try to deploy: ERROR: (gcloud.run.deploy) User EMAIL_ADDRESS does not have permission to access namespace NAMESPACE_NAME (or it may not exist): Permission 'iam.serviceaccounts.actAs' denied on service account PROJECT_NUMBER-compute@developer.gserviceaccount.com (or it may not exist). This issue occurs in one of the following situations: - The default Compute Engine service account does not exist in the project, and no service account is specified with the --service-account gcloudflag at the time of deployment. - The developer or principal deploying the service does not have the permissions for the default Compute Engine service account that are required to deploy. To resolve this issue: - Specify a service account using the --service-account gcloudflag. - Verify that the service account you specify has the permissions required to deploy. If you want to verify if the default Compute Engine service agent exists in your Cloud project, perform the following steps: Open the Cloud Console: Go to the Permissions page In the upper-right corner of the Permissions page, select the Include Google-provided role grants checkbox. In the Principals list, locate the ID of the Compute Engine service agent, which uses the ID PROJECT_NUMBER-compute@developer.gserviceaccount.com. Cloud Run Service Agent doesn't have permission to read the image The following error occurs when you try to deploy from PROJECT-ID using an image that is stored in Container Registry in PROJECT-ID-2: Google Cloud Run Service Agent must have permission to read the image, gcr.io/PROJECT-ID/IMAGE-NAME. Ensure that the provided container image URL is correct and that above account has permission to access the image. If you just enabled the Cloud Run API, the permissions might take a few minutes to propagate. Note that PROJECT-ID/IMAGE-NAME is not in project PROJECT-ID-2. Permission must be granted to the Google Cloud Run Service Agent from this project. To resolve this issue, follow the instructions for deploying container images from other Google Cloud projects to ensure that your principals have the necessary permissions. Serving errors This section lists issues that you might encounter with serving and provides suggestions for how to fix each of them. HTTP 403: Client is not authorized to invoke/call the service One of the following errors occurs during serving: 403 Forbidden Your client does not have permission to get URL from this server. The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header The request was not authorized to invoke this service To resolve this issue: - If the service is meant to be invocable by anyone, update its IAM settings to make the service public. - If the service is meant to be invocable only by certain identities, make sure that you invoke it with the proper authorization token. - If invoked by a developer or invoked by an end user: Ensure the developer or user has the run.routes.invokepermission, which you can provide through the Cloud Run Admin ( roles/run.admin) and Cloud Run Invoker ( roles/run.invoker) role. - If invoked by a service account: Ensure the service account is a member of the Cloud Run service and has the Cloud Run Invoker ( roles/run.invoker) role. Additionally, the Google-signed ID token must have the audience claim ( aud) set to the URL of the receiving service. If the project is within a VPC-SC perimeter, verify that VPC-SC policies are not denying run.googleapis.com/HttpIngresstraffic that originates from the caller's IP or identity. To check if this is the case: Open Logs Explorer in the Cloud Console (not the Logs page for Cloud Run): Enter the following text in the query field: resource.type="audited_resource" log_name="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Fpolicy" resource.labels.method="run.googleapis.com/HttpIngress" If you see any log entries after you use this query, examine the log entries to determine if you need to update your VPC-SC policies. HTTP 404: Not Found The following issue occurs during serving: You encounter an HTTP 404 error. To resolve this issue: - Verify that the app does not return 404 when you run it locally. Verify that the URL you are requesting is correct by checking the service detail page in the Cloud Console or running the following command: gcloud run services describe SERVICE_NAME | grep URL Inspect where your app logic may be explicitly returning 404s HTTP 429: Service reached its maximum number of container instances The following error occurs during serving: HTTP 429 The request was aborted because there was no available instance. The Cloud Run service probably has reached its maximum container instance limit. Consider increasing this limit. This error can also be caused by a sudden increase in traffic, a long container startup time or a long request processing time. To resolve this issue, increase the "max instance" settings, or, if you need more than 1000 instances, request a quota increase. HTTP 500: Cloud Run couldn't manage the rate of traffic The following error occurs during serving: HTTP 500 The request was aborted because there was no available instance This error can be caused by one of the following: - A huge sudden increase in traffic. - A long cold start time. - A long request processing time. - The service reaching its maximum container instance limit ( HTTP 429). - Transient factors attributed to the Cloud Run service. To resolve this issue, address the previously listed issues. In addition to fixing these issues, as a workaround you can implement exponential backoff and retries for requests that the client must not drop. When the root cause of the issue is a period of heightened transient errors attributable solely to Cloud Run, you can contact Support HTTP 500: Container instances are exceeding memory limits The following error occurs during serving: In Cloud Logging: While handling this request, the container instance was found to be using too much memory and was terminated. This is likely to cause a new container instance to be used for the next request to this revision. If you see this message frequently, you may have a memory leak in your code or may need more memory. Consider creating a new revision with more memory. To resolve this issue: - Determine if your container instances are exceeding the available memory. Look for related errors in the varlog/systemlogs. - If the instances are exceeding the available memory, consider increasing the memory limit. Note that in Cloud Run, files written to the local filesystem count towards the available memory. This also includes any log files that are written to locations other than /var/log/* and /dev/log. HTTP 503: Long running requests are timing out One of the following errors occurs during serving: HTTP 503 The request failed because either the HTTP response was malformed or connection to the instance had an error. [CRITICAL] WORKER TIMEOUT To resolve this issue: If your service is processing long requests, you can increase the request timeout. If your service doesn't return a response within the time specified, the request ends and the service returns an HTTP 504error. If requests are terminating earlier with error code 503, you might need to update the request timeout setting for your language framework: - Node.js developers might need to update the server.timeoutproperty via server.setTimeout(use server.setTimeout(0)to achieve an unlimited timeout) depending on the version you are using. - Python developers need to update Gunicorn's default timeout. HTTP 503: Unable to process some requests due to high concurrency setting The following errors occurs during serving: HTTP 503 The Cloud Run service probably has reached its maximum container instance limit. Consider increasing this limit. This issue occurs when your container instances are using a lot of CPU to process requests, and as a result, the container instances cannot process all of the requests, so some requests return a 503 error code. To resolve this issue, try one or more of the following: Increase the maximum number of container instances for your service. Lower the service's concurrency. Refer to setting concurrency for more detailed instructions. Connection reset by peer The following errors occurs during serving: Connection reset by peer This error occurs when an application has an established TCP connection with a peer across the network and that peer unexpectedly closes the connection. To resolve this issue: If you are trying to perform background work with CPU throttling, try using the "CPU is always allocated" CPU allocation setting. Ensure that you are within the outbound requests timeouts. If your application maintains any connection in an idle state beyond this thresholds, the gateway needs to reap the connection. By default, the TCP socket option keepaliveis disabled for Cloud Run. There is no direct way to configure the keepaliveoption in Cloud Run at the service level, but you can enable the keepaliveoption for each socket connection by providing the correct socket options when opening a new TCP socket connection, depending on the client library that you are using for this connection in your application. Identity token signature redacted by Google The following errors occurs during serving: SIGNATURE_REMOVED_BY_GOOGLE This can occur during development and testing in the following circumstance: - A user logs in using gcloudcommand-line tool or Cloud Shell. - The user generates an ID token using gcloudcommands. - The user tries to use the ID token to invoke a non-public Cloud Run service. This is by design. Google removes the token signature due to security concerns to prevent any non-public Cloud Run service from replaying ID tokens that are generated in this manner. To resolve this issue, invoke your private service with a new ID token. Refer to testing authentication in your service for more information. Issue caused by a limitation in the container sandbox The following errors occurs during serving in the container sandbox: Container Sandbox: Unsupported syscall setsockopt(0x3,0x1,0x6,0xc0000753d0,0x4,0x0) If your container runs locally but fails in Cloud Run, the Cloud Run container sandbox might be responsible for the failure of your container. To resolve this issue: Open Logs Explorer in the Cloud Console (not the Logs page for Cloud Run): Enter the following text in the query field: resource.type="cloud_run_revision" logName="projects/PROJECT_ID/logs/run.googleapis.com%2Fvarlog%2Fsystem" If you find a Container Sandboxlog with a DEBUGseverity and you suspect that it is responsible for the failure of your container, contact Support and provide the log message in your support ticket. Google Cloud support might ask you to trace system calls made by your service to diagnose lower-level system calls that are not surfaced in Cloud Logging logs. OpenBLAS warning in logs If you use OpenBLAS-based libraries such as NumPy with the first generation execution environment, you might see the following warning in your logs: OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k This is just a warning and it doesn't impact your service. This warning results because the container sandbox used by the first generation execution environment does not expose low level hardware features. You can optionally switch to the second generation execution environment if you don't want to have these warnings in your logs. Mapping custom domains Custom domain is stuck certificate provisioning state One of the following errors occurs when you try to map a custom domain: The domain is available over HTTP. Waiting for certificate provisioning. You must configure your DNS records for certificate issuance to begin and to accept HTTP traffic. Waiting for certificate provisioning. You must configure your DNS records for certificate issuance to begin. To resolve this issue: - Wait at least 24 hours. Provisioning the SSL certificate usually takes about 15 minutes, but it can take up to 24 hours. Verify that you've properly updated your DNS records at your domain registrar using the Google Admin Toolbox dig tool The DNS records in your domain registrar need to match what the Cloud Console prompts you to add. Confirm that the root of the domain is verified under your account using one of the following methods: - Follow the instructions for adding verified domain owners and check that your account is listed as a Verified Owner. Visit the following URL: Verify that the certificate for the domain is not expired. To find the expiry bounds, use the following command: echo | openssl s_client -servername 'ROOT_DOMAIN' -connect 'ROOT_DOMAIN:443' 2>/dev/null | openssl x509 -startdate -enddate -noout Admin API The feature is not supported in the declared launch stage The following error occurs when you call the Cloud Run Admin API: The feature is not supported in the declared launch stage This error occurs when you call the Cloud Run Admin API directly and use a beta feature without specifying a launch stage annotation. To resolve this issue, annotate the resource with a run.googleapis.com/launch-stage value of BETA in the request if any beta feature is used. The following example adds a launch stage annotation to a service request: kind: Service metadata: annotations: run.googleapis.com/launch-stage: BETA
https://cloud.google.com/run/docs/troubleshooting
CC-MAIN-2022-05
refinedweb
2,580
51.38
Introduction¶ Blessed is a thin, practical wrapper around terminal capabilities in Python. Coding with Blessed looks like this... from blessed import Terminal t = Terminal() print(t.bold('Hi there!')) print(t.bold_red_on_bright_green('It hurts my eyes!')) with t.location(0, t.height - 1): print(t.center(t.blink('press any key to continue.'))) with t.cbreak(): inp = t.inkey() print('You pressed ' + repr(inp)) Brief Overview¶ Blessed is a more simplified wrapper around curses, providing : - Styles, color, and maybe a little positioning without necessarily clearing the whole screen first. - Works great with standard Python string formatting. - Provides up-to-the-moment terminal height and width, so you can respond to terminal size changes. - Avoids making a mess if the output gets piped to a non-terminal: outputs to any file-like object such as StringIO, files, or pipes. - Uses the terminfo(5) database so it works with any terminal type and supports any terminal capability: No more C-like calls to tigetstr and tparm. - Keeps a minimum of internal state, so you can feel free to mix and match with calls to curses or whatever other terminal libraries you like. - Provides plenty of context managers to safely express terminal modes, automatically restoring the terminal to a safe state on exit. - Act intelligently when somebody redirects your output to a file, omitting all of the terminal sequences such as styling, colors, or positioning. - Dead-simple keyboard handling: safely decoding unicode input in your system’s preferred locale and supports application/arrow keys. - Allows the printable length of strings containing sequences to be determined. Blessed does not provide... - Windows command prompt support. A PDCurses build of python for windows provides only partial support at this time – there are plans to merge with the ansi module in concert with colorama to resolve this. Patches welcome! Before And After¶ = '' # Save cursor position. print(sc) if cup: # tigetnum('lines') doesn't always update promptly, hence this: height = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))[0] # Move cursor to bottom. print(tparm(cup, height - 1, 0)) print('This is {under}underlined{normal}!' .format(under=underline, normal=normal)) # Restore cursor position. print(rc) The same program with Blessed is simply: from blessed import Terminal term = Terminal() with term.location(0, term.height - 1): print('This is' + term.underline('underlined') + '!') Further Documentation¶ More documentation can be found at Bugs, Contributing, Support¶ Bugs or suggestions? Visit the issue tracker and file an issue. We welcome your bug reports and feature suggestions! Would you like to contribute? That’s awesome! We’ve written a guide to help you. Are you stuck and need support? Give stackoverflow a try. If you’re still having trouble, we’d like to hear about it! Open an issue in the issue tracker with a well-formed question.
http://blessed.readthedocs.io/en/latest/intro.html
CC-MAIN-2017-13
refinedweb
464
51.44
Redirect To Other Page From Pop Up Window With Response.redirect?Feb 13, 2010 how can i redirect to other page from pop up window with response.redirect.View 2 Replies how can i redirect to other page from pop up window with response.redirect.View 2 Replies ... I need to open a new window with Response.Redirect, Is it possible?View 2 Replies protected void ddlPrint_Changed(object sender, EventArgs e)View 4 Replies I have an query when user select any option it should redirect and open new tab in same browser, actually it worked fine in firefox and IE but in chrome it opens a new window. Below is the code. [Code].... How can do response.redirect to a new window without javasript? I also have a masterpage.View 8 Replies I know this has been asked many times and have saw the posts that it cant be done and there are alternative solutions. The caveat is that after clicking on the button this will load a new page with the target URL but I would want the current web form to remain as it is. That is essentailly two web forms side by side?()); First, I've taken the time to review this question which seems to be the most similar, however, the solution that seems to have been selected will not work in my scenario.Not to mention I worry about some of the comments claiming it to be brittle or an inadequate solution. [URL] -We have an XML document which basically contains all of the information for a Side menu. -We have numerous URLS which are stored in a constants class. -One of the elements in a string of XML (well call it label) is used to determine if the menu item is created as a LinkButton or a Label. -Links use a custom user control that is used standard for all links across the application (why suggestion on similar thread doesn't work - I don't want all links to open in a new window - just one) -One of the elements in a string of XML (well call it function) is used in a Switch statement to generate our links using Response Redirect. It may look something like this. [Code].... Given this scenario, I'm trying to find the best way to quickly open a New Window, when a specific case in this switch statement is met. Can it be done with Response Redirect (this seems to be arguable - people say no it can't, yet other people say they have made it work)? If not, what alternative can work here? I had a problem lately that I managed to have for it 2 solutions and I am wondering which one should I choose. Here the issue : When a user requests my site (), I am gonna redirect him to () because it is a multilingual site. I am using .NET routing to to that. In the Page_Load of the default.aspx page I check if the language in the Routing Collection is available, I don't redirect. If it is not available I redirect to (). Here is the code : if (Page.RouteData.Values.Count == 0) { if (SessionManager.IsUserAuthenticated) { //Redirect To User HomePage for his Main Language Page.Response.Redirect(UserManager.GetUserMainPageWhenLoggedIn(SessionManager.LoggedUser.LanguageID,true)); } else { Page.Response.Redirect(String.Format("~/{0}", Cultures.en.ToString()), true); Helpers.SetCulture(Cultures.en.ToString()); } } I am using Response.Redirect to do that. Now if I set to End The Response the method parameter, it will throw an exception so I can handle it throught try { this.InitializeLayout(); } catch (ThreadAbortException ex) { } catch (Exception ex) { ExceptionManager.LogException(ex); } If I don't end the Response, the page will execute the whole lifecyle, redirect and then do it again which results a double execution of the page. My main objective is not to execute the page 2 times to minimize processing ( if the site gets hammered by a big traffic). If I end the Response, a ThreadAbortExeption will be thrown and I think this is not good for the site.( I can catch it and not log it). what i have is the follwoing Page1.aspx.cs has the following redirection in it. Response.redirect(Errors.aspx) once i go to the errors.aspx page i have a back button but at the moment it does a history.back(-1) . That is not totally corect, what i want to do is when i click on the back button go to the page that originated the call ie Page1.aspx so it goes through the Page_Load in order to refresh statues on the page. What is the best way of achieving this?View 1 Replies I have used following code on my button click Response.Redirect [URL]; but the problem is i have to click 2 times for nevigation. when i clicked for fitst time it just refresh the page ...and second time it actually nevigates the page..View 6 Replies I am getting the following error when I leave my web inactive for a while "Response.Redirect.cannot be called in a Page callback." I'm storing the user ids in session and during page load I check to see if the user id exists if not then I redirect them to the login page. I am using devexpress controls, How can I get the redirect to work? I need to call a page from itself, but adding an argument ?id=FixNulls (see below example) [Code].... This argument string is also sent to other pages, depending on the program state, which is why I want to use a querystring. Why does the above code work when I and Redirecting to another page, but blow up when the Redirect is to the current page? Can I use a querystring and redirect to call the current page? I have 1 textbox and 1 button in my page..when users type their user name in text box they go to their page these are my code <div id="behcode"> <div id="divbehcodebtn"> <asp:ImageButton ID="ImageButton3" runat="server" CssClass="imgbtnbehcode" [code]... I have a collection of links I response.redirect to the first one. if the first one errors with page 404 ie page does not exist i want to redirect to the next one. If the next one errors I then want to redirect to the one after etc. Basically go through the collection and redirect to a link that doesnt error with page 404 error. is this possible in .net 2?View 3 Replies How can I make a Response.Redirect open in a new page? I guess it would be the ASP.NET equivalent of <a href="page.aspx" target="_blank">click here</a>. I have a lot of code on an OnClick event handler and it redirects at the end of the code. It would make it very simple if there was a way to do it in ASP.NET.View 5 Replies I'm using 2010 to build a website application targets .net framework 4. I use Response.Redirect(url) to transfer user to another page. All these redirect work fine when I debug. After I publish the website project to the sever. I visit that website on the server. All the redirects work fine but in one page. In that page. I have a button control. when user click the button, he/she will be transferred to another page. So in the button_onclick event, I have: Response.Redirect("~/WebPages/Benefit/CreateBenefitOpFields.aspx"); I just observed something with the .net 3.5 VS2010 Login control. It seems to response.redirect is doing something I cant explain: [Code].... after I hit the response.redirect all that is happening is that I stay on the login page and the URL changes to Why am I not properly redirected? I used server.transfer, that put me on the right page (Approval.aspx) BUT as soonas I clicked a button, I was back at Login.aspx. I have a logon/register control that is on several pages. Users are logged on with code: - FormsAuthentication.SetAuthCookie(Userid, False) Response.Redirect(Request.Url.AbsoluteUri) ' Round trip is necessary to complete logon All this was working OK, except that there was a problem with Internet Explorer users: if their browser had the default privacy setting the authorization cookie was rejected. There was no message, but they were not logged on. See [URL] To try to solve this problem I changed to cookieless authentication, but now the logon control doesn't work. The problem is that after cookieless authentication the URL changes from [URL] However Request.Url.AbsoluteUri remains even after the logon, and so with cookieless authentication the user is not logged on as there is no authentication ticket in the redirect URL. The problem is "solved" by changing the Redirect statement to Response.Redirect("~/login_pages/home2.aspx") which works perfectly for this particular page, but is obviously wrong when the control is on other pages. How do I write "Response.Redirect(current page)"? I am having a base class which implements some basic authentication for all the pages in the application. public class BasePage : Page { public void Page_PreLoad(object sender, EventArgs e) { if (!IsUserValid()) { Response.Redirect("default.aspx"); [Code].... How to stop page life cycle for AuthenticatedUser, if the user is invalid?
https://asp.net.bigresource.com/redirect-to-other-page-from-pop-up-window-with-response-redirect--8GB1HPH5d.html
CC-MAIN-2021-49
refinedweb
1,557
67.15
Lookup field in a Data Form Part - Wednesday, December 31, 2008 7:37 PM iamaracinghorseHey everyone! I'm having a problem here to which i cannot seem to find the answer. Perhaps you can help. I have a list - we'll call it 'articles' - and in that list is a lookup column called 'related articles' that allows a user to select other articles for the same list. When viewing items from this list in the default 'DispForm.aspx', the items in the lookup field are formatted beautifully, each on it's own line and linked to the item. However! When I try to build a custom Data Form Web Part (Or a custom display form even), the items from that field are plain text, with no link, separated by a semi-colon. What gives?! Why are they not linked to the items? Why can I not make that happen????? Anybody know? I've looked into the ddwrt namespace funtions, but none of them seem to apply to my situation. There must be a way to do this. It's very frustrating. Any help would be greatly appreciated. Thanks in advance. Answers - Friday, January 02, 2009 9:20 AM Xue-Mei Chang-MSFTMSFT, ModeratorHi, I think it is not possible out of the box; there is a workaround for you to get the ID of the list item: create a column in your “articles” list named "lookupID”, and then attach a SPD workflow to the “articles” list, add a action to the workflow “update list item”, update the “lookupID” to the “ID” of “articles” list when the “related articles” column value is equal to the column that you looked up. After this, you can edit the “related articles” column in the data form web part, set its format as “hyperlink”: Hope it can help you. Xue-Mei Chang - Edited byXue-Mei Chang-MSFTMSFT, ModeratorFriday, January 02, 2009 9:21 AMcode - Edited byXue-Mei Chang-MSFTMSFT, ModeratorFriday, January 02, 2009 9:25 AMformat - Marked As Answer byXue-Mei Chang-MSFTMSFT, ModeratorFriday, January 09, 2009 1:10 AM - All Replies After searching for some hours, I found a solution in SharePoint Designer itself. Just open the DispForm, right-click the FormField of the column where the lookup hyperlink should be and format the item as List Form Field. The same pull-down menu box as in Edit- and NewForm will appear. Search in the code (split mode and click the form field) for the code from the form field. Change controlmode="Edit" to controlmode="Display" It worked great for me... Good luck on it. Kindest regards, Quincy Thomas QT - Wednesday, December 31, 2008 9:34 PM Mike OryszakThe data is actually a name/value pair and the standard forms just handle it for you. For the display you should be able to just code the link and pass in the ID provided. I've worked with it in custom web parts, data views, etc. I haven't done a custom data form with one, but I imagine it would be much more difficult than a non-linked field. - Thursday, January 01, 2009 12:04 AM iamaracinghorseThank you so much for the reply! Unfortunately, I can't seem to locate the ID for the items in the lookup field. I'm not sure that it's returning that value. I can find the ID for the main item that's displaying, but I think it's only returning the 'Title' field for items in the lookup column. Does that make sense? Can you help mt to find the ID of the individual lookup-field items? - Monday, January 05, 2009 5:49 PM iamaracinghorseThank you, Xue-Mei Chang! That solution seems like it would work beautifully if the lookup field only allowed one value, but unfortunately, mine needs to allow multiple values. I'm wondering if your workaround would work for that? I'm thinking it wouldn't. This problem seems so strange because it's obviously possible to format these mutiple-value lookup fields as links to the items, as the default DispForm.aspx has them formatted that way. Urgh. Frustrating... - Tuesday, January 06, 2009 8:30 AM Xue-Mei Chang-MSFTMSFT, ModeratorHi, I found another way : But I think it is not possible for the multiple value lookup fields. One way that it can be accomplished is by splitting the multivalue string and creating the links manually. Xue-Mei Chang - Edited byXue-Mei Chang-MSFTMSFT, ModeratorTuesday, January 06, 2009 8:57 AMwords - - Tuesday, January 06, 2009 8:56 PM G. Laushine I know a rich text field could have multiple links. One way may be to have code populate that field with the lookup items, formatted with the links. Greg
http://social.msdn.microsoft.com/Forums/en-US/sharepointcustomization/thread/f5ca14c2-925b-4f8d-b306-f7c3d1696be3/
crawl-002
refinedweb
787
71.04
Conservapedia talk:What is going on at CP?/Archive124 Contents - 1 Fool me once ... - 2 Andy's grading - 3 "Create account" still locked, right? - 4 the lull before the lulz - 5 Is Andy Stupid? - 6 Rule of law - 7 Andy as a D&D Character - 8 Guns prevent AIDS, so saith CP... - 9 What's Wrong with Andy? - 10 Breaking News: Muslin on Xtian naughtiness - 11 Move down scandal! - 12 Mental problems - 13 Ken's Flickr page - 14 HSmom - 15 Three-Headed Monster - 16 TK and Checkuser - 17 Bad taste - 18 World History Lecture Eight - 19 Suicide by TK? - 20 How Convenient: "An immoral person is of course incapable of making a legitimate argument." - 21 Andy's spelling mistakes page - 22 An Informal Apology - 23 0 in mental problems by its contributors. - 24 Andy's Obama Hatred - 25 Stitwin! - 26 J00ni - 27 I refuse to go to a heathen dentist! - 28 Conservatube - 29 Speaking of mental health... - 30 Founder, TK, Bureaucrat, Senior Administrator, Admin, Junior Admin, Editor, Contributor, PEASANT. - 31 Schlafloff off RW? - 32 A little ♥ K e n D o l l ♥-like - 33 GENTLEMEN!!! - 34 Dosage - 35 On Good Samaritans Fool me once ...[edit] Tash loses sysop light. See what you've done MikeSalter Fretful? . Violence is the last refuge of the incompetent 21:50, 15 March 2009 (EDT) - One of the user rights is nsTeam1_talkRW. They have their own WIGO on us? ENorman 23:14, 15 March 2009 (EDT) Andy's grading[edit] I think there's nothing I hate more about Assfly's than the way he grades the homework of anyone who's actually smart (luckily it's rare that he has to do this). I mean, obviously student 18 is one of us, but he really should admit that this guy knows much more than he does about this subject. He basically says to his best student "if you want to understand scholasticism, don't read Summa Theologica, read my lectures!" If I ever meet Andy I will probably seriously kick him in the nuts. DickTurpis 22:18, 15 March 2009 (EDT) - frankly, if I knew one of my "students" were there just to make fun of me, I'd do the same thing, even if it made me "more the fool" in a sense. It's not like he doesn't know 18 is a spoof, so why would he treat that "student" with any respect at all?-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 22:44, 15 March 2009 (EDT) - I dunno, if I were a teacher/professor, the parodist/troublemaker would probably get more of my attention, and perhaps even respect. Like we try to do here on RW (and usually don't do very well), when the people who disagree with us turn up, they are our greatest asset (since echo chambers rarely create new "insights"). ħuman 23:19, 15 March 2009 (EDT) - Yes, but you are logical, and think that most of what is taught as "history" in schools, is relativily speaking, "ok", if not brilliant. People like andy think that they are right, but think that without fact to back them up... so they live in fantasy land. They don't like people who challenge their thinly held, gossamer like beliefs.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 00:15, 16 March 2009 (EDT) - Which is why Tim needs to grace us with his presence. WE MISS YOU TIM, COME BAAAAACCK~!!!! ENorman 00:16, 16 March 2009 (EDT) - You'd have something if his behaviour was limited to the spoof, but he was just as much an ass to ReneeStJ, who at that point had no connection to RW. What horrifies me is that Andy marks down the absolute wrong things while proving just how little he knows, and just how terribly stubborn he is about it. The man has no fucking clue what a Nation-State is, nor a Nation, yet he preaches to me, a guy with years of study in history and political studies, about ignorance. His response absolutely floored me: "England had a King. There was a State under that King such that in the early 1500s the King established a national church. Enough said." Yes, there was a State. Henry established a STATE church. Great ironclad logic, dipshit. Minus 3 for naming my favourite aspect of Scholasticism, Aquinas' theology, like he asked. And the coup de grace: "two is several." I quote the dictionary: "Several: Being of a number more than two or three but not many." His response to H7 is simply incomprehensible. 00:24, 16 March 2009 (EDT) - I think your work may come to some sort of fruition. The intelligent responses to his questions make his grading comments look like oversimplified, unprofessional nonsense. I think that if any student or parent (for whatever reason) saw the page, they'd at least consider the possibility that Andy's a fool who has no idea what he's talking about. They might also notice how terse Andy is with students who deviate from his thinking. The less people "educated" by him, the better. -- JArneal 02:48, 16 March 2009 (EDT) - Quoth the Assfly, ...there are more characteristics to the architecture than "stunning complexity." Yeah, apparently like the "many windows]" that let light in, hurrah for goth arcitecture, full marks! Do you physically have to blow Andy for a passing grade? --JeevesMkII The gentleman's gentleman at the other site 05:04, 16 March 2009 (EDT) - No you just need to parrot Andy back to himself, using language that would seem too simplistic for the simple English Wikipedia, so as not to cause Andy to feel intellectually inferior. - User 05:12, 16 March 2009 (EDT) - To Andy, that has the same effect as a blowjob. "You agree with me? Oh, yes! Yes! Yes!" MDB 07:32, 16 March 2009 (EDT) - Er, <utter disgusting warning>just as Bill Maher characterizes Darth Cheney as a guy who married the first girl to give him a handjob <ok, you were warned, don't blame me if you keep reading>, does anyone think that Schlafly idiot has ever had a blowjob?</utter disgusting over, too late, you read it.> ħuman 02:56, 17 March 2009 (EDT) - If one includes autofellation I'm a gonna hafta go with A-YES!" After all, what could be MOAR! conservative than doing (it for) yourself? 03:07, 17 March 2009 (EDT) CЯacke® "Create account" still locked, right?[edit] CP still has account creation locked, right? I suppose so, since I see "Log in" instead of "Log in / create account"... but then how are people still creating accounts? Is it being turned on for just a few hours a day and I'm missing it, or what? --Marty 03:04, 16 March 2009 (EDT) - CP goes in to what we call night mode when Andy goes to bed, and only comes back to life when Andy is up and around again. During night mode, you can't create new accounts and peons can't edit. Basically, since Andy doesn't trust anyone you have to await his pleasure before being allowed in. Check back sometime during the day, EST. --JeevesMkII The gentleman's gentleman at the other site 04:37, 16 March 2009 (EDT) the lull before the lulz[edit] I've just caught up on the last few days of wigocp and I just want to say - i think that slowdown in cp drama last week was just a building up of quality lulz ready to burst for the weekend, like some sort of fundie fart. I have laughed like a madman all the way down this talk page, it's just too much. Petition to auto-replace every instance of "two" on this wiki to "several". Runderful 07:13, 16 March 2009 (EDT) - I dare someone to replace the phrase 'two of every kind' in their flood/ark articles to 'several of every kind' - Lardashe Is Andy Stupid?[edit] Is Andy Schlafly stupid? No, I don't think so, at least not if we define stupid as "lacking intelligence". Obviously, the man has intelligence -- unintelligent people don't get Bachelor's Degrees in Electrical Engineering1 followed by a Harvard Law Degree, including working at the Law Review. I think his problem is not lack of intelligence, but inability to apply his intelligence -- or (geek moment here), in Dungeons and Dragons terms, he has high Intelligence, but low Wisdom. He's so biased by his own pre-conceived notions ("conservative = good! liberal = bad!", "I'm a conservative, therefore anyone who disagrees with me is a liberal!" etc etc etc ad infinitum ad nauseam...) he can't use his intelligence to form reasonable arguments, even if he's trying to argue conservative viewpoints. 1 Acknowledgment of bias: my degree is in Electrical Engineering, so it is a point of personal pride to think it requires intelligence to earn a BSEE. — Unsigned, by: MDB / talk / contribs - I'm secretly hoping he turns out to be the world's greatest and most committed troll ever possible. The only thing that stands in the way of this possibility is that he teacheswarps kids. Runderful 08:29, 16 March 2009 (EDT) Andrew Schlafly: STR 11 DEX 11 CON 11 INT 11 WIS 11 CHA 11 What's that in Warhammer? Totnesmartin 08:39, 16 March 2009 (EDT) M - 4 WS - 2 BS - 10 S - 3 T - 6 W - 5 I - 9 A - 3 Ld - 4 These are just estimates, but I declare them to be 95% accurate.-- Kriss AkabusiAAAWOOOGAAAR!!1 08:45, 16 March 2009 (EDT) - Warhammer? I've not played that since college, and my only memory of it involves this exchange: - Me: I toss the waitress a gold piece and tell her "keep the change." - GM: She looks at you, amazed. "Thank you, sir!" - Me: I just tipped her a week's salary, didn't I? - GM: No, more like a year's. 9 for initiative? Hmm. and 10 for BS is right, for current definitions of BS. - Andy thinks he's the Emperor of Man, but he's just an Ogryn. --Barikada. - In terms of Final Fantasy Tactics: - Andy (Mediator) - Weapon:Gun - Talk Abilities:Praise,Threaten,Preach,Solution(never works),Insult,Mimic Daravon(for the homeshcool kids) - Secondary (Calculator) - Math Skills: (all, but never work)--Nate River 12:50, 16 March 2009 (EDT) - No Finger Guard? NightFlare 01:36, 17 March 2009 (EDT) D&D? <gamesnob>How unrealistic</gamesnob>. Use GURPS, and give him Delusion (All Liberals are EVIL), Stubbornness, Fanaticism (Conservativism), and Intolerance. (Plus Patron (mom).) --Gulik 13:46, 16 March 2009 (EDT) - I can't buy him as a GURPS character. I mean who the hell takes all those disadvantages, and spends so little on skills? It's like he's min-minning or something. --Kels 16:42, 16 March 2009 (EDT) - Excuse me if I pass over all this gaming cruft and address the original question. I don't believe Andy is stupid in the sense of having a low IQ - you don't get engineering and law degrees if you have learning difficulties. However, just remembering stuff and being analytical about things doesn't necessarily make you a well-rounded, likable individual. Andy exhibits a very low emotional quotient - the ability to empaphise with others or see things from their point of view. Also he displays incredible arrogance; the conviction that he is always right and everyone else is wrong is a most distasteful trait which has been exemplified by the bastards at the heart of the recent financial crisis (or at the risk of invoking Godwin - Adolf Hitler). Yes, they were clever enough to find ways to make lots of money but this was done out of selfishness and with disdain for the masses. Really great people have a degree of humility and concern for their fellow (wo)man, something that Schlafly does not posess and that is what makes him such a bad teacher. He does not engage his students, he preaches at them. The reason he has failed at everything is his reluctance to admit to errors or see other points of view, something probably inherited from his reptile of a mother. Lily Ta, wack! 15:26, 18 March 2009 (EDT) - I believe that it is not so much a lack of knowledge. To me, it is a lack of problem solving skills. The way that Andy teaches is appears to be nothing more than the students regurgitating what Andy has said. Such answers require memory, not thought. Give Andy a problem that requires problem solving, not facts/statistics/quotes/opinions, and watch him fail--Nate River 13:52, 19 March 2009 (EDT) - It's more than that. Andy unquestionably has a severe lack of knowledge in these subjects, which wouldn't be a problem, except that he's teaching. I can't speak to his intelligence, but there's a fundamental difference between him and every scholar I've ever met: scholars are interested in learning. They may be the most egotistical, arrogant jackasses you've ever met, but they rely on the work and knowledge of others around and before them to build up an expertise. Andy, at every turn, denies the authority of every single expert imaginable; he only cites them if they conform with his preconceptions. For god's sake, he debated with RJJ when he was clearly out of his league on LBJ, and on the Illinois Constitution before that. He is simply not interested in learning, except where "insights" add to his range of crackpot theories, because learning presumes he's not omniscient. 14:08, 19 March 2009 (EDT) Rule of law[edit] Andy sez that Rule of Law is a conservative word not recognised by the dictionary. I'd like to refer him to the Oxford English Dictionary no less, which says:--PsyGremlinWhut? 08:42, 16 March 2009 (EDT) - That's from Oxford. That's a British school. Conservapedia uses good American dictionaries. OQED. MDB 08:54, 16 March 2009 (EDT) - Presumably his dictionary looks more like this. --Just passing by 11:25, 16 March 2009 (EDT) Andy as a D&D Character[edit] This time, without the random number generator. This is mostly based on first edition, because that's what I remember best... Andrew Layton Schlafly, Human1 3rd Level Cleric2 Lawful Annoying STR: 103 DEX: 103 CON: 103 INT: 154 WIS: 55 CHA: 46 1 Possible half-orc. Undetermined, but just look at his mother. C'mon... 2 Believes himself to be a 30th level paladin 3 Middle aged, sedentary job, looks a little flabby, but no obvious health issues 4 Well-educated 5 Completely unable to apply intelligence beyond the most simple concepts 6 Only able to attract a handful of henchmen, and many are secretly plotting against him. They don't call him "The Assfly" for nothing History: Born to a very minor noble family in the land of Conservia, Andrew has largely coasted throughout life based on his family. He studied Electrical Spells at a Tower of Wizardry, but considering he has not practiced such magery in nearly two score years, most believe he could not cast a Create Light spell without a Wand of Flashlight. Later, he studied the Law, daring to venture into the dreaded Dungeon of Harvard, but the key part of his studies there was his first encounter with his arch nemesis, Barack of Obama, who Andrew refers to as Barack the Socialist Muslim of Kenya, for reason that only make sense to himself. Note that the adversarial relationship is definitely not mutual; Barack may remember Andrew, but concerns himself with far more important things now, like solving the economic problems of an entire nation, defeating the forces of al Qaeda, restoring the tattered reputation of his land, and what he's going to have for lunch. He has attempted to use his and his family's position to launch one grand crusade after another, all of which have been defeated by small ripostes from the neighboring of Liberalstan. His latest wacky schemeplan is Fortress Conservapedia, an attempt to counter the far far far far far... larger Castle Wikipedia. (Note that Schlafly insists Castle Wikipedia is being constructed entirely by Liberalstan, but most adventurers who have been there report that, while Liberalstan has influenced it, many different realms have added blocks to its imposing walls.) While he insists that his castle will overtake his enemy's within five years, most outside observers feel that the chances of that happening are roughly on par with that of the Children's Crusade retaking the Holy Land. Equipment: Wand of Statistics: By holding this wand and speaking the magic word "PIDOOMA", Andrew can produce numbers that attempt to prove his point. For targets with Wisdom under 10, they will believe his arguments for 4d6 rounds. For those of higher wisdom, they will respond "huh?" and move on. Largely Defensive Weapon of Gun: Causes 10d100 damage, but can only be used if Andrew is attacked first. Ability: Andrew is completely immune to the spells Logical Argument and Well Sourced Facts. Those who attempt to cast those spells on Andrew have a 50% chance of suffering from Extreme Frustration for 1d6 rounds, leaving them unable to do anything other than continue to cast those spells on Andrew, who will still be immune to them. Note that every time those spells are cast on Andrew, there is another 50% chance of another 1d6 rounds of Extreme Frustration. (Yes, this could theoretically continue forever, however Schlafly usually eventually decides to stop using the ability and wander away, refusing to participate in melee any further). Disability: The sound of a Bugler induces terror in Andrew, leaving him unable to do anything beyond look around in paranoia for 3d6 rounds. MDB 10:05, 16 March 2009 (EDT) ADDITION: Disability: Andrew is unable to see trolls, even if his henchmen point them out to him. Trolls are only visible to him when they stand before him, yelling "I'm a troll, stupid!" MDB 10:05, 16 March 2009 (EDT) Funny![edit] Never played D&D, but this is funny.-- Kriss AkabusiAAAWOOOGAAAR!!1 09:56, 16 March 2009 (EDT) - Haha, that is too hilarious. But doesn't a cleric require a wisdom of at least 10 or 11 to cast spells? And I like his alignment. My friends and I like to give characters from TV shows and movies alignments and our conclusion for Will Turner from Pirates was that he is neutral-stupid. FernoKlump What the fuck Mr. Assfly??? That bastard DeanS deleted my petition! 09:59, 16 March 2009 (EDT) Thank you, thank you. I do have my moments. I guess this comes from years of reading "Giants in the Earth", the old Dragon Magazine column where the adapted characters from fantasy novels to AD&D terms. As far as requiring a Wisdom of ten to cast spells.... well, I didn't give Andy any spells, just special abilities. (Okay, I didn't think of that till you pointed it out, but I think I escaped it quite nicely, huh?) MDB 10:05, 16 March 2009 (EDT) - Doesn't this call for a new wiki project akin to Conservapedia:Liberals:_The_Garnering, write the GURPS: Conservapedia source book? --JeevesMkII The gentleman's gentleman at the other site 10:17, 16 March 2009 (EDT) - It is kind of fitting that Andy is a cleric who can't cast spells. FernoKlump What the fuck Mr. Assfly??? That bastard DeanS deleted my petition! 10:38, 16 March 2009 (EDT) Relocated[edit] Because you people have foolishly encouraged me with your praise, I've turned this into its own Fun page. Please add your further comments to its corresponding talk page. Help me, please! I titled my article Fun:Andy Schlafly as an Advanced Dungeons and Dragons Character, but that didn't put it into the Fun namespace. How can I change its namespace? MDB 10:50, 16 March 2009 (EDT) Guns prevent AIDS, so saith CP...[edit] Or something like that. I mean, really, come one. Z3rotalk 11:10, 16 March 2009 (EDT) - I read that a couple of times myself before WIgoing it.... I think what he's getting at is that the Democrats cared more about taking away guns then preventing AIDS.... The irony in that is dripping... I mean, for the past eight years, Bush has cut funding to groups that would distribute condoms and educate the masses in favor of the old "God wants you to zip it up." I must say, though, it's nice to see CP worried about us darkies for once. SirChuckBCall the FBI 11:56, 16 March 2009 (EDT) - But only worried in how it relates to liberals and spending. Sorta counts, I guess. Z3rotalk 12:05, 16 March 2009 (EDT) - You've got to wonder how someone like Andy would propose to stop this epidemic. Moar abstinence-only education...BECUZ IT WORKS! LALALALALA Neveruse513 12:51, 16 March 2009 (EDT) - Pretty much... There was an old E-mail joking that was floating around a few years back about the "GOP platform for (insert year here)" one of the items was "If you keep condoms out of schools, kids won't have sex." I thought that was a pretty good assessment of the mentality of the religious idiots who think Abstinence only education works. Personally, I like the unstated implication that it would be better for black America if everybody had unrestricted access to guns.... TK, I know you read this, and you're a fucking idiot. SirChuckBCall the FBI 12:55, 16 March 2009 (EDT) - Here in Chicago, we just had the 28th student killed this school year. I'm sure more guns is the answer. Z3rotalk 13:12, 16 March 2009 (EDT) - These children need MOAR GUNS!!!! EddyP 13:14, 16 March 2009 (EDT) - You see Zero, if Chicago issues everybody their own personal glock when they reached the age of seven and told their parents to be sure and teach them gun safety, the world would be fine. God knows that, as we live in a calm, rational society, everybody would use their guns only in self defense and never for retaliation, intimidation or in anger. SirChuckBCall the FBI 13:25, 16 March 2009 (EDT) - You're so right. Forget the push to tighten gun regulations in the city; glocks for everyone! I'm now a conservative, thanks to your brilliant insight. If only there was a website that catered to my new world view...Z3rotalk 13:37, 16 March 2009 (EDT) - I believe the Mexican carry combined with guns made in the USA with shoddy safety catches is a very effective tool at preventing the spread of sexually transmitted diseases. After all, it's pretty hard to have sex if you've shot your own cock off. --JeevesMkII The gentleman's gentleman at the other site 14:44, 16 March 2009 (EDT) - By the way, nice little Red Herring by the newspaper there. **west africa** has no worse an aids problem than any other 3rd world nation/3rd world region. It's *South africa* that has the AIDS epidemic. Why not just say "has a worse aids rate than China" or "has a worse aids rate than Vietnam" or any other poor nation. sighs... -- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 17:29, 16 March 2009 (EDT) - The same reason that everyone yells Socialists at Democrats. They're capitalizing on people's ignorance. Most people don't know what a Socialist stands for, but they know that "Socialist" is really close to "Communist" and Communist is bad.... Same principle. SirChuckBCall the FBI 18:49, 16 March 2009 (EDT) A thought about that philanthropic aid[edit] Teacake closes down that talk page section by throwing in a curve ball praising Bush's record on aid to Ethiopia. I was minded to dig through the bookshelves to find something I had read regarding the subject, and the truth about those vast $$ figures, and eventually found it in the (excellent) Monbiot tome, "Bring On The Apocalypse: 6 Arguments For Global Justice" (p.121): -. One has to open their eyes and look into the true meaning of things, Teacake, especially with the majority of the press/publications in the western world consisting of pure bullshit spin. I hope you do. You won't regret it. Godspeed. Fox 03:53, 18 March 2009 (EDT) What's Wrong with Andy?[edit] At least twice in less than a week, Andy has corrected himself in response to input from readers. Is he slipping? What went wrong with him? My initial thought was that his poor wife gave him "the annual", but then I remembered its Lent, and Andy would never partake of carnal pleasures during such a holy time. MDB 11:54, 16 March 2009 (EDT) - Yeah, but in each, he only offered a half apology, basically saying "I was right, but not as right as I could have been". That doesn't count. Z3rotalk 12:07, 16 March 2009 (EDT) - Is it a coincidence that the "corrections" are germane modifications to incredibly small matters? One correction comes from Hsmom about a common assumption, while the other plays into months of separating liberal words from the conservative list. He won't be "slipping" until he accepts a serious correction, like the existence of pre-20th century genocide or pre-Christian humour. This fits really well into the image I've gotten about many conservative Christians: they consider themselves perfect and infallible, but they also believe and call themselves humble and flawed. How better to reconcile these things than to accept tiny corrections of little importance? 12:58, 16 March 2009 (EDT) Breaking News: Muslin on Xtian naughtiness[edit] Jpatt reports that "U.K. Christian minister Noble Samuel of the hour-long live Asian Gospel Show is beaten by Muslims." [1] Pssst. Jpatt, way to go on leaving out the "‘faith hate’ assault" part because, as we all know, talking about why Christian persecution is the only true hate crime is confusing to the homosexuals and Jews. CPNuisance 13:16, 16 March 2009 (EDT) Move down scandal![edit] This is Conservapedia and we don't imitate liberal placement bias. We made ours up all on our own. [2] Newty's philandering was part of his personal life, which is at the bottom of the article, not his professional life, which is closer to the top. Duh. And don't write it as a personal attack [3].CPNuisance 13:47, 16 March 2009 (EDT) - Seeing how the GOP was on a serious "Family Values" kick during Newt's reign, I'd say his noxious hypocrisy is worth mentioning early on. --Gulik 13:50, 16 March 2009 (EDT) Mental problems[edit] I contributed. and I most definitely suffer from mental issues, so you are factually wrong, Andy. Course, i'm fully convinced you have a myrid of Mental disorders. Saying "no I don't" won't really cure them. but good shot. denial is the first step to recovery...orsomethinglikethat.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 17:04, 16 March 2009 (EDT) - I loled so hard that my boss yelled at me. Keep up the good work Andy! Z3rotalk 17:11, 16 March 2009 (EDT) - Yeah, no admitted mental problems. Aside from the multiple issues of Andy, TK and ♥ K e n D o l l ♥, who could fill a Bedlam or two just between the three of them. Koward is just an easily-led failure, and PJR's just plain easily led, so they probably don't count. --Kels 17:13, 16 March 2009 (EDT) - Combined with the very odd "Conservative triumph" bit further up, I think that Andy finally realized that almost the entire opposition is finally gone (Thanks to Senior Sysop Starscr-... I mean... TK, who never did anything wrong and was always on Andy's side), so he can go all-out with his increasingly silly claims. --Sid 17:18, 16 March 2009 (EDT) - they're comming to take me away, haha,hoho,hehe to the funny farm...-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 17:23, 16 March 2009 (EDT) - So Sid, you're suggesting that Andy's finally buying into ♥ K e n D o l l ' s ♥ delusionassumption that the more people say "WTF is wrong with you", that means they're smarting from you being so incredibly RIGHT? --Kels 17:32, 16 March 2009 (EDT) - Conservapedia: 84 million in page views, and 0 in mental problems by its contributors. Learn and teach the truth, and it will set you free. Your only regret will be that you waited so long before opening your mind to it. - I knew that reading CP alone would give me all the information I would ever need - but now, it stabilizes my mental health! I'm anxiously waiting for the incoming reports of blind people who could hear again after reading CP ! larronsicut fur in nocte 17:36, 16 March 2009 (EDT) Personally, I think a better ad would be a pic of Andy and his kids with the line "Conservapedia: It'll get you laid". Talk about giving hope to the hopeless! --Kels 17:41, 16 March 2009 (EDT) BTW, how long can Hsmom pretend that there is any sanity left in Aschlafly? I'm waiting for hew answer to this... larronsicut fur in nocte 17:47, 16 March 2009 (EDT) - - I changed the WIGO to suit my views on the subject. I hope noone minds >.<. It was designed with the intent of hitting the watching sysops the hardest. EddyP 17:49, 16 March 2009 (EDT) Wow, I mean just wow. I'm still a contributor to Conservapedia, seeking to bloat increase the size of Conservapedia beyond the capability of Andy to sustain it financially once Mama Syphilis Assfly keels over and I have rapid cycling Type II Bi-Polar disorder, severe paranoia & chronic insomnia. Three problems for the price of one contributor. Looks like Andy's wrong again.--stunteddwarf 18:16, 16 March 2009 (EDT) - I reckon it might be a slight wink-wink nudge-nudge that they're taking the piss. No one can think like that, can they? F**k it, I'm giving up on humanity so long as that man is alive. ArmondikoVgnostic 18:23, 16 March 2009 (EDT) - What will happen when they reach 100 million page views? Just imagine Bethany: "OMG OMG OMG OMG!!!" Or Ken: "Fabulous!" (sorry for the stereotype.) --JJ4eI christen thee Sir Annoyz Alot 22:58, 16 March 2009 (EDT) - What I just love is the clumsy illiteracy, and frankly, stupidity, in the line "Conservapedia: 84 million in page views, and 0 in mental problems by its contributors." Really, what the hell prompted him to add the "0 in MP" part to his latest boast? Does he mean they score "zero" on the "mental problems" test? ħuman 16:47, 17 March 2009 (EDT) Ken's Flickr page[edit] From ♥ K e n D o l l ♥'s userpage, this is truly bizzare, he seems to be trying to conquer Flickr by adding random hitler under the username "Atheism" BadgerBadger 17:41, 16 March 2009 (EDT) - Link? Totnesmartin 18:54, 16 March 2009 (EDT) - [4] Mei is useful. This is operation wtf. Mei 18:57, 16 March 2009 (EDT) - He's trying (and badly failing) to make himself look like a crowd by taking yet another alias and then claiming himself as a source. The same way he took on a number of false names in order to spam any number of message boards and blogs. Problem is, he's really bad at it. --Kels 19:07, 16 March 2009 (EDT) - Yeah. And this one is especially transparent because the image had been on the CP main page for AGES, so everybody knows who it comes from. And that's not even factoring in the idiotic linkspam on the Flickr page. --Sid 19:21, 16 March 2009 (EDT) - And for gods sake, look at GFasten's user page. Come on Ken - you muppet, you can do better than that....cant you? Ace McWickedRevolt 20:44, 16 March 2009 (EDT) - I, for one, hope they continue to play the Hitler card. It's going to backfire on them eventually.. THAT can't look too good for Christians methinks. Jimaginator 08:35, 17 March 2009 (EDT) HSmom[edit] Is not long for this world. We should place bets when she gets permabanned, and by who. My vote is TK next week. Z3rotalk 17:51, 16 March 2009 (EDT) - Just amazing. And all she did was ask about celebrating bathhouses on the main page. She's the best editor they have, and they're about to drive her off. Meritocracy my ass! CorryThose are balls. 17:54, 16 March 2009 (EDT) - Has anyone ever dropped her an invite by e-mail? I know she's supposed to have been having e-mail problems with CP lately, but who's to say TK never sent an e-mail in the first place? More on topic, she should have seen what would happen to her as soon as CPAdmin1 left; they're very similar people IMO. EddyP 17:56, 16 March 2009 (EDT) - (EC) I find the end of that Assfly quote a little disturbing. The suggestion that she could "insulate" her children from the problems that liberal children have and that they in turn could then "insulate" their friends reminds me very much of Dawkins comparing religion to a virus. If you get sick enough you start your own wiki and attempt to "insulate" people en masse over the internets. --Horace 18:00, 16 March 2009 (EDT) - I'm amazed by the entirety of Andy's reply, seeing as it has nothing at all to do with the question HSmom asked in the first place. I wonder if he even read it. --Kels 18:03, 16 March 2009 (EDT) - Yes, Andy's response is really, really bizarre. Her comment was, if anything, overly polite for something as strange as that bathhouse news item. -Lardashe - It's pretty stright forward. He doesn't like her, cause she challenges him. But she does so in teh single cleanest, most nice, most articulate way possible, while still being a mom and a home schooler. He has nothing on her, so every time she corrects him, politely, it galls him to the core. He's got to get something on her. He will push and push like an abusive husband, till she lashes out, then say "see, all your fault for yelling at me, wife".-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 18:15, 16 March 2009 (EDT) (Unindent) I think the mask may have slipped a little in this post. A "clueless mom?" If she is a gung-ho conservative home-schooling mom, why haven't her kids made an appearance yet? From Andy's perspective that has to be the most galling aspect of HSmom, her kids don't take his course...-- Antifly Now with 50% less retirement! 20:13, 16 March 2009 (EDT) - How do you know? If there are infiltrators in his course, how does he know who his students are? I know someone said some of them are real life kids he meats weakly. but if there are others that just signed up off the blog, I'm not sure you can say someone like HSmom wouldn't keep her children's identities in an internet course of dubious value from their creepy instructor.CPNuisance 20:40, 16 March 2009 (EDT) - Well, I think its safe to say that if her kids were on he wouldn't treat her the way that he does (remember he's chivalrous). I think we have established that all of the students are in his real-life class, with the exception of the student that Andy picks on.-- Antifly Now with 50% less retirement! 20:56, 16 March 2009 (EDT) - I'll bet pi-squared dollars (donated to the next RW fundraiser) that HSMom is fretful. Bondurant 05:12, 17 March 2009 (EDT) - Any takers for an over-under on the first ban length? I'm thinking 3 hours. Neveruse513 08:53, 17 March 2009 (EDT) - I think that she'll email andy and just stop contributing. . Violence is the last refuge of the incompetent 08:57, 17 March 2009 (EDT) - Yeah, you're probably right...but a mini parthian from hsmom would be epic. Neveruse513 09:00, 17 March 2009 (EDT) - Re: "clueless", yeah, that was epic. Could have been innocent, but... really? First off, it immunizes her against AS calling her clueless (should memorialize it at teh clueless article as "self-immunization"?), and second, if it was carefully considered (and when is hsmom anything but that?), it perhaps belies a passing knowledge with our fetishes over certain AS phrasings here. And, yeah, as I said above in another thread, AS didn't go anywhere near answering her question, he just use his quote generator and deleted the "you're clueless" from the result. ħuman 16:59, 17 March 2009 (EDT) Three-Headed Monster[edit] This gave me a laugh.-- Antifly Now with 50% less retirement! 18:25, 16 March 2009 (EDT) - DarHitlin? Madness, who could have done such a thing? He is the Painkiller 19:00, 16 March 2009 (EDT) - Haha, I just noticed it on recent changes, it's posted on Conservative's talk page: BadgerBadger 19:05, 16 March 2009 (EDT) - In four words: "READY TO FORM VOLTRON!" --Sid 19:29, 16 March 2009 (EDT) - I can form head? CPNuisance 20:30, 16 March 2009 (EDT) TK and Checkuser[edit] Seriously, can this guy answer any question without making snarky implications about IP addresses and geolocation? (See also here for another post along the same lines from just a few sections above on that same page.) And does this count as an ad hominem argument? --Sid 18:58, 16 March 2009 (EDT) - It certainly felt like an ad hominem when he said it to me. But he was correct on every point except the moral relativist jab, which I found puzzling. I am and was a childless liberal atheist jew masquerading through deceit as a conservative. I made some rookie mistakes in that round that won't get repeated.CPNuisance 19:25, 16 March 2009 (EDT) - It is more an "I can see your house from here" style threat. - User 19:39, 16 March 2009 (EDT) - And it was creepy. I owned TK in that discussion, albeit with the largely offensive weapon of masquerading through deceit as a conservative, so it's weak of him to just end the debate with an ad hominem attack on my deceitful sock. What a predictable buzzkill.CPNuisance 20:28, 16 March 2009 (EDT) - I posted the exchange as a WIGO. Hope you don't mind. --Irrational Atheist 21:24, 16 March 2009 (EDT) - Mine was the other one, but yours is creepier. Huzzah.CPNuisance 21:38, 16 March 2009 (EDT) This is a "terror site"!? Beautiful! 21:46, 16 March 2009 (EDT) Didn't somebody at one point have photos of Terry's house? I think it's time for a repost. --Marty 05:25, 17 March 2009 (EDT) - his googlemap postcode has recently been deleted for privacy/stalking so I can't see a photo being approved. . Violence is the last refuge of the incompetent 06:02, 17 March 2009 (EDT) - I think he's just pissed that he gave his own personal info out to the LA Times, so now any potential employers can Google him (and who doesnt these days) and get the Conservapedia connection and see how he behaves there. Bad taste[edit] Is it just me, or does TK's news piece on the late Ron Silver contain a rather distasteful pun in its wording?...[5] Jammy 20:33, 16 March 2009 (EDT) - Esophageal cancer puns are always in season! Seriously, though, RIP Ron Silver, the best canceled TV villain ever. --Marty 05:29, 17 March 2009 (EDT) World History Lecture Eight[edit] Oh, crap, Andy's going for extra lulz. "The King James Bible established a framework of knowledge of the English language, and it began to develop rapidly afterward." Say what? "English is unique in its ability to develop new words, at a rate of about 1000 new words per year." Unlike, say, all other modern languages? "English has the smallest alphabet of major languages, including its lack of accented, hybrid, and pictograph characters." Major languages, perhaps. But the Rotakas alphabet is the smallest Latin-based alphabet still in use. The German alphabet has only the ß in addition to three umlaut-able vowels; however, these characters are regularly reduced to "ss" or vowel+"e" using normal keyboards. Therefore, if Andy wants to exclude the accents of "mêlée" and "naïve", then the modern German alphabet can also have the same 26 letters lacking any accents. "English features easy interchangeability of nouns, verbs, and adjectives, without much variance in form for pronouns and verbs. That promotes easy communication through brief, cryptic messages, the style preferred by electronic media." I'm sure that was the point of the King James Bible's promotion of the language? I'm lost to the purpose of this paragraph. "English enjoys a powerful pipe-like quality, such that one phrase can be cut and pasted to another phrase with ease." This sounds more like Ed Poor's mental fart than anything. "Computer-based cutting and pasting text works more efficiently in English than in many other languages, such as those using pictorial characters." I'm sure the Japanese would love to know the inefficiency of their language on computers, even though they're one of the top producers of the machines. Just tons of stupid with a subject far out of Andy's grasp. --Irrational Atheist 22:41, 16 March 2009 (EDT) Well, he's right on the last point. Kind of, sort of, in the most roundabout way possible. Japanese and Chinese suck for computers, because making a 256+ key keyboard is simply impractical. This difficulty is worked around using a language called Pinyin. Essentially, the user types things in in Pinyin, it's translated to the hopefully-correct Japanese, and displayed as Japanese. The More You Know! Barikada 22:58, 16 March 2009 (EDT)I'm stupid. Barikada 03:26, 17 March 2009 (EDT) - No you're not. Just ever so slightly incorrect. I didn't even know how Chinese would use a standard keyboard, you explained it.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 11:31, 17 March 2009 (EDT) - I don't know why, but it finally hit me why Andy's lectures always seem to remind me of something. I couldn't quite place it until tonight. Andy is Stephen Colbert if the character were real. Sure, Andy lacks the charisma Colbert would have, but otherwise? Spot on. The stupidity, the lack of logic, the simple-mindedness and petty grudges, the truthiness - its all there. I know that Stephen Colbert based the character a bit on Stone Philips, but it makes you wonder if there wasn't a little Andy in there, too. Kaalis 00:29, 17 March 2009 (EDT) - I wonder if his cut and pasting includes infixes. Prefixes and suffixes are easy. But an infuckingfix isn't that common in english. And verbing nouns makes english teachers hemorrhage. --Shagie 00:34, 17 March 2009 (EDT) - On a side note, the suggestions I made a month ago, and confirmed by active conservapedian AlanE, remain unchanged. Philip II will just have to send his Armada before he's even born. Tough break. --CWaddell 00:37, 17 March 2009 (EDT) - God how I wish he would get off his language kick. It was bad enough when he was talking about fields I had a Highschool or 1st level college knowledge in, (and luckily for my sanity, he doesn't talk much about Indians), but now he's sorta on turf I care about... and all i want to do is bang my head. How can anyone so...how can you say "i have to prove that I'm the best, America is the best, therefore english is the best with such gumption. (and I don't knwo about chinese, but Japanese write in Kanas on the computers, which is native to their writing system, and is phonetic. They didn't have to invent new language like Pinyin.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 01:11, 17 March 2009 (EDT) - Factual Error - My favorite is "In Spain, Philip II (1638-1715), who was the great-grandson of Isabella and Ferdinand, worked to cleanse Spanish territories of all religions but Catholicism, and viewed Elizabeth I of England as his main rival.". As Elizabeth lived from 1533-1603, something is amiss here, an obvious error, more easily to spot as it was mentioned on the talk page Feb 23rd, 2009! Could it be that Andy mixed Philip II of Spain (1527–1598) with Louis XIV of France (1638-1715)? --larronsicut fur in nocte 03:27, 17 March 2009 (EDT) - He does have them confused: "The nature of an absolute monarch was expressed well in this famous quote attributed to Louis XIV (1527-1598), “L’etat c’est moi!” (I am the state)." - User 07:17, 17 March 2009 (EDT) - Trouble is: anyone correcting his "facts" has a fair chance of being condemned as having read it here - naughty. . Violence is the last refuge of the incompetent 07:35, 17 March 2009 (EDT) - I don't know, seems to me several good users who were not "regulars" here (if posters at all) have tried to correct Andy on these lectures - only to be told to shut up cause you are not as smart as the Great Andy, and if Andy wrote it, he must know about it cause he's, you know, The Great Andy. -- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 11:21, 17 March 2009 (EDT) - I fixed the "bold for everyone who posts after this point" problem... Pesky semi-colons. The Foxhole Atheist 11:31, 17 March 2009 (EDT) - Interchangeability of word classes is a good thing? I thought verbing weirds a language (not that I'm really against it, nouning and verbing and adjectiving words can be quite fun... ::tailwags bushywolftailfully::). "Cryptic" is suddenly a good thing? Oh, and size of the alphabet is a misleading statistic if the orthography itself is crap; Andy conveniently doesn't mention the weirdness of English orthography. (Wai kant Inglish spiikers dzast spell things laik thei aar pronaunst? That wud impruuv the laivs ov houmskuuld tshildren, dzast foo van eksampl.) --wwwwolf (barks/growls) 11:56, 17 March 2009 (EDT) - I"m sure you all have seen 1 or more of these poems, but I always laugh (or cry) when I read them. .-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 12:05, 17 March 2009 (EDT) (I fixed the link by adding a space after it ħuman ) - Wi kaen't spel fownetykli bikoz ov dhiz gaadaem vaewlz! Maednys! -- YossieSpring in Fialta 16:19, 17 March 2009 (EDT) Ahh, the great language of Chinese. Is Andy really going to leave the myth of the Triangle trade in there without exposing it for the liebel deceit that it is? --BoredCPer 16:05, 17 March 2009 (EDT) - 1)languages are not phonetic or not, Andy. WRITING SYSTEMS are. 2)hebrew is classified by even the most basic of systems as a phonetic writing system. there are really only two options, phonetic of some kinds (alphabed, syllablical and abjad) or logoio/symbolic writing. Hebrew is a phonetic language, even though it lacks vowels. reading "writing systems 101" instead of pulling things you think sound "logical" to you, might help you and your students. Course, you think that chinese is incapible of expressing new words, new ideas, etc., grrrrrrrrrrrrrrrr. oh, wonder what he thinks of Sign language as a language?-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 19:40, 17 March 2009 (EDT) - Speaking of Chinese expressing new words, one of the crazy things I learned recently about Chinese is that their periodic table doesn't need abbreviations; whenever a new element is discovered, they make up a new character for it! Who needs a big word like "praseodymium" when you could just say 鐠 pǔ? --Marty 23:53, 17 March 2009 (EDT) - That is weird, I can't see 105-109 but I can see 110 and 111. What new fonts do I need installed on my computer? - User 00:00, 18 March 2009 (EDT) - The "stoopid get" also doesn't know the difference between a tsunami and a tidal wave - a tidal wave is caused by tides, a tsunami is caused by undersea earthquakes. Andy Schlalfy is a teacher? My arse! Lily Ta, wack! 17:05, 18 March 2009 (EDT) Suicide by TK?[edit] What is SStaple thinking questioning what the banhammer is for? Doesn't he know TK or ED will smite him for daring to question his betters? --BoredCPer 23:52, 16 March 2009 (EDT) - He is your boss - He has never disagreed with his boss - He has never heard of teacher evaluations - He does not know what "insult" means I wasn't around for the old TK madness, so I sometimes doubt the "TK is just out to destroy CP" theory, but this . . . This is Bugler-esque. Coarb 03:30, 17 March 2009 (EDT) And he has not take responsibility for his actions, even not to his peers: - (Block log); 04:02 . . TK (Talk | contribs) blocked Whraglyn (Talk | contribs) with an expiry time of 5 years (account creation disabled, e-mail blocked) (Troublemaker: Administrators decisions are final. Threats of contacting other Admins and/or harassment will not be tolerated. Bye.)</font> --larronsicut fur in nocte 04:09, 17 March 2009 (EDT) - I guess 360 degree review isn't a phrase that has penetrated whatever S&M parlour TK works at. --JeevesMkII The gentleman's gentleman at the other site 04:30, 17 March 2009 (EDT) - Ok, firstly, thank you for an image that will haunt me to my grave. Secondy, it's basically just TK engraving his self-imposed MYOB rule in stone, much like his bitchcolleague Geo.Plrd closing the abuse page. --PsyGremlinWhut? 04:34, 17 March 2009 (EDT) - seriously, man, I am asking you in all seriousness, how can he go any further off the edge? I can't wait to find out... Neveruse513 08:48, 17 March 2009 (EDT) - That has to be one of his more bizarre rants. --PsyGremlinWhut? 09:38, 17 March 2009 (EDT) - He's trying to match Bugler, but failing miserably as he writes so poorly. 10:41, 17 March 2009 (EDT) - Man, Bugler had panache. He had style. TK's just playing the lounge. -- YossieSpring in Fialta 16:07, 17 March 2009 (EDT) - I know the lounge, I've played the lounge and TK, sir, is not good enough for the lounge. SirChuckBCall the FBI 17:27, 17 March 2009 (EDT) <- Wait, you've played the lounge and didn't see him? Hint: he's not part of the official entertainment, he's the meth-fueled bouncer lurking in the shadows. He got a side gig at EPIDEMIC 09, by the way, watching over the 8 hour, eleven band all ages party. Although he got confused and stole their logo to illustrate a CP borken news item about AIDS. ħuman 18:16, 17 March 2009 (EDT) (PS, what part of © Copyright 2009 Wyndham City Council doesn't he understand?) (PPS, I emailed the author with some links) I got mail[edit] "Thanks for bringing this to my attention. Much obliged. As we have copyright to this artwork, I will contact the site's administrators and have the logo and any reference to it removed." ħuman 20:48, 17 March 2009 (EDT) - Someone from Wyndham posted at CP about their logo it's been removed. Refugeetalk page 05:27, 18 March 2009 (EDT) - ....and once again TK burns the evidence. (Deletion log); 08:36 . . TK (Talk | contribs) deleted "Conservapedia:Desk/Copyright" (Author request: doesn't want her phone number left up.) here's a shot (phone number redacted) FJF 13:50, 18 March 2009 (EDT) - hey my link isn't working anymore. :( "The database did not find the text of a page that it should have found, named "Conservapedia:Desk/Copyright" (Diff: , 641097). " At least someone got a picture. Refugeetalk page 18:52, 18 March 2009 (EDT) - But the question I'm wondering is... did TK remove the image/logogogogo? Or did he just delete the Copyright page and do the proverbial "washing hands gesture" and walk off? NorsemanCyser Melomel 08:58, 19 March 2009 (EDT) - PJR actually did the deed as far as I recall (probably further enamouring himself to TK et al). And of course, now nobody can complain officially about CP breaking copyright, thanks to TK. I wonder if he's trying to get Andy sued? --PsyGremlinWhut? 09:15, 19 March 2009 (EDT) How Convenient: "An immoral person is of course incapable of making a legitimate argument."[edit] This was already WIGOed but the edit summary was not. The odd thing is I agree with TK, more or less, in that I think argument is an ethical act and it is possible to argue un-ethically (dishonestly or purely rhetorical (If I can convince you of X then X must be true, no matter what)--thus illegitimately. The rub of course is that in CP-land all non Christians are immoral and all liberal are immoral, so any argument that you can define as liberal or not made from a christian context is by definition immoral and therefore illegitimate.(Other than that we aren't biased to facts here) Therefore when Andy says "no legitimate arguments have been raised against crazy topic X" he is literally correct in the context of his bizarro world. I think we're done here. Will you turn out the lights when you leave? Me!Sheesh!Mine! 09:55, 17 March 2009 (EDT) - TK is cracking. Basically every response to anyone questioning anything lately has been "you're a deceitful liberal/open your mind and learn conservative values/bye." BTW, it's pretty clear to me from his recent edits that he's reading RW as much as CP. Hi TK -- I can tell you're suffering. You should seriously consider taking a CP break and working on yourself. The tone of much of what you're doing is hateful and way too highly energized -- you deserve some peace.CPNuisance 10:39, 17 March 2009 (EDT) - He doesn't need a break--Hatefulness is TK's reason for being. The common speculation here on RW is that TK is trying to bring down CP from within, but I disagree. TK just likes being an asshole, and CP is a place where an asshole can thrive (provided they're the right kind of asshole). Birds of a feather, and all that.--WJThomas 11:12, 17 March 2009 (EDT) - Agreed. TK's not a parodist, nor is he scheming to bring down CP through complex infighting. He's just an asshole, plain and simple, that's all. DogP 11:42, 17 March 2009 (EDT) - I think TK is a parodist it is just that he has never officially broke cover here at RW. He is content to maintain his act over here as well. As for his motives, I certainly don't believe he is a sincere contributor to CP like Karajerk or PJR for instance. He is playing a different game. His motives may well be simple day-to-day trollish entertainment, but he has shown in the past an ability to plan and organize so he could in fact have some sort of master plan the details of which are hidden to us. And yes, he no doubt reads every word in the commonly used talk spaces of RW. Me!Sheesh!Mine! 12:21, 17 March 2009 (EDT) @Sheesh: I'm not sure what you mean by "argument is an ethical act", but I don't think arguments themselves (the premises and conclusions) are subject to moral evaluations. This is of course different from "arguing" (the putting forth of arguments), which very well might be. At any rate, I think TK couldn't possibly be more wrong. I assume by "legitimate" he either means a sound argument or a valid argument. To determine if an argument is sound we ask if it is possible that the premises could be true and yet the conclusion be false. If it is possible, the argument is not sound. To determine if an argument is valid, we take a sound argument and ask "are the premises true?" If they are true the argument is valid. If a sound argument has true premises, the conclusion is always true. This is true regardless of any facts (including whether they are being deceitful) about the person putting forth the argument. Soundness and validity govern the arguments put forth by everyone from creationists to Hitler and is the ONLY criteria I know of to judge an argument. Bjones 13:27, 17 March 2009 (EDT) - Please don't @ me (this is where a smilely would go). I meant that putting forth an argument is an ethical act. Trying to convince someone a certain thing is true or compell them to some action through the use of rhetorical devices is an ethical act. Thus, as TK suggested (Hi TK!), to the extent that there can be fair arguments you can't mount a legitimate one from an unethical or amoral position. You can try (Hi Andy, et al!). You can sometimes make effective arguments from a unethical positions though use or threat of force (Hi all!), or by mounting and defending disengenious assumptions(Hi PJR!), but that's not quite the same thing. 72.218.136.212 19:57, 17 March 2009 (EDT) - TK is a sociopath and shit-stirrer par excellence. When he wipes an alleged RW account at CP he discharges some pre-come but at the same time he's getting off on the knowledge that he's stifiling CP by applying an overlarge range-block. Two birds with one stone. Lily Ta, wack! 18:42, 18 March 2009 (EDT) Andy's spelling mistakes page[edit] I'm not sure if this has been WIGO'd yet or not, and I'm too lazy to check, but Andy has created a page devoted to spelling mistakes caused by lack of phonics. Let me say that again. Andrew Schlafly has created a page devoted to spelling mistakes. Why bother adding a joke? MDB 10:33, 17 March 2009 (EDT) - Like fuckin' Sham-Wow, it sells itself! NorsemanCyser Melomel 10:41, 17 March 2009 (EDT) - No jokes needed indeed. We need a graph of Andy's insightful theories and articles in order of insanity. This is in the "Fuckin' Nuts" range. 10:43, 17 March 2009 (EDT) It's not about spelling mistakes--it's about reading mistakes.--WJThomas 11:08, 17 March 2009 (EDT) - exactly WJT, he basically makes the point that "if public schools taught phonics, no one would ever ever ever make a mistake while reading something." The man has lapped himself SirChuckBCall the FBI 11:14, 17 March 2009 (EDT) - Does no one else get it? (oh, you aren't dyslexic, so maybe don't understand how much we rely on computers). these are not phonetic mistakes, they are mistakes Andy has made (likely) online or at work because his little spell checker didn't say "that's a mis-spelled word", but someone pointed out to him, probably after "publishing" or filing, that it was the wrong word. by saying it's "common" or blaming everyone else, he doesn't have to address his own short comings.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 11:18, 17 March 2009 (EDT) - I read it as a page dedicated to making fun of others' mistakes. ("HA-HA!! That retard said immortality instead of immorality! Only a liberal who never learned phonics would do something so dumb!").--WJThomas 11:25, 17 March 2009 (EDT) So lack of phonics is why Schlafly keeps making such silly mistakes as mixing up "fusillade" and "fuselage"? He should certainly buy himself a big package of that phonics stuff then..... --Just passing by 12:24, 17 March 2009 (EDT) - I'm getting a particular glow from the example that shows Gore perhaps losing 10,000 votes in FL. Would that have been enough to swing the 'lection? I guess Andy likes it because it makes liberal voters look stoopid? PS, I found a typo in my $100 "millenium" atlas... ironically, "typography" was substituted for "topography". ħuman 17:24, 17 March 2009 (EDT) - Damned liberal atlas. They probably don't even mention how English is the Pinnacle of language, and that Iraq is safer now after we liberated it from the guys who blew up the Twin Towers.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 19:26, 17 March 2009 (EDT) - Well, on point one, they list places in foreign countries in the "local" spelling, with the english version smaller underneath, so, yeah. And point two didn't happen yet when this was published (ca. 2000). ħuman 16:48, 18 March 2009 (EDT) An Informal Apology[edit] I would like to offer my sincere apology for my careless vandalism last Friday night. I feel I owe all of you an explanation: I had a little much to drink and I was upset that TK had sniffed out what I thought was a pretty good sock. I got a little paranoid, and from what I remember I made some wild accusations about whom I thought was a mole. What I did was idiotic and I'm quite relieved that no permanent damage was done. I respect the work that so many of you have put into this site, and I assure you that you will not have anymore trouble from me in the future. Sincerely, Jorge 10:44, 17 March 2009 (EDT) - Don't drink and do the intertubes. It may cause boobs you will later regret:-) Auld Nick 11:00, 17 March 2009 (EDT) - Whut? there's no moles here... a couple of weasels maybe... --PsyGremlinWhut? 12:47, 17 March 2009 (EDT) - We got some mowses that occasionally chew on the server... -- YossieSpring in Fialta 15:57, 17 March 2009 (EDT) - At one point we had a hamster, but I haven't seen it in ages... any idea where it's got to? --Marty 23:59, 17 March 2009 (EDT) - Sorry Marty, it got to big for the house so Trent gave it away to a family in the country, it has a nice big farm to run around on now. Those gunshot you heard? Oh that was just Human trying to scare off some birds. - User 00:03, 18 March 2009 (EDT) - Yup, that Aimless Blaster sure helped out. ĵ₳¥ášÇ♠ʘ is writing a comment 00:06, 18 March 2009 (EDT) 0 in mental problems by its contributors.[edit] Would someone care to explain the new 'news' tidbit at the top of the CP frontpage Conservapedia: 84 million in page views, and 0 in mental problems by its contributors. Learn and teach the truth, and it will set you free. Your only regret will be that you waited so long before opening your mind to it. Dr Schlafly personnaly gave a psychological assessment to all his contributors? - Oh, the irony is so delicious, I can taste it from here... "Open your mind to the truth that being a close-minded, intolerant, fundamentalist bigot is the only way to be free!" Fuck you, Andy Schlafly. The Foxhole Atheist 11:36, 17 March 2009 (EDT) - Does that lead sentence even make grammatical sense? "0 in..." Oh wait, it's Andy we're talking about. --PsyGremlinWhut? 12:36, 17 March 2009 (EDT) - Anyone who can seriously assert that ♥ K e n D o l l ♥ has no mental health problems almost certainly has mental health problems of their own in the "divorced from reality" field. --JeevesMkII The gentleman's gentleman at the other site 12:38, 17 March 2009 (EDT) - I think Mr Schlafly is saying that contributors don't exhibit mental problems in their role as wiki contributors. Clearly he has no way of knowing about other unrelated problems.--ConservapediaRoolz 12:41, 17 March 2009 (EDT) - And ♥ K e n D o l l ♥? Does he edit in a perfectly sane fashion? Bastard bastard Hoover! 13:10, 17 March 2009 (EDT) - And Ed Poor's "Dinner and a Movie" blogs, that come off drunken if that just can't be considered stable or normal.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 13:12, 17 March 2009 (EDT) - Disregarding even ken and ed, what about Andy? If that man doesn't have some form of degenerative mental illness (even if it is only raging alcoholism), I would be deeply surprised. Kaalis 13:14, 17 March 2009 (EDT) - None of these people's contributions, however poorly written or haphazard, are evidence of real mental problems. Plenty of sane people have trouble writing in a coherent way. I expect that if Mr Schlafly thinks a contributor has mental problems, he blocks them, so from his point of view everyone who remains must be sane. And of course he doesn't think he himself has anything wrong!--ConservapediaRoolz 13:17, 17 March 2009 (EDT) - People with real mental problems can write quite coherently. Mental problems and writing skills have nothing to do with each other either way. But the fact that Andy *cannot* hear dissent, *cannot* accept any argument without simply blowing his top; the fact that he is *quite* delusional at times about what we would call "the real world" suggests that he has some serious personality disorders that could use some profession help. You need only listen to him say "you believe in school prayer, therefore I know what you will say about EVERYTHING" to understand that his world is not the world of reality and not just in "gest" or fun, but something doesn't fire right in his head. The level of conspiracy he sees in the government; the lack of cogitative dissonence... that's not normal.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 13:25, 17 March 2009 (EDT) - I agree that Mr Schlafly has certain prejudices and preoccupations, but I don't think that constitutes mental illness - few people have the insight to see the world as it really is all the time. He can be a bit overbearing, but then again, it's his blog to do what he likes with. Judging people based on the view you get over the internet is bound to give distorted results, so I would exercise caution in doing so.--ConservapediaRoolz 13:30, 17 March 2009 (EDT) - Yeah, except you started this by saying that is the sole criteria that the Arsefly is using to judge people's mental state. Anyway, in ♥ K e n D o l l ♥'s case, it isn't just his writing that suggests he has problems, although his homosexuality obsession tends to suggest he's in severe denial about something. Rather it is his pattern of other behaviour. His delusions of grandeur (he honestly seems to think his articles have some effect on evolution and atheism, for example) is a key part, his unwillingness to supply his real name or identity even to his fellow sysops (he has used at least two pseudonyms in private CP discussions thus far) as well as his insistence that his obvious socks elsewhere aren't in fact him at all. Face it, the guy has issues. --JeevesMkII The gentleman's gentleman at the other site 13:35, 17 March 2009 (EDT) - And, in my opinion, less about any mental illnesses their editors might have (we'll never know) then the fact that he boasts none of them have any problems. As has been said, there's no reliable way to diagnos this over the internet. Z3rotalk 13:37, 17 March 2009 (EDT) - a) How do we know the contents of private CP discussions and b) How do we know that his real name is Kenneth DeMyer, and not another pseudonym? Bastard bastard Hoover! 13:54, 17 March 2009 (EDT) - As you may remember, the ever helpful TK allowed us to see the SDG archives last time he blew his top. We know from emails forwarded to that group that he used to style himself "David Jensen", and also that CP came to the conclusion from IP addresses that he was in fact Ken DeMyer. There's also sound, if rather stalky, reasons that I won't go in to to believe that Ken is in fact his real name and not just another psuedonym. --JeevesMkII The gentleman's gentleman at the other site 14:09, 17 March 2009 (EDT) Pretty much every fundie suffers from a form of grandiose delusional disorder. Remember, these people have a personal relationship with the creator of the universe, who gives them pearls of wisdom about the sinful nature of buttsecks. Neveruse513 14:03, 17 March 2009 (EDT) - I think I figured it out! Ignoring the illiteracy, of course. Remember, AS thinks that liberalism causes mental illness, and being conservative basically insures one against it. Ipso facto, dipso mania, since CP is solidly conservative, none of its contributors suffer from "mental problems". I still want to know what on earth prompted him to babble about it like that in his periodic pageview bragging on the news ticker. ħuman 17:42, 17 March 2009 (EDT) - I think he's running down these days. With TK running every voice of dissent out of town, he doesn't have anyone to play with. He wants to get out his Captain Andy hat and torpedo the liberals, but by now, everybody knows to stay clear of the main page and don't feed the Andy troll, hence, he's coming up with more and more obvious incitments to argue. SirChuckBCall the FBI 17:55, 17 March 2009 (EDT) In reply to User:WaitingforGodot Are mental illness and writing ability really not inversely correlated at all? I for one, often find it difficult to distinguish logically sound yet incoherent writing from insane ramblings. At some point, if some writing is bad enough, it seems impossible to figure out what the author was trying to say. Coarb 18:58, 17 March 2009 (EDT) - Still don't think it's right to jump to conclusions about mental health from what people post on the internet. As for why Mr Schlafly posted that in the first place... it probably wasn't that thoroughly thought out, and I would think there was an element of hyperbole underlining his triumphal feeling at getting so many page views.--ConservapediaRoolz 19:25, 17 March 2009 (EDT) - grins, you need more goat. No one is ready to prescribe anti-psychotics, or put him in a white coat. -- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 19:50, 17 March 2009 (EDT) - The diagnosis of mental illness is really a question of degree. Most people are not truly rational even though they may act in a rational way in regard to their circumstances. And someone who is completely rational in everything they do probably has some sort of mental illness as irrationality is a fundamental part of humn nature. So while Andy and the other "nutty" sysops may not be certifiable they are certainly eccentric and en route to a psychological condition. Lily Ta, wack! 19:19, 18 March 2009 (EDT) Andy's Obama Hatred[edit] Ok, I get the fact that Andy hates and resents Obama because one became the POTUS and the other became.... Well Andy, but this post is off the charts when measured in bizarre factor. First off, does Andy really think that Barack Obama is personally writing, coding, and uploading the White House web page? Two, does he know that the Administration is correct in this? Once Obama officially names someone, they are considered an appointment, but they cannot begin serving until confirmed by Congress, and three, did he miss that large column that reads "Senate Confirmation Date?" Andy, we're all worried about you.... SirChuckBCall the FBI 13:32, 17 March 2009 (EDT) - Stop pointing out factual errors in perfectly reasoned arguments, liberal deceiver! Z3rotalk 13:36, 17 March 2009 (EDT) - The terms are used interchangeably in this context in Article II of the Consty. So everyone can be right. I wonder if past administrations are as stupid as Andy thinks Obama's is for using "appoint" in a way that displeases the Assfly.CPNuisance 14:34, 17 March 2009 (EDT) - Jesus, doesn't Andy know how to use Google? Even Fox News calls them "appointments" before they've been confirmed. [7] Bjones 13:43, 17 March 2009 (EDT) - Zero, I am a Penguin Knight, we don't deceive! SirChuckBCall the FBI 13:47, 17 March 2009 (EDT) - Well, isn't this a case for Hsmom - as DinsdaleP is history? larronsicut fur in nocte 13:49, 17 March 2009 (EDT) - "SirChuckB" (obviously not your real name), your rant above is silly. I looked at your contributions and you say you don't believe Jesus is God, so I'm confident you're wrong. Furthermore, you deny that gun ownership reduces moral decay. As I've said before, Conservapedia concerns more than politics. We have over 20,000 entries here. Insistence on last wordism in violation of our rules, without contributing substance to this encyclopedia, could result in account blocking. In Christ.--Aschlafly 17:57, 17 March 2009 (EDT) - "Aschlafly," your lack of comprehension is indicative of your political ideology. Its clear that you are a liberal who has nothing better to do than troll us. Tell me, what are your positions on Gun Control and School Prayer? I am 99% certain that you also believe in the theory of evolution and gravity. EternalCritic 14:05, 17 March 2009 (EDT) - We desperately need a {{tkquote}}{{tkdismissal}}. Neveruse513 14:09, 17 March 2009 (EDT) - TK doesn't reuse things as often and his style isn't nearly as distinct. Probably wouldn't be too hard to make a {{Jinxquote}} though. A TK one would probably require checkuser powers to abuse and be a creepy stalker. EternalCritic 14:14, 17 March 2009 (EDT) - EternalCritic, you would probably get a lot more done on this Wiki if you stopped moving around the West Midland area of the United Kingdom. Please familiarize yourself with the Commandments or otherwise be elsewhere. On second thought, after reviewing your edits it seems that the best course of action would be to wish you a sincere Godspeed. (BTW, all tkdismissals must end with teh banhammer and an e-mail block) Neveruse513 14:18,, - Your grammar isn't quite bad enought o be Ken's. EternalCritic 15:17,, OH GOD IT HURTS MY BRAIN EternalCritic 17:14, 17 March 2009 (EDT) In light of your recent edits to Archaeopteryx, the consensus among senior administrators is that you are a vandal. Like all parodists, it is apparent that you are a sock of Trent. I have unilaterally without discussion decided that you will be blocked. You need to remember that this is the trustworthy encyclopedia, and overly critical comments, such as yours about Conservative are pointless and futile and will be reverted. In conclusion, if you think you were blocked unfairly, and would like to discuss this, please use the "email this user" feature, which I was careful to disable. Karajou 15:36, 18 March 2019 (UTC) Stitwin![edit] Great god, Ken. The least you could do is have Darwin be one third, Hitler be one third, and Stalin be one third. --<choose> <option>Input The ResistorOutput</option> <option>CoyoteOver 450 pages watched NOT including talk pages</option> <option>The Trickster</option><option>Acionyx</option> 17:26, 17 March 2009 (EDT) - Maybe he's leaving room for another face later on, Hmm, Mao Zedong was a commie and an atheist like Stalin, and we could add a KKK hood in there, and a fraction of Manson's head, and the eyes of Satan, and a werewolf. Just keep on showing Darwin sharing a face with scary people. He is the Painkiller 20:21, 17 March 2009 (EDT) - Who wants to make it for him? And then send it by e-mail? --<choose> <option>Input The ResistorOutput</option> <option>CoyoteOver 450 pages watched NOT including talk pages</option> <option>The Trickster</option> <option>Acionyx</option> 20:52, 17 March 2009 (EDT) J00ni[edit] Sorry TK, I was wrong, no offence. Here. TK: Troublemaker! Block! Broccoli 17:40, 17 March 2009 (EDT) - And the lesson is.... TK is a dick, but we knew that.... Hey Tk, cause I know you read this... Can you tell exactly what Bush's Not Congress initiative was? I can't seem to find information about it anywhere. SirChuckBCall the FBI 17:45, 17 March 2009 (EDT) - TK's behaviour seems to have become more extreme of late. I think something in real life must have set him off. My guesses are: He has been stalking his ex-wife in the deluded hope of a reconciliation and she has taken out a restraining order on him; one of his kids blanked him in the street; he can't get a particularly troublesome egg stain off his favourite brown tie; an attractive young lady got up and moved to a different seat when he sat next to her on a bus; the local Walmart has run out of its cheapest variety of instant coffee. Pure speculation, but I'm 96% certain it's one of those.Matt 17:53, 17 March 2009 (EDT) I refuse to go to a heathen dentist![edit] Foxtrot doesn't know any Jews— Unsigned, by: Coarb / talk / contribs Foxtrot somehow also knows the sexual orientation and religion of the firefighters in his town. I'm not exactly sure how he knows. Coarb 17:56, 17 March 2009 (EDT) - Two things on this, A... I love he talks about it like it's some external trait he could detect in an insant, and B. I almost feel sorry for Andy, seeing obvious parodists ravage his site like that... It's like watching Road Runner cartoons: you know what's going to happen, but you feel sorry for Wile E. just a little bit. SirChuckBCall the FBI 17:51, 17 March 2009 (EDT) I just hope he never needs a lawyer, doctor, or dentist. Or wants to join our Discordian Anarchosyndicalist Jewish conspiracy to get his hands on some of that Hollywood and banking industry money! CPNuisance 18:05, 17 March 2009 (EDT) - Your standard model evangelical comes with all-points gaydar at no extra cost. After all, if you're throwing a dinner party you don't want it rudely interrupted by sodomites demanding you bring out your guests that they might know them. --JeevesMkII The gentleman's gentleman at the other site 18:14, 17 March 2009 (EDT) - If that happens, just offer them your wife and virgin daughter instead.... I mean, if they wanna know the man, I'm sure they'll take some hot women instead. And remember, it's in the bible, so it's all right. SirChuckBCall the FBI 18:34, 17 March 2009 (EDT) - Then later, you hot daughters will get you drunk and sleep with you. That's Andy's favourite bit of the Bible. --JeevesMkII The gentleman's gentleman at the other site 18:45, 17 March 2009 (EDT) Conservatube[edit] The favorites reek Ken all over this shit heap, but Christ Andy's voice is scary. Also, seems rather suspicious that comments were disabled on the page. ENorman 18:08, 17 March 2009 (EDT) - To paraphrase Monty Python: Ken may be an idiot, but he's no fool. SirChuckBCall the FBI 18:39, 17 March 2009 (EDT) - MOAR HITLER favorites - its nice that Conservapedia likes HITLER isnt it .. 67.72.98.45 18:13, 17 March 2009 (EDT) - The first thing I thought when I read about this on WIGO was that Ken must be behind it. I'm not the least bit surprised. Also, I like how he took The Hour's piece on them and phrased it as if they made it. -- YossieSpring in Fialta 19:11, 17 March 2009 (EDT) - It looks like the Hitler video that is favorited is the one that was whored out to ♥ K e n D o l l ♥'s evolution article. He is the Painkiller 20:34, 17 March 2009 (EDT) - Having watched The Hour video, I've finally come to terms with how Conservapedia was created. You know how sometimes in class some kid would throw up a superficially-good-but-actually-rubbish idea? Like "if we don't have enough money for public services, why don't we just print it?" or "why don't you use the electricity supplied by the power plant to fuel the power plant?" - and then the teacher sort of nods along saying it's a really interesting idea and maybe they should send a letter to a representative just so as not to hurt the kids feelings and to make them feel creative and clever? Well one day in Schlafly's class some innocent said what equated to "why don't a bunch of kids and a failed lawyer try and create a more accurate knowledge resource than wikipedia?", and history was made.Bil08 22:07, 17 March 2009 (EDT) - "failed lawyer" ? The great and awesome Ashlafly was originally a superb engineer but made those intel guys feel inadequate so he decided to become a lawyer and leave the little people to do the engineering bit. Having graduated from a prestigious law school he is now counsel to a vast and respected medical association and doing a spectacular job. No one is prepared to face his mighty wrath in open court , which is why he hasn't appeared there. :) This has been a "True History of the World Factbook presentation" 67.72.98.45 23:26, 17 March 2009 (EDT) - Yeah, the AAPS really blew the lid off of Obama's mind control techniques. And the think he almost got elected! Oh wait... CorryThose are balls. 00:38, 18 March 2009 (EDT) - Wait... Was THIS the "Ides of March" deal? Please tell me "No." Such a fucking waste... The Foxhole Atheist 01:04, 18 March 2009 (EDT) - Actually good point it was three days ago. Well another complete fizzer by ♥ K e n D o l l ♥, so all those months of build up for what? 3 links from YouTube, not impressed. - User 01:07, 18 March 2009 (EDT) - I wonder when ♥ K e n D o l l ♥ will inevitably return to Youtube to find Andyquote liberally plastered all over the comments section. He is the Painkiller 06:36, 18 March 2009 (EDT) Okay, this is totally not a Ken production. Moar Hitler in faves, and, for some obscure reason that even the Google engineers can't explain, "Gay Education" somehow appears in the related videos - undoubtedly, Google's Giant Robot Brain has deemed that this video has to be extremely relevant to the discussion at hand. (I know, it's thanks to the "education" tag in the video, but still.) Joking aside, I think this entrée to the fashionable field of video is just a good example of how not to do things. What makes YouTube a great website? How do people get drawn to the successful channels? Two things: Original content and free commenting/replying/embedding. So far, there's no original content on this channel (just crappier quality repost of a video that has been in YouTube for 10 months through the official channel of the show) and the channel comments are disabled, and no doubt they'd love to kill the rest of the comments too. And I seriously think that loudly and proudly launching the channel with damn near no content at all is a massively horrible move. --wwwwolf (barks/growls) 14:21, 18 March 2009 (EDT) - I'm predicting a venomfangx-style censorship effort. Upload your video, sock up and give yourself a single five-star vote. Disable ratings. Turn on comment approval. Approve only positive comments... ???? Profit!!! Neveruse513 14:24, 18 March 2009 (EDT) - ROFL! You noticed the "gay education" cartoon, too? It's pretty informative, if you watch it. Does some decent Fundy-busting. Given Kenny's propensity for having a whole sock TRUNK, I am willing to bet that the user Since33AD is him as well. The entire 30 seconds of the "favorited" video is simply Conservative's standard forum sock plea of "Have you guys checked out... blah, blah, blah...". I called him on his shit, too. I am fully expecting to find my account suspended when I get home from work today, as I used some wonderfully colored language in doing so. I need to learn to relax. I need to learn to relax. I need to learn to relax. The Foxhole Atheist 14:38, 18 March 2009 (EDT) - From the faves: Supernatural...POWERS!. -- YossieSpring in Fialta 22:57, 18 March 2009 (EDT) - I counted the use of "SUPERNATURAL POWER" 9 times in the first 2:30. Of course then its a 6 min plug for conservapedia. I wonder if he can't tell the difference between fiction and non-fiction.--ScottA 00:31, 19 March 2009 (EDT) - NephilimFree? The same NephilimFree that has been a source of rather good quotes over at FSTDT? ...we're witnessing epic things unfold here. --wwwwolf (barks/growls) 03:37, 19 March 2009 (EDT) Speaking of mental health...[edit] Not only does Ken, in his latest piece of "gentlemen" drivel thinks that no-one can see through his online persona's (despite his trademark writing style) but he also thinks that no one is able to refute his evolution article (see here ken). ANNNND on top of this, Andy's recent behaviour seems to suggest that he believes Conservapedia can cure mental illness. These actions in themselves are products of deeply flawed minds. Ace McWickedRevolt 18:43, 17 March 2009 (EDT) - Ken is... Ken. The man's gone on about how we can't possibly prove his socking because he won't admit it since his earliest Newton days here. And Andy has made the whole "conservatism -> mental health" link a good while ago, so the "Conservapedia -> mental health" one shouldn't come as a surprise. --Sid 18:49, 17 March 2009 (EDT) - Wow... how many revisions did it take him to write that novel? The EmperorKneel before Zod! 18:56, 17 March 2009 (EDT) MOAR Only 11. i would have expected upper 20's. - Well lets just check one statement.... By my count, Ken edited the Homosexuality article about 14 times in Feb of 09... Or course, that may have been two sentences with Ken. Furthermore, of the current 50 edits in the log, going back to early Nov 08, 49 of them are Ken and 1 is DeanS. That gives me a total of 98% Ken.... don't challenge us on things we can check. by the way Ken, do you know why your rarely edit the article? BECAUSE YOU LOCKED IT DOWN AND KEEP HOLD OF IT LIKE A 3 YEAR OLD. That's why you idiot. SirChuckBCall the FBI 19:02, 17 March 2009 (EDT)PS After posting this, I went out to 100 edits and Ken was 99 of them. I had to go out to 250 before I found a name other than Ken or the one DeanS. I know see that Gentleman Emperor has taken it all the way and found 6 that were not you... 98.8%, you've really moved on. (EC, dammit)Gentleman Conservative, In regards to your claim that you have "moved on" aafter creating your homosexuality article, might I refer you to here?. In case you are lazy, of the 500 edits displayes, 6 were not by you. Sincereley, Gentelman The EmperorKneel before Zod! 19:03, 17 March 2009 (EDT) P.S. :):):):):):):) - In order: - We like homosexuals around here, we don't pretend they are bad and then write endlessly on how bad they are. - Bible, whatever take it or leave it, it is a personal choice. - Your evolution article is crap and only an idiot would be persuaded by it. I started a rebuttal Conservapedia:Evolution and got bored, the whole article is quotes that can easily shown to have been taken out of context. Epic Phail. - We can tell by your witting style and also the fact that the first contribution a new user makes to a forum is something stupid like "have you seen this article on Conservapeida, articles on this website soon obtain a high Google ranking" (I shit you not he basically wrote that at RichardDawkins.net). - Strange that despite people believing it has never been shown in a double blind experiment. - ♥ K e n D o l l ♥ you are a lying idiot. - User 19:05, 17 March 2009 (EDT) - FWIW, I've been thinking about homosexuality a lot lately, because two of my best friends started dating and it's totally cute. But I don't think that's really what Ken's on about. That, and the usual yaoi/slash speculations about various fictional characters, but you gotta let us have our fun, y'all! --Kels 22:59, 17 March 2009 (EDT) Okay, went back 1000 and 9 edits were un-ken. He has 7 straight 100-limit pages that are EXCLUSIVELY him. The EmperorKneel before Zod! 19:25, 17 March 2009 (EDT) - One one forum, a Totally Not Ken guy went from "Hey, have you seen this article about evolution/atheism/homosexuality on CP? I think the author makes a few interesting points!" to "I have added new material, what do you think?" within the same thread. And yeah, the style is always the same. Always the same. Always, some user signs up, only to immediately plug the evolution article, followed by him claiming that nobody on the entire planet will ever refute a single statement in it and that all these things are simply "candid quotes" that "atheists/evolutionists try to discredit just because they find them uncomfortable". Yawny yawn. --Sid 20:42, 17 March 2009 (EDT) Hey guys, I found this really cool hard-hitting article on Evolution and you might want to check it out. It features accurate scientific data, and hard-hitting quotes by evolutionists, and is not afraid to explore the Darwin-Hitler connection. While you're there, you might want to check out the new article on Atheism as well. It should have you quaking in your liberal boots. So long! I'm off to add new material. CDesignpropensitist 22:15, 17 March 2009 (EDT) - Let me look at your new drivel shall we: - I wasn't expecting to find Conservapedian Daniel121 anywhere but at Conservapedia, try a few less redundancies when you write. Again we like homosexuals, some of our members are homosexuals, we don't care. Yes we have done a page bump to Homosexual Obsession, we also did one to one of those 4 you are keeping track of so you are wasting your time with that stat list because we are manipulating it. - Why amend the homosexuality article to include prop 8 when you have an article on it? Beside prop 8 was politics not sexuality it probably doesn't belong in the article anyway. What is the point of your statement come to that? - Every article should have some content from other users it is a fucking wiki if you wanted to do monologues get your own website or blog. Again what is your point here? - Finally again we don't care if only one other person on the internet likes our article. Besides what is the top result for a search on evolution? Wikipedia. We pretty much support its content anyway so why bother redoing it? - Yet again ♥ K e n D o l l ♥, Epic Phail. - User 22:58, 17 March 2009 (EDT) Dearest Ken, You still have not figured out how to do multiple citations to the same reference. It's been over two years! Come on! Your Mayo Clinic Links are broken, your sources incredibly biased, and nary a citation to a peer-reviewed source. Your article lacks any scholarly value, and you can't even make your own argument, you just quote mine. Sterilewalkie-talkie 23:10, 17 March 2009 (EDT) - Anyone else laugh when they read this Kenny Baby - it's really funny the way you repeat yourself when you write your drivel to us in regards to stuff you did, when you repeat yourself when writing to us in regards to stuff you did. I refer you to your second paragraph in your PPS. Learn to write, you mad old badger, or the world will continue to ignore you, as they are now. Well....even if you could write, they'd ignore you. DogP 16:25, 18 March 2009 (EDT) Founder, TK, Bureaucrat, Senior Administrator, Admin, Junior Admin, Editor, Contributor, PEASANT.[edit] Andy expands the user levels yet again. I wonder if that means that people who aren't "real contributors" are actually bound to the Contributor's Guidelines... ;) --Sid 20:32, 17 March 2009 (EDT) - Conservatives like to know their exact place in a nice comfy rigid heirarchy... ħuman 20:47, 17 March 2009 (EDT) - Could we get a calculation of who, over the last four months, has contributed once or more per day on overage? Coarb 21:08, 17 March 2009 (EDT) - "talk talk talk" gets you banned. less you're a sysop.-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 22:13, 17 March 2009 (EDT) - I wanted to try to sock up, but unless I am a complete dolt, they've obfuscated and/or removed the "Create Account" option from their log in/create account page. How do you even get a foot in the door, now? Oh well... TK's body count finally has a cap in place, I guess. The Foxhole Atheist 02:03, 18 March 2009 (EDT) - CP has gone into night mode. It has been along time since I have edited there, but editing use to go on at 10:30pm where I live, which is still 6 hours away. - User 02:09, 18 March 2009 (EDT) Schlafloff off RW?[edit] A Schlafloff has begun on Conservapedia's channel's only video. - There are some familiar names here. - User 23:15, 17 March 2009 (EDT) - Who doesn't love a good Schlafloff? ENorman 23:22, 17 March 2009 (EDT) - EnDSchultz1 is certainly not from the sockdrawer] EternalCritic 23:26, 17 March 2009 (EDT) - Oh come on Javascap, at least put in a link when you do that. Also stick on in for the quote generator, Poe's law and Ken DeMyer, I want them to sore up the rank of a search engine starting with G. - User 23:30, 17 March 2009 (EDT) - I don't think youtube does links, and if it does, I am very sure it would be hard to do. ĵ₳¥ášÇ♠ʘ is writing a comment 23:32, 17 March 2009 (EDT) - A lot of forums recognise anything that starts with http:// as a link, give it ago. Especially - User 23:36, 17 March 2009 (EDT) - I am just looking forward to seeing the response to the RW bomb being dropped (ole ole ole) ĵ₳¥ášÇ♠ʘ is writing a comment 23:40, 17 March 2009 (EDT) - It will be a no comment channel in less than an hour. Yeah we have ruined something again! - User 23:41, 17 March 2009 (EDT) - "Anonymous User", I asked you a simple question. Are you going to answer it?? I wasted time with your unsubstantial additions and you say you don't believe Jesus is God, so I'm confident you're a complete denialist. And you persist in denying the obvious truth that the best of the public prevents genocide. Contrary to what many of you obese atheists like to claim, if you want to discuss your political views, then you have to describe them first. Your comment is like asking if I have any evidence that 2+3=5! Try to open your mind in the future.--Andy Schlafly 15:36, 18 March 2019 (UTC) - I never grow tired of that thing. And to π, YES! We decietful liburals have united for a common cause to subvert teh true American Values!11!!! ĵ₳¥ášÇ♠ʘ is writing a comment 23:44, 17 March 2009 (EDT) - Anonymous070777 is my sock over there on teh yootoobes. How long until they disable comments? Any takers? The Foxhole Atheist 02:05, 18 March 2009 (EDT) - Wot?!? What have I done now? It wasn't me, honest guv!Mick McT 04:32, 18 March 2009 (EDT) - Ah Andy. I can tell with a 95% certainty that those gerbils must be chafing rather than giving pleasure, what with you riding that insanity chicken at the same time. That is as obvious and undeniable as η(au + v, w) = aη(u, w) + η(v, w) where v is the + the weight of a gerbil on Pluto. But please, by all means continue with your assertion that gun control causes abortion and that non-abstinence based sex education leads directly to genocide and an unreasonable belief in Darwinistic evolution.--stunteddwarf 10:14, 18 March 2009 (EDT) A little ♥ K e n D o l l ♥-like[edit] This is a non-sequitur which you are all free to ignore, but less than 4 days after the deletion we have had 9,369 view of WIGOCP. This page gets huge traffic. That is all really, sorry for pointing out the obvious I was just a little over come when I noticed. - User 01:36, 18 March 2009 (EDT) - Gentleman Pi, it is obvious what is happening here. Conservatives are flocking to WIGO in order to get the wisdom. Ace McWickedRevolt 02:33, 18 March 2009 (EDT) - Wait, this page got deleted? What did I miss? I understand someone (don't know who) somehow borked the page... could someone bring me up to speed? ĵ₳¥ášÇ♠ʘ is writing a comment 09:23, 18 March 2009 (EDT) - Basic story, assuming all statments are true is as follows: User:Jorge got blitzed and was having some fun, and decided to delete WIGOCP thinking it would just be restored. After it was done, he discovered the difficulty. WIGO stayed blank with just some strange crap Jorge had written until another user, I wanna say Nx figured out how to disable the time out feature and restore it. That is all. SirChuckBCall the FBI 12:27, 18 March 2009 (EDT) GENTLEMEN!!![edit] May I present... Dransdarwitalimao! - Reading from left to right: Dracula*, Charles Manson, Charles Darwin, Adolf Hitler, Josef Stalin, Mao Zedong. (*It's actually not Dracula; it's Bram Stoker's vampire character from Mark of the Vampire, as you can tell by the bullet wound on his temple, but whatever.) I wanted to get Hannibal Lecter too, but I couldn't find a good recognizable pic. --Marty 02:31, 18 March 2009 (EDT) - Mason? Hmmm you reckon? Perhaps. Ace McWickedRevolt 02:35, 18 March 2009 (EDT) - Not Mason, Manson! [8] --Marty 02:41, 18 March 2009 (EDT) - What we really need to do is build one of those photo collages where the overall picture is made of lots of little photos, as with the Bush/Iraq War casualties one. I'm fairly sure there are bits of open source software that do that. The only problem is, actual creationists would probably steal it and use it for purposes other than taking the piss out of ♥ K e n D o l l ♥. --JeevesMkII The gentleman's gentleman at the other site 02:43, 18 March 2009 (EDT) - (Edit: Photomosaic.) Yeah, I see no reason for us to make an awesome photomosaic dissing Darwin. Let's make an awesome photomosaic dissing Andy. Or poison dart frogs. Or whatever, really. Photomosaics are awesome. --Marty 02:50, 18 March 2009 (EDT) I mean "let's make an awesome photomosaic where the picture is a poison dart frog," not "let's poison dart frogs", but I guess whatever floats your boat Other faces yet to incorporate: Lecter. Pinhead. Pennywise the Clown. The Surgeon's Photo. Nosferatu (which ♥ K e n D o l l ♥ has already mashed up with Barack Obama). Liberace. --Marty 03:02, 18 March 2009 (EDT) - And for the equilirium scientists/monsters, Dawkins and Lenski. Barraki 05:11, 18 March 2009 (EDT) For a very limited time only: [9] For the source, Google "Metapixel". I'm going to sleep now. --Marty 04:25, 18 March 2009 (EDT) - Superawesome photomosaic app at AndreaMosaic (windows, mac and linux versions) Fox 05:49, 18 March 2009 (EDT) Dosage[edit] One edit a day keeps madness away ... Well, according to Aschlafly, one edit is not sufficient: - CSGuy, your substantive contributions have averaged less than one-a-day over the past four months. In fact, I just had a hard time finding a single significant contribution by you. So, to get your resistance up by Conservapedia, at least one substantive contribution a day over the past four month is necessary. Who fulfills this conscription? I'll be generous and allow every contribution to the main space to be counted as substantive. Taking the data from March 13th, 2009, there were 14,149 editors contributors lads who have made at least one edit at CP. But only 2090 did so during the last four month - of which 73 edited at least once a day, though only a meager 53 made a sufficient number of edits to the main-space. Congrats, Aschlafly! But perhaps you should change the headline: - 84 million in page views, and 0 in mental problems by its contributors. to something like - 84 million in page views, and perhaps 53 sane contributors. But as cp:User:Conservative is in this number, the salutary effect of CP remains doubtful. larronsicut fur in nocte 05:08, 18 March 2009 (EDT) - How many of those 53 were blocked later? - User 06:23, 18 March 2009 (EDT) - Here you go: AddisonDM ( sysop, Siteadmin ), AlanE, AlexanderM, Aschlafly ( sysop, bureaucrat, checkuser, Siteadmin ), BertSchlossberg ( Upload, edit, Block ), BrianCo, BRichtigen, Bugler, Canuck, Chippeterson ( Upload, Block ), CMcFreeze, Conservapedia1, Conservative ( sysop, checkuser ), CPalmer, CSGuy, Daniel1212, DeanS ( sysop, checkuser, Siteadmin ), DeniseM ( Upload, edit, Block ), DevenG, DuncanB ( sysop, Siteadmin ), Dwain, Ed Poor ( sysop, checkuser, Siteadmin ), Foxtrot ( Upload, edit, Block ), Frey, Geo.plrd ( sysop, checkuser, Siteadmin ), GregL, HelpJazz, Hsmom ( edit ), Iduan, Ieuan, JessicaT ( sysop, Siteadmin ), Joaquín Martínez ( sysop ), Jpatt ( sysop, Siteadmin ), JY23 ( Block ), Karajou ( sysop, checkuser, Siteadmin ), Krysg, Learn together ( sysop, checkuser, Upload, edit, Block, Siteadmin ), Markr, MikeSalter, Philip J. Rayment ( sysop, checkuser, Siteadmin ), Redirect fixer, RickD ( edit ), RJJensen ( sysop, Siteadmin ), RodWeathers, SamY, Sulli, Taj ( Upload, edit, Block ), TerryH ( sysop, checkuser, Siteadmin ), TK ( sysop, checkuser, Siteadmin ), Tolkiendil, WesleyS ( Block ), WilliamBeason. - Interestingly, CSGuy made the cut. But that's just because I have to stick to facts, not to higher insights... larronsicut fur in nocte 08:25, 18 March 2009 (EDT) - I had a few socks get blocked that had made maybe half a dozen substantive edits before they opened their mouths on talk pages and outed themselves and liberals masquerading through deceit as christian conservatives. They're not on the list, I suspect because their edits got eaten. With one of them not only did TK block him, but he reverted all of his edits, and then handcopied back all of the minor ones, including spelling and grammar edits and other minor corrections, so he could get credit for them. - I was two members of the goon squad, but neither shows up as such on that list. Credit where credit's due... :-( Fretfulporpentine 11:23, 18 March 2009 (EDT) - De Groin's Law of the Conservation of Wiki-Substance holds that an edit to a non-talk page does not lose its substantivenessness merely because it was reverted and then reinserted by another user. A Corollary is that a fact's truthiness exists only in its assertion.CPNuisance 09:57, 18 March 2009 (EDT) - You really seem to like the phrase "liberals masquerading through deceit as christian conservatives", CPN. --PsyGremlinWhut? 10:02, 18 March 2009 (EDT) - I love it. And I'm honored to have been accused of doing it. I'll do it again. Join me. CPNuisance 10:10, 18 March 2009 (EDT) - RodWeathers and BrianCo were blocked as well. There might be some others in there too.--ConservapediaRoolz 09:22, 18 March 2009 (EDT) - So ignoring the goon squad members, there's a total of 16 ordinary editors. Yup, just the kind of editing force you need to take on Wikipedia. --PsyGremlinWhut? 09:40, 18 March 2009 (EDT) - hmm...how do you define the goon squad? Neveruse513 09:41, 18 March 2009 (EDT) - Those with blocking powers and more. HSMom only has edit rights, so she falls into the non-goon category. --PsyGremlinWhut? 09:46, 18 March 2009 (EDT) If I was CSGuy, I'd be pretty insulted by that. He's made over 2,500 edits to Conservapedia, and been there since 2007. Yet Schlafly smacks him down as an unsubstantive contributor. Dreaded Walrus 11:09, 18 March 2009 (EDT) On Good Samaritans[edit] Ignoring Andy's strange assertion that the term "Good Samaritan" was not available to the translators of the King James Bible, he also claims that the point of the Good Samaritan story was "genuine charity is the best approach." Well, that's certainly part of the point, but there's another point to the story modern audiences miss. The 1st Century Jewish target audience of the Parable loathed Samaritans, and the feeling was mutual. So, charity was not the sole point of the story; the point was also that someone who would have been expected to be least likely to help was the one who helped. A modern version might go like this. An American Christian was mugged and beaten in the city. A Catholic priest saw him lying in the gutter, but said, "I have to go hear confession." A Baptist minister then saw him, but said, "I must go finish Sunday's sermon". Then, a Muslim imam saw, and helped him. Sorry for the sermon, but I heard this take on the story once in church, and I found it absolutely fascinating. (Yes, I'm a churchgoer, just the open-minded progressive type.)— Unsigned, by: MDB / talk / contribs - I think in Andy's case this would be akin to a parable entitled 'The Good Liberal' and that's just far too much of an oxymoron on his eyes. StarFish 08:28, 18 March 2009 (EDT) - Yeah, I've always thought people missed that key aspect of the story. As you said, far more about enemy being the one to help, than about "helping" in some kind of general sense. And why would andy say the KJV didn't have the term "good Samaritan". They had the term "good" "god" (at least as far back as Beowulf) and "Samaritan", a person from Samar. What "term" is missing?-- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 09:39, 18 March 2009 (EDT) - Oh dear! Here's an older mention of the good Samaritane - "O Lord I am the woonded man, and thou art the good Samaritane: powre oile into my wounds, and bind them up." - From 'A handfull of hole-some (though homelie) hearbs' printed 1584[10], 27 years before the KJV was published. - The man is a complete and utter dick. Auld Nick 10:43, 18 March 2009 (EDT) - Okay, the version for Andy. - A good, right thinking American conservative was visiting Washington, DC to attend CPAC. The conservative did not have his gun with him, since he followed the city's unjust gun laws. He was set upon by robbers and left for dead. - An NRA member drove by in a Lincoln Navigator and noticed his plight, but thought, "well, if he had been carrying a gun, he would have been able to defend himself. He deserves his fate." He sped away to the NRA headquarters off I-66 to have dinner at the restaurant there. - Then, a pro-life activist walked by, but she said to herself, "he's an adult and can take care of himself. I have to go save defense little babies." She picked up her protest sign and headed to that day's protest at Planned Parenthood. - But, a gay liberal drove by in his Prius, and saw the conservative, and took pity on him. He folded down the back seat, to allow plenty of room for the wounder conservative to lie down. He then drove him to the hospital, where he was admitted to the emergency room. - The admissions nurse told the liberal that the conservative didn't have health insurance. The liberal pulled out his Greenpeace logo MasterCard and said "let him stay till he's fully recovered; don't kick him out as soon as you legally can." He then called some of his other liberal friends, and they held a bake sale at the organically grown locally raised food co-op to to raise money to pay conservative's bills. - When the conservative left the hospital, he learned the man who saved him was gay, so he went to get an AIDS test because he though all gays carried AIDS and it was spread by casual contact. He then started calling all of his favorite talk radio shows, blaming liberal social values for his mugging. MDB 11:02, 18 March 2009 (EDT) Other Terms[edit] A propos Conservative Terms: how, by Andy's very own logic, can there have been such a thing in the 17th and 18th century, considering that he also claims in the very same "essay" that "conservative" as a term (and therefore, by his reasoning, as a concept) originated as late as 1831? Were those Terms somehow officially conservatized after conservativism was invented, err, discovered? --Just passing by 11:34, 18 March 2009 (EDT) - Another word listed in his "this was not available" list is "personhood". course WikiPedia (horrors of liberalism that it is) states Person and personhood were used in concepts in the early Christian theological tradition, during the first centuries A.D. by the Church Fathers. -- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 11:39, 18 March 2009 (EDT) - I think Andy would be fine with believing that conservatism was an eternally true political ideology placed in the universe by God himself to be discovered by those with the correct way of thinking. It reminds me of an old SNL skit from back in the '80's when Reagan nominated Douglas Ginsburg in the wake of Bork's epic downfall. Ginsburg's nomination got skuttled because it came out that he had regularly used pot, and possibly even with some of his law students. That led to the skit, in which a really high Ginsburg described to similarly really high students how originalism was the one true judicial philosophy because Madison hadn't written the Constitution, but had really just discovered it as a holy object (which really, I think, gets to the essential insanity of originalism because the philosophy is really set up as though that were the case). Kaalis 12:47, 18 March 2009 (EDT) - A quick question, as I don't have a dictionary handy... In this sections of rancid excrement Andy and a few parodist mention conservative terms that dictionaries refuse to recognize due to their liberal mindset... But I can't remember, do dictionaries have multiple words terms like that? I mean, one of their example is illegal alien. A dictionary would have a definition for illegal, and for alien, but would any dictionary have an entry for a term like that? SirChuckBCall the FBI 15:23, 18 March 2009 (EDT) - As I read it, he is complaining that "the dictionaries" haven't yet made up words (helpfully suggested by him in the central column) for his made-up conservative concepts (left column). That's not exactly how dictionaries work though. --Just passing by 15:39, 18 March 2009 (EDT) - Chuck, 1) it depends on the dictionary. OED, in its 27 volums, is clearly more likely to include those phrases, but generally a phrase is only included if the words as a whole mean something other than what they mean individually, or if for some reason they are so used that the average reader needs to know them. "Illegal Alien" is not a compound word. it is 2 words that mean dude who is in a country illegally. "home maker" however means "dudette who cleans", not one who builds homes. (I think homemaker is really one word, but that would be the difference if it were two words). -- En attendant Godot"«Oh, my Lolita, I have only words to play with! V.Nabokov» 17:06, 18 March 2009 (EDT)
https://rationalwiki.org/wiki/Conservapedia_talk:What_is_going_on_at_CP%3F/Archive124
CC-MAIN-2019-13
refinedweb
19,077
71.24
In this we will discuss about the ASP.NET Roles and Membership API from MVC perspective. We will try to see how the default Roles and Membership provides can be used for authentication and authorization in an MVC application. We will also see how we can implement custom forms authentication in an ASP.NET MVC application. When we are working on application in which authentication and authorization is a key requirement, we will find the ASP.NET roles and membership feature very useful. The basic principle and mechanism for forms authentication in ASP.NET MVC is same as of that of ASP.NET Webforms. But since we don't have the server controls with us the way to use it will be a little different from that of the webforms. Nevertheless, since the core principle behind the Forms authentication is same, I suggest following articles will provide a quick recap on ASP.NET Forms authentication and how it can be implemented and customized in WebForms applications. Webforms WebForms. Before moving ahead, let us first see the two main type of authentications that are used mostly in ASP.NET applications. We will be discussing the form authentication in details in the rest of the article. The default ASP.NET Roles and Membership classes come in very handy when we want to provide authentication and authorization in our applications. Using the default membership API will use the membership database and provide us will all the functionality required to manage the user roles and membership. ASP.NET also provides a way to implement custom Roles and Membership to take more granular control over things. We might still find ourselves in situations where we need to have our own database for tracking users and their roles. The reasons could be: So let us first discuss the default membership API and what visual studio provides us out of the box. We will then move on to taking the full control on authorization and authentication on our hand by implementing custom forms authentication. To enable forms authentication we need to perform following steps in our application. Now we will see how the default membership API does all these things for us and how we can implement all these steps ourselves. When we create an MVC internet application. The visual studio project wizard does all these above mentioned steps for us. it will create a Membership database in the App_data directory of our application (actually the location depends on the connectionstring specified in web.config file). connectionstring web.config It will generate the Controller ode that will check the database for user authentication, create the authentication cookie and creation of Principal based on the roles configured in our database. It will also generate all the view required for authentication. The image below shows the generated Controller, Views and the database. Controller Principal Controller The Roles and user can be configured either from code or from the Web Site Administration Tool(WSAT) in the same manner as of that in WebForms application. So let us create a role called "admin" and 2 users "admin" and "user" using WSAT. The "admin" will be in "admin" role and the "user" will not be in any role. Web Site Administration Tool(WSAT) WSAT Now from the applications perspective, we only need to mark the views that need authentication and authorization and the default membership classes and the generated classed will take care of performing the authentication and authorization. Let us say that we want only authentication users to be able to view the Home/Index page. And only the users in "Admin" role can access the Home/About page. To do this we need to decorate the respective action in controller with the authorize attribute as: Home/Index Home/About public class HomeController : Controller { [Authorize] public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } [Authorize(Roles="Admin")] public ActionResult About() { return View(); } } And that is all that is required to require authentication and authorization if we are using default Membership API and the visual studio generated code for authentication and authorization. We can do some level of customization in the AccountController class if we need some added functionality. AccountController Note: The article does not contain a sample for the default membership usage because it is just the matter of creating a new MVC 3 internet application and all the code will be generated by visual studio itself. It is highly recommended to look at the AccountController class to see how it is performing various operations. Now if we don't want to use the default membership API and the visual studio generated code then we can choose to implement our own authentication and authorization mechanism. To do this we will have take care of implementing all the steps required for forms authentication that we discussed earlier in the article. So let us create and empty MVC 3 application and see how we can implement custom forms authentication. Now the first thing that we need to do is to configure the application to use the Forms authentication. This can be done in the web.config file. <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> let us now create a small database that we will use to perform authentication. This database contains only two users like our old earlier example. "admin" and "user". "admin" is in "admin" role and "user" is not in any role. Note: The database is neither optimized nor normalized as that was not the main intent of this article. A real world example of database will be more optimized and perhaps more complex. The passwords will not be in clear text for sure, They will either be encrypted or "hashed & salted". Now to perform data access let us use entity framework so that we don't have to write all the boilerplate code required to create our model and data access logic. The generated entity for our database will look like: let us now go ahead and create a controller that will take care of the authentication logic. We will create the functionality for Login and Logout but other functionality are user creation and password change can be easily implemented on same lines(its the matter of validating the user Model and performing CRUD operations on the table after encryption or hashing and salting). Here is our controller with login and logout action: public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(User model, string returnUrl) { // Lets first check if the Model is valid or not if (ModelState.IsValid) { using (userDbEntities entities = new userDbEntities()) { string username = model.username; string password = model.password; // Now if our password was enctypted or hashed we would have done the // same operation on the user entered password here, But for now // since the password is in plain text lets just authenticate directly bool userValid = entities.Users.Any(user => user.username == username && user.password == password); // User found in the database if (userValid) { FormsAuthentication.SetAuthCookie(username, false);"); } Now in the above code when the user tries to login we will check if the user with the given user credentials exist in the user database or not. If it exist we set the authentication ticket and move forward. Now if our password was encrypted or hashed we would have done the same operation on the user entered password before checking in database, but since the password is in plain text lets just authenticate directly. Now before moving ahead let us look at the view that will take the user credentials and perform the authentication. Let us now create a simple Controller which will contain two actions. One action that can be performed by any authenticated user and other that can be performed by the users in "admin" role only. Controller public class HomeController : Controller { [Authorize] public ActionResult Index() { ViewBag.Message = "This can be viewed only by authenticated users only"; return View(); } [Authorize(Roles="admin")] public ActionResult AdminIndex() { ViewBag.Message = "This can be viewed only by users in Admin role only"; return View(); } } Now when we run the application, we can see that the users will be asked to enter their credentials when they try to access the Home controller's views. Upon successful login they will be able to see the Index page. But if we try to look at the AdminIndex page we will not be able to see that. The reason for that is that currently the users roles are not being used. AdminIndex Now to use the roles specified in our database,'s Role details in this principle object. To do that we need to override a method called FormsAuthentication_OnAuthenticate in global.asax. This method is called each time ASP.NET framework tries to check authentication and authorization with respect to the current Principle. FormsAuthentication_OnAuthenticate global.asax; string roles = string.Empty; using (userDbEntities entities = new userDbEntities()) { User user = entities.Users.SingleOrDefault(u => u.username == username); roles = user.Roles; } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } } And now when we run our application we can even access the AdminIndex page. Now we have all the steps required to implement the custom forms authentication in place. We have successfully implemented custom forms authentication in an ASP.NET MVC application. Note: This article contains code snippets that are only for demonstration of concepts of the article and it does not follow any best practices Only the logic should be taken from this article as the code in the article is not of production quality. In this article we have tried to look into ASP.NET roles and membership API. We saw how MVC project comes with the default Membership API implementation and some default Controllers and view which can be utilized to easily integrate forms authentication in an MVC application. We also saw how we can take full control over the forms authentication and implement custom forms authentication. This article has been written from a beginner's perspective. hope this has been informative. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) General News Suggestion Question Bug Answer Joke Rant Admin Man throws away trove of Bitcoin worth $7.5 million
http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF?PageFlow=FixedWidth
CC-MAIN-2013-48
refinedweb
1,733
54.02
Stuff at the Top of an SVG If you’ve ever opened up an SVG file to look at the code, you’ve probably thought to yourself: “What’s all that stuff at the top? DOCTYPE, version, xmlns, xmlns:xlink… what’s their purpose, and can I get rid of them?” Unlike the majority of SVG code—which is readable and understandable to an English-speaker—these bits at the top can seem completely foreign. I’ve asked those same questions myself, so, in preparation for my upcoming course on SVG workflows in Sketch (that’s launching in 2 weeks!), I’ve done a ton of research and made this cheat sheet for designers and developers. ⚠️ Note: This article only applies to SVG graphics used on modern websites—which is by far their most common use case. Some of the guidelines in this article might not hold up with less-common use cases, like re-importing an SVG back into a design tool, converting it into a different type of file, or using it on an older website that isn’t HTML5. 🌿 This is a living document. If you are extremely knowledgeable about this topic, or have encountered situations where the points from this article don’t hold up, please let me know. Together, let’s keep this accurate and up-to-date! I do declare! The majority of these “things” at the top of an SVG are called declarations. When you give a web browser (or any other software) your SVG file or SVG code to display, the browser needs to know which language you’re speaking. That’s what most of these declarations are for. But when you’re using your SVG on a modern webpage, as most of us are, some of these aren’t necessary; others are effectively obsolete; and some are only useful some of the time. That’s why I’ve created this list of guidelines, based on the two most common scenarios for using SVG. ✴️ Practical Guidelines All of the ways to present an SVG on a website effectively fall into two categories: 1. the SVG is linked as an independent file, or 2. the SVG’s code is incorporated into the webpage itself. The latter is typically achieved by nothing more than pasting the SVG code into an HTML5 page, right alongside other elements on the website—a method known as “inline SVG.” Based on these two categories, here’s what you need and what you don’t: 1. Using an SVG as an independent graphic - Remove the DOCTYPE declaration ( <!DOCTYPE svg …) (Sketch and Illustrator don’t include this in SVGs anymore) - Keep the XML declaration ( <?xml …) just in case. In my tests it wasn’t necessary, but the consensus from my research is that it is advisable. - Remove the versionattribute (it’s never needed) - Keep the xmlnsnamespace declaration - Keep the xmlns:xlinkXLink declaration if some part of your SVG uses “ xlink” (most likely a <use>, <a>, or <image>element’s xlink:hrefattribute). If you aren’t sure, keep it. 2. Using an SVG “inline” with HTML code on a webpage - Remove the DOCTYPE declaration ( <!DOCTYPE svg …) (Sketch and Illustrator don’t include this in SVGs anymore) - Remove the XML declaration ( <?xml …) - Remove the versionattribute (it’s never needed) - The xmlnsnamespace declaration isn’t necessary on most modern webpages, but it doesn’t hurt to keep it just in case. - Keep the xmlns:xlinkXLink declaration if some part of your SVG uses “ xlink” (most likely a <use>, <a>, or <image>element’s xlink:hrefattribute). Like the xmlnsdeclaration, xmlns:xlinkisn’t necessary on most modern webpages, but it doesn’t hurt to keep it. Other things at the top of your SVG: You may also notice attributes like viewBox, width, height, and preserveAspectRatio at the top of your SVG. Unlike the declarations and attributes mentioned above, these do affect the visual result of your graphic. They are worth keeping unless you know exactly what you’re doing. You’ll also notice that many design tools include a comment about the software used to export the SVG. For example: <!-- Generator: Sketch 44.1 (41455) - --> OR, <!-- Generator: Adobe Illustrator 19.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> These comments are harmless, and are always safe to delete. A Note on Optimization The popular optimization engine SVGO—which powers Sketch’s SVGO Compressor plugin and the web app SVGOMG—has options to remove the unwanted declarations and attributes for you. It’s even smart enough to check for the presence of elements using xlink, to keep that declaration on the <svg> element when necessary. That’s super convenient and generally reliable. But ultimately you’re the only one who knows how your SVG will be used, so I hope the guidelines in this article will help you decide when to use those optimizations and when to turn them off. What do these acronyms mean? Don’t let these terms intimidate you; they’re all based on simple ideas. XML stands for “Extensible Markup Language,” which is simply a versatile way to structure information—like an outline with some extra punctuation. XMLNS stands for “XML namespace.” A namespace is a set of element and attribute names. For example, SVG’s <title> and <rect> elements are part of its namespace. A different format based on XML might have its own <title> or <rect> elements; it’s important to declare which namespace your graphic is using, so browsers know how to interpret the code. XLink stands for “XML Linking Language.” It’s just a set of common ways to link between things within a file (ex: connecting a gradient to the shape that uses it) or to things outside of the file (ex: creating a clickable link to another webpage). Sources and Further Learning The information in this article draws from extensive research through online resources, conversations with engineers who work on browsers and design tools, and my own empirical tests across browsers. If you’d like to learn more about Namespaces and why their declarations are important, read this fantastic short article on the Mozilla Developer Network. Some of the most helpful online sources I found were Stack Overflow conversations, like this one about XML declarations, this one about XMLNS and version, and this one which touches on XLink too. The SVGO plugin to remove DOCTYPE cites this article. This MDN piece reiterates that DOCTYPE should be excluded. My Own Tests My tests reinforced the other research. I tested SVGs with combinations of these declarations included and excluded—then implemented them on an HTML5 webpage as inline SVG, HTML <img> tags, CSS background-image, and background-image on CSS :after content. I tested across recent versions of Safari, iOS Safari, Firefox, Chrome, Edge (15), and Internet Explorer (9, 10, and 11). I was surprised to find consistent results across browsers with inline SVG. When it comes to this “stuff at the top,” inline SVG appears to be hands down the most reliable and forgiving way of implementing SVG on the web. The most notable issue I encountered overall was that independent graphics (non-inline) didn’t render without proper namespaces. Even the omission of an xmlns:xlink attribute, when it was necessary, caused this issue in all browsers. So keep those namespace declarations! This article was inspired by my upcoming course SVG Workflows in Sketch. I wish I had resources like this when I was learning SVG, so I’m determined to provide some of those missing pieces for other designers. The course aims to bridge the gap between what you know in Sketch, and the amazing things you’ll create with SVG. You can also sign up for my newsletter to be the first to know when I publish new design articles and resources.
https://medium.com/@pnowelldesign/stuff-at-the-top-of-an-svg-f3ad198eb54e?utm_source=frontendfocus&utm_medium=email
CC-MAIN-2017-26
refinedweb
1,302
62.68
Easily use Outpan API to get product info from its barcode Project description Python client for the Outpan.com API Usage You’ll first need to create an account and get your API key. Once you have your API key and the package is installed - see below - you are set and ready to go. Getting ready To access the Outpan API you’ll need to create an instance of OutpanApi with your API key. You’ll use this object to access the API. from outpan import OutpanApi api = OutpanApi(my_api_key) Getting a product’s data Now that you are set it is time to make calls to the API. The first thing you will want to do is retrieve a product information. For our test we’ll use the test barcode 078915030900. api.get_product("078915030900") This call will return the product’s data as a dict: {'attributes': {'Care': 'Dishwasher safe', 'Colors': 'White', 'Manufacturer': 'Progressive International', 'Material': 'Plastic, Stainless Steel', 'Part Number': 'GPC-5000'}, 'gtin': '0078915030900', 'images': ['', '', '', '', ''], 'name': 'Progressive International Cherry-It Pitter', 'videos': ['', '', '']} Accessing v1 API Available until Jan. 1st 2016, the v1 API allows you to retrieve specific attributes of a product using the methods list below: from outpan import OutpanApiV1 # Note that we are importing a different class api = OutpanApiV1(my_api_key) api.name("078915030900") api.attributes("078915030900") api.images("078915030900") api.videos("078915030900") The output of these calls is the dict as returned by the API. From the command line Thanks to the awesome python package parse_this the Outpan API is accessible directly from the command line!!! python outpan.py --help will give you the help message to know how to use it. A quick overview of the previous methods we’ve already talked about: python outpan.py 123456789 get-product 0796435419035 # Available for v2 python outpan.py 123456789 name 0796435419035 python outpan.py 123456789 attributes 0796435419035 python outpan.py 123456789 images 0796435419035 python outpan.py 123456789 videos 0796435419035 These command lines use the (fake) API key 123456789 to 1. Retrieve the full info of product 0796435419035 - only command available for v2 2. Retrieve the name of product 0796435419035 3. Retrieve the attributes of product 0796435419035 4. Retrieve the image links of product 0796435419035 5. Retrieve the video links of product 0796435419035 Creating or editing a product’s name If you want to create a new object or edit an existing product you can use the method api.add_edit_product_name as showed below: api.add_edit_product_name("078915030900", "new_name") Note that this method does not return anything and will replace any existing name. Creating or editing a product’s attribute You can also edit or create a product’s attribute using the method add_edit_product_attribute as follow: api.add_edit_product_attribute("078915030900", "attribute_name", "attribute_value") Note that this method does not return anything and will replace any existing attribute. INSTALLING OUTPAN outpan can be installed using the following command: pip install outpan or using easy_install: easy_install outpan Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/outpan/
CC-MAIN-2022-27
refinedweb
511
63.9
A little bit of lunchtime coding. def closeBracket(openbracket): if openbracket == '{': return '}' elif openbracket == '(': return ')' elif openbracket == '[': return ']' if __name__ == "__main__": testcase = ('{{[{{{{}}{{}}}[]}[][{}][({[(({{[][()()]}}{[{{{}}}]}))][()]{[[{((()))({}(())[][])}][]()]}{()[()]}]})][]]}{{}[]}}') teststack = [] position = 0 for c in testcase: if c == '{' or c == '(' or c == '[': #push the open character on the stack teststack.append(c) if c == '}' or c == ')' or c == ']': #check first to see if the stack is empty and #if it is report the position if not teststack: print "Failed at position %d" % position break #it's not empty, so pop the last appended character off f = teststack.pop() #if this character is the respective close character #of the character that got popped off, we're good if closeBracket(f) == c: print "All good at position %d" % position #if the popped character isn't the respective close #character, then fail and report position elif closeBracket(f) != c: print "Failed at position %d" % position position = position + 1 Oof, the source code formatting in WordPress is so bad. I guess my interspersed comments aren’t helping readability. Here’s a Gist: I used Python because it has .append() and .pop() for lists ready to go. Every open bracket in the string in testcase gets pushed onto the stack (appended onto the list), and when a close bracket is encountered I pop the last pushed open bracket off the stack. This popped off open bracket is sent to closeBracket(), and closeBracket() returns the respective close bracket. So, if the encountered close bracket matches the respective close bracket of the popped of open bracket, we’re all good. If it doesn’t (or if the list is empty) it fails and reports the position. A ham-fisted explanation for a ham-fisted program. Had I not already been familiar with the notion of a stack I’d have been super lost on puzzle #2. I worry that there is a new trick to the third puzzle, so this might take me a bit longer to figure out. I think that this whole puzzle set is part of Cueup’s job application process. I hope they eventually post some of the interesting solutions their applicants submit. Nice of them to make it public – it’s rather enjoyable (so far!). Hey, I’m stuck with the below replies since a day and a half. “Near you is a rabbit using a computer, reading JIRA tickets.” “I think I saw something in the ticket about newlines not counting as characters.” Would you please help me what did you reply to arrive at this second question? Thanks a lot! Just type in “talk rabbit”. The rabbit presents the next problem. My code: 1. count opening parens, brackets, and braces separately 2. count closing parens, brackets, and braces separately 3. if for any reason closing parens, brackets or braces outnumber the opening ones, return the index 4. remember to subtract the number of newlines
https://chrisheydrick.com/2013/01/22/my-solution-to-the-second-colossal-cue-adventure-puzzle/
CC-MAIN-2019-39
refinedweb
477
72.87
The Microsoft SQL Server JDBC team is proud to announce the availability of our v1.2 CTP2 (beta) release. The driver is downloadable at. The direct link to the download page is In this CTP release, we added SSL encryption support to the driver on top of the Adaptive response buffering support available in CTP1. Jimmy Wu, SQL Server Disclaimer: This posting is provided "AS IS" with no warranties, and confers no rights PingBack from SQL Server 2005 JDBC Driver 1.2 CTP August 2007公開 Have some problems with the sqljdbc.jar versions 1.1 and 1.2 with Vista. If we use the jdk 1.4 we get the error "The SQL Server login requires an SSL connection." If we use the jvm 1.6 we are able to get a connection. Are there some know problems with Vista and this driver and different versions of the jvm? Have narrowed down the code to the basic which I will now include. import java.sql.*; public class testSqlServer2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { java.lang.Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection c = java.sql.DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=mydb;user=testadmin;password=admin;SelectMethod=cursor "); System.out.println("We have connection!"); } catch (Exception ex){ ex.printStackTrace(); } } } rkbean@gmail.com Hi Kevin, Given your symptoms, I take it that your server forces encryption, i.e. does not allow unencrypted connections. MS SQL Server 2005 JDBC driver started supporting SSL only with v1.2 CTP2. Hence, if you are using any earlier version such v1.1 or v1.2 CTP1, you will not be able to connect to a server that forces encryption. This is by design. If you are using v1.2 CTP2, I have good news. We have just shipped v1.2 RTW which is available at the following link. To answer your question with respect to JDBC v1.2 RTW, failure to connect to a server that forces encryption is expected if you are using a JVM whose default JSSE provider does not support strong hash (i.e. certificate hash size > 4K) Some 1.4 JVMs fall into this category. Moving to later JVM versions would solve this issue. Hopefully this answers your question. Please follow up if you need more information. Additionally, assuming that you are using selectMethod=cursor to work around memory limitations in JDBC v1.1, I suggest you now use JDBC v1.2 feature responseBuffering=adaptive. This property is designed to replace selectMethod=cursor while boosting performance. You can read more about responseBuffering in the following blog article. Thanks! Yesim [MSFT] Hi Yesim , Recently I downloaded version 1.2 release of the Microsoft SQL Server 2005 JDBC Driver. Thanks a ton to Microsoft for providing many new features such as Adaptive Buffering , SSL Encryption , Tightly Coupled XA Transactions etc. I am mainly concerned about SSL part of it and would be grateful if you can solve my queries or forward it to app- ropriate forum. 1 ) I tried connecting to SSL enabled SQL Server 2005 through a sample program provided by Microsoft along with this package ( Version 1.2 ) and I succeeded whereas in previous versions I use to get an exception as "The SQL Server login requires an SSL connection." My connection string is as follows "jdbc:sqlserver://Ip adress of dataserver machine:1433;databaseName=master;user=sa;password=sapassword" . Ideally we should only get an SSL connection when we request it else an error message should be thrown informing the user that dataserver requires an SSL connection. This would help in choosing between type of communication a user needs with dataserver. The scenario now is like forcing a user to have SSL communication if dataserver forces it. A flag may be added as ssl should be mandatory or auto . 2 ) Current driver 1.2 is not capable of communicating with MS SQL Server 2000 both in case of SSL and Non – SSL cases , The error which we receive in both cases is : Oct 18, 2007 4:57:17 PM com.microsoft.sqlserver.jdbc.SQLServerConnection Prelogin WARNING: ConnectionID:1 TransactionID:0x0000000000000000 Prelogin response packet not marked as EOM The TDS protocol stream is not valid. To communicate with both MS SQL Server 2000 and 2005 a user will have to maintain both the drivers which may increase complexity of the application , like loading both driver in a single process , etc etc . . . If version 1.2 id built on top of Sql server 2000 JDBC drive then it should be able to handle following 4 cases : i ) SQL Server 2005 – SSL , ii ) SQL Server 2005 – Non – SSL , iii ) SQL Server 2000 – SSL , iv ) SQL Server 2000 – Non – SSL . If this single driver handles all above 4 cases , life of a developer and application developed by him/her would become less complex. 3 ) Last but not the least , the SQL Server 2000 JDBC driver connects with both kind of SQL Server 2000 instances i.e. SSL and Non – SSL without any certificate of flags specified. I was able to establish non – SSL connection with SQL Server 2000 using two third party JDBC drivers which I think is not appropriate behaviour. 4 ) I have also noticed that when SQL Server 2005 is running in Non – SSL mode i.e. "ForecEncryption=No" and our Client application requests SSL communication , we are not warned about server is not runnning in SSL mode , could you please explain this ? Kindly correct me I am wrong anywhere as I am just a beginner and don’t have much knowledge on this subject . Thanks a lot. Sincerly , Sudhansu Tiwari Please ignore 2 and 3 above. I Identified the issue related to 2 and 3 above , SP4 for SQL 2K wasn’t properly intstalled on my system , hence a re-installation did the trick. Thanks. Hi Sudhansu, Thanks for you feedback. I’m glad to hear that issue 2 and 3 have been resolved. Regarding question 1 in your feedback, we will take your request into consideration in a future release. While we were designing the SSL support, we looked around the JDBC community and saw that there weren’t any standardized driver behavior around this. We decided to error on the side of assuming the client application wanting to connect to the backend SQL Server without adding complexity to the already complex connection URL property list. Regarding question 4 in your feedback, the "ForceEncryption" setting used by SQL Server is control whether SQL Server will allow a non-SSL client connection. When set to "No", SQL Server will support both a clear connection and a SSL connection. When set to "No", if the client application requests SSL encryption, SQL Server will enable SSL encryption for the particular connection. If the client application does not request SSL encryption, then a clear connection is established. Note: With SQL Server 2005 and the v1.2 JDBC driver, the user credentials is always encrypted using SSL (assuming proper JVM SSL configuration) to enhance security. Hope that answers your questions. Sincerely, Jimmy Wu [MSFT] Hi, I have downloaded the driver to install for SQL SERVER 2005 Express. sqljdbc_1.0.809.102_enu.exe But when I try to open it as instructed, I get an error message that the program is not a valid win32 application. Please Advise, Regards, Dafna Any reason you are donwloading the 1.0 driver. You should down load 1.2 driver. Mugunthan[MSFT] Hi, I’ve compiled the sample Connect.java code and when tried to connect to SqlSever 2008 with the 1.2 sqljdbc jar I get the following error. C:webserverTomcat6webappsjkonfigWEB-INFclasses>java Connect Sep 9, 2008 11:14:18 AM com.microsoft.sqlserver.jdbc.TDSChannel enableSSL WARNING: TDSChannel ( ConnectionID:1 TransactionID:0x0000000000000000) SSL handshake failed: RSA pre master secret error) at Connect.getConnection(Connect.java:33) at Connect.displayDbProperties(Connect.java:55) at Connect.main(Connect.java:102) Error Trace in getConnection() : The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: RSA premaster secret error. Error: No active Connection Any idea why? Force encryption is turned off and server athenication is turn on. This is driving me crazy. Sample code and lastest version of everything. java 1.6, sqlserver 2008, sqljdbc1.2, Vista. thanks any help would be greatly appreciated. jim s Hi Jim S, We’ve posted a general SSL connectivity troubleshooting blog post which you can find here (). Our past experience typically point us to some modified JSSE configuration. Please follow the information in the blog post to verify the JSSE providers are correct. HTH, Jimmy Hi Jimmy, We are using the JDBC driver to a mirrored SQL Server 2005 setup. Recently we had a case where the client failed to connect when there was a failover. com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: SQL Server did not return a response. The connection has been closed.. com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: SQL Server did not return a response. The connection has been closed.. This error has not occurred on other occasions where the DB has failed over, both before and after the above incident. We are concerned that the JDBC handling of failovers is unreliable. Environment is: JDBC sqljdbc_1.2.2828.100_enu jdk1.5.0_12 Red Hat 5.1 Any comments? Mark Hello, My trying to connect to SQL Server 2005 from a UNIX machine but I get an error. The configuration setings that I use are: Driver:com.microsoft.jdbc.sqlserver.SQLServerDriver URL:jdbc:microsoft:sqlserver://<serverName>:<portNumber>;databaseName=<myDataBase>;SelectMethod=Cursor The eror message is: Failed to open input block: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 1 (""): Data type 0x38 is unknown. Any one can help? Thanks. Regards, Miguel
https://blogs.msdn.microsoft.com/jdbcteam/2007/09/05/sql-server-2005-jdbc-driver-v1-2-aug-ctp-is-live/?replytocom=183
CC-MAIN-2017-47
refinedweb
1,678
58.69
The return of Silvio Berlusconi Mamma mia Italians may come to regret electing Silvio Berlusconi once again See article Readers' comments Reader comments are listed below. Comments are currently closed and new comments are no longer being accepted. Sort: Seems to me that the "Economist" is a little embarassed by its previous arrogance. There has been a stunning lack of balance in reporting. Romano Prodi, for example, abused his previous position as EU-Commission chief to interfere in Italian politics and position himself for the elections that came later. But that was ok, coz Mr Prodi is "good", and Mr Berlusconi is "bad". Why is he bad? Because he has a sense of humour, and dares to make politically incorrect statements? Because his allies do not want to fill up Italy with migrants unwelcome by a majority of the people? Because Mr Berlusconi's media is not singing the praises of Anglosaxon-style debt-capitalism? Because Mr Berlusconi did some shady deals in the past (as most billionaires would have) and does not feel like being jailed for it now? Not good enough reasons. Prodi and his self-righteous ilk have failed. If activist leftist judges leave Mr Berlusoni alone now, he might just find the time to bring the country in order. Good luck to him anyways ... To AwateaEveryone knows about Montanell's comments on Berlusconi being a liar. After having been ignored for most of his life because he was not a leftist, it was enough for him to have made those comments on Berlusconi to make him a hero.Pity few know that, soon after his death a book was published in which it is stated that, for all his life, Montanelli lied about having been an antifascist who had to escape to Switzerland during the war. Apparently he was actually spying for the fascists.I haven't read the book, but have read about it. The title is "Passaggio in Svizzera. L’anno nascosto di Indro Montanelli".Heros do not existTo AnglocalabroDefining Sevrgnini a wanna-be posh is simply great: congratulations @ anglocalabroYes I have been following the Italian news and your predictions are becoming reality...... We are going to been United with the Russian Federation...I agree with you about Peppe Severgnini. I never liked that guy..... I'm longing for people like Indro Montanelli. Did I like ferrari, and why Italian like spaghetti al dente? Where the two main questions in which my students greeted me when I was teaching economics light years ago. I always disappointed my students telling that I preferred reliability than aesthetics, thus the reason I buys only Japanese cars. For these students who ate ,yes, canned spaghetti for breakfast, I had to propose to the academic board that I started teaching propers Italian cooking as a an elective liberal arts course. While at first my colleagues were skeptical at my unorthodox course, it became the most popular course with a long waiting list. My students their parents teachers and staff learned to eat spaghetti in a proper manner, and never asked me about spaghetti al dente. I wish I could teach economics 101, immigration policies, and civic duty courses again, this time though to Berlusconi supporters. Ignorance is the source of every blithe in the world..... I agree with Girolamo about his opinion on Beppe Severgnini. I just can't stand the guy and his shallow, pretentious, wanna-be-posh, ideas and attitude in general. To: Awatea, Dear friend, if you heard the news today, you might be likely to grin wondering at my prediction which took shape of reality earlier today at around 12 o'clock. As I wrote yesterday here, today mr. Berlusconi and Mr. Putin dedicated a great deal of the conference (therefore imagine how much longer during closed talks) to the Alitalia-Aeroflot deal. With good peace of all those swallowing his b...e (berluscorie) about the threat of communists and marxists and martians as well.. They spoke exhaustively about Eni-Gazprom business and Alitalia-Aeroflot deal. Now, it would take too long discussing the Eni-Gazprom deal and I am sure that not many of the commentators here are very familiar with what has been going on with Gazprom in the last 5 years about the distribution grid business all over Europe and the baltic pipeline and the caspian one. Well, of course newspapers and magazines wrote about it but very far from reality. Only a BBC special programme represented murky and grim aspects of the Gazprom rise with all killings, bribings, detentions and financial abuses involved. Anyhow, the Alitalia issue is a more intriguing too, if possible. Because as many transportation analysts (and even this magazine) foresee, in the next future (except for low cost companies), there will be a dramatic shrinking of national airlines. It is very likely that within 20-30 years, maybe sooner, there will be only 4 or 5 big conglomerates sharing all majors between them (we're not talking about sharing code here, but 4 or 5 big carriers that group all the others in terms of M & A (mergers and acquisitions). It should be clear now, of course, that this alleged pride about the urge of a "national" carrier is absolutely groundless. It's outrageous how mr. Berlusconi takes advantage of people ignorance in this country rising fears about the possibility that being Alitalia owned by a foreign country all the touristic flows will be diverted to the nation of the carrier. I mean, those are bullshits of such a low and insulting level that I feel personally offended. For anyone who has a little knowledge of how transportation policies at large work, this is just treating people like idiots. Unfortunately it seem that there a lot of them here (in Italy). Of course I dont mean that all those who voted for mr. Berlusconi are idiots and as we can see here, lots of educated and literate indeed voted for him. But please, let me wonder that those clever, literate and educated people did so for the desperation represented by the opposition. The electorate that supported Berlusconi is of course composed by a (minor) group of people who voted for him because of their personal interest, perfectly aware that such a man would not be fit even to run Zimbabwe government. But a large deal of his electorate dream of sailing a motoryacht and drive a mercedes casting their vote for the mogul. Of course, if I were in Zimbabwe and I had not hope, I would have voted for Mugabe..Maybe. But I would have admitted my sin and the reasons why. @serenissimoYour choice to return to Italy is everybody's sacrosanct choice of every Italian citizens.It was your choice of words in encouraging millions of young Italians to leave Italy because they don't agree with Berlusconi, that irked me.I have met a few Italian-Americans who after spending most of their lives working in the USA, have decided to RETIRE in Italy, not because of politics, but to stay close to relatives. Some of these Italians hoewver, moved back to the USA after a while.... and return (Italy) there only for a few months of the year.Good luck, and God bless you. Mamma mia, I was about to collapse when I saw Berlusconi’s picture in the above article. Why does the Economist now consider Berlusconi’s return to power as “astonishing”? The magazine’s staff itself previously stated, explicitly, that Berlusconi’s victory seemed all but inevitable. I do, however, fully agree with the three main factors presented by the Economist on what assured the Cavaliere his place. I dearly hope for Italy that Berlusconi has more convenience in doing good than wrong for the Country. Xcp: Italy is, and will always be, a pleasant place to live in. However, the effect of politics in Italy is more subtle than someone would normally think. Politicians divert public attention with gossip, brawls, false evidence, and empty promises. Berlusconi brainwashes people through his powerful control of the media. The church is omnipresent in the education system, and organized crime slyly limits freedoms. Now, Italian typical lifestyle (as you mention, Scudetti, moto GP, ill-clad and silent models on TV, derby...) appears unaltered by politics. In reality, it is defined by the very decisions taken by the “elite”. Do not underestimate the impact of politics on daily lives, as you will soon notice changes as a consequence of this shift in power. Furthermore, I think it is more detrimental than beneficial for Italy to be oversimplified as the place for loud and bella vita, a Country of “Ferraristi”, or the international dispenser of spaghetti. Etti: Italians tend to get along well with tourists or foreigners, indeed. Some even say the Italians are the most welcoming and warm people in Europe. However, this is only true with having to do with respectful and civilised people. Problems arise when groups of unidentified people decide to literally invade the coasts and get their way through prostitution, dealing, rapes and thefts. Are they foreigners or are they invaders? True, the league wants controlled migration, which is a reasonable and noble reform. My question is why they have to do it which such xenophobic resentments, and why only for half of Italy. I’m sure that the millions of unemployed or underemployed Italians would be glad to work even for a low wage, which you imply would be reserved for immigrants offering cheap labor. Italy does not have the right infrastructures to house these many immigrants. There barely are enough jobs for Italians. Hello italians and non, I'm living and working (and paying taxes !!) in Italy since 2003, but I'm not italian, I have spanish nationality. I've read some comments about the Zapatero's Spain and italian youngters going out,...(?)I do not understand. To me Italy is a nice country to live in, with or without Berlusca. To tell you the truth I didn't notice much of a difference between right-left-right. It doesn't matter much really. The political area set up in Italy is very complicated. The country itself is not homgeneous, from Valle D'Aosta to Sicilia is like talking about night and day. Berlusconi or not will not make the difference, unless,...he really starts thinking of leaving politics and dares to make the structural and unpopular changes the country needs. I don't see Italians much confident in their political class though. Scudetto, Formul one and Moto GP are more interesting really for them, the politicians do not deserve more. More or less like in Spain,... Let's see what happens in the next 5 years in Italy, GDP ?, Public finances ? who wants to bet how long it takes to Lega nord to ruin the Berlusca goverment ? Forza Ferraristi !! I am a foreinger living in North-Italy and I can affirm that foreigners are NOT discriminated respect of Italians (according to European statisctics Italians are those who are able to live well with foreigners). (By the way, the recent European trend is closing boarders respect European citzens!!!) I deeply disagree with the fact that migration is good itself: it's rather harmful without adeguate measures in order to help their integration in the society (it was empirically demonstrated by economists). What the League wants is a legal and CONTROLLED migration (think of please the extension of the Italian coast and the closeness of the African continent). They are aware of the fact that low cost labour of migrants is necessary to enhance economic efficiency in the industrial north. "Lunch all'Economist, quattordicesimo piano. Solita Londra grigio-azzurra, solite poltrone rosse, soliti amici incuriositi, solite notizie italiane: Berlusconi vince le elezioni.” Beppe Severgnini wrote this yesterday this on his blog.So now we know who is one of the consultants of the Economist. Ridicolous people give ridicolous suggestions.Does anyone remember ever having read anything original by Severgnini? Dear Awatea,What is wrong in wishing to move back to my Country, that I love, where I was born and lived for 35 years?What is wrong in watching my Country TV and reading my Country online news?Does these things make me not a fully integrated/active citizen?If so, I shouldn't even read the Economist, since it is not an American publication. I just said that if someone want to leave the Country because of Berlusconi, they should do it and not just chat about it.As for me, I moved to the US to work for a very successful Italian company (not owned by Berlusconi or his family...), but was never my intention to change my passport.... Go read Luca Ricolfi on la stampa 18/04, search for “razzismo etico”. Ethical Racism is what he defines this annoying attitude by which trendy opinion makers discard italians who voted Berlusconi as a bunch of stupid, dishonest, corrupt, and so on.In an other article the Economist wonders "How many aspiring prime ministers could get away with describing older female supporters as their “menopause section”?" Whch is of course a very good question, and no doubt a bad joke.But which other prominent politician could get away with saying "� nella fascia meno acculturata che sfonda la destra", which is a plain insult and not a joke. But this statement by D'Alema didn't even get to prime time, while any stupidity by Berlusconi provokes international earthquakes.As Zola wrote in his famous J'accuse "c'est un prodige d'iniquit�"But victims of racism. are victims, racists are racists: I'd rather be a victim than a racist The Economist has devoted so much ink about. @ serenissimo, Reading your uneducated comments, I came to the conclusion that USA's IQ average will benefit from your departure.Italians have been leaving Italy for abroad in droves way before Berlusconi entered Italian politics. Most of these Italians have become very successful and have integrated to their new adopted country. A minority of these Italians, instead of integrate in their host country, and become full active citizens, keep watching RAI television. Ironically these Italians return to Italy and find millions of new immigrants doing menial jobs. These immigrants, are marginalized and discriminated by people like Berlusconi and Lega supporters, because these non-Italians "don't integrate to Italians culture and way of life". How ironic.I encourage people like @serenissimo when returning to Italy, to pick up one of these many new menial jobs that Berlusconi's economic "miracle" will generate. I agree in large part with the article. Indeed all the Berlusconi's tv have depicted the crisis as the only responsability of Prodi. In part it's true that the previous government has risen taxes, but it was largely due to the bad economic legacy of Berlusconi: 5 years of lack of growth (blaming for this the 9/11); no control over Euro currency introduction, which led to progressive impoverishment; the growth of the debt and of the public spending; no liberalizations. He has promised the cut of taxes and the increase of salaries, but we have this situation: One of the highest debt in the world. Seven reterees out of ten workers. The lowest wages in Europe. The lowest birth rate, and so a population that's getting increasingly older. One of the highest rate in corruption in Europe, and a similar income-tax evasion . A third of Italy under Mafia's control. We would need a new Churchill, who promised tears and blood to heal Italy,not a dream seller. Pierluigi Few days ago, You wrote: "Several pointers to the future can be discerned. Italy's next government will be uncompromisingly right wing." Really?!? Why don't You say that actual LaDestra's(extremely right Party) leaders were part of the previous Berlusconi's Government and now they are proscribed from the coalition? You also wrote: "The People of Freedom movement includes Gianfranco Fini's former neo-fascists." Have You ever heard about "Svolta di Fiuggi"? Further on: "And, unlike Mr Berlusconi's previous governing alliance, it will not include the centre-right Union of Christian and Centre Democrats." You seem to be very broad and You sigh for the exclusion of these Parties... Thanks to God, they've been excluded!! They're against: common-law marriage, abortion, stem cell research, assisted fecundation, RU-486 and so on. Thanks for Your attention and sorry..I'm stupid, I voted Berlusconi @ Luis La SalleNot even a miracle will put Berlusconi in Lady Thatcher league. Thacher, a person with integrity, heroism, determination and love for free market principles is no comparison to a crook like Berlusconi. Hoping that her successful labor and economic reforms in the UK, will be repeated in Italy under a Belrusconi III regime, confirms to me that you and others Berlusconi worshipers don't know the man very well, let alone Lady Thatcher. I'm Italian, but I live and work in the US. Last night I was watching an Italian political TV show on Rai International. They said that a a lot of young Italian people (maybe millions) want now to move out of Italy, likely to the Spanish Zapatero heaven, as they can't stand Berlusconi return.That is a great idea! I strongly encourage them to do it.As for me, I'm now considering to finally move back to Italy...... After the last extremely partial article I'M AFRAID. Not because you, the Economist, are indirectly insulting more then a half Italians (around 30 million people), Not because you are insulting an enterpreneur and poltician with partial and distorted information since years, Not because you have the courage of talking about Mediaset, which, ask every italian, is the most impartial media, when you are writing partial articles like this. But because I unfortunately and very sadly have the proof that media , even the one which I read every week and in which I believed, have the power of distroing people and entire nation's image. What I can suggest to people who have read this article and have no other information about Italy and its politics it's: be critic! ask yourself who is behind this article! ask yourself why 30 million people made a choice, and respect those people! Come here and watch Italian media with your eyes, before judging. ( by the way I am an Economist subscriber, I am an italian, as well as an international student, I voted the PD!, and I respect my new President) What should I think when reading about other nations politics in your newspaper? What should I think about the information you provide to millions of people? I'M AFRAID!
http://www.economist.com/comment/26425
CC-MAIN-2014-15
refinedweb
3,129
63.09
3D text shape node. More... #include <Inventor/nodes/SoText3.h> 3D text shape node. This node defines one or more strings of 3D text. In contrast with SoText2, 3D text can be rotated, scaled, lighted, and textured like all other 3D shapes. Optionally (setting the parts field) each character in a 3D text string may be a true three dimensional object. This shape is created by extruding an outlined version of the character (in the current typeface) along the current profile, as defined by nodes derived from SoProfile. The default text profile, if none is specified, is a straight line segment one unit long. The text position is always at the local origin (0,0,0). A transform node, e.g. SoTranslation, must be used to position the text in 3D space. The text is always rendered in its local XY plane. A transform node, e.g. SoRotation, may be used to rotate the text plane in 3D space. Text supports both single byte Latin1 (ISO8859-1) characters and multi-byte UNICODE characters. ISO8859-1 is an 8-bit character set which is a superset of the older 7-bit ASCII character set. See the SbString class for more information. Rendering: The typeface and size (default = 10) are specified using an SoFont node. The scale factor, if any, in the current transform is applied to this size. 3D text characters may be rendered using lines, polygons or textured rectangles depending on settings in the SoFont node. Textured rendering is recommended. It generally has the best performance (minimum geometry) and the best image quality (because antialiasing is applied). Rendering styles: Additional styles can be applied using an SoTextProperty node, including underline, strikethrough, background and background outline. Complexity: The quality (degree of tesselation) of SoText3 line and polygon rendering depends on the SoComplexity node's value field. The quality of SoText3 textured rendering depends on the SoComplexity node's value and textureQuality fields, plus the SoTextProperty node's textureQualityRange field. If there is no SoComplexity the textureQuality is 1. See SoFont for more discussion. Material: SoText3 uses the current set of materials when rendering. If the material binding is OVERALL, then the whole text is drawn with the first material. If it is PER_PART or PER_PART_INDEXED, the front part of the text is drawn with the first material, the sides with the second, and the back with the third. Lighting: By default lighting is only computed for the "front" face of geometry, including SoText3, meaning that the back face of the text will be black when lighting is enabled. To illuminate both sides, enable "two sided" lighting using the SoShapeHints node's vertexOrdering field. But note that, unlike most geometry, you should set the vertexOrdering field to CLOCKWISE, not COUNTERCLOCKWISE. Texture: Textures are applied to 3D text as follows. On the front and back faces of the text, the texture origin is at the base point of the first string; the base point is at the lower left for justification LEFT, at the lower right for RIGHT, and at the lower center for CENTER. The texture is scaled equally in both S and T dimensions, with the font height representing 1 unit. S increases to the right on the front faces and to the left on the back faces. On the sides, the texture is scaled the same as on the front and back. S is equal to 0 at the rear edge of the side faces. The T origin can occur anywhere along each character, depending on how that character's outline is defined. Performance: A scene graph containing a large number of SoText3 nodes will generally have much better rendering performance using a text specific caching mechanism called accumulation rendering mode. However some features are not available and significant time may be required to build (or rebuild) this cache. See the SoTextProperty node enableTextAccumulation field for more information. Justification: Horizontal alignment of the text can be specified using the justification field. Both horizontal and vertical alignment can be controlled using an SoTextProperty node, however the justification setting in this node overrides the horizontal setting unless the justification field is set to INHERITED. Picking: Text can be picked (SoRayPickAction) like any other geometry. If a text node has been picked then SoPickedPoint can return an SoTextDetail object. This object contains information about which string (in a multi-string text node) was picked and which character within the string was picked. Antialiasing: Shape Antialiasing type is SoShape::TEXT. SoRayPickAction Performs a pick on the text. The string index and character position are available from the SoTextDetail. SoGetBoundingBoxAction Computes the bounding box that encloses the text. SoCallbackAction For non-stroke fonts,if any triangle callbacks are registered with the action, they will be invoked for each successive triangle used to approximate the text geometry. For stroke fonts, if any line segment callbacks are registered with the action, they will be invoked for each successive line segment used to approximate the text geometry. SoComplexity, SoFont, SoFullSceneAntialiasing, SoProfile, SoText2, SoTextDetail, SoTextProperty DirectUnicode, StrokeFonts, TextProperties Justification types. Text3 part values. Creates a 3D text node with default settings. Indicates placement and alignment of strings. With LEFT justification, the left edge of the first line is at the (transformed) origin, and all left edges are aligned. RIGHT justification is similar. CENTER justification places the center of the first string at the (transformed) origin, with the centers of all remaining strings aligned under it. Use enum Justification. Default is LEFT. Which parts of text are visible. Note that, for speed, the default for this field is FRONT only. Defines the distance (in the negative y direction) between the base points of successive strings, measured with respect to the current font height. A value of 1 indicates single spacing, a value of 2 indicates double spacing, and so on. The text string(s) to display. Each string will appear on its own line.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_text3.html
CC-MAIN-2021-04
refinedweb
984
57.16
Name: Full name here Due: September 19, 2016 by 11:00am In this week's lab, we continue with learning about the fundamentals of using Sage for computational work. Whereas last week we focused on becoming more familiar with the interface of Jupyter notebooks and the basic syntax and features of Sage, in this lab we will practice three important concepts from programming. These are functions, loops, and conditionals, and they are available for use in Sage thanks to its Python base. These concepts show up all the time in computational science work (and programming in general) and they are important building blocks of software. Despite the rather complicated logical structures one can build using these tools, these concepts are relatively simple to understand. So if you've never worked with these before, do not worry! It's all about practice and trying ideas out. An example of the general structure for defining a function is: def functionname(input1, input2, ...): <body> Note that there is a 4-space indent for the <body> field. Forloop structure The structure of a for loop is: for <var> in <sequence>: <body> Note that there is a 4-space indent for the <body> field. The for loop completes once the full sequence has been iterated over. if/elseconditional structure The structure of the if/else conditional statement is: if <condition>: <statements> else: <statements> Note that there is a 4-space indent for the <statements> field. The <condition> must evaluate to either True or False. This is done by writing mathematical comparisons in the <condition> field, such as 50 > 20 ( True), 100 <= 50 ( False), and 25 == 25 ( True). If the <condition> is True, then the <statements> under if are run. If it's False, then the <statements> under else are run. whileloop structure The structure of a while loop is: while <condition>: <body> Note that there is a 4-space indent for the <body> field. The while loop will continue indefinitely as long as the <condition> field evaluates to True. Once it evaluates as False, the loop stops. Congratulations! You've just been hired to work at ABC Banking Corp as a software engineer. Unlike most of today's banks, ABC Banking Corp has been slow to adopt new technology, meaning that they've been doing all their banking using paper and desk calculators. You've been tasked with bringing them into the 21st century by developing software that can automate their banking needs. Your first assignment is to develop software that can assist their banking representatives with calculating investments. One of the financial products that ABC Banking Corp offers to its customers is a 10-year certificate of deposit (CD) with an annual interest rate of 1%. This CD is an example of a financial product with compounding interest. Your task is to create a function named cdapr that contains a for loop that will take the initial principal (the customer's deposit) and calculate the value of the CD by the end of the 10-year period. In the event that you remember the compounding interest formula from another class (it contains the exponential e), assume in this scenario that you've forgotten the formula (this exercise will demonstrate that an algorithmic approach to a calculation can simplify the math). Hint: Let P be the value of the initial deposit and r be the interest rate. After one year, the value of the investment will be P1yr=P(1+r). After two years, the value of the investment will be P2yr=P1yr(1+r), and so on. In the code box below, define a function named cdapr that takes a single input, the initial principal, and then calculates the value of the CD after 10 years. Run the code box when you are done. Hint: The final line of your cdapr function needs to output the final value of the investment. Use the def myfunction(num): print num will print out the supplied number. Running myfunction(10.5) will output 10.5000000000000 In the code box below, use the cdapr function that you defined above to calculate the value of the CD when you start with the following principals: Your manager is happy to see that your software is already working as described. However, work doesn't end. The bank offers many different CD investment options, and each one has a different interest rate and number of years for the investment period. Your manager wants you to modify the function to take two additional inputs, the interest rate and the number of years for the CD investment, and edit the code so that the function calculates the value of the investment given the supplied principal, interest rate, and the number of years of the investment. Copy your cdapr function into the code box below to use as a starting point, rename it cdapr_v2, and implement the specified modifications. Run the code box when you are done. Now let's test that the modified function works as intended. Use cdapr_v2 to calculate the following investments (the first one tests that you still get the same output as in Exercise 2): Your manager is very pleased so far with your progress. She has now informed you that many of ABC Banking Corp's CD's will be moving to an alternative to the annual interest rate, so another modification for your function is needed. The alternative will be to calculate the accrued interest in terms of a nominal interest rate and a specified number of compounding periods. So, for example, instead of a 1% annual rate compounded annually, the interest might be compounded quarterly. This means the account would earn 0.25% interest every 3 months instead of 1% each year. Copy your cdapr_v2 into the code box below to use as a starting point, rename it cdapr_v3, and implement the specified modifications. The function should take as input the starting principal, the annual interest rate, the number of compounding periods per year, and the number of years of the investment. Run the code box when you are done. Use cdapr_v3 to calculate the following investments: In Exercise 4 and Exercise 6 you calculated an investment with a starting principal of $3000, an annual interest rate of 2.2%, and an investment period of 5 years, but one was compounded annually and the other quarterly. What interest rate compounded annually in function cdapr_v2 would you need to have to get the same investment return for the cdapr_v3 function that was compounded quarterly? Explain how you determined this. Hint: Use the "trial-and-error" approach by using a while loop that checks whether the two values are close enough. The basic algorithm would be to guess an interest rate, compare it with the anually compounded calculation, and if the difference between the two calculations does not fall within a reasonable tolerance (the two outputs should be accurate within a fraction of a penny, at least), change the interest rate and try again. ABC Banking Corp also offers retirement investment accounts where customers can deposit a fixed amount of money per year that gets added to their total principal, which is then compounded at a fixed annual interest rate. Your manager wants you to modify the cdapr_v2 function to calculate and output the value of a retirement account so that they can pitch these to potential customers. Copy your cdapr_v2 function into the code box below, rename it retirement, and implement the specified modifications. The variable you used to specify the initial principal will now be the amount of money deposited per year by the customer. Run the code block when you are done. Hint: The yearly deposit should be added to the principal before calculating the interest. The account should also start with principal=0 before the first deposit. Use the retirement function you just defined to calculate the final value of the following retirement accounts: Your manager has one more assignment for you before you can leave for the day. The retirement accounts do not operate for free, ABC Banking Corp collects annual fees from the accounts as part of their service. However, they do not start charging the annual fee until a retirement account has at least $50000. Furthermore, the annual fee, which is 0.8%, is only applied to the dollars added to the principal above the $50000 threshold. Finally, the fee is calculated after the yearly deposit but before the annual interest is added in. The annual interest is also calculated after the yearly deposit but before the annual fee is collected. For example, say a retirement account has $55000, the yearly deposit is $2500, and the annual interest rate is 5%. The calculations would proceed as follows: (55000 + 2500) * 0.05 = 2875 (55000 + 2500 - 50000) * 0.008 = 60 55000 + 2500 + 2875 - 60 = 60315 Copy your retirement function into the code box below, name it retirement_v2, and implement the fee structure described above. Create an input for the annual fee so that you can change it from 0.8%. Round the final result to the nearest penny. Run the code block when you are done. Hint: You will have to use an if/else conditional statement when calculating the fees. Using the retirement_v2 function you just defined, recalculate the final value of the retirement accounts specified in Exercise 9. How much does each retirement account pay total in fees when compared with the fee-less calculations? Your manager is about to close up, but you want to see if you should do your own retirement investments through ABC Banking Corp or through their competitor CDE Investors Lmtd. Each has a retirement account where, if you make an annual deposit of $3500 for 40 years, you'll get an annual interest rate of 5.5%. The fees at CDE Investors Lmtd. are calculated in the same way as ABC Banking Corp, except because of computational automation CDE Investors Lmtd. is able to charge a lower 0.4% annual fee. However, CDE Investors Lmtd. is an hour drive from your home and each deposit to the retirement account must be done in person, so you're not sure if it's worth the effort to save just 0.4% in fees. But, thanks to your function, you can figure out how much you'd save. Using the retirement_v2 function, calculate what your final investment value would be when the annual fees are reduced to 0.4%. How much would you save? Do you think this amount of savings would make traveling an hour to CDE Investors Lmtd. worth it?
https://share.cocalc.com/share/08d5fc07a0b2f4b4f393615e58cf4b70851203de/Week%2003%20Lab/CDS-102%20Week%2003%20Lab.ipynb?viewer=share
CC-MAIN-2020-10
refinedweb
1,764
61.46
Built in YAML provider Since Beta 6, resteasy comes with built in support for YAML using the Jyaml library. To enable YAML support, you need to drop in the jyaml-1.3.jar in RestEASY's classpath. Mime Types The Yaml provider recognises three mime types: text/x-yaml text/yaml application/x-yaml Example This is an example of how to use Yaml in a resource method. import javax.ws.rs.ConsumeMime; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.ProduceMime; @Path("/yaml") public class YamlResource { @GET @ProduceMime("text/x-yaml") public MyObject getMyObject() { return createMyObject(); } ... }
https://developer.jboss.org/wiki/BuiltInYamlProvider
CC-MAIN-2018-43
refinedweb
103
61.53
Using Inheritance Inheritance in C# gives us the ability to create classes which are derived from existing classes. In new derived classes, we only have to specify the methods that are new or changed. All the others are provided automatically from the base class we inherit from. To see how this works, lets consider writing a simple Rectangle class that draws itself on a form window. This class has only two methods, the constructor and the draw method. namespace CsharpPats { public class Rectangle { private int x, y, w, h; protected Pen rpen; public Rectangle(int x_, int y_, int w_, int h_) x = x_; //save coordinates y = y_; w = w_; h = h_; //create a pen rpen = new Pen(Color.Black); } //----------------- public void draw(Graphics g) { //draw the rectangle g.DrawRectangle (rpen, x, y, w, h); Shashi Ray Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/kb/404-using-inheritance.aspx
CC-MAIN-2018-13
refinedweb
152
61.26
If. Help me out, since I’m not creative enough to envision non-academic scenarios where such things are needed.. About all I can think of was back to Database class where we mangled a disk simulator to write B-tree database structures to the fake disk, and read them back into arbitrary data records. In that scenario, no data was ever aligned, and it was pretty obnoxious. Outside of that, I’ve never dealt with data alignment or needing to have it aligned in any commercial software I’ve worked on. So why would someone want or need to know this ? Well, x86 CPUs are quite forgiving about memory alignment, so you can get away with ignoring it altogether. (The code will run more slowly when accessing incorrectly aligned data, but it will still be correct.) Other CPUs can raise an exception or do other Bad Things when you try to access misaligned data, and then correct alignment becomes vital. In other words, if you ignore alignment issues, you can write code that seems to be perfect ANSI C, and runs on PCs, but dies spectacularly when running it on something else… I have a binary file format that I needed to support (years ago) across different versions of Windows (16bit and 32bit). Since the default alignments are different for 16bit and 32bit programs, I was able to force the alignment to be the same in all environments. Basically, my case was being able to pass structured data between different computers. I think the need for this is fairly rare. As njkayaker says, anything involving structured data might need specific alignment, if only for speed. This is especially important for using network protocols efficiently. The Win32 API is built on structures, some of which have unnatural alignment. 3D code and high-speed stuff that depends on the cache will require careful alignment. In managed languages it matters less, but if you’re writing in C++, you should always know at least roughly what your memory looks like. This may mark me as a newbie to this territory, but why not just stick with union any time you need alignment? It’s standard, and doesn’t have the many caveats that you attach to the other methods. Most major backup formats use packed data structures on tape or in backup files. B – I almost never see structure packing used when a program runs on a platform, and is "self contained". I see it quite a bit when two programs, running on different computers, are trying to communicate using a shared set of structures. Anonymous above touched on the same point with Network structures. ‘C’ is very vague about structure packing. For example, on the embedded RISC processor I’m using now, the compiler likes to align everything on 32 bit boundaries; so a structure like: struct { unsigned char a; unsigned char b; } c; takes 8 bytes of memory. If I pass this structure across a communications port (Say, TCP/IP across Ethernet, or even USB) to another computer, the second computer may not correctly read the data. If, for example, the compiler on the second computer aligns the two elements on byte boundaries, the structure would only take up 2 bytes on the second computer, and the likelihood of succesfully transferring information between the two is low. I’ve done intense systems-level programming in C and C++ for over two decades. In that time I’ve found about a dozen compiler bugs, used goto in production code perhaps three or four times, and had to step outside the portable parts of the languages to specify data alignment twice. On the other hand, I’ve had to know what the compiler was doing about alignment pretty much every day. And just because I was able to use the portable portions of the language to get the alignment I needed doesn’t mean the code was portable — ifdefs are frequently needed. Back in the day the Unix programming community was infected by the "all the world is a VAX" disease. Programmers who had the luxury of workingonly on the VAX believed ints were 32 bits and if p is null then *p is zero, to name just two of the symptoms of this disease. Today it is the PC that forms the basis for what most programmers think they know about portability. This is another one of those posts from Mr. Chen that is incredibly valuable if you happen to need it but completely useless otherwise. If you think it is useless that’s just because the scope of your work has not yet included the need for it. Think and learn. Word to the wise: in the brave new multicore world alignment and allocation issues will become one of the two or three determining factors of program performance. This is really very different from anything most programmers have experienced before, and to fix the problems post-hoc will be very hard. When it comes to packing, I would prefer gcc’s way of doing it – struct {…} attribute ((packed)). This method allows to specify the alignment requirement as an attribute to the structure definition itself, rather than as a separate #pragma push & pop pack. I have seen code in many places where a header file has #pragma pack(push) in the top and a pop at the end. When an unaware user copies one of these packed structures, then the results are scary. Vijairaj: Read Raymond’s post again. Look for the paragraph where he shows __declspec(align(16)). B: Unions cannot pack things tighter than they otherwise would be Frank hit it on the head. If you have shared data, you often must be explicit about the alignment. It can get really hairy when you have a 32bit program writing data that will be read bya 64bit program. That’s when alignment matters most. It is also rather important to pack persisted data since smaller reads make for faster reads. Finally, in Windows shell namespace extensions, it is a common practice to pack IDLists since they take up memory and are sometimes persisted. Forcing the alignment is not enough for reading/writing a binary file format (or passing data to/from another computer). You also have to worry about endianess (for instance, TCP/IP is big-endian, while x86 is little-endian). So as you’re a shell guy, whose bright idea was it to specify SHCOLUMNINFO as 1-byte alignment? Was the expectation that there would be so many columns in a details view that the saving would be worthwhile? Really? Even when Explorer was first written for Cairo back in 1991? What pisses me off is the inability to get aligned memory back from new[] operator. Say you have a class: class Foo { public: }; When you do this: Foo *p = new Foo[5]; It will crash because of MOVAPS in the constructor is expecting 16-byte aligned memory. To fix the problem, you have to overload new[] and delete[] and use _mm_malloc() and _mm_free() even though compiler could align the memory for you — I believe it has enough information about the Foo object size and alignment requirements at compile time. "This may mark me as a newbie to this territory, but why not just stick with union any time you need alignment? It’s standard, and doesn’t have the many caveats that you attach to the other methods." Unions allow different types to -share- the same memory by forcing an alignment that works for all the types. (Note that heap memory is typically aligned for all types: It’s union for all.) The "packing" stuff mucks with the gaps between different memory blocks in a structure (it has nothing to do with sharing). Shouldn’t you be casting to (misaligned_members *) instead of (misaligned_members)? And isn’t the function HeapAlloc(), not HeapAllocate()? But other than that, thanks for the fantastic information :) Automatic (stack) allocation doesn’t guarantee the correct alignment, only "good enough" alignment, i.e., given "type stack_variable;", "(INT_PTR)&stack_variable % TYPE_ALIGNMENT(type)" might not be zero. This is an issue if half your code is in user mode and the other half in kernel mode, and you need to call ProbeForRead/ProbeForWrite on one such object (they will raise STATUS_DATATYPE_MISALIGNMENT). Setting packing to a larger value won’t help. The safest solution is to declare "type" as "DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) type" I ran into a compiler bug around the time when openmp was new in vc, it didn’t align declspec’ed stack variables correctly. Pragma pack was far more common on DOS-based handheld computers, because packing could actually make the difference between the customer’s data fitting into RAM and not fitting. This counted for both running program memory and ‘disk’ storage, for these devices didn’t have fixed disks, only RAM disks of up to 4MB, but RAM was very expensive on these units! On Windows CE on ARM processors you want to avoid it like the plague because it massively bloats your code, as the processor itself will generate misalignment faults, so the code has to include every possible pattern for misalignment. In a very few cases when porting code from the old devices to the new, we want the on-‘disk’ structures to be the same, and we’ll leave the packing pragma in. Otherwise, it comes out. B, the other problem with only ever using union is that it only provides a way to increase the packing – you can’t reduce it, so say you have the following struct struct { short a; short b; int c; } a; By default on WIN32 using VC++ a and b will be packed into four bytes (IIRC) and c will follow so sizeof(a) will be 8 bytes. If you wanted a to occupy four bytes, this could be done with a union (this is most often done when you have a one element array at the end of a structure which is really of variable length). Unfortunately, if you have this struct ( short a; int b } a; a will be two bytes followed by two bytes of padding to make b dword aligned (again on win32 with VC++) – there is no way that I know of with a union to tell the compiler that actually you want the size of this structure to be six bytes. Are there cases where misalignement of data on Windows/x86 causes slower execution? Most docs I searched were either for RISC architecture, or were somewhat imprecise with the concept. For example, the following link: Speaks about performance issue on 386 and RISC processors, but nothing on 486 or pentiums. Are these last processors immune to the speed degradation induced by misaligned data? Thanks! "Are there cases where misalignement of data on Windows/x86 causes slower execution?" There are also cases where it causes NO execution. For SIMD data types if you acccess unaligned memory with MOVAPS/MOVDQA (instead of MOVUPS/MOVDQU) you get a crash. MOVUPS/MOVDQU in combination with unaligned memory can result in 50% slower execution time compared to properly aligned data and MOVAPS/MOVDQA. Always align your data in memory, especially for SIMD data types! Also, if you have two threads accessing variables which reside next to each other in memory, make sure you align those variables to the cache line boundary (i.e. so that they end up in different cache lines) in order to prevent false sharing which is a significant performance penalty). Here — Intel® 64 and IA-32 Architectures Optimization Reference Manual: You may find that x86 is not as forgiving when it comes to alignment after all, it is just that some of you have chosen to ignore it. > You need to improve your search engine skills. Thanks. I’m reading the page right now. At first glance, I’m feel like, ahem, I’m reading japanese… :-p Anyway, this is the way we learn, so… :-) > You may find that x86 is not as forgiving when it comes to alignment after all, it is just that some of you have chosen to ignore it. Thanks for the link to the PDF. I will forward the info to the people who *did* make misalignement-related decisions years before I joined the team. ;-p I know the feeling. I work with a large codebase that’s pretty much entirely been #pragma pack(1)’d — largely because it’s been inherited from way back in the DOS ages and it has a lot of structures representing on-disk record layouts. I’ve been itching to get rid of it (or at least reduce the scope a bit) for a while now but haven’t been able to get approval. Interestingly it all still runs just fine even with the misalignments — and this is for a soft-real-time control system, so performance is important… I got badly bitten by alignment issues on an embedded platform. The X86 version ran without problems, but on the PPC version I was getting the occasional wrong value for a floating point number. It turned out to be a bug on the logic board. Reading a misaligned float on that particular processor was supposed to raise an exception, but the exception was being lost and the program was silently continuing with zero instead of the proper value. Discovering it was an alignment issue took a bit of psychic debugging to start with. Fixing it was the next problem. I couldn’t change the alignment so I had to write a macro to copy the misaligned data (as a bit-pattern) into an aligned buffer and then read it from there as a float. Finding every instance where the program read a float that could possibly be misaligned was an experience I would prefer not to have to repeat. It is not out of the question that there are one or two instances left in there, and I might never know. There are still a few pages on MSDN which refer to ‘386’ as a general term for 32-bit x86 processors. For 386, generally, read ‘386 and later’ unless specifically noted otherwise. Another thing you need to watch out for is misaligning anything you plan to use with interlocked instructions. If you do, x86 processors will still perform the requested operation (add, exchange, compare) BUT it won’t be properly interlocked – it’ll do two read/write cycles to the two aligned locations with the LOCK line asserted, but the intra-CPU bus doesn’t have any way to associate the two operations as being atomic. I’m not sure but I think Raymond’s example link is actually talking about how the Intel Fortran compiler is using SSE instructions (that would fit with the 16-byte = 128-bit alignment), although it could be related to cache lines (the processor *actually* asks for data from main memory in cache-line chunks, to take advantage of the ‘burst mode’ sequential output of all RAM modules since EDO, unless performing interlocked accesses or other non-combining reads or writes). I’m not sure how big current cache lines are, I think it’s 64 bytes. Speaking of cache lines, here’s something interesting I found relating to Core 2: apparently regular unaligned reads are not too bad, but you get a perf hit if they cross cache line boundaries, and an even bigger one crossing page boundaries. Source:. Because cache line boundaries and page boundaries are (large) multiples of 8 bytes, if your structures are aligned you’ll be OK, or at least you won’t hit this particular problem. A lot of programmers have a mental model of the computer that is twenty years out of date. To understand the modern machine, I suggest watching Herb Sutter’s presentation to the Northwest C++ Users’ Group, "Machine Architecture: Things Your Programming Language Never Told You" at. Raymond, you state: C language standard does not state (or even know) anything about alignment. In fact, the way a union is described, a compiler is even free to treat a "union" like a "struct", and still be a C compiler. Another option for a compiler might be to put the ch at ((char*)&Alignment)[1] or so, and still be according to the C standard. (No, I am not arguing if this would make sense in most cases, but the compiler is indeed free to do so). The fine print: There is NO way to do this totally portable. Of course, experience tells us that on most compilers, this will indeed work.
https://blogs.msdn.microsoft.com/oldnewthing/20071227-00/?p=24013
CC-MAIN-2017-43
refinedweb
2,767
66.67
. For a light version of sigslots suitable for firmware projects, see ecl_sigslots_lite. Anywhere that triggers an event requiring a callback to be executed can be implemented with a signal. These can be placed anywhere in your code and can be connected to one or many slots. Anywhere that a callback function is required can be implemented with a slot. These can be placed anywhere in your code and are initialised with either a static (global) function, or a member function. Once initialised, they can be hooked up to a signal.: #include <ecl/sigslots.hpp> // The types using ecl::Signal; using ecl::Slots; You will also need to link to -lecl_sigslots. Loading of slots can be done directly to free or member functions through the constructors. Below is a simple example for various types of loading. void f(const int& i) {} class A { public: void f(const int& i) {} }; // ... A a; Slot<const int&> slot0(f); Slot<const int&> slot1(&A::f,a); Signal<const int&> signal; Slot<const int&> slot(f); signal.connect("Dudes"); slot.connect("Dudes"); Signals and slots have no limit to the number of connections they may make. Every time a signal emits, the connected slots are consecutively run with the data that is emitted. signal.emit(3); // Pass the '3' to all the slot functions.. A signal can relay another signal, effectively posing temporarily as a slot. @code Signal<> signal; Signal<> signal_relay; Slot<> slot(f); signal.connect("First_Topic"); signal_relay.connectAsSlot("First_Topic"); signal_relay.connect("Second_Topic"); slot.connect("Second_Topic"); signal.emit();: A a; Signal<> sig_void; Slot<> slot_void0(g); Slot<> slot_void1(&A::g,a); sig_void.connect("void_test"); slot_void0.connect("void_test"); slot_void1.connect("void_test"); sig_void.emit(); ecl::SigSlotsManager<>::printStatistics(); would print output: Topics Name: void_test # Subscribers: 2 # Publishers : 1.
https://docs.ros.org/en/jade/api/ecl_sigslots/html/
CC-MAIN-2021-21
refinedweb
289
57.67
In windows explorer (and linux gnome) shows for each file a thumbnail or icon. Like with EXEs, images, videos, txt-files, ini-files, Word documents and so much other file types. Now is my question: Is there a way to get a (preferably large) icon by file. Something like: public static BufferedImage getThumbnail(File file) {...} It looks like there is no AWT way of doing this. If you're using Swing, there is a method you can use to get a Swing Icon... import javax.swing.filechooser.FileSystemView; import javax.swing.Icon; ... Icon ico = FileSystemView.getFileSystemView().getSystemIcon(file); You can also convert that Icon back into an Image (most likely a BufferedImage, but I haven't tested it): Image image = ((ImageIcon) ico).getImage(); There is also a class to get the icon directly, but this class is JDK dependent. On Sun JDK's it's the sun.awt.shell.ShellFolder class. If you're using SWT, things are a bit trickier.
https://codedump.io/share/3w9Fz84F2XkT/1/java-how-to-get-the-thumbnail-from-a-file
CC-MAIN-2016-50
refinedweb
161
67.96
[QBS] How to link project references? I had put our project dependencies as references. I am able to build them, but at the link time the linker is unable to find builded libraries (added to cpp.staticLibraries property). I had try to put the path in the cpp.libraryPaths, it doesn't works and as the output folder of references is generated it's not a good idea to put the path hard coded. I saw in documention that it's recommanded to put dependencies as Depends item, but I parsing issues of the qbs file. I don't understand what is wrong to use it like that : @ import "Dependencies/boost/boost.qbs" as Boost Project { Depends {name: "Boost"} ... } @ Error : @ ASSERT: f File not found: "............\qtsdk\qt-creator\src\shared\qbs\lib\language\projectresolver.cpp @ PS : All my subprojects use StaticLibrary item, and I am using QtCreator 3.0.1
https://forum.qt.io/topic/40169/qbs-how-to-link-project-references
CC-MAIN-2018-43
refinedweb
150
66.74
Numpy bool arrays don't work with Pythran backend It doesn't seem to be possible to pass a bool array to a jit-compiled function with the Pythran backend. I didn't try with other backends. Here's an example: import numpy as np from transonic import jit, Array, wait_for_all_extensions, typeof @jit def test1(a: Array[bool, "2d"]): return np.any(a) @jit def test2(a: Array[np.bool_, "2d"]): return np.any(a) a=np.zeros((3, 3), dtype=bool) print(typeof(a).dtype) # <class 'numpy.bool_'> test1(a) test2(a) wait_for_all_extensions() # test1(a) # RuntimeError: Error while compiling code generated by Transonic. # test2(a) # RuntimeError: Error while compiling code generated by Transonic. Here's the full error: ERROR: Error! File /home/daniel/.transonic/pythran/__jit__/__ipython__2a84652c03a07addf471009730705153/test1_e01fe91fc194dbb64a836622629125ff_39043f4db47a419004b852bfb822da1d.cpython-37m-x86_64-linux-gnu.so has not been created by pythran Pythran stderr: CRITICAL: I am in trouble. Your input file does not seem to match Pythran's constraints... E: Invalid Pythran spec near 'bool_' (line 2) To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information
https://foss.heptapod.net/fluiddyn/transonic/-/issues/36
CC-MAIN-2021-43
refinedweb
185
51.75
------------------------------------------------------------ revno: 106608 committer: Juanma Barranquero <address@hidden> branch nick: trunk timestamp: Sun 2011-12-04 18:13:01 +0100 message: Fix emacsclient bug where "-n -c" does not open a new frame on Windows. * lib-src/emacsclient.c (decode_options) [WINDOWSNT]: Don't force tty = 0; instead, treat both -c and -t as always requesting a new "tty" frame, and let server.el decide which kind is actually required. Reported by Uwe Siart <address@hidden> in this thread: * lisp/server.el (server-delete-client): On Windows, do not try to delete the only terminal. (server-process-filter): On Windows, treat requests for a tty frame as if they were for a GUI frame if the running server is in GUI mode. modified: lib-src/ChangeLog lib-src/emacsclient.c lisp/ChangeLog lisp/server.el === modified file 'lib-src/ChangeLog' --- a/lib-src/ChangeLog 2011-11-30 08:13:05 +0000 +++ b/lib-src/ChangeLog 2011-12-04 17:13:01 +0000 @@ -1,3 +1,11 @@ +2011-12-04 Juanma Barranquero <address@hidden> + + * emacsclient.c (decode_options) [WINDOWSNT]: Don't force tty = 0; + instead, treat both -c and -t as always requesting a new "tty" frame, + and let server.el decide which kind is actually required. + Reported by Uwe Siart <address@hidden> in this thread: + + 2011-11-30 Chong Yidong <address@hidden> * emacsclient.c (main): Condition last change on WINDOWSNT === modified file 'lib-src/emacsclient.c' --- a/lib-src/emacsclient.c 2011-11-30 15:43:33 +0000 +++ b/lib-src/emacsclient.c 2011-12-04 17:13:01 +0000 @@ -638,6 +638,22 @@ if (display && strlen (display) == 0) display = NULL; +#ifdef WINDOWSNT + /* Emacs on Windows does not support GUI and console frames in the same + instance. So, it makes sense to treat the -t and -c options as + equivalent, and open a new frame regardless of whether the running + instance is GUI or console. Ideally, we would only set tty = 1 when + the instance is running in a console, but alas we don't know that. + The simplest workaround is to always ask for a tty frame, and let + server.el check whether it makes sense. */ + if (tty || !current_frame) + { + display = (const char *) ttyname; + current_frame = 0; + tty = 1; + } +#endif + /* If no display is available, new frames are tty frames. */ if (!current_frame && !display) tty = 1; @@ -654,14 +670,6 @@ an empty string"); exit (EXIT_FAILURE); } - - /* TTY frames not supported on Windows. Continue using GUI rather than - forcing the user to change their command-line. This is required since - tty is set above if certain options are given and $DISPLAY is not set, - which is not obvious to users. */ - if (tty) - tty = 0; - #endif /* WINDOWSNT */ } === modified file 'lisp/ChangeLog' --- a/lisp/ChangeLog 2011-12-03 20:44:19 +0000 +++ b/lisp/ChangeLog 2011-12-04 17:13:01 +0000 @@ -1,3 +1,10 @@ +2011-12-04 Juanma Barranquero <address@hidden> + + * server.el (server-delete-client): On Windows, do not try to delete + the only terminal. + (server-process-filter): On Windows, treat requests for a tty frame as + if they were for a GUI frame if the running server is in GUI mode. + 2011-12-03 Glenn Morris <address@hidden> * textmodes/texinfmt.el (batch-texinfo-format): Doc fix. (Bug#10207) === modified file 'lisp/server.el' --- a/lisp/server.el 2011-11-22 15:18:56 +0000 +++ b/lisp/server.el 2011-12-04 17:13:01 +0000 @@ -307,11 +307,13 @@ (setq server-clients (delq proc server-clients)) - ;; Delete the client's tty. - (let ((terminal (process-get proc 'terminal))) - ;; Only delete the terminal if it is non-nil. - (when (and terminal (eq (terminal-live-p terminal) t)) - (delete-terminal terminal))) + ;; Delete the client's tty, except on Windows (both GUI and console), + ;; where there's only one terminal and does not make sense to delete it. + (unless (eq system-type 'windows-nt) + (let ((terminal (process-get proc 'terminal))) + ;; Only delete the terminal if it is non-nil. + (when (and terminal (eq (terminal-live-p terminal) t)) + (delete-terminal terminal)))) ;; Delete the client's process. (if (eq (process-status proc) 'open) @@ -1035,7 +1037,11 @@ (setq tty-name (pop args-left) tty-type (pop args-left) dontkill (or dontkill - (not use-current-frame)))) + (not use-current-frame))) + ;; On Windows, emacsclient always asks for a tty frame. + ;; If running a GUI server, force the frame type to GUI. + (when (eq window-system 'w32) + (push "-window-system" args-left))) ;; -position LINE[:COLUMN]: Set point to the given ;; position in the next file.
http://lists.gnu.org/archive/html/emacs-diffs/2011-12/msg00043.html
CC-MAIN-2016-30
refinedweb
742
64.41
putc(3) BSD Library Functions Manual putc(3) NAME fputc, putc, putc_unlocked, putchar, putchar_unlocked, putw -- output a character or word to a stream LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdio.h> int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putc_unlocked(int c, FILE *stream); int putchar(int c); int putchar_unlocked(int c); int putw(int w, FILE *stream); DESCRIPTION The fputc() function writes the character c (converted to an ``unsigned char'') to the output stream pointed to by stream. The putc() macro acts essentially identically to fputc(), but is a macro that expands in-line. It may evaluate stream more than once, so argu- ments given to putc() should not be expressions with potential side effects.. RETURN VALUES), putwc(3), stdio(3) STANDARDS The functions fputc(), putc(), and putchar(), conform to ISO/IEC 9899:1990 (``ISO C90''). The putc_unlocked() and putchar_unlocked() functions Mac OS X 10.8 - Generated Thu Aug 30 10:32:58 CDT 2012
http://www.manpagez.com/man/3/fputc/
CC-MAIN-2018-51
refinedweb
163
67.18
We Can map ON_WM_KEYDOWN message to view class, Similarly Can i map ON_WM_KEYDOWN message to my window which is derived from CWnd? I tried it, but i'm not getting message to my window. I want to map ON_WM_KEYDOWN message to my window. How to achieve it? -pkalp Your CView (I'm assuming you are referring to such a class) IS derived from CWnd. If you look at documentation for MFC-function OnKeyDown() you'll see that it IS a CWnd-function. Therefore, there should be no problem overriding it in any class you'd like derived from CWnd. Are you sure that when you say that the messages don't get to your CWnd-derived class, that this class has focus? Maybe if you posted some code, we could investigate some more. I think that what you're trying to achieve should be "a walk in the park". "Soccer - it is not a matter of life and death - it's far more important than that" Bill Shankly I've two window (CChildView dervied from CWnd and CVSeriesWindow derived from CWnd). From CChildView, i'm creating object for CVSeriesWindow and placing that window in my CChildView. When i scroll my mouse, CMainFrame's OnMouseWheel() is called, from there i'm calling CChildView and then i'm passing it to CVSeriesWindow. When mouse scroll is working, then why key down message is not getting called. Am i wrong in mapping? What could be wrong? -pkalp Isn't it kind of odd to override OnMouseWheel(), or any other CWnd method for that matter, in CMainFrame class? That class is normally used to handle "non-client-area" messages, such as menu selections, caption hits etc. But, I'm no expert, so maybe it's fine... That leads me to my next question; Where is your WM_KEYDOWN message handler implemented? That is; In which class do you have your override of CWnd::OnKeyDown() implemented? If you have something like CVSeriesWindow::OnKeyDown(), AND this window has focus when you hit a (non system) key, the WM_KEYDOWN message should definitively end up in that handler. If it doesn't, I would have to see some code to try and pin-point better... As already stated, it sounds like your window is loosing focus when you scroll. does the message show up in PreTranslateMessage Code: BOOL FOO::PreTranslateMessage(MSG *pMSG) { if (pMSG->message == WM_KEYDOWN) AfxMessageBox("BLAH"); return (BASE_FOO::PreTranslateMessage(pMSG)); } BOOL FOO::PreTranslateMessage(MSG *pMSG) { if (pMSG->message == WM_KEYDOWN) AfxMessageBox("BLAH"); return (BASE_FOO::PreTranslateMessage(pMSG)); } Wakeup in the morning and kick the day in the teeth!! Or something like that. "i don't want to write leak free code or most efficient code, like others traditional (so called expert) coders do." In CMainFrame, i receive mouse wheel message and i'm passing it to CChildView. In ChildView class, i created object for CVSeriesWindow. if(!m_pSeriesWindow) { m_pSeriesWindow = new CVSeriesWindow(this); } In CVSeriesWindow class constructor, i've created my window (CVSeriesWindow) using CWnd::Create() function. Focus is on CVSeriesWindow, I'm able to load images on CVSeriesWindow and it is visible. Then why OnKeyDown() is not called? void CVSeriesWindow::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { AfxMessageBox("key down"); CWnd::OnKeyDown(nChar, nRepCnt, nFlags); } What is wrong? -pkalp It doesn't look like anything is wrong here. I'm still leaning towards the theory that focus somehow isn't where we expect it to be... Here's something to try out to determine for sure if focus is in your CVSeriesWindow: What if you implement your OnMouseWheel handler in the CVSeriesWindow instead of CMainFrame, just for testing? If CVSeriesWindow has focus when you turn the wheel, the message should get there without having to pass it from CMainFrame. Alternatively, you could make a temporary message handler for WM_MOUSEMOVE and check if that one is called when you move the mouse over your CVSeriesWindow. What if you click in the CVSeriesWindow with the mouse just prior to pressing a key? Clicking in a window sets focus to that window. Another option is to use CWnd::GetFocus() to determine which window actually has focus. Trick is to find a good spot to call it. Maybe your CMainFrame implementation of OnMouseWheel() could be a reasonable place? Just throwing out ideas/tips here, because the code you posted I think should work just fine. Nothing spooky there as far as I can see... UPPSSS..... Remembered just after posting that WM_MOUSEMOVE doesn't require focus to get passed to the window the mouse is over. That message is therefore useless to use for checking focus. I think, however, that WM_MOUSEWHEEL require focus of the window it's getting passed to. Sorry... Actually i've a window(CVSeriesWindow). In CVSeriesWindow, i placed objects of CVImageWindow (derived from CWnd) in the form of grid. What i need is to scroll using keyboard (up and down key) to see the remaining CVImageWindows in my window. When i click in the CVSeriesWindow with the mouse, CVImageWindow's OnLButtonDown() is called. When i scroll with the mouse, CMainFrame's OnMouseWheel() is called. But when i press key, nothing is called. How to scroll and see the image window when key press message is not called? Is there any method to invoke that event? -pkalp Originally Posted by pkalp When i click in the CVSeriesWindow with the mouse, CVImageWindow's OnLButtonDown() is called. This leads me to believe that focus is in CVImageWindow and NOT in CVSeriesWindow, where you're keydown-handler is located. Have you tried to implement a key down handler in CVImageWindow, and see if it is called there when you press a key? Since your two windows are not related you cannot expect the handler in CVSeriesWindow to be called if focus in fact is on CVImageWindow... If you want to ensure operations on CVImageWindow to be handled in CVSeriesWindow, I would suggest deriving CVImageWindow from CVSeriesWindow if it is possible. Then, CVSeriesWindow would technically have focus also if CVImageWindow has it because CVImageWindow in this case IS a CVSeriesWindow. Good luck I tried by keeping key down handler in CVImageWindow also, but nothing is called when i press key. CVSeriesWindow key down handler is also not called. Is there any method to invoke key down event. -pkalp Well, I'm running out of ideas here... Maybe one last "shot from the hip"; Can you trap the WM_KEYDOWN message somewhere else? Maybe in your CChildview or CMainFrame, and pass it on to your desired window by means of PostMessage or SendMessage, or perhaps just call OnKeyDown directly for your desired class. Guess you have a CVSeriesWindow object in CChildView that could be used to invoke the CVSeriesWindow::OnKeyDown(). It's an odd approach, but it might work. Point is that we need to locate the WM_KEYDOWN message. Some window gets it. Pretty sure of that, unless you find yourself in a situation where no window actually has focus. Not sure how that can happen, but it is referred to as a possible state in MSDN, so I guess it can happen. None of my window is calling OnKeyDown(). None of my window is calling when i press key. There is a distinct difference when pressing a mouse buttonn and a keyboard key. When a mouse button is pressed, the window in which it is pressed GETS the focus I think. A keyboard key press is sent to the whatever window has focus at that time. I.e. there is necessarily no coupling between say the location of the mouse cursor and which window has focus. When yo say that "None of your windows are calling when you're pressing key", do you have WM_KEYDOWN handlers in place in "all" of your windows to verify this? I'd suggest you take som time and try to find out which window has focus. Use GetFocus(). If none has focusm, this returns NULL. If not it returns a pointer to the CWnd that has it. If you then use GetClassName() for example you can find out which of your classes has it. For debug purposes it might be an idea to call GetFocus in a timer function or something, to ensure that the function is called. If you do a TRACE of the class name, you can monitor in your output window which classes has focus as your program runs. Sorry, I don't have a solution, can only give tips on how and where to start looking. Let me know if you get any closer... Forum Rules
http://forums.codeguru.com/showthread.php?350603-ADO-error-reading-an-empty-field&goto=nextoldest
CC-MAIN-2018-22
refinedweb
1,419
72.97
Hi all! I have a array problem I can not figure out. I have an array that I copy in a method and returns the copy, but I do not get a copy of the array. I just get strange values. public class AClass { private float[] original = new float[5]; private float[] finalyStore = new float[5]; public AClass() { //init orginal original[0] = ..... finalyStore = testToCopy(); } private float[] testToCopy() { float[] copyOfOriginal = new float[5]; for(int i=0; i < original.length; i++) { copyOfOriginal[i] = original[i]; } return copyOfOriginal; } } The code is just a short snippet to clear out what I mean. What comes out in "finalyStore" is not the same as "original". If I just copy the entire array it works fine: copyOfOriginal = original; return copyOfOriginal; What am I missing? Where do I think wrong? Many thanks in advance! Marcux
https://www.daniweb.com/programming/software-development/threads/368675/array-copy-problem
CC-MAIN-2017-26
refinedweb
138
66.84
On 9/26/06, MikeyBoy <fjoyuwmc@yahoo.com> wrote: > > Hi Rob, forgive my ignorance, I'm just starting out with ActiveMQ. I am > puzzled where the activemq-dotnet.dll file you mentioned comes from. I built > my own NMS.dll file using MSVS using just the NMS source, which does not > contain any ActiveMQ namespace. Do I also need to build activemq-dotnet.dll? > Are the DLLs available for download anywhere? I'm missing something > here...TIA, M There's currently no DLL to download (unfortunately we're still waiting for the maven csharp plugin to be fixed) - but you can build it yourself using NAnt as described here... -- James -------
http://mail-archives.apache.org/mod_mbox/activemq-users/200609.mbox/%3Cec6e67fd0609252355m3fa06a8dlcb8a50941afa3083@mail.gmail.com%3E
CC-MAIN-2016-22
refinedweb
110
78.65
New Year '20 Offer New Year '20 Offer Hadoop Training Program (20 Courses, 14+ Projects) This Hadoop Certification Training includes 20 courses, 14 Projects with 135+ hours of video tutorials and Lifetime access. You will also get verifiable certificates (unique certification number and your unique URL) when you complete each of the 20 courses. This Hadoop certification course will help you learn about MapReduce, HDFS, Hive, PIG, Mahout, NoSQL, Oozie, Flume, Storm, Avro, Spark, Splunk, Sqoop, Cloudera. Big Data and Hadoop Training Hadoop Architecture and HDFS MapReduce - Beginners and Advanced Hive - Beginners and Advanced PIG - Beginners and Advanced What you get in this Hadoop Training Program? Online Classes Technical Support Mobile App Access Case Studies About Hadoop Certification Training Course Hadoop Training Course Curriculum To make things easy for you, here’s a comprehensive Hadoop certification course. You need to invest around 70 hours to complete this all-in-all course. Before we ever talk about the target audience, FAQs, let’s look at the course curriculum in detail – Goals This Training is solely focused on Apache Hadoop open source software which plays an important component in Big Data Analytics and its storage. It is designed to make the readers a well certified Big Data practitioner by providing rich hands-on experience and training on Hadoop. Objectives The Objective if the training revolves around the various topics which are part of Hadoop technology and help make a user well profiled in Big Data. The main highlighted topics are Hadoop, Big Data, NoSQL, HIVE, PIG, HDFS, Mahout, MapReduce, Oozie, Avro, Storm, Spark, Flume, Splunk, Cloudera, Sqoop, Traffic Analysis, Data Analysis, Loan Analysis, Data Management, Sales Analysis, Survey Analysis, salary Analysis, Sensor Data Analysis, YouTube Data Analysis, Log Data Analysis, etc. Going through these topics we help easily grasp all the deep earnings within Hadoop and Big Data. Course Highlights This Hadoop and Big Data Training will help you become a proficient Big Data Expert. It will hone your skills by providing all the necessary topics needed to develop your full grasp over Hadoop Technology and empower it. Some of these courses are discussed below: - The first section kick starts you with Big Data and Hadoop Introduction, its usage, and benefits in the real-world scenario. Further we’ll discuss the Hadoop Architecture and HDFS (Hadoop Distributed File System) wherein we’ll go through the backdrops of legacy systems and HDFS benefits over it and also learn about the Map Reduce and its configuration. Further on we’ll go through concepts such as secondary sorting in Hadoop and Joins and also, we will discuss the Map/Reduce method for join in Hadoop (all basic and advanced concepts). At last the section will be finished at Hive learnings and its concepts. - In the second section, we’ll learn all the advanced concepts in Hive including sorting, joins, bucketing, ranks, purge, SCD, etc. Next up we’ll discuss the basic and advanced concepts of PIG such as operators used, functions, commands, PIG vs HIVE, etc. - In the third section, we’ll start with NoSQL introductions, its difference from relational database, database design paradigms in NoSQL, etc. Further on we’ll learn Mahout and its usage in Hadoop including concepts such as its architecture, subversion, CBayes classifier, canopy clustering, etc. Further on we’ll learn Apache oozie, Apache storm, Apache flume, Apache Avro, Apache Spark wherein we’ll discuss their architecture, data flows, features and their usages with Hadoop and also we’ll discuss all the beginner and advanced level concepts in Apache Spark such as its components and usage of Scala with it along with it. At last we’ll also go through Splunk wherein we’ll discuss its fundamentals, Knowledge objects, Tags, Alerts, Macros, and Administration with concepts such as authentication, index, index buckets, etc. Project Highlights In order to improve the efficiency of the training it various business. - The first project introduced is Sales Data analysis using Hadoop – HDFS. Here we’ll dig deep into the problem statement such as fetching customer name with highest sales, fetching total number of large deal sizes, etc. And result in a suitable project which fulfill our objective. Next up we’ll create a project Tourism survey Analysis, wherein we’ll use the concepts of HDFS to fulfill the problem statement and predict a countries tourism count and various other statistics using Hadoop. Next up we’ll make a project named Faculty Data Management which will also use the concepts of HDFS wherein the project goal is to provide relevant lectures faculty details on a portal. - Further we’ll make a project named as Ecommerce Sales Analysis which will make use of Hadoop and HDFS architecture for its making. Here the goal of project is to get a report on the sales figure of a customer on an Ecommerce website for various conditions. Next up we’ll make a project called Salary Analysis where we’ll use Hadoop to make detailed report on salary attribute fulfilling each of user’s query regarding Salary such as salary for a quarter, etc. Next up we’ll make a project named Health Survey Analysis which will use HDFS architecture for its making. - Further we’ll make project on Traffic Violation Analysis using HDFS, Analyzing Loan Dataset using PIG/MapReduce, Hive-Case study on Telecom Industry, Customer Complaints using HIVE/MapReduce, Social Media Analysis using HIVE/PIG/MapReduce/Sqoop, Sensor Data Analysis using HIVE/PIG, YouTube Data Analysis using PIG/MapReduce, etc. Hadoop Certification of Completion What is Hadoop? Hadoop is an open source, big data processing engine. This works in a distributed environment with help of multiple computers (which offers local computation and storage) in a cluster to process the data. Hadoop is a scalable solution, wherein servers can be added or removed from the cluster dynamically. Hadoop continues to operate without interruption. As Hadoop is Java-based, its compatible with all the platforms. And that’s the reason behind Java as main prerequisite for Hadoop. Hadoop is basically made up of two layers - MapReduce: It’s a parallel computing model that processes a large volume of data. It can efficiently and easily process multi-terabytes of data. - HDFS: HDFS is highly fault-tolerant, a distributed file system designed to run on commodity hardware. It has master-slave architecture. One HDFS cluster consists of one name node and rest other as data node. Name node is responsible to manage the file system namespace & provides access to file to clients. Whereas Data nodes serve read and write requests from the file system’s clients. Along with that, they also perform block creation, deletion, and replication upon instruction from the Name Node. Hadoop Training course? Today top-notch companies are relying on Hadoop environment because of exponential growth of data. And hence they are in dire need of good Hadoop developers which can support and build highly reliable applications (processing gigs and terabytes of data). Knowing Hadoop in and out, will make you capable of tweaking its parameters, writing new scripts, understanding Hadoop behavior. Ultimately, this all will make you run Hadoop efficiently with low cost. How to scale Hadoop with more nodes, how to increase/decrease the replication factor of Hadoop etc. are the queries which will be handled well after grabbing the skills from this Hadoop training certification course. This will also focus on skills of deploying Hadoop for block processing, batch processing, real-time processing from various kind of data like audio, video, log and machine-generated data. You will get the skills of processing unstructured data as well, which will a great add-on, because processing unstructured data has always been on the difficult note than structured data. Pre-requisites to Hadoop Training Certification Course - Willingness to pursue a career and Basic knowledge in Analytics: Every individual who wants to pursue career in Analytics domain, Big Data and MapReduce should make themselves capable enough to understand the need of these all. They should have eager to persistently practice and brush up the knowledge in analytics. If you are committed to analytics career, this course will boost your skills and will make you a asset for your organization. Skill and passion together gives perfection to your work. - Basic knowledge of Java: Learning Hadoop means learning HDFS & MapReduce. All programs or scripts written in MapReduce is in form of Map & reduce tasks. This task gets easier to write when you have background of Java with you. Request will be to brush up Java basics first and then take this course. Target Audience for this Hadoop Certification Course - Students of Analytics: If you’re a student of Analytics and want a career in analytics domain. This Hadoop certification will make you build the gap between your college curriculum and industry related to Hadoop by giving you practical and live experiences of Hadoop projects. - Influenced Professional: If you are among the professional who are awed by the frequently used words like big data and Hadoop. You should satiate your learning bud by taking this Hadoop certification. Basic level of technical knowledge can prove to be beneficial, in long run of your successful career by strengthening your prospectus. - Analytics Professionals: If you are already into analytics and want to take your career path to next level, this Hadoop certification is definitely for you. Deep concept and working commands will help you go deeper and challenge yourself. Now a day, many analytical designations are newly opening in corporate world, which demands well to do knowledge of big data & MapReduce things. So that technical decisions are better made. Hadoop Training Course FAQ’s Why should I do this Hadoop certification course? This course is ideal for candidates who aspire to make their career in data analytics and for the professional who want to enhance their technical skill in analytic domain or big data domain. This course will give you confidence to deal with any analytical and big data problem with a smooth go. From setting up the Hadoop environment to processing gigs of data parallelly, with efficient use of nodes, this will give you entire picture over it. I don’t have a background in Analytics, can I do this Hadoop certification? The answer is partially Yes and No. Without the basic knowledge of Analytics, it gets difficult to understand the worth of doing processing in Hadoop. If you don’t have basic knowledge, you surely understand the framework architecture and working principles. However, relating it to analytics might not be that easy. Get your basics right and you are more than welcome to do this course. Would this Hadoop training certification help me in my career advancement? No Doubt about that. Learn from this course, get your hands dirty with your rigorous practice, and this will create golden opportunities for you. You will find yourself attracted towards this field and even excel in this field as well. How do I enroll for this Hadoop certification course? You can enroll in this Hadoop Training Course through our website. You can make an online payment using the following options (anyone): - Visa debit/credit card - Master Card - PayPal Once the online payment is done, you should automatically receive a payment receipt. And with that you should receive access information, via email. For any more help, you can reach out to our Learning consultant. Sample Preview of this Hadoop Training Course Career Benefits of this Training on Hadoop - It an obvious and not denying fact, that Hadoop (that is HDFS) is the most reliable storage layer and the base for using any big data processing tool. It enables application to work on multiple nodes, dealing with peta bytes of data. Looking at the today’s as well as forecasted big data market, knowing Hadoop can be proved a great advantage. As all components like Pig, Hive, Scoop, Mahout uses Hadoop as its base. Knowing Java and Map reduce coding will make you boost your career in big data domain. - Taking this Hadoop training course will surely give you confidence you stand out in crowd. As almost organization tend towards getting more diversified, HDFS is great fit when it comes to store data irrespective of data types. As data is considered the new Gold, there will always be necessity of fast big data processing. Hadoop Training Course Testimonials Review Analysis in Hadoop Training Hadoop Training and HDFS Basics on Cloudera First part of the course is very useful. It explains in a good way how traditional applications process data and what is their limit. HDFS – hadoop distributed file system is the main focus of the course. Unlike vertically oriented systems, it supports horizontal systems where files are being shared between servers. Map Reduce functionality are also explained and the main part of the course is focused on cloudera which is one of the hadoop distributions built on top of the apache hadoop as the layer of abstraction. Linked Denis Alibašić Great course The course is comprehensive and gives a very splendid introduction of all that is out there. It is recommended for those who have absolutely no idea at all of the hadoop ecosystem. It only gives a small flavor of all the different components and it is up to the listener to branch out and do the in-depth study. Linked ISMAIL SANNI very good introduction This introduction to Hadoop is very well structured and absolutely Easy to understand. It contains lots of content as structure, reading and writing algorithm and first steps in programming some small Programm which reads and counts out words in sentences to make the Hadoop function visible. Thanks. Linked Dominik Denny
https://www.educba.com/data-science/courses/hadoop-certification-training/
CC-MAIN-2020-16
refinedweb
2,269
51.58
Vassili Maroussov wrote: > Dear ROOTers, > > I cannot compile the file in the attachment, although the <iostream> is > included: > > ---------------------------- > [pcmspur5] ~/TreePlay > g++ -c count_trees.cxx -I`root-config --incdir` > count_trees.cxx: In function `int count_trees(const char*)': > count_trees.cxx:20: `cerr' undeclared (first use this function) > count_trees.cxx:20: (Each undeclared identifier is reported only once > for. Maybe you forgot to open the namespace for the standard library? using namespace std Phone : 06 7259 4824 Room : c0 28b ------------------------------------------------------------Received on Tue Mar 14 2006 - 17:00:41 MET This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:31:57 MET
https://root.cern.ch/root/roottalk/roottalk06/0324.html
CC-MAIN-2022-21
refinedweb
104
68.67
One. I tried a few out, then ended up putting a few of them together, but I now have a solution which seems to work quite well and seems to give a method of accessing other programmer defined options in game. The way I’ve made it accessible is through the Settings charm in Windows 8. In case you don’t use this much (let’s face it, I don’t), it appears if you touch or put your mouse to the top right hand corner of your Windows 8 screen and click the Settings cog icon. When not in an app it just shows computer settings, but in an app in shows you options as defined by the programmer. There are 4 parts to adding the privacy policy; some declarations of namespaces, an args call, 2 new methods and a privacy policy itself. Beginning with the privacy policy itself, it needs to be available online somewhere so that you can access it. Mine is currently available at is you wanted to have a look. Because my app uses no external resources I just say that I access nothing, a quick search can find the policies used by other people who had this issue as well. Once it is available we can code in access to it. Next we have the namespace declarations. At the top of your Game1.cs, add the following: using Windows.UI.ApplicationSettings; using Windows.System; Next up comes the two methods; setting up the option and the action(s) that option has. The first method sets up the option in the settings window, namely the name of the command to appear and linking to what it does. The code looks like this: void SuperPong_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args) { SettingsCommand privacyPolicyCommand = new SettingsCommand("privacyPolicy", "Privacy Policy", (uiCommand) => ShowPolicyPage()); args.Request.ApplicationCommands.Add(privacyPolicyCommand); } Where the first line sets up the options and the second line gets windows to add the option to the settings window. You can see the method ShowPolicyPage() here. This is binding the method as the action which occurs when the option is selected. The ShowPolicyPage() method looks like this: private async void ShowPolicyPage() { Uri uri = new Uri("http:// YOUR PRIVACY POLICY ADDRESS .com"); await Launcher.LaunchUriAsync(uri); } Where the uri is the address of your policy (in case I hadn’t made it obvious) and the Launcher opens the the website so that the user can view your policy. The last thing we have to add is the call to the methods to set up the new Option. This is done in LoadContent() so it is only set up once. It is only one line; SettingsPane.GetForCurrentView().CommandsRequested += SuperPong_CommandsRequested; Add this calls the methods which set everything up for you. Based on this I think it is possible to add actual options this way, such as in game settings like difficulty and volume. I will look in these at a later date, but for now just getting the privacy policy accessible was the aim. I’ll put the websites I used down the bottom of this post, the second of which has more information about what you can put in the individual options. Adam Sources: Thanks to my father who shared with me regarding this webpage, this webpage is genuinely awesome.
https://adamboyne.wordpress.com/2013/07/03/adding-a-privacy-policy-and-other-settings-to-an-xna-windows-8-game/
CC-MAIN-2020-50
refinedweb
549
62.07
Subject: Re: [Boost-build] creating timestamped zip-files? From: Steven Watanabe (watanabesj_at_[hidden]) Date: 2009-01-20 14:50:33 AMDG Michael Medin wrote: > I posted a few days ago aking how to make a custom command utilize the > tag feature, but apparently this was impossible so now I post instead > trying to find a solution to my problem. > > I want to create a "zip" file along the lines of the following: > <program name>-<architecture>-<version>-<date>.zip > The version is extracted from a .h file, the architecture from the > build, and the date from the system clock. The program name is "known". > But how can i accomplish this? > I currently use the <tag> feature to do the same for a wix based > installer (msi.wix) which works splendidly but the zip is anaction and > actions do not care about the tag feature. I suspect that the easiest way is to make a zip generator (untested): # zip.jam type.register ZIP : zip ; generators.register-composing zip.make-zip : : ZIP ; actions make-zip { # ... } This allows import zip ; zip my-zip-archive : sources :
https://lists.boost.org/boost-build/2009/01/21141.php
CC-MAIN-2021-21
refinedweb
181
67.45
Oh and for anybody who wants to know how to lose weight, it's dead simple, just follow this formula: Nc = F - (Bmr + E) Where Nc = Net Calories, F = food calories consumed, Bmr = Basal Metabolic Rate, E = Calories burned during exercise. The part you left out is Bmr = f(F, Ft, E) where f is a non-linear function that we don't fully understand and Ft = type of Food and is a catchall for the impact of different types of food on your metabolism. A naive reading of your original equation might lead people to assume that Bmr is a number rather than a function of the other variables. A more accurate formula would be: Nc = F - (f(F, Ft, E) + E) Also worth noting that F = g(F, Ft, E) where g is a function describing your body's hunger and fullness sensing mechanisms as well the decision making neural pathways in your brain. The ability to solve a differential equation or write an elegant piece of software or make a correct decision under psychologically challenging conditions is very much influenced by F and Ft. So I think your simple equation would be more accurately written as: Nc = g(F, Ft, E) - f(F, Ft, E) - E I distributed the subtraction to remove an extraneous pair of parentheses. Since g and f are non-algebraic functions it's understandable that solving this equation is a bit more complicated than the simplistic arithmetic that your original equation implies. In my sun-drenched community, a few wealthy Republican early adopters have rooftop solar installations that supply all their needs. I'm curious about your methodology. Can you elaborate on how you determined their affiliation? Do you personally know all the people in your community with rooftop solar or did you determine their party affiliation in some other manner? Can you also clarify whether you merely mean that they are registered to vote in republican primaries, or do you have solid evidence that they vote a strict republican hard line in all elections regardless of candidates or issues? There are a scattering of houses with rooftop solar in some of the neighborhoods where I run (on foot for exercise, not for political office) but it would never have occurred to me to research the political party affiliation of the homeowners. I love drivers like you, you pay $40K for a car and sell them 3 years later for $10K. I buy cars like this for $10K and drive them for many years. Thanks for blowing $30K so that I can drive a fancy car. Really? I buy new and drive till it dies so I haven't priced vehicles since 2007, but I just did an online search for 2011-2012 sedans for under $11,000 with under 100,000 miles and I didn't find anything other than econoboxes within 50 miles of my ZIP code. Maybe a few of the Fords and Nissans might have been above the econobox level, as I said I haven't priced cars in years, but I didn't see a single $10,000 car that I would consider a luxury brand. Can you link to a few listings of three year old cars for $10k that originally sold for $40k? the problem of being unable to drive is a "first world problem" And since the first world is comprised of a large number of countries with prodigious intellectual and industrial production capability it should hardly come as a surprise that the first world is applying those capabilities to solving first world problems such as this. What would be surprising and sad would be if the industrial machine that won World War 2 were no longer capable of applying resources to the resolution of its own problems. If you are unable to drive and live in a place where there is no public transportation, then you should sell your nice cozy house, leave your nice cozy town and move to a city where there is adequate public transportation. Becoming dependent upon your family is nothing but a choice you (and sometimes your family) make. Ah yes, a brilliant suggestion. Just what anyone who has suffered a debilitating illness, accident or age related loss of physical and mental capacity should do: move away from everything and everyone they know so that they can start fresh as a mentally and/or physically disabled newbie in an unfamiliar place with no family or friends to turn to for help. We want employees that work for free! Actually they want 100% the opposite. They want revenue so they can continue to pay employees. If they had employees that would work for free they could just open source the product and stop worrying about revenue. The problem is, in most software companies if you allow your revenue to drop to zero your employees will likely leave when the paychecks start bouncing. I'm a huge proponent of Open Source, but if you're an existing company contemplating open sourcing your existing code base you'd better have a clear plan on where your revenue will come from or you'll end up a former company with abandoned open source dead project. This is one of the better Ask Slashdot questions recently. Spare batteries are all over the place. Airports in particular have shops where you can buy precharged ones. It's just that now they all have USB ports so they're all universally compatible rather than differing for each mobile device. I also have a battery *case* for my iPhone which allows me to charge it with a micro USB cable like everything else. No swapping required, just push a button to start or stop charging the internal battery from the case battery. On my last trip I traveled with a large battery with two USB outputs, one charger with a long cord and five USB outputs, and a couple of micro-USB cables. That's all I needed for my android phone, iphone, android tablet and Atom based Windows convertible laptop/tablet. Not a single device specific charger or spare battery in the lot (unless you consider the battery built into the iPhone case, which I don't because the case stays on the phone all the time and is no bigger than the otterbox case that many people use.) I'm glad the days of carrying multiple models of spare battery are over. Your stunning command of rhetoric is an inspiration elementary school children everywhere. (Well, the younger ones anyway. The older ones have likely surpassed you. Many of them even know the difference between "your" and "you're") I have docking stations at home and work so I get multiple large screens and trackballs for my laptop, but yesterday I received the AOC USB powered monitor that's been available for a while. I actually ordered the $90 older model. It's big and bulky (although not very heavy at all) but I plan to take it with me on the occasions when I'm expecting to be working in a non typical place AND needing extra space. I don't think I'd want to lug this slide enjoy thing all over the place. It may have a few specialized use cases, but in general you'd be better off if you have any way to get good quality display port monitors at your normal work places. Makes perfect sense to me. I talk to people on the phone all the time, but it seems rude to just call someone without first sending an instant message or text to ask if they're free. My usual response when someone IMs me asking if I'm free is to give them an estimate (usually 5-15 minutes) of how long I need to complete what I'm working on so that I'm free to talk. A phone ringing unexpectedly is an annoying interruption and listening to a voice mail is a nuisance. No AC required. USB powered, bridges wifi to RJ45.... Even with the added cost of a USB battery (or the sort available everywhere for recharging phones) it's still well under you $100 laptop as well as smaller and lighter. The OS configuration may be harder for people who are not familar with concepts like iptables and/or network namespaces. Just out of curiosity, when you say "Python" are you including iPython Notebook and Pandas and the rest of the SciPy/NumPy modules or are you comparing R strictly to "plain" Python scripts? But it has probably been drunk by at least one dinosaur. Why imagine when you can just buy them? Heated socks and vests and jackets and pants are hardly new. I got mine from Gerbing years ago but there are other brands as well. I can't tell what you're advocating, can you clarify? Are you making the case that planes shouldn't have black boxes? Or are you advocating that they shouldn't have insurance? If entropy is increasing, where is it coming from?
http://slashdot.org/~Paul+Carver
CC-MAIN-2015-40
refinedweb
1,517
65.86
How to convert map to JSON string in Java In this tutorial, we will learn how to convert Map to JSON String. For this, first of all, we will learn What is the map? Answer. The map contains the values on the basis of keys ie. key-value pair (as a dictionary in python). Each pair of key and value is known as the entry. The map contains unique values of keys. The map does not allow duplicate keys, but it can allow duplicate values. There are - Two interfaces for implementing maps( ie. Map and SortedMap) - Three classes for implementing maps(ie. HashMap, LinkedHashMap, TreeSet) as Map is an interface so we cannot create the object of Map, therefore, we use these classes. What is the JSON string? Answer. Full-Form of JSON is JavaScript object notation. It is a lightweight format, therefore we can say that it is more preferable to use (lighter than XML), and as a result, we use it for data-interchange. JSON is easy to read and write and language-dependent. Java program to convert Map to JSON String - First of all, we will import all the packages required ie. - java.util.*; - java.io.IOException; - org.codehaus.jackson.map.ObjectMapper; We use HashMap for creating a key-value pair ie. the map. HashMap allows null keys( but only once ), the null value( multiple times). We use - java.io.IOException for handling input-output Exceptions. We use a try-catch block for handling exceptions. - org.codehaus.jackson.map.ObjectMapper for converting java objects and matching JSON constructs ie. ( javascript object notation). For using org.codehaus.jackson.map.ObjectMapper we need to add the Jackson-all-1.9.0 jar file. Link to download jar-file:: 2. Then we will create a new class of any name. 3. After this, we will create the main method in our class. Java Code Below is given our desired Java code: import java.io.IOException; import java.util.*; import org.codehaus.jackson.map.ObjectMapper; public class JavaApplication27 { public static void main(String a[]){ ObjectMapper objmapper = new ObjectMapper(); Map<String, String> mapobj = new HashMap<String, String>(); mapobj.put("phone", "iphone x"); mapobj.put("imei number", "ankdk9495jfj"); try { String jsonoobj = objmapper.writeValueAsString(mapobj); System.out.println(jsonoobj); } catch (IOException e) { System.out.println(e); } } } objmapper is the object of the ObjectMapper class. * Map<String, String> mapobj = new HashMap<String, String>() helps us for creating map( ie. key-value pair).We can also use * HashMap<String, String> mapobj = new HashMap<String, String>() instead of the above one. Both the above statements are almost the same. Both statements are used for creating a map. We use mapobj.put(string, string) for entering values to the map. Further, in the try-catch block, we are using writeValueAsString of ObjectMapper class that creates JSON from java object and returns the generated JSON as a String. Then we are printing the generated JSON as a String with the help of variable jsonoobj. Also, read: Java Higher Order Functions
https://www.codespeedy.com/convert-map-to-json-string-in-java/
CC-MAIN-2020-45
refinedweb
501
69.79
Latest Happenings and Future of Groovy: 1.8, 2.0 and Beyond - | - - - - - - - Read later My Reading List Performance and productivity improvements have gone into recent editions (1.6, 1.7 and 1.8) of Groovy and more are on tap. Recently InfoQ got a chance to catch up with Guillaume Laforge, the project lead for Groovy. We spoke about the recent history of improvements to the Groovy language, a programming language that builds on top of Java syntax and adds languages features from Python, Ruby and Smalltalk as well as quite a few tricks of its own. We also spoke about what is on the plate for future Groovy development. Guillaume discussed improvements to Groovy for domain specific languages, performance improvements for handling integers, annotation triggered AST transforms, GPars parallel/concurrency library, new built-in language support for JSON, improvements to Grape package management, passing closures to annotations, improvements to closures to support recursive closure calls without fear of stack overflows, and much more. These are features available in Groovy 1.8. AST transformations streamline writing Groovy code without the boilerplate code, productivity killers, that other languages force you to write. Grape provides Maven/Ivy like package dependency management at the the Groovy script level so scripts can be run standalone and just fetch their dependencies. The ability to pass closures to annotations allows the creation of design by contract style development with Groovy. Guillaume also discussed Groovy adoption and what is on the roadmap for 1.9 and 2.0 as well as planned support for Java 7 features in Groovy including multi-catch and invoke dynamic. The invoke dynamic support could give Groovy a bump in performance overall. Guillaume mentioned Groovy adoption rates and how well Groovy is doing. Groovy has always allowed you to add types for documentation purposes, but it seems dynamic Groovy is going the Dart route of allowing static compile time checking as well, Guillaume covers this as well. InfoQ: Can you give us an overview of the latest novelties in Groovy 1.8? With Groovy 1.8, we worked on several fronts. First of all, Groovy is well known for its ability to author Domain-Specific Languages, for writing expressive and readable business rules. For that purpose, we introduced a grammar enhancement (called "command chains") that allows developers to create nicer DSLs, by allowing you to make more dots and parentheses optional for chained method calls. With this approach, you can even write plain English sentences in your DSLs! We also continued our runtime performance improvements, in particular in the area of primitive type calculations. As long as you don't do any monkey patching on numbers or such, and if you specify your variables to be of primitive types, Groovy is able to use the JVM bytecode instructions, like iadd to add two ints together, rather than doing the boxing / unboxing dance and calling methods on Integer and friends. That way, the performance of your primitive calculations becomes much closer to Java than they were with older versions of Groovy. Besides that, the Groovy distribution now includes the GPars parallel and concurrent library. We've worked on adding a few more utilities further improving the functional flavor of our Groovy closures. We added support for dealing with JSON payloads. And we added several new useful AST (Abstract Syntax Tree) transformations, and some handy control tricks to customize the Groovy snippets you may be integrating in your application (for instance, preventing infinite loops, or such). For some more details on all these features, don't hesitate to have a look at the release notes of Groovy 1.8 . InfoQ: What are AST transforms and how are developers using them? AST Transformations stand for Abstract Syntax Tree transformations. It's somehow a compiler plugin, if you will. The AST is the in-memory representation of your program, made of class, method, property, statement, variable nodes, etc, before it gets compiled to Java bytecode. AST transformations are the ability to hook into the Groovy compilation process, and let you modify the structure of your program, before we generate the final bytecode for the class. With that capability, you are able to add new methods, add checks in your code transparently, generate some other classes, etc. It opens up a lot of interesting possibilities. There are two kinds of such transforms in Groovy: local and global transformations. Global ones are applied to every compilation unit, whereas local ones are triggered by annotations. For the latter, for example, you could annotate a class with @ToString to invoke the transformation that adds a nice default toString() implementation in your class. Developers are using such transforms to further simplify the life of their users, by doing some compile-time metaprogramming, instead of the usual dynamic runtime meta-programming that people use with dynamic languages. This has the nice benefit of being a compilation feature, which doesn't add a particular overhead at runtime. And overall, it's generally for making users' code even more expressive and concise. InfoQ: Can you give us a few examples of the AST transformations that were added to Groovy? Groovy 1.6 and 1.7 introduced several useful transforms, such as @Delegate for having methods delegated to one of your fields annotated with that annotation, or @Immutable to make your class immutable, as the name implies. Groovy 1.8 adds several new useful transforms such as the various @Log transforms to inject a logger in your classes and wrap your logging statements with the required "if" checking the log level, @InheritConstructors to add constructors implementing the super constructors and delegating to them (think for instance when you have to extend an Exception class), @WithReadLock / @WithWriteLock to simplify the use of java.util.concurrent's ReentrantReadWriteLock. There's the combination of @ToString, @EqualsAndHashCode, @TupleConstructor and @Canonical, to add toString(), equals(), hashCode() methods, and a constructor with the various properties you've declared as parameters. As usual, the objective of all these new transforms is to let developers streamline their code by focusing more on the business code they need to write, than on the nitty-gritty boilerplate they were forced to write with other languages. Productivity of the language is key to successful projects! InfoQ: How hard it it to write your own AST transforms? To write AST transforms, you'll need to have some knowledge of the Groovy AST APIs. So it's not totally trivial. But thankfully, Groovy has a few tricks in its bag to help you author your transforms. First of all, with the Groovy console, you are able to see the structure of the Groovy AST so that you can mimick what you see there for the piece of code you want to generate or modify. There's also the AST Builder class which offers 3 different mechanisms for building pieces of AST, from a code fragment, from the code included in a closure, or using a builder API for constructing the AST structure yourself in a less verbose manner than manipulating the AST classes directly. Writing AST transforms is a fair bit of work, but Groovy helps you in this task. InfoQ: What is GPars? Who uses it? Why was it included with Groovy 1.8? A few years ago, the Groovy team was interested in the trends of computing which sees our computers becoming more parallel (multiple processors, multiple cores). It was clear back then already that Groovy needed to support this trend, by offering higher level of power and expressiveness to tackle the parallelism and concurrency problems. Java and the JDK offer some primitives like threads, and the various wait / notify / notifyAll methods, and more recently all the nice additions to the java.util.concurrent packages. Groovy obviously offers some improvements in its core for these aspects, but higher level concepts exists that we wanted to provide to our users. That's how the GPars project, lead by JetBrains' advocate Vaclav Pech, came to be, because we wanted to offer higher level features, such as Actors, Dataflow concurrency, Software Transactional Memory, Agents, and various enhancements to java.util.concurrent's executors, parallel arrays, fork / join, map / filter / reduce, etc. GPars is a project in its own right, with its own roadmap. Initially, we had thought of merging it inside Groovy directly, but with the community that gathered around the project, and to let it evolve at its own pace, we chose to embed it in the Groovy distribution instead. In passing, what's also nice with GPars is that it's not just a Groovy parallel / concurrency library, but it also supports a Java API so you can use it from Java as well, without enforcing the usage of Groovy as a language -- although of course the code won't be as compact with Java. Don't hesitate to have a look at the GPars project for your next concurrent and parallel needs . And in particular look at the detailed GPars user guide. InfoQ: What is grape and how has it been improved? Grape, with its @Grab annotation, is a feature that let you define dependencies that your script, or even class, may need. For example, I could add in my script: @Grab("groupId:artifact:version") to an import, and Groovy will download and cache the dependency so that it's available on the classpath when executing your script. It's very handy when you want to share scripts with your co-workers, because you just need to share the script itself, and you don't need to package the dependencies or such. In Groovy 1.8, the enhancements are around the string value passed to that annotation, and to the @GrabResolver annotation (for specifying a specific repository), to have a compact notation to describe your dependencies and their origin. InfoQ: What support has been added for reading and producing JSON? JSON is everywhere nowadays, and more and more REST APIs blossom on the Web only offering JSON payloads. Groovy's always been great at handling XML, both for consuming and producing XML content with its XML builders and parsers, so we wanted to add the same level of support in Groovy 1.8 for JSON. So we introduced a "slurper" that parses JSON content, as well as a streaming and non-streaming "builder" that let you build JSON payloads, in very concise ways, without the need of implementing some special marshalling. As examples, if you wanted to create a person JSON object, you could write: def json = new JsonBuilder() json.person { name "Guillaume Laforge" age 34 } Which would generate: { "person": { "name": "Guillaume Laforge", "age": 34 } } Of if you parse the commit messages from the Groovy repository mirror on GitHub, you could write this: import groovy.json.* def endpoint = "" def content = endpoint.toURL().text def parser = new JsonSlurper() def commits = parser.parseText(content) // navigate the object graph // and print each commit message commits.commit.message.each { println it } This JSON support is very similar to Groovy's existing XML support, and makes life much easier to handle JSON documents. InfoQ: You mentioned some improvements to closures, especially for their functional flavor, what can you tell us about these? Groovy's first-class citizen closures as well as all the methods of the Groovy Development Kit enhancing the various JDK collection classes (each / collect / findAll / etc.) are the basis of the functional capabilities of Groovy. They let you iterate, filter, transform collections and their values, and many more things. In Groovy 1.8, we added a trampoline() method to closures which allows you to stack up closure invocations serially for your recursive algorithms, rather than exploding the stack with recursive calls. A closure function like factorial would calculate results for up to 40 or more, but fail beyond with a StackOverflowException, whereas a slightly rewritten implementation using the trampoline() call on your closure will let you calculate factorial(1000) and higher without blowing. Closures are now composable and reverse composable with the left shift << and right shift operators >> respectively, so you can compose the computation of your closures, and get a new closure in return that you can call and pass around. We've also added a memoize() function which remembers the outcome of previous invocations of your closure for a given set of parameter values. This is particularly handy for calculations that might take a long time, but be careful, as your closures should be side-effect free and always return the same results for the same parameter values, otherwise you'd easily get some surprises in your results! The memoization feature is using an LRU cache, but there are variants of that method which let you have finer control over the cache, by letting you decide how many results you want to cache. InfoQ: Annotations can now take closures as parameters. Why is it important to pass closures to annotations? What type of annotation could you build that took closures? Java annotations are somewhat limited in that they accept just a limited set of possible of values: primitives, strings, annotations, classes and arrays of these. But you cannot pass instances of your own classes, or things like that. Groovy goes a bit beyond what annotations allow by encoding closures in the form of closure classes -- so Java is happy to see a Class as parameter. With annotation closure parameters, you annotate fields or methods with things like @Validate({ name.size() > 0 }), if you want to add some validation rules to your methods parameters or field values. This is going to be useful for framework developers as well. This has been already used by the GContracts library which adds the "Design by Contract" paradigm to Groovy by using annotation closure parameters, for implementing pre- / post-conditions, invariants, and so on. So have a look at GContracts to have a little taste of what you can achieve with that feature. InfoQ: Which IDE do you use to do Groovy programming? I'm using Eclipse SpringSource Tool Suite and IntelliJ IDEA. I've been developing with IntelliJ IDEA for about 8 years or so, so I'm very used to that IDE, and spend more time with it than with Eclipse. But both IDEs really provide awesome support for Groovy and Grails, with all the usual features you'd expect (code browsing, navigation, hovers, refactorings, debugging, running, and more). Both are very good choices if you've developing with Groovy and Java. I've also heard that NetBeans are in the process of updating their aging Groovy support as well, so NetBeans might get back on track with its competitors here soon. InfoQ: How is Groovy adoption going? Is it increasing? Does the community seem to be getting bigger? For Open Source projects like languages or other libraries, it's not easy to track the adoption rates. So you have to look at various indicators, like numbers of persons subscribed to the mailing-lists, download statistics, or even more subjective elements like online or conference polls about favorite alternative languages and such. From those few elements, Groovy is doing very well and is increasing, and seems to be the most popular alternative language on the JVM these days. For example, if we look back at the download stats from our previous release, in just two months, we had already accumulated close to 400K downloads of the Groovy distribution at Codehaus -- the foundation that hosts the Groovy project. And that number is not even accounting for the Maven Central downloads or the other projects using Groovy like Grails, Gradle, Griffon, etc! So a pretty pessimistic estimate would lead me to think we have at least half a million Groovy users out there! It could possibly be more than twice that number but it's very hard to tell exactly. InfoQ: What's going to be the next major version of Groovy, and what will it provide? We updated our roadmap recently to revise our version number scheme a little. The next version will be Groovy 2.0, instead of 1.9 as initially envisioned, since we have added some very interesting features and believe it deserved a full version bump. We have some other exciting changes in store so you might see the version incrementing a little faster than it has previously. We won't go as fast as Google Chrome or Mozilla Firefox in terms of version number increase, but we'll continue on our trend of releasing a major version a year or so. The expected release of Groovy 2.0 should be at the end of the first quarter of 2012. So what are we working on in Groovy 2.0? Well, three major features: JDK 7 support with invoke dynamic support and project coin enhancements, static type checking, and we're investigating adding static compilation as well. First of all, for those who will have upgraded to JDK 7 and its invoke dynamic bytecode instruction and APIs, you'll be able to get the performance boosts for all the dynamic aspects of Groovy. The exact gain is still unsure at this stage, but we're confident that this support should continue increasing the performance of the Groovy runtime. Ultimately, for later versions of Groovy that would be based on JDK 7+, we would even be able to get rid of some optimizations we've built over the course of time to make Groovy faster, thus making Groovy a bit slimmer by relying on JDK's own classes and JIT optimizations. For those who are still on JDK 5 and 6, we're looking at the invoke dynamic backport, or into different code path in our code base to continue supporting those older versions of the JDK, so that our users don't have to upgrade to JDK 7 as a requirement for using a newer version of Groovy. You will also be able to use the Project Coin enhancements of Java 7, such as the multicatch, the binary literals, or underscore in literals -- others like string in switch didn't even need to be implemented, since Groovy's switch accept much more than primitives, strings, etc. What's interesting here, by the way, is that those language enhancements will also be available for older JDKs, and you won't have to upgrade to JDK 7 to get your multicatch clauses, for example. Next, static type checking. Throughout the years, we've noticed that a good share of our users are integrating Groovy in their applications as a Java scripting language, Groovy being an almost superset of Java. Those users would not use all the dynamic features of the language, and would just code in Groovy the same kind of things they'd code in Java, manipulating their internal APIs, etc. A common complaint of that user base is that Groovy would complain only at runtime that some typos in method names or variables were made, rather than catching such errors at compilation time. So Groovy 2.0 introduces a @TypeChecked annotation which will let you annotate a method or a class for which you want static type checking to happen. It does some clever type inference, checks methods and variable names, verifies correct assignments, and so on. With all the cleverness of that static type checking mode, the Groovy compiler knows a lot more about your code than ever before, and it opens up an interesting possibility. For those parts of your code base where you're not doing advanced metaprogramming tricks, and that are correctly type checked, we are in a position to generate the same kind of bytecode as Java, bypassing the Meta-Object Protocol of Groovy. The MOP is what makes Groovy dynamic, but in those parts where you don't need all the dynamicity of Groovy, but you want performance as fast as Java, you could use static compilation! And that's what we're investigating in Groovy 2.0. So we're actively discussing those two aspects, static type checking and static compilation, within the Groovy community these days. So don't hesitate to join the discussion there if you want to give your input. Rate this Article - Editor Review - Chief Editor Action Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think Go go! by 孙 奇辉 Re: Go go! by Guillaume Laforge Re: Go go! by 孙 奇辉 Here Fantom author wrote:Fantom vs Kotlin (and other JVM langs) fantom.org/sidewalk/topic/1581 Groovy IDE support by Richard Hightower Groovy, like many languages that JetBrains supports, has excellent IDE support in IntelliJ. I'd say the support rivals that of Java. Also if you use types, as Groovy has always allowed, code completion and refactoring works really well. Groovy + IntelliJ = a much more productive combination than Java + Eclipse IMHO. That said, I mostly use Java + Eclipse these days. Oh the irony! I have never and I mean never liked the support I got for Groovy with Eclipse and/or NetBeans. Utter nonsense. It may be better now. But... ack!!!! Fantom, Kotlin, Dart (the one that runs in the JVM), Groovy, JRuby, Scala, Ceylon, Jython, Clojure etc. the choices are many.
https://www.infoq.com/news/2011/11/groovy-updates/
CC-MAIN-2016-30
refinedweb
3,550
60.14
scalaz-nettyscalaz-netty Getting StartedGetting Started First, you'll need to add the RichRelevance Bintray resolver setting to your SBT file: resolvers += "RichRelevance Bintray" at "" If you want to be able to use snapshot releases, replace releases with snapshots. With the resolver configured, add the following dependency specification: libraryDependencies += "org.scalaz.netty" %% "scalaz-netty" % "0.4.2" Builds are published for Scala 2.11.8, and for 2.12.x for versions at or above 0.4.2. The latest stable release is 0.4.2. Versions that end in 'a' in the 0.3.x series use scalaz 7.2.x, versions without use scalaz 7.1.x. The 0.3.2 versions contain one additional feature over the 0.3,, which has only been tested on Linux and may not work elsewhere. The upstream dependencies for this project include the following: For version 0.4.1 and 0.4.2: - scalaz 7.2.7 - scalaz-stream 0.8.6a - scodec-bits 1.1.2 - netty 4.0.42.Final For version 0.4: - scalaz 7.2.5 - scalaz-stream 0.8.4a - scodec-bits 1.1.0 - netty 4.0.40.Final For version 0.3 and 0.3.2: - scalaz 7.1.7 - scalaz-stream 0.8 - scodec-bits 1.0.12 - netty 4.0.36.Final And for version 0.3a and 0.3.2a: - scalaz 7.2.2 - scalaz-stream 0.8a - scodec-bits 1.0.12 - netty 4.0.36.Final Snapshot releases follow the version scheme master-<sha1>, where the " sha1" component is the Git commit that was snapshotted. Not all commits will have corresponding snapshot releases. You can browse the list of snapshot releases on bintray. ExampleExample import scalaz.netty._ import scalaz.stream._ import scalaz.concurrent._ import java.net.InetSocketAddress import scodec.bits.ByteVector /* * A simple server which accepts a connection, echos the incoming * data back to the sender, waiting for the client to close the connection. */ def log(msg: String): Task[Unit] = Task.delay(println(s"$msg")) val address = new InetSocketAddress("localhost", 9090) val EchoServer = merge.mergeN(Netty server address map { incoming => for { exchange <- incoming _ <- Process.eval(log("accepted connection")) _ <- exchange.read to exchange.write } yield () }) /* * A simple client which sends ByteVector(1, 2, 3) to the server, * prints its response and then shuts down. */ val BasicClient = Netty connect address flatMap { exchange => for { _ <- Process(ByteVector(1, 2, 3)) to exchange.write data <- exchange.read take 1 _ <- Process.eval(log(s"received data = $data")) } yield () } // Usage: // scala> EchoServer.run.runAsync(_ => ()) // press Enter when this completes to acquire new prompt // scala> BasicClient.run.run Future WorkFuture Work - Byte buffers are copied upon receipt. The only way to safely address this problem will be to integrate with Scodec and decode against the directly allocated byte buffers. Not hard to do, really... - Exceptions probably don't propagate properly under all circumstances. LicenseLicense Licensed under the Apache License 2.0. For more information, please see LICENSE.txt. Opening a pull request signifies your consent to license your contributions under the Apache License 2.0. Don't open a pull request if you don't know what this means.
https://index.scala-lang.org/richrelevance/scalaz-netty/scalaz-netty/0.4?target=_2.11
CC-MAIN-2021-49
refinedweb
530
56.42
current position:Home>[Python crawler] multithreaded daemon & join() blocking [Python crawler] multithreaded daemon & join() blocking 2022-01-30 22:31:01 【Dream, killer】 「 This is my participation 11 The fourth of the yuegengwen challenge 2 God , Check out the activity details :2021 One last more challenge 」. The collection Python Reptiles are slow ? Learn about concurrent programming The guardian thread stay Python In a multithreaded , After the code of the main thread runs , If there are other child threads that have not been executed yet , Then the main thread will wait for the execution of the child thread before ending ; This will create a problem , If a thread is set to infinite loop , That means the whole main thread ( Python Program ) It can't end . Let's take a look at . import threading import time # Non-daemon thread def normal_thread(): for i in range(10000): time.sleep(1) print(f'normal thread {i}') print(threading.current_thread().name, ' Thread start ') thread1 = threading.Thread(target=normal_thread) thread1.start() print(threading.current_thread().name, ' Thread end ') Copy code The above results can be seen , The main thread ( MainThread ) Although it's over , But the child thread is still running , When the child thread runs , The whole process is just beginning The real end . If you want to terminate the main thread while terminating other unfinished threads , You can set the thread to The guardian thread , If only the daemon thread is still executing and the main program ends , that Python The program can exit normally . threading Module provides two ways to set daemon threads . threading.Thread(target=daemon_thread, daemon=True) thread.setDaemon(True) import threading import time # The guardian thread ( Mandatory waiting 1s) def daemon_thread(): for i in range(5): time.sleep(1) print(f'daemon thread {i}') # Non-daemon thread ( No forced waiting ) def normal_thread(): for i in range(5): print(f'normal thread {i}') print(threading.current_thread().name, ' Thread start ') thread1 = threading.Thread(target=daemon_thread, daemon=True) thread2 = threading.Thread(target=normal_thread) thread1.start() # thread1.setDaemon(True) thread2.start() print(threading.current_thread().name, ' Thread end ') Copy code The above will thread1 Set to daemons , The program is in Non-daemon thread And The main thread ( MainThread ) After completion of operation , End directly , therefore daemon_thread() The output statement in did not have time to execute . The output in the figure shows MainThread Thread end Still outputting normal_thread() What's in the function , as a result of It will take some time from the end of the main thread to the forced stop of the daemon thread . Inheritance of daemon threads The child thread will inherit the current thread's daemon attribute , The main thread defaults to Non-daemon thread , Therefore, the new threads in the main thread are also... By default Non-daemon thread , But in The guardian thread When a new thread is created in , Will inherit the current thread daemon attribute , So is the child thread The guardian thread . join() Blocking In a multithreaded crawler , Generally, multiple threads crawl the information of different pages at the same time , Then, it is analyzed and processed uniformly , Statistical storage , This requires waiting for all child threads to execute , To continue the following processing , And that's where it comes in join() The method . join() The function of the method is to block ( Hang up ) Other threads ( The thread that is not started is different from the main thread ), Wait for the called thread to run, and then wake up the operation of other threads . Look at an example .1.join() thread2.start() print(threading.current_thread().name, ' Thread end ') Copy code It's just for thread1 Use join() , Pay attention to join() The location of , It's in thread2.start() Performed before startup , After execution thread2 And the main thread are suspended , Only thread1 After thread execution , thread2 And The main thread will execute , Because here thread2 Not a daemon thread , So when the main thread ( MainThread) After execution , thread2 Will continue to run . See here , Is there a question ? If you follow the execution process of the above code , The whole program has completely become a single threaded program , That's why join() Caused by improper use position of . Let's change the above code a little .2.start() thread1.join() print(threading.current_thread().name, ' Thread end ') Copy code Now the program is really multithreaded , Now we use join() When the method is used , Only the main thread is suspended , When thread1 After execution , To execute the main thread . Finally, we need to explain , join() Method blocking is object independent , And whether to guard threads , Whether or not the main thread is irrelevant . Attention should be paid when using , To really multithread, you need to start all the sub threads , Call again join() , Otherwise it will become a single thread ! This is all the content of this article , If it feels good . Let's go with a compliment !!! For beginners PythonOr want to get started PythonLittle buddy , You can search through wechat 【Python New horizons 】,
https://en.pythonmana.com/2022/01/202201302231000486.html
CC-MAIN-2022-27
refinedweb
831
53.65
#include <qgsfillsymbollayerv2.h> Reimplemented from QgsFillSymbolLayerV2. Color for endpoint of gradient, only used if the gradient color type is set to SimpleTwoColor. Color ramp used for the gradient fill, only used if the gradient color type is set to ColorRamp. Coordinate mode for gradient. Controls how the gradient stops are positioned.gsSymbolLayerV2. Gradient color mode, controls how gradient color stops are created. Gradient spread mode. Controls how the gradient behaves outside of the predefined stops Type of gradient, eg linear or radial. Implements QgsFillSymbolLayerV2. Rotation angle for gradient fill. Can be used to rotate a gradient around its centre point Reimplemented from QgsFillSymbolLayerV2. Offset for gradient fill. Units for gradient fill offset. Starting point of gradient fill, in the range [0,0] - [1,1]. Sets the starting point of the gradient to be the feature centroid. End point of gradient fill, in the range [0,0] - [1,1]. Sets the end point of the gradient to be the feature centroid.
https://api.qgis.org/2.6/classQgsGradientFillSymbolLayerV2.html
CC-MAIN-2020-34
refinedweb
160
53.27
Bart De Smet's on-line blog (0x2B | ~0x2B, that's the question) Note: This post is part of the follow-up for the Developer & IT Pro Days 2007 session entitled "Internet Information Services (IIS) 7.0 - End-to-End Overview of Microsoft's New Web Application Server". Attendees will be able to download the slides and will get the video recording of the entire session as well. Using these posts, attendees should be capable of reproducing the entire demo part of the session. Furthermore, others who didn't attend the session will be able to get a better idea of what IIS 7.0 provides by following the demo steps outlined in these posts. In order to implement the demos, one should have IIS 7.0 installed on Windows Vista (or Windows "Longhorn" Server). One of the most exciting pillars of IIS 7.0 is its extensibility mechanism. In the dark ages of IIS 5.0 and IIS 6.0 (not to speak about the stone ages of IIS 4.0) the story around extensibility wasn't particularly good. As the matter in fact, there was the (difficult) world of ISAPI for unmanaged code developers, while managed code developers were rather limited in their extensibility capabilities, living in their ASP.NET stack. Let's explain the extensibility pain in IIS 6.0 in some more detail, by looking at the HTTP pipeline: What you're looking at is the pipeline that lives in a worker process of the web server. Requests come in at the very left bottom corner of the image, flowing through the unmanaged code stack on the left. Upon receival of a request, it passes the ISAPI filters, on to various "modules" for logging, custom errors, etc finally reaching the determine handler stage. In there, the extension of the request (more or less) is inspected to find out the party responsible for further request processing. Assume for now that the extension is .aspx, causing the web server to load the ISAPI for ASP.NET which is implemented in aspnet_isapi.dll (recall the aspnet_regiis.exe /i stuff used to register ASP.NET with the IIS server, which creates these mappings). Now we're on the right-hand side of the picture, having the request flow through a series of managed code HTTP modules (implementing IHttpModule) that have indicated their interest in certain events (like Begin_Request). Again, we reach a phase where the request is mapped on to an appropriate handler, which happens to be PageHandler in case of .aspx requests, effectively serving the request and generating a reponse. Finally, the response flows through the inverse path, back to managed code HTTP modules, on to the left-hand side again, flowing through module stuff in IIS and ISAPI filters. So, what are our conclusions? A few observations: IIS 7.0 gets rid of this problem by making managed code and unmanaged code extensibility both first class citizens in the web server. This is achieved by means of a so-called unified pipeline, as illustrated below: In the center of the slide, you can see the unified pipeline implemented in the core IIS 7.0 web server engine. This pipeline has intrinsic knowledge of both native modules as well as managed code IHttpModule modules. At any stage of the pipeline, any kind of module can be invoked to do some processing (like logging, authentication and authorization assistance, caching, etc). Finally, when we reach the execute handler stage, mapping on an appropriate handler - native or managed - is performed in order to finalize the request processing. Notice that ASP.NET is no longer registered as a separate ISAPI with the web server, it has become an intimate friend of IIS 7.0 :-). Time for the demo; let's create a simple logging module using managed code. using System; using System.Web; HttpApplication app = sender as HttpApplication; if (app != null) { string path = app.Server.MapPath(String.Format("~/logs/{0:yyyyMMdd}.txt", DateTime.Now)); using (FileStream fs = File.Open(path, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("{0:HH:mm:ss} - {1}", DateTime.Now, app.Request.Url); } } } <httpModules> <add name="Logger" type="HttpLogger" /> </httpModules> <system.webServer> <modules> <add name="Logger" type="HttpLogger" /> </modules> </system.webServer> You can download the sample code over here. Enjoy and stay tuned for the next parts in this series! Note: This post is part of the follow-up for the Developer & IT Pro Days 2007 session entitled "Internet
http://community.bartdesmet.net/blogs/bart/archive/2007/04/04/extending-iis-7-0-part-1-a-simple-http-logging-module.aspx
crawl-002
refinedweb
747
58.18
From: Jan Langer (jan_at_[hidden]) Date: 2002-11-12 13:36:11 Edward Diener wrote: > 1) Are the get(), put() functions somewhere, like in the boost namespace ? > Is there a doc for the parameters these functions take, or is it the intent > that if one wants to use them, one looks in the source code to figure them > out ? > > 2) What is the necessary interface to a property map which you mention > above. I see property map categories, property traits, property map types, > but I am missing an understanding from the documentation of the necessary > interface for creating a property map ? there are subpages for each property map category. perhaps you have missed to read them. the first time i read the property map doc i somehow missed these subpages and was also had problems understanding the documentation. eg:
https://lists.boost.org/Archives/boost/2002/11/39404.php
CC-MAIN-2019-22
refinedweb
139
60.55
As HD mentioned, F5 has been inadvertently shipping a static ssh key that can be used to authenticate as root on many of their BigIP devices. Shortly after the advisory, an anonymous contributor hooked us up with the private key. Getting down to business, here it is in action: 18:42:35 0 exploit(f5_bigip_known_privkey) > exploit [ ] Successful login [*] Found shell. [*] Command shell session 3 opened ([redacted]:52979 -> [redacted]:22) at 2012-06-22 18:42:43 -0600 id; uname -a uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) Linux [redacted] 2.4.21-10.0.1402.0smp #2 SMP Mon Feb 15 10:23:56 PST 2010 i686 athlon i386 GNU/Linux ^Z Background session 3? [y/N] y 18:42:35 1 exploit(f5_bigip_known_privkey) > Of course, since it's just a regular ssh key, you can easily just drop it in a file and use a standard ssh client. ssh -i ~/.ssh/f5-bigip.priv root@8.8.8.8 The advantage of using Metasploit to exploit this weakness is in the session management and rapid post-exploitation capabilities that the framework offers. This bug is also interesting in that it gave us a good test case for using static SSH credentials as an exploit module rather than auxiliary. The key difference between exploit and auxiliary modules is usually the need for a payload. If it needs a payload: exploit. Otherwise, it's auxiliary. In this case it's a little blurry, though, because it results in a session, which is typically an exploit trait. Some of our authentication bruteforce scanners get around this with some ruby acrobatics so they can still create a session despite not having a payload or a handler. From a module developer perspective, this exploit has a few interesting aspects that you won't see elsewhere. First, and probably most important, it doesn't upload a payload to the victim. The connection itself becomes a shell, so it doesn't need to but that presents a bit of a problem with the framework's design. Fortunately there is a payload for exactly this situation: cmd/unix/interact. This simple payload is different from most; all it does is shunt commands from the user straight to the socket and back. It uses a "find" handler similar to the way a findsock payload works. To tell the framework about the payload and handler this exploit will require, we need a block in the module info like so: 'Payload' => { 'Compat' => { 'PayloadType' => 'cmd_interact', 'ConnectionType' => 'find', }, }, Since there is really only one payload that works with this exploit, it also makes sense to set it by default: 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/interact' }, Next, it uses our modified Net::SSH library to connect to the victim. Most exploits will include Msf::Exploit::Remote::Tcp or one of its descendants; those related mixins all set up the options everyone is familiar with: RHOST, RPORT, etc. Since this one does not, we have to do it manually like so: register_options( [ # Since we don't include Tcp, we have to register this manually Opt::RHOST(), Opt::RPORT(22), ], self.class Lastly, because the handler is of type "find" we must call handler() to get a session. Most Remote::Tcp exploits don't have to do this if they are not compatible with "find" because the handler will spawn a session whenever a connection is made (either reverse or bind). However, all exploits that are compatible with "find" payloads must call handler() at some point. Normally there is a global socket created by the Tcp mixin when you call connect() but in this case it is necessary to let the handler know our socket is now a shell. def exploit conn = do_login("root") if conn print_good "Successful login" handler(conn.lsock) end end This was a fun module to write. The devices it targets can be a goldmine for a pentester who likes packets since they're basically a giant packet sink that lets you read and modify traffic willy nilly. ARP spoofing is noisy and DNS poisoning is hard, let's just own the firewall.
https://www.rapid7.com/blog/post/2012/06/25/press-f5-for-root-shell/
CC-MAIN-2021-31
refinedweb
695
58.92
X-Posted from my use.perl journal (though this meditation is a bit different). I know many would rather not see another module in the XML namespace, but I've started putting together a proof of concept called XML::Composer (it was originally called XML::JFDI with apologies to Jesse). It will let you write really, really bad XML. It will also allow you to write XML "variants" like the awful Yahoo! IDIF format. Namespaces? It doesn't know about 'em or care about 'em. If you want to use a colon in an attribute name, go ahead. Want to inject an XML snippet from somewhere else? Go ahead. It will simply do whatever you tell it to do. It's a sad fact of life that there's a lot of bad XML "variants" out there that we, as developers, have to live with (maybe this module should be called XML::Awful). The primary idea is to be able to write XML in just about any format you want. Frequently this means that it will cheerfully produce bad XML, but rather than spend hours scouring the docs only to find yourself reporting another bug, you can quickly and easily tweak what you want. Unfortunately, most of the modules in the XML namespace are geared towards producing correct XML. Sometimes you need to produce bad XML so you roll your own XML generator and hope no one ever sees it. The aim of XML::Composer is to make bad XML easy to write. If you have to produce it, at least you should produce it as easily as possible. use XML::Composer; my $xml = XML::Composer->new({ # tag method 'ns:foo' => 'foo', 'bar' => 'bar', 'ns2:baz' => 'baz', }); $xml->Decl; # add declaration (optional) $xml->PI('xml-stylesheet', {type => 'text/xsl', href="$xslt_url"}) +; $xml->foo( { id => 3, 'xmlns:ns2' => $url}, $xml->bar('silly'), $xml->Comment('this is a > comment'), $xml->Raw('<bad tag>'); $xml->baz({'asdf:some_attr' => 'value'}, 'whee!'), ); print $xml->Out; if ($xml->Validate) { # false for above example } __END__ <?xml version="1.0"> <?xml-stylesheet type="text/xsl" href="$xslt_url"?> <ns:foo <bar>silly</bar> <!-- this is a > comment --> <bad tag> <ns2:baz asdf:whee!</ns2:baz> </ns:foo> [download] This module (not yet on the CPAN) assumes that you, the programmer, know what you're doing. It's designed for agile development: produce something quickly but have a test suite to verify that your output is correct. In short, there is a very specific design philosophy here and I wouldn't recommend it for those who don't have test suites, but it makes coding very fast (and no, it doesn't use AUTOLOAD to build those methods). Thoughts? Cheers, Ovid New address of my CGI Course. How about calling it XML::Composter? Garbage in, garbage out! After Compline,Zaxo Bwahahaha! Brilliant. This deserves more than the one ++ I can give. Makeshifts last the longest. You should go talk to a gardener. Garbage in, garbage out? More like Garbage in, good natural fertilizer out. So I don't think "Composter" is the right term. Also ... I don't think the "XML::Awful" is a good name. That's unnecessary duplication. "XML" eq "Awfull". Jenda -sam Actually, it can be used to generate perfectly valid XML and it's pretty easy to do. The main thing is that it trusts you to actually know what you're doing. So long as you have decent tests, there shouldn't be a problem. Since it has the potential (according to the user's skill/intent) of being either perfectly compliant with or unconstrained by certain XML "constraints", perhaps better to call it "Text::XMLout" (oops, there's that tongue in the cheek again), or even just Text::XML (there's nothing by either name as yet). (update: in case anyone missed the pun, the Webster's definition of "Lout" is "noun: an awkward brutish person") So which modules am I supposed to use if I want to make XML? The very few times I've had to deal with this I found myself having to manually encode data for interpolation into a string area. I also found that XML::Simple made it difficult to create XML that had the tags in all the right order so it would still pass DTD validation. So please let me know what is actually supposed to be used and probably include that in your module too. Monk 1: What X should I use? Monk 2: My favourite is a. Monk 3: Oh, I always use b. b rules! Anonymonk 1: Oh, come on, b is the sux0r! It can't even handle z properly Monk 3: Can't we just get rid of anonymonks? They're such a pain. Monk 4: Everyone I know is using c. Seems to do the job for me ... Translation: oi, you could start a flamewar with a question like that. :-) I may not have many tools in my XML toolbox, but XML::Twig has seemed to handle everything so far. Admittedly it won't handle "bad" XML as Ovid is trying to do, but for "good" XML production, I've been quite happy with XML::Twig. My requirements when I chose XML::Twig were to be able to read in an XML template, look up data from other data sources, process it, and insert transformed data into the XML template, and then have that parsed/used by a Java application where order usually mattered. XML::Twig allowed me to turn around that project in a matter of time that impressed me. YMMV There are tons of modules that let you write XML. <snark>Which one you want to use depends upon which set of bugs you want to avoid</snark>. Seriously, XML::Genx and XML::Writer are both fairly decent thought getting namespaces to work can be excruciatingly painful. So which modules am I supposed to use if I want to make XML I tend to use either Template Toolkit or HTML::Mason. I just modified my code so that attributes are passed in an array reference instead of a hash reference, thus preserving attribute order. Update: I modified it again so it takes either a hashref or an arrayref. The only thing I'd love to see is a way of parsing XML-like data so that the crap you have to hand-roll a parser for is easier to work with. Though, I'm pretty sure this is beyond the scope of this module. In short, there is a very specific design philosophy here and I wouldn't recommend it for those who don't have test suites, but it makes coding very fast Maybe the coding is faster, but what about debugging, especially in the case of bad xml? If your goal is to make it easier to generate XML quickly, perhaps a wrapper to lessen the book-keeping code on one of the existing modules might be a better approach. The wrapper doesn't work. There are many companies that routinely generate and use XML that is not well-formed. While it's terrible to have to work with this, most existing XML modules don't play with with poorly formed XML (as well they shouldn't). Also, debugging is a snap. Unlike the existing modules, the interface is very transparent. You get exactly what you ask for. 1. Keep it simple 2. Just remember to pull out 3 in the morning 3. A good puzzle will wake me up Many. I like to torture myself 0. Socks just get in the way Results (283 votes). Check out past polls.
http://www.perlmonks.org/index.pl?node_id=496522
CC-MAIN-2016-44
refinedweb
1,273
73.27
table of contents NAME¶ punycode_decode - API function SYNOPSIS¶ #include <punycode.h> int punycode_decode(size_t input_length, const char [] input, size_t * output_length, punycode_uint [] output, unsigned char [] case_flags); ARGUMENTS¶ - size_t input_length - The number of ASCII code points in the input array. - const char [] input - An array of ASCII code points (0..7F). - size_t * output_length - The caller passes in the maximum number of code points that it can receive into the output array (which is also the maximum number of flags that it can receive into the case_flags array, if case_flags is not a NULL pointer). is greater than that. - punycode_uint [] output - An array of code points like the input argument of punycode_encode() (see above). - unsigned char [] case_flags - A NULL pointer (if the flags are not needed by the caller) or an array of boolean values parallel to the output array.. DESCRIPTION¶ Converts Punycode to a sequence of code points (presumed to be Unicode code points). Return value: The return value can be any of the Punycode_status values defined above. If not PUNYCODE_SUCCESS, then output_length , output , and case_flags might contain garbage. REPORTING BUGS¶¶:
https://manpages.debian.org/bullseye/libidn11-dev/punycode_decode.3.en.html
CC-MAIN-2022-21
refinedweb
179
53.61
Unanswered: Ext.application does not create App object/namespace Unanswered: Ext.application does not create App object/namespace Hi All, I am creating a new project using Ext 4.1 and attempting to use the MVC architecture however I have hit an issue in that the behaviour I am getting does not match the documentation. Specifically I am using the following code: Code: Ext.application({ name: 'MyApp', appFolder: 'Scripts/App', launch: function () { alert(MyApp); } }); What I am expecting is the call to Ext.application to create a global variable, in this case named "MyApp", as detailed in the documentation here: Which when referring to this method states: This does several things. First it creates a global variable called 'MyApp' - all of your Application's classes (such as its Models, Views and Controllers) will reside under this single namespace, which drastically lowers the chances of colliding global variables. So I should subsequently be able to use code as follows to address the application elsewhere: MyApp.getApplication() So right now I am stuck because I don't have any way to address the application object. Can anyone point out what's going on here please? It seems that Ext.application will only create application namespace if it has to load at least one application class, such as a controller (by using controllers config), viewport (with autoCreateViewport set to true), or a normal class with requires config. My solution is explicitly create application namespace: Code: Ext.application({ name: 'App', ... launch: function(){ var me = this; Ext.namespace(me.name); ... } }) Great - thanks for the response vietits. On 4.1.1a it is created, but MyApp.getApplication() method does not exist. Why ?Using Ext with cachefly Working on LAMPExt No, with 4.1.1a, the situtation is still the same. It won't create application namespace if it won't have to load any application class. Code: Ext.application({ name: 'App', appFolder: 'app', launch: function() { console.log(App); // this will cause error "Uncaught ReferenceError: App is not defined" } });
http://www.sencha.com/forum/showthread.php?244147-Ext.application-does-not-create-App-object-namespace
CC-MAIN-2015-18
refinedweb
332
58.08
Sibling package imports Tired of sys.path hacks? There are plenty of sys.path.append -hacks available, but I found an alternative way of solving the problem in hand. Summary - Wrap the code into one folder (e.g. packaged_stuff) - Create setup.pyscript where you use setuptools.setup(). (see minimal setup.pybelow) - Pip install the package in editable state with pip install -e <myproject_folder> - Import using from packaged_stuff.modulename import function_name Setup The starting point is the file structure you have provided, wrapped in a folder called myproject. .└── myproject ├── api │ ├── api_key.py │ ├── api.py │ └── __init__.py ├── examples │ ├── example_one.py │ ├── example_two.py │ └── __init__.py ├── LICENCE.md ├── README.md └── tests ├── __init__.py └── test_one.py I will call the C:\tmp\test_imports\. .the root folder, and in my example case it is located at api.py As a test case, let's use the following ./api/api.py def function_from_api(): return 'I am the return value from api.api!' test_one.py from api.api import function_from_apidef test_function(): print(function_from_api())if __name__ == '__main__': test_function() Try to run test_one: PS C:\tmp\test_imports> python .\myproject\tests\test_one.pyTraceback (most recent call last): File ".\myproject\tests\test_one.py", line 1, in <module> from api.api import function_from_apiModuleNotFoundError: No module named 'api' Also trying relative imports wont work: Using from ..api.api import function_from_api would result into PS C:\tmp\test_imports> python .\myproject\tests\test_one.pyTraceback (most recent call last): File ".\tests\test_one.py", line 1, in <module> from ..api.api import function_from_apiValueError: attempted relative import beyond top-level package Steps - Make a setup.py file to the root level directory The contents for the setup.py would be* from setuptools import setup, find_packagessetup(name='myproject', version='1.0', packages=find_packages()) - Use a virtual environment If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder) - Create virtual env python -m venv venv - Activate virtual env source ./venv/bin/activate(Linux, macOS) or ./venv/Scripts/activate(Win) To learn more about this, just Google out "python virtual env tutorial" or similar. You probably never need any other commands than creating, activating and deactivating. Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis PS C:\tmp\test_imports> python -m venv venvPS C:\tmp\test_imports> .\venv\Scripts\activate(venv) PS C:\tmp\test_imports> and your folder tree should look like this** .├── myproject│ ├── api│ │ ├── api_key.py│ │ ├── api.py│ │ └── __init__.py│ ├── examples│ │ ├── example_one.py│ │ ├── example_two.py│ │ └── __init__.py│ ├── LICENCE.md│ ├── README.md│ └── tests│ ├── __init__.py│ └── test_one.py├── setup.py└── venv ├── Include ├── Lib ├── pyvenv.cfg └── Scripts [87 entries exceeds filelimit, not opening dir] - pip install your project in editable state Install your top level package myproject using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package. In the root directory, run pip install -e . (note the dot, it stands for "current directory") You can also see that it is installed by using pip freeze (venv) PS C:\tmp\test_imports> pip install -e .Obtaining collected packages: myproject Running setup.py develop for myprojectSuccessfully installed myproject(venv) PS C:\tmp\test_imports> pip freezemyproject==1.0 - Add myproject.into your imports Note that you will have to add myproject. only into imports that would not work otherwise. Imports that worked without the setup.py & pip install will work still work fine. See an example below. Test the solution Now, let's test the solution using api.py defined above, and test_one.py defined below. test_one.py from myproject.api.api import function_from_apidef test_function(): print(function_from_api())if __name__ == '__main__': test_function() running the test (venv) PS C:\tmp\test_imports> python .\myproject\tests\test_one.pyI am the return value from api.api! * See the setuptools docs for more verbose setup.py examples. ** In reality, you could put your virtual environment anywhere on your hard disk. Seven years after Since I wrote the answer below, modifying sys.path is still a quick-and-dirty trick that works well for private scripts, but there has been several improvements - Installing the package (in a virtualenv or not) will give you what you want, though I would suggest using pip to do it rather than using setuptools directly (and using setup.cfgto store the metadata) - Using the -mflag and running as a package works too (but will turn out a bit awkward if you want to convert your working directory into an installable package). - For the tests, specifically, pytest is able to find the api package in this situation and takes care of the sys.pathhacks for you So it really depends on what you want to do. In your case, though, since it seems that your goal is to make a proper package at some point, installing through pip -e is probably your best bet, even if it is not perfect yet. Old answer As already stated elsewhere, the awful truth is that you have to do ugly hacks to allow imports from siblings modules or parents package from a __main__ module. The issue is detailed in PEP 366. PEP 3122 attempted to handle imports in a more rational way but Guido has rejected it one the account of The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. Though, I use this pattern on a regular basis with # Ugly hack to allow absolute import from the root folder# whatever its name is. Please forgive the heresy.if __name__ == "__main__" and __package__ is None: from sys import path from os.path import dirname as dir path.append(dir(path[0])) __package__ = "examples"import api Here path[0] is your running script's parent folder and dir(path[0]) your top level folder. I have still not been able to use relative imports with this, though, but it does allow absolute imports from the top level (in your example api's parent folder). Here is another alternative that I insert at top of the Python files in tests folder: # Path hack.import sys, ossys.path.insert(0, os.path.abspath('..'))
https://codehunter.cc/a/python/sibling-package-imports
CC-MAIN-2022-21
refinedweb
1,077
59.19
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module with a \"write end\" and a \"read end\". A minimal -- complete instance defines 'readChan' and one of 'writeChan' or -- 'writeList2Chan'. class SplitChan i o | i -> o, o -> i where -- | Read the next value from the 'OutChan'. readChan :: o a -> IO a -- | Write an entire list of items to a chan type writeList2Chan :: i a -> [a] -> IO () writeList2Chan = mapM_ . writeChan -- | Write a value to a Chan type. writeChan :: i a -> a -> IO () writeChan c = writeList2Chan c . return -- | A class for 'SplitChan' types that can be instantiated without programmer -- input. /e.g./ the standard haskell @Chan@ is a member of this class, however -- a bounded chan type that took an @Int@ to define the buffer size would not. class (SplitChan i o)=> NewSplitChan i o where newSplitChan :: IO (i a, o a) -- ------------------------------- -- INSTANCES FOR STANDARD TYPES -- -- ------------------------------- instance SplitChan C.Chan C.Chan where writeList2Chan = C.writeList2Chan writeChan = C.writeChan readChan = C.readChan instance NewSplitChan C.Chan C.Chan where newSplitChan = do c <- C.newChan return (c,c) -- an MVar is a singly-bounded Chan. Think about it. instance SplitChan MVar MVar where writeChan = putMVar readChan = takeMVar instance NewSplitChan MVar MVar where newSplitChan = do v <- newEmptyMVar return (v,v)
http://hackage.haskell.org/package/chan-split-0.4.0/docs/src/Control-Concurrent-Chan-Class.html
CC-MAIN-2016-30
refinedweb
200
85.59
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo You can subscribe to this list here. Showing 2 results of 2 howdy folks, Im just posting this to notify those interested that the next jyleo was released a couple of days ago. An address for download is: jyleo is the jython/java implementation of Leo(literate editor and outliner). Beyond being built in jython I think this release will be interesting to jython users because of its shell: the JythonShell. The JythonShell is a swing based jython shell that is modeled upon IPython, some Emacs and some nutty ideas of my own. Ive been building it I guess since last year. jyleo and the jythonshell require: a Java 5 a jython2.2a1( 0 shouldn't work, anyway whose using that anymore... :D) some screenshots of jyleo and the shell can be seen here: the bottom links take you to the pretty pictures, leouser --------------------------------- Yahoo! Photos Got holiday prints? See all the ways to get quality prints in your hands ASAP. I've incorporated some code and ideas from Michael Spencer into a new version of the ReloaderWindow (with some changes apparently needed to work with Jython and some other renaming and changes related to debugging that). Apparently func_defaults is readonly in Jython but not Python? So presumably, any changes to function defaults you want to use right away will require a complete restart. And also it seems that somehow in Jython "getattr" for a field in a class and a class's "__dict__" disagree on what is returned for a method (possibly different than Python, or perhaps I do not understand something here?). Anyway, these improvements should allow recursive reloading of nested objects, though I haven't really tested that. More importantly for general use, they also remove the need to parse the source file by the program and the related dependency on a specific type of indentation spacing. The more complete copying also means that changes to imports are now usable in the new code without a complete restart. In general, the ReloaderWindow is working more smoothly in terms of minimizing the need to restart an application, especially because it reloads all changed globals in a module -- classes, functions, constants, and all imports. The biggest caveat is if you are using a global variable in a module to save current state for your application (as opposed to saving state in a window or a window-held instance somewhere); that global would get reinitialized if you reload the module. This could perhaps be worked around by putting these globals in some special module apart from most of the code you might want to reload. I also added some improved exception handling to fix a bug in case a module import fails (like from a syntax error) to put back the old module instead of leaving your application without the module. :-) The ReloaderWindow can also now do a regular reload, but you get a big warning message if you try this -- because if you reload a module defining the event handling code for an open window, then you will no longer be able to change the behavior of that window directly. Some unused code like for menu handling and now parsing was also removed. While the Reloader could probably easily reload any module you have loaded from anywhere, for now I'm sticking with only listing the modules in the application's current directory (how I usually develop a GUI app). While it's still a ways from the typical Smalltalk which lets you easily modify code while it's running under the debugger, ReloaderWindow 0.2 pretty much suits my current needs and aspirations at this point, given what I think is realistic to expect with only a small effort under Python/Jython. I'm hoping it makes my development effort somewhat more productive and more fun; we'll see. It would be nice if it told you what files had changed recently, though, but then it would have to poll or use one of the fancier file tracking services, which seems like too much trouble for now. So, I would now label this Beta (instead of Alpha) software. :-) It might even be easy enough and stable enough to use for only slightly experienced Jython developers at this point (though I would need some feedback from satisfied users to be sure of that; it would not surprise me if there were still some major gotchas in there somewhere). TO USE: add this code to your Swing GUI Application startup script import ReloaderWindow window = ReloaderWindow.ReloaderWindow() window.setVisible(1) Then double click on a module name when you want to "special" reload it after modifying the GUI event handling code (or other support code) in your running application (be sure to save the changed code in your editor first). Much thanks again to Michael for his code and suggestions; his contribution has made it much better than it was. --Paul Fernhout
http://sourceforge.net/p/jython/mailman/jython-users/?viewmonth=200601&viewday=15
CC-MAIN-2015-22
refinedweb
841
64.54
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Introduction to Reflection11:40 with Unsubscribed User We take one more sidestep during this course, this time to what's called reflection. Reflection is a programming technique that allows us to examine (and even modify) the structure of objects at run-time. During this video, we'll practice some basic reflection so that we can utilize these techniques to check for the presence of our @Doc annotation. Using Reflection to Interact with Methods During this video, we take a brief look at how we can use reflection to examine a class at runtime, getting certain pieces of information about its methods. To see more, check out the official documentation of the Method class. Using Class<?> You may have noticed that in the video, I declared a variable with Class<?> as follows: Class<?> clazz = MathUtils.class; Whenever you see a pair of angle brackets following a class name in Java, it refers to what's called a generic. Think of a generic as a parameter, except that its value must be specified as a type, and must be specified upon declaration and when using a constructor. When a class is defined using a generic (like Class in Java is defined), upon declaration, you can specify the type of class that will pertain to the variable declaration. Where you may have seen this before is with an ArrayList, for example: ArrayList<String> names = new ArrayList<String>(); In this case, you are telling the Java compiler that names will hold an ArrayList of String values. Then, when you call names.get(0), for example, the compiler knows that the returned value is a String, and as such you could call String methods on it. The question mark, as it relates to generics, is called a wildcard. Without any other keywords, the single ? means that the type is any class that extends Object, which is literally any Java class. You'll have limitations in what you can do with the variable itself, since the compiler won't know what type is being used. Give it a shot yourself. In workspaces, try doing the following: import java.util.ArrayList; public class TestString { public static void main(String[] args) { ArrayList<?> names = new ArrayList<String>(); names.add("Kermit the Frog"); } } Notice the compiler error that occurs when you try to call names.add(...). It's not that the ArrayList that is created and stored into names isn't an ArrayList of Strings, it's just that since you used the question mark when declaring names, the compiler doesn't know that the items will be Strings. Change the question mark to String, and the compiler is happy. As for the example in the video, out of brevity, I chose to use the question mark. With a few more keystrokes, I could have declared the variable as follows: Class<MathUtils> clazz = MathUtils.class; I chose this declaration because it has no impact on what we need to accomplish. As you can see, with an ArrayList, it has a significant impact. - 0:00 Reflection is a feature in programming languages where by you can - 0:04 write code to examine the structure of classes or objects, and - 0:07 even modify their structure and behavior. - 0:10 Right now we're not interested in modifying structure or behavior. - 0:13 We'll focus instead on examining the structure. - 0:17 That is, we'll want to write code that cracks the hood of the MathUtils object - 0:22 to look at its annotations and method declarations. - 0:26 Some refer to this part of reflection as introspection. - 0:29 For simplicity, I'll just use the term reflection. - 0:34 Let's hop over to the main class and practice some reflection - 0:36 techniques that will be helpful in processing our annotations. - 0:39 The first thing we'll need to be able to do is utilize the class object itself. - 0:44 Let's examine the structure of the MathUtils class by grabbing a reference to - 0:48 the class. - 0:52 Let's add a comment here saying that we're getting a class objects. - 0:57 And I will define it. - 1:03 And store into it a reference to the class. - 1:07 Now, hey, since we're using the MathUtils class for - 1:10 the first time in this Java file, let's be sure to import that. - 1:18 Wonderful. - 1:20 Notice that I'm not calling this variable class. - 1:25 Remember that class is a reserved keyword in Java, and - 1:29 in many other programming languages, as well. - 1:31 This means that it can't be used as an identifier to name a variable, a method, - 1:36 or a class. - 1:37 So one of convention is to replace the S's in class with Z's, - 1:42 which is what I've done here. - 1:44 Now that we have a reference to the class object itself, - 1:47 let's look at the MathUtils class's methods. - 1:51 You might think to yourself, what do you mean look at the class's methods? - 1:54 I could just click over to MathUtils.java and look at them myself. - 1:58 And you'd be right, but even though we programmers can - 2:02 look at a bunch of code and see everything that is present, the power of programming - 2:06 comes from having a computer do the work so that we don't have to. - 2:10 What we like to do is write some code that allows our application to get - 2:12 the details of an object during run time, this is reflection. - 2:17 After all the JVM will be able to do this much faster than we ever could. - 2:22 Also, we wouldn't have to plop ourselves in front of the computer while our program - 2:26 is examining these objects, but if we really insisted on sticking around - 2:30 while it runs we can at least grab a tasty beverage and - 2:33 kickback while our program does all the work. - 2:37 Let's examine the MathUtils class by taking a peak at its methods. - 2:40 We'll start by calling a method on the class object called, quite intuitively, - 2:44 GetMethods. - 2:48 So here, we'll get all declared methods, And - 2:53 we will call that method that I just referenced. - 3:02 And since we're using the method class for the first time, we better import that, - 3:07 as well. - 3:14 This will be the starting point from which we can look at various characteristics of - 3:18 these methods, such as their modifiers, private, public, static, etc. - 3:22 The number of parameters and the return types among other things. - 3:26 You can find out what all your options are by checking out the JavaDocs for - 3:29 the method class on the Oracle website. - 3:31 I put a link to this in the teacher's notes. - 3:34 We'll focus here on the ones I just mentioned since they're a particular - 3:38 importance to us in this project. - 3:40 Let's loop over this array of methods, and - 3:42 display each of those pieces of information that I mentioned. - 3:47 I'll write a loop now that summarizes what we want to do. - 3:51 So here, we'll loop over the methods. - 3:55 We use our enhanced for loop, also called a for-each-loop. - 4:03 And let me include some comments here that displays what we intend to do. - 4:07 We'll display the method name, the parameter account, - 4:14 the return type, And the modifiers. - 4:26 Let's start with a method name. - 4:28 This one is pretty straightforward. - 4:30 We'll display a single line, and the method we need to use is called getName. - 4:33 So for this, I will display a formatted string with System.out.printf. - 4:40 I'll include a placeholder for the actual method name, - 4:43 as well as a new line character. - 4:45 I'll stick into that placeholder the results of m.getName. - 4:53 So that we don't go too far down a potentially error ridden path, - 4:57 let's run our code now. - 4:59 To do this, I'm first gonna pull up my console so - 5:02 I have plenty of room to see the output that my program is generating. - 5:06 Okay, we'll clear, we'll compile to the out - 5:11 directory with a class path as a source directory, - 5:17 and here is the Java file that we want to compile. - 5:26 Great! - 5:27 All compiles well. - 5:29 Let's run this thing! - 5:31 Using the Java command, I'll specify the class path as the out directory, and - 5:35 then include the fully qualified name that includes the package name of the main - 5:40 class. - 5:45 Cool! - 5:46 Look at all those methods. - 5:48 But, wait, I didn't declare all those methods in our MathUtils class. - 5:54 You probably already see what's happening in here. - 5:56 The methods that are returned when we call getMethods include not only the declared - 6:01 methods from the MathUtils class, but also inherited methods. - 6:06 Now, if we want to focus on the declared method and - 6:09 exclude things like toString and hashCode and getClass, - 6:13 we simply call a method that returns only declared methods. - 6:18 This one is called, again, intuitively getDeclaredMethods. - 6:23 And when we loop over those we'll see only methods that we - 6:26 put in the MathUtils class. - 6:29 Let's recompile and rerun our code to see the results. - 6:37 Clear before I run. - 6:41 And there we go. - 6:42 There are the five methods that are present in the MathUtils class. - 6:47 Next, let's display the number of parameters for each method. - 6:51 To accomplish this, we'll use the get parameter count method which gives you - 6:54 exactly what you think it should, the number of parameters. - 6:57 I'll use formatted output here again to display the count. - 7:08 I'll include a tab character here just for nice formatting. - 7:11 I'll say the number of params, and then include a placeholder - 7:15 where we will stick the actual parameter count, as well as a newline character. - 7:20 Into that placeholder, I will stick m.getParameterCount. - 7:26 Capital C. - 7:30 Let's run it again and see if our output matches what we expect. - 7:36 I'll recompile. - 7:39 We'll clear, and we'll run again. - 7:42 And there we go, - 7:43 the number of parameters is correctly listed under each method name. - 7:47 Pretty cool. - 7:50 Another piece of information we can get from our methods using reflection is - 7:53 the return type. - 7:54 Let's display this in a similar fashion. - 7:58 So under Display return type, I will display another line of formatted output, - 8:05 Which includes, again, a tab character for a nicely formatted output. - 8:09 Here's the return type. - 8:11 My string placeholder and my new line character. - 8:17 And I'll stick into that placeholder the results of getReturnType. - 8:25 Let's recompile and rerun, see what we get. - 8:30 All compiles well. - 8:31 We clear. - 8:34 And I'll run again. - 8:35 And there we go. - 8:36 We get the return types for each one of our methods. - 8:41 Now, in the case of return types that are classes, the output contains the fully - 8:44 qualified name of the class, which means that it includes the package name. - 8:48 For example, here java.lang.Double. - 8:52 If you don't want that then you can get what's called the simple name. - 8:55 So I'll tack onto this return value here, and - 8:58 we'll use .getSimpleName. - 9:03 Let's recompile and rerun and see what our results are. - 9:09 Recompile, all clear, and rerun. - 9:13 Cool, much simpler return types there. - 9:18 The last piece of information about each method that we'll examine - 9:20 are the modifiers. - 9:22 This one's a big trickier than the others because when we call Git modifiers in - 9:25 the method object, we actually get back in int value. - 9:29 Let's stick it into an int variable for now and I'll show you how we can - 9:32 convert this int into a string that represents all modifiers as you'd expect. - 9:38 So I'll create an int variable called mods and call getModifiers. - 9:47 Then, let's see what this output produces. - 9:49 System.out.printf, again, - 9:53 using my tab character. - 9:57 Here's a placeholder for the int modifier. - 10:05 We'll save that. - 10:07 Now, if we compile and run this program, you'll see those ints. - 10:10 Let's do that now. - 10:18 There they are. - 10:19 Modifiers 9, 9, 10. - 10:24 These aren't particularly meaningful to us, but - 10:27 if we use a convenience method provided by the modifier class, - 10:31 we can get a space separated string representing all modifiers. - 10:36 To do this, I'll add a line of code that includes a string variable called - 10:41 modString, or modStr as an abbreviation. - 10:44 And the modifier class includes a static method called toString that accepts - 10:48 a parameter, unlike the standard toString method. - 10:52 I'll pass to it the int. - 10:54 Now, if I swap out this for - 10:59 modString, I should see that modifier string that this static method produces. - 11:03 Now, I've just introduced a new class here, of modifier. - 11:06 So in order for this to compile, I know I'm gonna have to go up and import that. - 11:10 Let's go add that import statement now. - 11:13 Import java.lang.reflect.Modifier. - 11:18 And with that in place, let's compile our code. - 11:24 We'll clear, and rerun. - 11:27 There we go. - 11:28 We see those modifiers exactly as we would have expected them. - 11:33 Having practiced almost all of the reflection we'll need for - 11:36 coding the Doc Processor class, let's go there in the next video.
https://teamtreehouse.com/library/java-annotations/writing-your-own-annotation/introduction-to-reflection
CC-MAIN-2017-30
refinedweb
2,527
73.37
26 U.S. Code § 6039D - Returns and records with respect to certain fringe benefit plans (a) In general Every employer maintaining a specified fringe benefit plan during any year beginning after December 31, 1984, for any portion of which the applicable exclusion applies, shall file a return (at such time and in such manner as the Secretary shall by regulations prescribe) with respect to such plan showing for such year— (5) the name, address, and taxpayer identification number of the employer and the type of business in which the employer is engaged, and (b) Recordkeeping requirement Each employer maintaining a specified fringe benefit plan during any year shall keep such records as may be necessary for purposes of determining whether the requirements of the applicable exclusion are met. (c) Additional information when required by the Secretary Any employer— (1) who maintains a specified fringe benefit plan during any year for which a return is required under subsection (a), and shall file such additional return. Such additional return shall be filed at such time and in such manner as the Secretary shall prescribe and shall contain such information as the Secretary shall prescribe. The Secretary may require returns under this subsection only from a representative group of employers. (d) Definitions and special rules For purposes of this section— (1) Specified fringe benefit plan (2) Applicable exclusion The term “applicable exclusion” means, with respect to any specified fringe benefit plan, the section specified under paragraph (1) under which benefits under such plan are excludable from gross income. Source(Added Pub. L. 98–611, § 1(d)(1),Oct. 31, 1984, 98 Stat. 3176; amended Pub. L. 99–514, title XI, § 1151(h), title XVIII, § 1879(d)(1),Oct. 22, 1986, 100 Stat. 2507, 2906; Pub. L. 100–647, title I, § 1011B(a)(24), title III, § 3021(a)(15)(A),Nov. 10, 1988, 102 Stat. 3486, 3631; Pub. L. 101–508, title XI, § 11704(a)(24),Nov. 5, 1990, 104 Stat. 1388–519; Pub. L. 105–34, title XVI, § 1601(h)(2)(D)(iii),Aug. 5, 1997, 111 Stat. 1092.) Codification Another section 6039D, added Pub. L. 98–612, § 1(b)(1),Oct. 31, 1984, 98 Stat. 3180, also related to returns and records with respect to certain fringe benefits, prior to repeal by Pub. L. 99–514, title XVIII, § 1879(d)(2),Oct. 22, 1986, 100 Stat. 2906, effective, except as otherwise provided, as if included in the provisions of the Tax Reform Act of 1984, Pub. L. 98–369, div. A, to which such repeal relates, see section 1881 ofPub. L. 99–514, set out as a note under section 48 of this title. Amendments 1997—Subsec. (d)(1). Pub. L. 105–34substituted “129, or 137” for “or 129”. 1990—Subsec. (d)(3). Pub. L. 101–508substituted “the employer).” for “the employer)”. 1988—Subsec. (c). Pub. L. 100–647, § 1011B(a)(24), amended directory language of Pub. L. 99–514, § 1151(h)(3), see 1986 Amendment note below. Subsec. (d). Pub. L. 100–647, § 3021(a)(15)(A)(ii), inserted “and special rules” after “Definitions” in heading. Subsec. (d)(3). Pub. L. 100–647, § 3021(a)(15)(A)(i), added par. (3). 1986—Subsec. (a)(6). Pub. L. 99–514, § 1151(h)(2), added par. (6). Subsec. (c). Pub. L. 99–514, § 1151(h)(3), as amended by Pub. L. 100–647, § 1011B(a)(24), inserted at end “The Secretary may require returns under this subsection only from a representative group of employers.” Subsec. (d). Pub. L. 99–514, § 1151(h)(1), amended subsec. (d) generally. Prior to amendment, par. (1) defined a specified fringe benefit plan as (A) any qualified group legal services plan (as defined in section 120), (B) any cafeteria plan (as defined in section 125), and (C) any educational assistance plan (as defined in section 127), and par. (2) defined “applicable exclusion” as meaning (A) section 120 in the case of a qualified legal group services plan, (B) section 125 in the case of a cafeteria plan, and (C) section 127 in the case of an educational assistance plan. Pub. L. 99–514, § 1879(d)(1), in amending subsec. (d) generally, added subpars. (1)(A) and (2)(A). Former subpars. (1)(A) and (B) and (2)(A) and (B) were redesignated as subpars. (1)(B) and (C) and (2)(B) and (C), respectively. 1988 Amendment Amendment by section 1011B(a)(24) III, § 3021(a)(15)(B),Nov. 10, 1988, 102 Stat. 3631, provided that: “The amendments made by this paragraph [amending this section] shall apply to years beginning after 1984.” Effective Date of 1986 Amendment Amendment by section 1151(h) ofPub. L. 99–514applicable to years beginning after Dec. 31, 1988, with certain qualifications and exceptions, see section 1151(k) ofPub. L. 99–514, as amended, set out as a note under section 79 of this title. Amendment by section 1879(d) 1(g)(2) ofPub. L. 98–611, set out as an Effective Date of 1984 Amendment note under section 127 of this title. Nonenforcement of Amendment Made by Section 1151 of Pub. L. 99–514 for Fiscal Year 1990 No monies appropriated by Pub. L. 101–136to be used to implement or enforce section 1151 ofPub. L. 99–514or the amendments made by such section, see section 528 ofPub. L. 101–136, set out as a note under section 89.
http://www.law.cornell.edu/uscode/text/26/6039D?qt-us_code_tabs=0
CC-MAIN-2014-10
refinedweb
894
66.13
Hi everyone, I try to use the XML-RPC-API of Bugzilla with Groovy-XMLRPC. I cannot access the User.login method for some reason. But I cannot figure out why. Can anyone tell me, what I am doing wrong? [code] def username = "mail@mail.com" def password = "mySecret" def serverUrl = "" println("URL: " + serverUrl) def serverProxy = new XMLRPCServerProxy(serverUrl) def user = serverProxy.User.login(username, password) println("user: " + user) [/code] gets the error: [error] call Failure: fault string = "Can't use string ("mal@mail.com") as a HASH ref while "strict refs" in use at Bugzilla/WebService/User.pm line 39. : Server", fault code = 0 [/error] Any hints? MArtin
http://fixunix.com/mozilla/412484-xml-rpc-user-login-does-not-work-print.html
CC-MAIN-2015-11
refinedweb
109
63.05
What will we cover in this tutorial? We will learn how to visualization time series data in a DataFrame with Matplotlib. This tutorial will show you. - How to use Matplotlib with DataFrames. - Use Matplotlib with subplots (the object-oriented way). - How to make multiple plots in one figure. - How to create bar-plots Want to access the code directly in Jupyter Notebook? You can get the Jupyter Notebooks from the GitHub here, where there are also direct links to Colab for an interactive experience. Step 1: Read time series data into a DataFrame A DataFrame is a two-dimensional tabular data. It is the primary data structure of Pandas. The data structure contains labeled axes (rows and columns). To get access to a DataFrame data structure, you need to import the Pandas library. import pandas as pd Then we need some time series data. You con download your own CSV file from financial pages like Yahoo! Finance. For this tutorial we will use a dataset available from the GitHub. remote_file = "" data = pd.read_csv(remote_file, index_col=0, parse_dates=True) The pd.read_csv(…) does all the magic. We set the index_col=0, which sets the first column of the CSV data file to be the index. This is the dates. Then we set parse_dates=True, to ensure that dates are actually parsed as dates and not as strings. This is necessary to take advantage of being time series and index with time intervals. Step 2: Import Matplotlib in Jupyter Notebook When you import Matplotlib in Jupyter Notebook, you need to set a rendering mode. import matplotlib.pyplot as plt %matplotlib notebook We will use the notebook mode, which is interactive. This enables you to zoom in on interval, move around, and save the figure. It is common to use inline mode for rendering in Jupyter Notebook. The inline mode creates a static image, which is not interactive. Step 3: Use Matplotlib the Object-Oriente way Matplotlib can be used in a functional way and an object-oriented way. Most use it in a functional way, which often creates more confusion, as it is not always intuitive how it works. The object-oriented way leads to less confusion for the cost of one extra line of code and parsing one argument. Hence, the price is low for the gain. fig, ax = plt.subplots() data['Close'].plot(ax=ax) ax.set_ylabel("Price") ax.set_title("AAPL") The first line returns a figure and axis (fig and ax). The figure is where we put the axis, and the axis is the chart. The actually plot is made by calling the DataFrame, actually, we access the column Close in this case, which is the Series of the time series of the historic Close prices. Confused? Don’t worry about the details. Notice, that we parse ax=ax to the plot. This ensures that we render the chart on the returned axis ax. Finally, we add a y-label and a title to our axis. Step 4: Creating multiple charts in one Matplotlib figure How can we create multiple charts (or axes) in one Matplotlib figure? Luckily, this is quite easy. fig, ax = plt.subplots(2, 2) data['Open'].plot(ax=ax[0, 0], title="Open") data['High'].plot(ax=ax[0, 1], title="High") data['Low'].plot(ax=ax[1, 0], title="Low") data['Close'].plot(ax=ax[1, 1], title="Close") plt.tight_layout() Here we see a few differences. First, notice plt.subplots(2, 2), which will return a figure fig, and a list of lists with 2-by-2 axes. Hence, ax is a two dimensional list of axes. We can access the first axis with ax[0, 0,], and parse it as an argument to plot. This continues for all the 4 plots we make, as you see. Finally, we use plt.tight_layout(), which will ensures that the layout of the axes does not overlap. You can try without to see the difference. Step 5: Create a bar-chart with Matplotlib Finally, we will make a bar-chart with Matplotlib. Actually, we will render a horizontal bar-chart. fig, ax = plt.subplots() data['Volume'].loc['2020-07-01':'2020-08-15'].plot.barh(ax=ax) We do it for the volume and only on a limited interval of time. This shows you how to take advantage of the time series aspect of the DataFrame. Next step The above is part of the FREE 2h Video course.
https://www.learnpythonwithrune.org/matplotlib-visualization-for-dataframe-time-series-data/
CC-MAIN-2021-25
refinedweb
742
68.97
Bug #9226closed Getting method `inspect' called on unexpected T_NODE object (0x000000025ddea8 flags=0x109089c klass=0x0) (NotImplementedError) from Hash#inspect Description We're trying to get a green RSpec build against ruby 2.1.0.preview2, and we're getting this very odd failure on travis: The line where it's failing is here: It's calling inspect on a Hash and blowing up with that confusing error. The hash that's causing this failure (if that helps) is here: It's the { :ruby => lambda { } } hash being passed to filter_run_excluding. Updated by tmm1 (Aman Karmani) over 8 years ago I was able to reproduce this on trunk with the following patch to rspec: --- a/lib/rspec/core/command_line.rb +++ b/lib/rspec/core/command_line.rb @@ -20,6 +20,7 @@ module RSpec @configuration.output_stream = out if @configuration.output_stream == $stdout @options.configure(@configuration) @configuration.load_spec_files GC.stress=true @world.announce_filters @configuration.reporter.report(@world.example_count) do |reporter| With the patch, you can see different results during script/rspec_with_simplecov spec -b --format progress boot due to object re-use: exclude {:ruby=>#Proc:./spec/spec_helper.rb:149} exclude {:ruby=>RSpec::ExampleGroups::RSpecCoreConfiguration::SeedUsed} exclude {:ruby=>#RubyVM::Env:0x007ff5ec199198} I noticed that RSpec::Core::FilterManager was using Hash#merge, and after some debugging I confirmed that the following patch fixes this issue on trunk: --- a/hash.c +++ b/hash.c @@ -1429,6 +1429,7 @@ rb_hash_replace(VALUE hash, VALUE hash2) st_table *old_table = RHASH(hash)->ntbl; if (old_table) st_free_table(old_table); RHASH(hash)->ntbl = st_copy(table2); OBJ_WB_UNPROTECT(hash); } return hash; Updated by charliesome (Charlie Somerville) over 8 years ago Instead of shading the hash, we could probably do something like this: diff --git hash.c hash.c index a52e02f..e7a505e 100644 --- hash.c +++ hash.c @@ -1414,22 +1414,9 @@ rb_hash_replace(VALUE hash, VALUE hash2) table2 = RHASH(hash2)->ntbl; - if (RHASH_EMPTY_P(hash2)) { - rb_hash_clear(hash); - if (table2) hash_tbl(hash)->type = table2->type; - return hash; - } - - if (RHASH_ITER_LEV(hash) > 0) { - rb_hash_clear(hash); - hash_tbl(hash)->type = table2->type; - rb_hash_foreach(hash2, replace_i, hash); - } - else { - st_table *old_table = RHASH(hash)->ntbl; - if (old_table) st_free_table(old_table); - RHASH(hash)->ntbl = st_copy(table2); - } rb_hash_clear(hash); hash_tbl(hash)->type = table2->type; rb_hash_foreach(hash2, replace_i, hash); return hash; } Updated by tmm1 (Aman Karmani) over 8 years ago - Category set to core - Assignee set to ko1 (Koichi Sasada) - Priority changed from Normal to 5 Updated by ko1 (Koichi Sasada) over 8 years ago I like charliesome's approach. Could you commit it? Updated by tmm1 (Aman Karmani) over 8 years ago - Status changed from Open to Closed - % Done changed from 0 to 100 This issue was solved with changeset r44060. Myron, thank you for reporting this issue. Your contribution to Ruby is greatly appreciated. May Ruby be with you. hash.c: fix WB miss issue in Hash#replace - hash.c (rb_hash_replace): add a write barrier to fix GC mark miss on hashes using Hash#replace [Bug #9226] [ruby-core:58948] Updated by tmm1 (Aman Karmani) over 8 years ago Committed. I was surprised but RGENGC_CHECK did not find this issue. Updated by ko1 (Koichi Sasada) over 8 years ago - Status changed from Closed to Open - % Done changed from 100 to 0 OMG That is another issue.... Updated by myronmarston (Myron Marston) over 8 years ago Wow, thanks for the quick fix :). Updated by tmm1 (Aman Karmani) over 8 years ago With r44059, I can reproduce this issue with the following ruby code. I confirmed RGENGC_CHECK=2 does not complain. def create_oldgen_hash @h1 = {} GC.start end def replace_with_young_hash h2 = {"a"=>"b"} @h1.replace(h2) h2 = nil end create_oldgen_hash replace_with_young_hash GC.start(full_mark:false,immediate_sweep:false) p @h1 Updated by tmm1 (Aman Karmani) over 8 years ago - Status changed from Open to Closed - % Done changed from 0 to 100 This issue was solved with changeset r44109. Myron, thank you for reporting this issue. Your contribution to Ruby is greatly appreciated. May Ruby be with you. gc.c: build complete object graph for RGENGC_CHECK_MODE * gc.c (reflist_add): return 0 if reference already exists * gc.c (allrefs_add): return 1 on newly added references * gc.c (allrefs_i): follow references to construct complete object graph. before this patch, RGENGC_CHECK could fail to verify some WB miss issues. [Bug #9226] [ruby-core:58959] Updated by tmm1 (Aman Karmani) over 8 years ago After r44109, RGENGC_CHECK_MODE is able to detect the original Hash#replace miss issue: $ ./miniruby test1.rb gc_marks_check_i: WB miss 0x7fb33b053bb0 (T_HASH) -> 0x7fb33b033f90 (T_STRING) test1.rb:15: [BUG] before_marks: GC has problem. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/9226
CC-MAIN-2022-27
refinedweb
738
56.35
SYNOPSIS awk [ DESCRIPTION awk is a file-processing language which is well suited to data manipulation and retrieval of information from text files. This reference page provides a full technical description of awk. If you are unfamiliar with the language, you may find it helpful to read the online AWK Tutorial before reading the following material. An awk program consists of any number of user-defined functions and rules in the form: pattern {action} There are two ways to specify the awk program: Directly on the command line. In this case, the program is a single command line argument, usually enclosed in apostrophes (') to prevent the shell from attempting to expand it. By using the -fprog option. You can only specify program directly on the command line if you do not use any When you specify files on the command line, those files provide the input data for awk to manipulate. If you specify no such files or you specify You can initialize variables on the command line using var=value You can intersperse such initializations with the names of input files on the command line. awk processes initializations and input files in the order they appear on the command line. For example, the command awk -f progfile a=1 f1 f2 a=2 f3 sets a to 1 before reading input from f1 and sets a to 2 before reading input from f3. Variable initializations that appear before the first file on the command line are performed immediately after the BEGIN action. Initializations appearing after the last file are performed immediately before the END action. For more information on BEGIN and END, see Patterns. The awk -v v1=10 -f prog datafile awk assigns the variable v1 its value before the BEGIN action of the program (but after default assignments made to built-in variables like FS and OFMT; these built-in variables have special meaning to awk, as described in later sections). awk divides input into records. By default, newline characters separate records; however, you may specify a different record separator if you want. One at a time, and in order, awk compares each input record with the pattern of every rule in the program. When a pattern matches, awk performs the action part of the rule on that input record. Patterns and actions often refer to separate fields within a record. By default, white space (usually blanks, newlines, or horizontal tab characters) separates fields; however, you can specify a different field separator string using the You can omit the pattern or action part of an awk rule (but not both). If you omit pattern, awk performs the action on every input record (that is, every record matches). If you omit action, awk writes every record matching the pattern to the standard output. awk considers everything after a # in a program line to be a comment. For example: # This is a comment To continue program lines on the next line, add a backslash (\) to the end of the line. Statement lines ending with a comma (,), double or-bars (||), or double ampersands (&&) continue automatically on the next line. Options -Fere specifies an extended regular expression to use as the field separator. -fprog runs the awk program contained in the file prog. When more than one -foption appears on the command line, the resulting program is a concatenation of all programs you specify. -vvar=value assigns value to var before running the program. You can specify this option a number of times. Variables and Expressions There are three types of variables in awk: identifiers, fields and array elements. An identifier is a sequence of letters, digits and underscores beginning with a letter or an underscore. For a description of fields, see the Input subsection. Arrays are associative collections of values called the elements of the array. Constructs of the form, identifier[subscript] where subscript has the form expr or expr,expr,.... refer to array elements. Each such expr can have any string value. For multiple expr subscripts, awk concatenates the string values of all exprs with a separate character SUBSEP between each. The initial value of SUBSEP is set to \034 (ASCII field separator). Fields and identifiers are sometimes referred to as scalar variables to distinguish them from arrays. You do not declare awk variables and you do not need to initialize them. The value of an uninitialized variable is the empty string in a string context and the number 0 in a numeric context. Expressions consist of constants, variables, functions, regular expressions and subscript in array conditions (described later) combined with operators. Each variable and expression has a string value and a corresponding numeric value; awk uses the value appropriate to the context. When converting a numeric value to its corresponding string value, awk performs the equivalent of a call to the sprintf function (see Built-In String Functions). The one and only expr argument is the numeric value and the fmt argument is either %d (if the numeric value is an integer) or the value of the variable CONVFMT (if the numeric value is not an integer). The default value of CONVFMT is %.6g. If you use a string in a numeric context, and awk cannot interpret the contents of the string as a number, it treats the value of the string as zero. Numeric constants are sequences of decimal digits. String constants are quoted, as in "a literal string". Literal strings can contain the escape sequences shown in Table 1, Escape Sequences in awk Literal Strings. awk supports extended regular expressions (see regexp). When awk reads a program, it compiles characters enclosed in slash characters (/) as regular expressions. In addition, when literal strings and variables appear on the right side of a ~ or !~ operator, or as certain arguments to built-in matching and substitution functions, awk interprets them as dynamic regular expressions. Table 1: Escape Sequences in awk Literal Strings - Note: When you use literal strings as regular expressions, you need extra backslashes to escape regular expression metacharacters, since the backslash is also the literal string escape character. For example the regular expression, /e\.g\./ when written as a string is: "e\\.g\\." awk defines the subscript in array condition as: index in array where index looks like expr or (expr,...,expr). This condition evaluates to 1 if the string value of index is a subscript of array, and to 0 otherwise. This is a way to determine if an array element exists. When the element does not exist, this condition does not create it. Symbol Table You can access the symbol table through the built-in array SYMTAB. SYMTAB[expr] is equivalent to the variable named by the evaluation of expr. For example, SYMTAB["var"] is a synonym for the variable var. Environment An awk program can determine its initial environment by examining the ENVIRON array. If the environment consists of entries of the form: name=value then ENVIRON[name] has string value "value" For example, the following program is equivalent to the default output of env: BEGIN { for (i in ENVIRON) printf("%s=%s\n", i, ENVIRON[i]) exit } Operators awk follows the usual precedence order of arithmetic operations, unless overridden with parentheses; a table giving the order of operations appears later in this section. The unary operators are +, -, ++ and --, where you can use the ++ and -- operators as either postfix or prefix operators, as in C. The binary arithmetic operators are +, -, *, /, % and ^. The conditional operator expr ? expr1 : expr2 evaluates to expr1 if the value of expr is non-zero, and to expr2 otherwise. If two expressions are not separated by an operator, awk concatenates their string values. The operator ~ yields 1 (true) if the regular expression on the right side matches the string on the left side. The operator !~ yields 1 when the right side has no match on the left. To illustrate: $2 ~ /[0-9]/ selects any line where the second field contains at least one digit. awk interprets any string or variable on the right side of ~ or !~ as a dynamic regular expression. The relational operators are <, <=, >, >=, == and !=. When both operands in a comparison are numeric, awk compares their values numerically; otherwise it compares them as strings. An operand is numeric if it is an integer or floating point number, if it is a field or ARGV element that looks like a number, or if it is a variable created by a command line assignment that looks like a number. The Boolean operators are || (or), && (and) and ! (not). Short Circuit Evaluation is used when evaluating expressions. With an && expression, if the first operator is false, the entire expression is false and it is not necessary to evaluate the second operator. With an || expression, a similar situation exists if the first operator is true. You can assign values to a variable with var = expr If op is a binary arithmetic operator, var op= expr is equivalent to var = var op expr except that var is evaluated only once. See Table 2, awk Order of Operations for the precedence rules of the operators. Command Line Arguments awk sets the built-in variable ARGC to the number of command line arguments. The built-in array ARGV has elements subscripted with digits from zero to ARGC-1, giving command line arguments in the order they appeared on the command line. The ARGC count and the ARGV vector do not include command line options (beginning with -) or the program file (following var=value and the names of input data files. awk actually creates ARGC and ARGV before doing anything else. It then walks through ARGV processing the arguments. If an element of ARGV is an empty string, awk skips it. If it contains an equals sign (=), awk interprets it as a variable assignment. If it is a minus sign (-), awk immediately reads input from the standard input until it encounters the end-of-file; otherwise, awk treats the argument as a file name and reads input from that file until it reaches end-of-file. - Note: awk runs the program by walking through ARGV in this way; thus if the program changes ARGV, awk can read different files and make different assignments. Input awk divides input into records. A record separator character separates each record from the next. The value of the built-in variable RS gives the current record separator character; by default, it begins as the newline (\n). If you assign a different character to RS, awk uses that as the record separator character from that point on. Table 2: awk Order of Operations awk divides records into fields. A field separator string, given by the value of the built-in variable FS, separates each field from the next. You can set a specific separator string by assigning a value to FS, or by specifying the FS = "[,:$]" says that commas, colons or dollar signs can separate fields. As a special case, assigning FS a string containing only a blank character sets the field separator to white space. In this case, awk considers any sequence of contiguous space and/or tab characters a single field separator. This is the default for FS; however, if you assign FS a string containing any other character, that character designates the start of a new field. For example, if you set FS="\t" (the tab character), texta \t textb \t \t \t textc contains five fields, two of which contain only blanks. With the default setting, this record contains only three fields, since awk considers the sequence of multiple blanks and tabs a single separator. The following list of built-in variables provides various pieces of information about input. NF number of fields in the current record NR number of records read so far FILENAME name of file containing current record FNR number of records read from current file Field specifiers have the form $n where n runs from 1 through NF. Such a field specifier refers to the nth field of the current input record. $0 (zero) refers to the entire current input record. The getline function can read a value for a variable or $0 from the current input, from a file, or from a pipe. The result of getline is an integer indicating whether the read operation was successful. A value of 1 indicates success; 0 indicates end-of-file encountered; and -1 indicates that an error occurred. Possible forms for getline are: - getline reads next input record into $0 and splits the record into fields. NF, NR and FNR are set appropriately. - getline var reads next input record into the variable var. awk does not split the record into fields (which means that the current $n values do not change), but sets NR and FNR appropriately. - getline <expr interprets the string value of expr to be a file name. awk reads the next record from that file into $0, splits it into fields and sets NF appropriately. If the file is not open, awk opens it. The file remains open until you close it with a close()function. - getline var <expr interprets the string value of expr to be a file name and reads the next record from that file into the variable var, but does not split it into fields. - expr | getline interprets the string value of expr as a command line to be run. awk pipes output from this command into getline and reads it into $0 in a manner similar to getline <expr. See the System Function section for additional details. - expr | getline var runs the string value of expr as a command and pipes the output of the command into getline. The result is similar to getline var <expr. You can only have a limited number of files and pipes open at one time. You can close files and pipes during execution using the close(expr) function. The expr must be one that came before | or after < in getline, or after > or >> in print or printf. For a description of print and printf, see the Output section. If the function successfully closes the pipe, it returns zero. By closing files and pipes that you no longer need, you can use any number of files and pipes in the course of running an awk program. Built-In Arithmetic Functions - atan2(expr1, expr2) returns the arctangent of expr1/expr2 in the range of -pi through pi. - exp(expr), log(expr), sqrt(expr) returns the exponential, natural logarithm, and square root of the numeric value of expr. If you omit (expr), these functions use $0 instead. - int(expr) returns the integer part of the numeric value of expr. If you omit (expr), the function returns the integer part of $0. rand() returns a random floating-point number in the range 0 through 1. - sin(expr), cos(expr) returns the sine and cosine of the numeric value of expr (interpreted as an angle in radians). - srand(expr) sets the seed of the rand()function to the integer value of expr. If you omit (expr), awk uses the time of day as a default seed. Built-In String Functions - n = gsub(regexp, repl, string) works the same way as sub(), except that gsub()replaces all matching substrings (global substitution). The return value is the number of substitutions performed. - pos = index(string, str) returns the position of the first occurrence of str in string. If index()does not find str in string, it returns zero. - len = length(expr) returns the number of characters in the string value of expr. If you omit (expr), the function uses $0 instead. The parentheses around expr are optional. - pos = match(string, regexp) searches string for the first substring matching the regular expression regexp and returns an integer giving the position of this substring counting characters; the count starts at one. If it finds no such substring, match()returns zero. This function also sets the built-in variable RSTART to pos and the built-in variable RLENGTH to the length of the matched string. If it does not find a match, match()sets RSTART to zero and RLENGTH to -1. You can enclose regexp in slashes or specify it as a string. - n = ord(expr) returns the integer value of first character in the string value of expr. This is useful in conjunction with %c in sprintf(). - n = split(string, array, regexp) splits string into fields. regexp is a regular expression giving the field separator string for the purposes of this operation. This function assigns the separate fields, in order, to the elements of array; subscripts for array begin at 1. awk discards all other elements of array. split()returns the number of fields into which it divided string (which is also the maximum subscript for array). regexp divides the record in the same way that the FS field separator string does. If you omit regexp in the call to split(), it uses the current value of FS. - str = sprintf(fmt, expr, expr...) formats the expression list expr, expr, ... using specifications from the string fmt, then returns the formatted string. The fmt string consists of conversion specifications which convert and add the next expr to the string, and ordinary characters which sprintf()simply adds to the string. These conversion specifications are similar to those used by the ANSI C standard. Conversion specifications have the form %[flag][x][.y]c where x is the minimum field width y is the precision c is the conversion character flag is a flag character In a string, the precision is the maximum number of characters to be printed from the string; in a number, the precision is the number of digits to be printed to the right of the decimal point in a floating point value. If x or y is * (asterisk), the minimum field width or precision is the value of the next expr in the call to sprintf(). The conversion character c is one of following: d decimal integer i decimal integer o unsigned octal integer x,X unsigned hexadecimal integer u unsigned decimal integer f,F floating point e,E floating point (scientific notation) g,G the shorter of e and f (suppresses non-significant zeros) c single character of an integer value; first character of string s string The lowercase x prints alphabetic hex digits in lowercase while the uppercase X prints alphabetic hex digits in uppercase. The other uppercase and lowercase pairs work similarly. flag is a sting consisting of characters from the following list that provides additional formatting information: - left justifies the field; default is right justification 0 leading zero prints numbers with leading zero ' displays thousands separator when TK_USE_CURRENT_LOCALE is set. (Only with decimal integer and floating point conversions) " same as ' - Note: A single or double quote included in the flag string may require appropriate quoting for it to be interpreted correctly. When flag contains a ' or " character and the TK_USE_CURRENT_LOCALE environment variable is set, a thousands separator is displayed. The digital grouping character (for example, a comma in the United States) as set by the Regional and Language Options control panel applet is used as the thousands separator. When flags contains ' or " and TK_USE_CURRENT_LOCALE is unset, no thousands separator is displayed. For example, the following MKS KornShell commands: export TK_USE_CURRENT_LOCALE=1 awk 'BEGIN { printf("%'\''10d\n",123456)}' display: 123,456 while the MKS KornShell commands: unset TK_USE_CURRENT_LOCALE awk 'BEGIN { printf("%'\''10d\n",123456)}' display: 123456 - n = sub(regexp, repl, string) searches string for the first substring matching the extended regular expression regexp, and replaces the substring with the string repl. awk replaces any ampersand (&) in repl with the substring of string which matches regexp. You can suppress this special behavior by preceding the ampersand with a backslash. If you omit string, sub()uses the current record instead. sub()returns the number of substrings replaced (which is one if it found a match, or zero otherwise). - str = substr(string, offset, len) returns the substring of string that begins in position offset and is at most len characters long. The first character of the string has an offset equal to one. If you omit len, substr()returns the rest of string. - str = tolower(expr) converts all letters in the string value of expr into lowercase and returns the result. If you omit expr, tolower()uses $0 instead. - str = toupper(expr) converts all letters in the string value of expr into uppercase and returns the result. If you omit expr, toupper()uses $0 instead. System Function - status = system(expr) runs the string value of expr as a command. For example, system("tail " $1) calls the tail command, using the string value of $1 as the file that tail examines. The standard command interpreter runs the command as discussed in the PORTABILITY section, and the exit status returned depends on that command interpreter. User-Defined Functions You can define your own functions using the form function name(parameter-list) { statements } A function definition can appear in the place of a pattern {action} rule. The parameter-list contains any number of normal (scalar) and array variables separated by commas. When you call a function, awk passes scalar arguments by value, and array arguments by reference. The names specified in the parameter-list are local to the function; all other names used in the function are global. You can define local variables by adding them to the end of the parameter list as long as no call to the function uses these extra parameters. A function returns to its caller either when it performs the final statement in the function, or when it reaches an explicit return statement. The return value, if any, is specified in the return statement (see the Actions section). Patterns A pattern is a regular expression, a special pattern, a pattern range, or any arithmetic expression. BEGIN is a special pattern used to label actions that awk performs before reading any input records. END is a special pattern used to label actions that awk performs after reading all input records. You can give a pattern range as pattern1,pattern2 This range matches all lines from the line that matches pattern1 to the line that matches pattern2, inclusive. If you omit a pattern, or if the numeric value of the pattern is non-zero (true), awk performs the resulting action for the line. Actions An action is a series of statements terminated by semicolons, newlines, or closing braces. A condition is any expression; awk considers a non-zero value true and a zero value false. A statement is one of the following or any series of statements enclosed in braces. # expression statement, for example, assignment expression # if statement if (condition) statement [else statement] # while loop while (condition) statement # do-while loop do statement while (condition) # for loop for (expression1; condition; expression2) statement The for statement is equivalent to: expression1 while (condition) { statement expression2 } The for statement can also have the form for (i in array) statement awk performs the statement once for each element in array; on each repetition, the variable i contains the name of a subscript of array, running through all the subscripts in an arbitrary order. If array is multi-dimensional (has multiple subscripts), i is expressed as a single string with the SUBSEP character separating the subscripts. The statement break exits a for or a while loop immediately. continue stops the current iteration of a for or while loop and begins the next iteration (if there is one). terminates any processing for the current input record and immediately starts processing the next input record. Processing for the next record begins with the first appropriate rule. exit[(expr)] immediately goes to the END action if it exists; if there is no END action, or if awk is already performing the END action, the awk program terminates. awk sets the exit status of the program to the numeric value of expr. If you omit (expr), the exit status is 0. return [expr] returns from the execution of a function. If you specify an expr, the function returns the value of the expression as its result; otherwise, the function result is undefined. delete array[i] deletes element i from the given array. print expr, expr, ... is described in the Output subsection. printf fmt, expr, expr, ... is also described in the Output subsection. Output The print statement prints its arguments with only simple formatting. If it has no arguments, it prints the current input record in its entirety. awk adds the output record separator ORS to the end of the output that each print statement produces; when commas separate arguments in the print statement, the output field separator OFS separates the corresponding output values. ORS and OFS are built-in variables, the values of which you can change by assigning them strings. The default output record separator is a newline and the default output field separator is a space. The variable OFMT gives the format of floating point numbers output by print. By default, the value is %.6g; you can change this value by assigning OFMT a different string value. OFMT applies only to floating point numbers (that is, ones with fractional parts). The printf statement formats its arguments using the fmt argument. Formatting is the same as for the built-in function The print and printf statements write to the standard output. You can redirect output to a file or pipe as described later. If you add >expr to a print or printf statement, awk treats the string value of expr as a file name, and writes output to that file. Similarly, if you add >>expr, awk appends output to the current contents of the file. The distinction between > and >> is only important for the first print to the file expr. Subsequent outputs to an already open file append to what is there already. To eliminate ambiguities, statements such as print a > b c are syntactically illegal. Use parentheses to resolve the ambiguity. If you add |expr to a print or printf statement, awk treats the string value of expr as an executable command and runs it with the output from the statement piped as input into the command. As mentioned earlier, only a limited number of files and pipes can be open at any time. To avoid going over the limit, use the print and printf are also available as functions with the same calling sequence, but no redirection. EXAMPLES awk '{print NR ":" $0}' input1 outputs the contents of the file input1 with line numbers prepended to each line. The following is an example using var=value on the command line. awk '{print NR SEP $0}' SEP=":" input1 awk can also read the program script from a file as in the command line: awk -f addline.awk input1 which produces the same output when the file addline.awk contains {print NR ":" $0} The following program appends all input lines starting with January to the file jan (which may or may not exist already), and all lines starting with February or March to the file febmar: /^January/ {print >> "jan"} /^February|^March/ {print >> "febmar"} This program prints the total and average for the last column of each input line: {s += $NF} END {print "sum is", s, "average is", s/NR} The next program interchanges the first and second fields of input lines: { tmp = $1 $1 = $2 $2 = tmp print } The following example inserts line numbers so that output lines are left-aligned: {printf "%-6d: %s\n", NR, $0} The following example prints input records in reverse order (assuming sufficient memory): { a[NR] = $0 # index using record number } END { for (i = NR; i>0; --i) print a[i] } The next program determines the number of lines starting with the same first field: { ++a[$1] # array indexed using the first field } END { # note output is in undefined order for (i in a) print a[i], "lines start with", i } The following program can be used to determine the number of lines in each input file: { ++a[FILENAME] } END { for (file in a) if (a[file] = = 1) print file, "has 1 line" else print file, "has", a[file], "lines" } The following program illustrates how you can use a two dimensional array in awk. Assume the first field of each input record contains a product number, the second field contains a month number, and the third field contains a quantity (bought, sold, or whatever). The program generates a table of products versus month. BEGIN {NUMPROD = 5} { array[$1,$2] += $3 } END { print "\t Jan\t Feb\tMarch\tApril\t May\t" \ "June\tJuly\t Aug\tSept\t Oct\t Nov\t Dec" for (prod = 1; prod <= NUMPROD; prod++) { printf "%-7s", "prod#" prod for (month = 1; month <= 12; month++){ printf "\t%5d", array[prod,month] } printf "\n" } } As the following program reads in each line of input, it reports whether the line matches a pre-determined value: function randint() { return (int((rand()+1)*10)) } BEGIN { prize[randint(),randint()] = "$100"; prize[randint(),randint()] = "$10"; prize[1,1] = "the booby prize" } { if (($1,$2) in prize) printf "You have won %s!\n", prize[$1,$2] } The following example prints lines, the first and last fields of which are the same, reversing the order of the fields: $1= =$NF { for (i = NF; i > 0; --i) printf "%s", $i (i>1 ? OFS : ORS) } The following program prints the input files from the command line. The function infiles(f,i) { for (i in f) delete f[i] for (i = 1; i < ARGC; i++) if (index(ARGV[i],"=") = = 0) f[i] = ARGV[i] } BEGIN { infiles(a) for (i in a) print a[i] exit } Here is the standard recursive factorial function: function fact(num) { if (num <= 1) return 1 else return num * fact(num - 1) } { print $0 " factorial is " fact($0) } The following program illustrates the use of getline with a pipe. Here, getline sets the current record from the output of the wc command. The program prints the number of words in each input file. function words(file, string) { string = "wc " file string | getline close(string) return ($2) } BEGIN { for (i=1; i<ARGC; i++) { fn = ARGV[i] printf "There are %d words in %s.", words(fn), fn } } ENVIRONMENT VARIABLES - PATH contains a list of directories that awk searches when looking for commands run by system(expr), or input and output pipes. - TK_USE_CURRENT_LOCALE specifies whether or not to use relevant information from the current locale. When set, current locale information is used; when unset, the default locale information is used. - Note: Current locale information is set using the Regional and Language Options control panel applet. For awk, this environment variable determines the characters displayed for the decimal point and the thousands separator. Any other environment variable may be accessed by the awk program itself. DIAGNOSTICS Possible exit status values are: - 0 Successful completion. - 1 Any of the following errors: - — parser internal stack overflow - — syntax error - — function redefined - — internal execution tree error - — insufficient memory for string storage - — unbalanced parenthesis or brace - — missing script file - — missing field separator - — missing variable assignment - — unknown option - — invalid character in input - — newline in regular expression - — newline in string - — EOF in regular expression - — EOF in string - — cannot open script file - — inadmissible use of reserved keyword - — attempt to redefine built-in function - — cannot open input file - — error on print - — error on printf - — getline in END action was not redirected - — too many open input/output streams - — error on input/output stream - — insufficient arguments to printf or sprintf() - — array cannot be used as a scalar - — variable cannot be used as a function - — too many fields - — record too long - — division (/ or %) by zero - — syntax error - — cannot assign to a function - — value required in assignment - — return outside of a function - — may delete only array element or array - — scalar cannot be used as array - — SYMTAB must have exactly one index - — impossible function call - — function call nesting level exceeded - — wrong number of arguments to function - — regular expression error - — second parameter to "split" must be an array - — sprintf()string longer than allowed number of characters - — no open file name - — function requires an array - — is not a function - — failed to match - — invalid collation element - — trailing \ in pattern - — newline found before end of pattern - — more than 9 \( \) pairs - — number in [0-9] invalid - — [ ] imbalance or syntax error - — ( ) or \( \) imbalance - — { } or \{ \} imbalance - — invalid endpoint in range - — out of memory - — invalid repetition - — invalid character class type - — internal error - — unknown regex error When an awk program terminates because of a call to LIMITS Most constructions in this implementation of awk are dynamic, limited only by memory restrictions of the target machine. On Windows systems, awk limits dynamic data to the amount of available conventional memory, the longest input record to 20000 bytes, and the number of fields to 4000. The parser stack depth is limited to 600 levels. Attempting to process extremely complicated programs may result in an overflow of this stack, causing an error. The maximum record size is guaranteed to be at least LINE_MAX, as returned by getconf. The maximum field size is guaranteed to be LINE_MAX. With MKS Toolkit, LINE_MAX is set to 8192 bytes. Input must be text files. PORTABILITY POSIX.2. x/OPEN Portability Guide 4.0. All UNIX systems. Windows 2000. Windows XP. Windows Server 2003. Windows Vista. The The standard command interpreter that the Using MKS AWK MKS Toolkit 9.2 Documentation Build 16.
http://www.mkssoftware.com/docs/man1/awk.1.asp
crawl-002
refinedweb
5,538
52.09
Create a Card Flip Effect For Flash Player 10 using ActionScript 3 by 11 June, 2008 5:53 pm23. Requirements TextMate or Your Choice of text editor Flash Player 10 Sample files: Prerequisites Before you get started you will need a means by which to publish Flash 10 SWF files. This process involves downloading a nightly build of the Flex 3 SDK. Lee Brimelow of gotoAndLearn.com has a great video tutorial You will also need to make sure that you have the Flash Player 10 Beta installed on your machine. This article also assumes a basic understanding of ActionScript 3. which steps you through the process of downloading and publishing your Flash 10 SWFs. Getting Started Let’s take a look at what we are going to be building before we dive into the code. Click on the image below to see the card flip effect (requires Flash Player 10): Once you have Flash Player 10 installed and have your system setup to publish using the Flex 3 SDK you can get started writing the CardFlip class. Getting started with the class should be easy for those of you familiar with writing ActionScript 3 classes. This article will detail a simple card flip using external image files and external SWF files. To start, we will create the class using image files and then cover the changes that are made to use an external SWF in their place. First let’s take a look at the classes we will be using in our package: package{ import flash.display.Sprite; import flash.display.StageQuality; import flash.display.Bitmap; import flash.events.*; import flash.geom.PerspectiveProjection; import flash.geom.Point; import flash.filters.DropShadowFilter; import gs.TweenMax; As you can see we import a number of classes that will be leveraged to make our class function. Most of these are native classes that you have probably used before with the exception of PerspectiveProject and TweenMax. PerspectiveProject is a class that is new to Flash Player 10, we will get into its usage later.TweenMax is an excellent class which provides easy and efficient tweening for DisplayObject properties and filters. More about TweenMax is available at GreenSock. Setting up the SWF for the Flex 3 SDK If you are new to Flex or have not used the Flex SDK you may not have ever worked with Flex Meta Tags. The following code is pretty self-explanatory and is used to setup the stage for our SWF since we are not creating this content in FlexBuilder or the Flash IDE. [SWF(width="600",height="400",backgroundColor="#FFFFFF",framerate="30")] Creating the Class Now that our stage has been setup we can start writing the class and defining our variables. In the example below you will see that I am using additional Flex Meta Tags. In this case I am using the Embed Meta Tag.This will allow me to import external assets into my SWF at compile time. In the example below I import front.jpg and back.jpg. On the line following each of the Embed Meta Tags I create a variable to hold a reference to the external assets. As you can see, the variables defined, CardFrontBitmap and CardBackBitmap are data typed as Class. This will allow me to easily create new instances of these items from within my class. In the code below you will also see variables defined to hold our images, drop shadow, rotation values and which side of the card is being viewed. public class CardFlip extends Sprite{ [Embed(source='front.jpg')] public var CardFrontBitmap:Class; [Embed(source='back.jpg')] public var CardBackBitmap:Class; private var card:Sprite; private var cardFront:Sprite; private var cardBack:Sprite; private var cfb:Bitmap; private var cbb:Bitmap; private var ds:DropShadowFilter; private var cardRotationFront:Number = 0; private var cardRotationBack:Number = 45; private var side:String = "front"; Creating the Constructor Now that our variables are out of the way we can setup the constructor for the class. Initially we setup our stage to keep our content from scaling. Next, we create a new DropShadowFilter to be used on our card to help achieve the effect of the card flipping. I also create a new Sprite named card, it will be used to hold all of the Sprites and external images that we will be using in the class. public function CardFlip(){ stage.quality = StageQuality.BEST; stage.scaleMode = "noScale"; stage.showDefaultContextMenu = false; stage.align = "TL"; ds = new DropShadowFilter(10, 45, 0x000000, 0.5, 5, 5, 1, 3, false, false, false); card = new Sprite(); card.filters = [ds]; Remember the variables we set when we created our Embed Meta Tags? Now is the time to use them. Here I assign the variables cfb (which I made stand for “Card Front Bitmap”) and cbb (“Card Back Bitmap”) to new instances of our CardFrontBitmap and CardBackBitmap class. The cfb and cbb variables are bitmaps so that they are able to easily load in my external image files. I want my card to have its registration point in the middle of itself instead of having a 0x and 0y registration.In order to do that I offset the position of cfb and cbb by half of their width and height. You will also notice that I set the scaleX property of the cbb to -1. This flips the image horizontally so that the back of the card appears correctly when the card is flipped. Had I not set the scaleX property here, the back of the card would appear flipped horizontally and the text would be backwards reading from right to left. Once all of my properties are set I add cfb and cbb to two Sprite containers. I named the sprites cardFront and cardBack. I add these Sprites to the card Sprite I created earlier. You will also notice that I then initially set the visibility to false for the back of the card since we don’t need to see that yet. cfb = new CardFrontBitmap(); cfb.x = (cfb.width/2)*-1 cfb.y = (cfb.height/2)*-1 cardFront = new Sprite(); cardFront.addChild(cfb); card.addChild(cardFront); cbb = new CardBackBitmap(); cbb.scaleX = -1; cbb.x = (cbb.width/2); cbb.y = (cbb.height/2)*-1 cardBack = new Sprite(); cardBack.addChild(cbb); cardBack.visible = false; card.addChild(cardBack); Now that we have our external images created and card face Sprites created and added to our card Sprite, we can add the card Sprite to the Display List. I pushed the x and y properties to 200 just to get my card away from the edge of the stage a bit. I also update the initial rotation of the card to my cardRotationFront variable that I defined. addChild(card); card.x = 200; card.y = 200; card.rotation = cardRotationFront; Setting the PerspectiveProjection PerspectiveProjection is new in Flash Player 10. Basically it works somewhat like a 3D camera. It will control the perspective in which we are looking at a give object. PersepectiveProjection defaults to the origin of the parent container. If we did not change our PerspectiveProjection projectionCenter, the card would not appear to be flipped when we set the rotationY property to 180. In order to make sure that we are looking dead center on the card from the front we set the perspectiveProjection projectionCenter to 200x and 200y so that it matches the location to which we have moved the card Sprite to on the stage. You can learn more about PerspectiveProjection by reading the Flash Player 10 API Documentation. this.transform.perspectiveProjection.projectionCenter = new Point(200,200); this.transform.perspectiveProjection.fieldOfView = 45; Creating and Assigning the Flip To finish off the constructor I add an event to the card Sprite that will call the flip method whenever the card is clicked. card.addEventListener(MouseEvent.MOUSE_DOWN,flip) } Now that we have the flip method being called we can create the flip method itself. The flip method is a pretty basic function. It contains a basic switch statement which checks to see which side of the card we are currently viewing. Once that is determined, it uses the TweenMax class to handle several property changes.The beautiful thing about TweenMax is that it allows us to update multiple properties and filters in one call.If you are unfamiliar with the usage of TweenMax you can rad up on it at GreenSock. In the flip method below, you will see that for flipping to the back we set the new rotationY property to 180, rotate the card to the specified rotation and modify the drop shadow. The same logic applies in the case of flipping the card from the back to the front again. In addition to changing the properties mentioned above, we also created a parameter called onUpdate. This allows us to call a function every time the property values have been changed through the cycle of the tween. In this case, we call the setSideVisibility method which we will discuss next. public function flip(e:MouseEvent):void{ switch(side){ case "front": side = "back"; TweenMax.to(card, 1, {rotationY:180,rotation:cardRotationBack,onUpdate:setSideVisibility,dropShadowFilter:{blurX:5, blurY:5, alpha:0.5, distance:-10}}); break; case "back": side = "front"; TweenMax.to(card, 1, {rotationY:0,rotation:cardRotationFront,onUpdate:setSideVisibility,dropShadowFilter:{blurX:5, blurY:5, alpha:0.5, distance:10}}); break; } } Determining Which Side of the Card to Make Visible: At this point all of the heavy lifting is done. All we need to do is determine which side of the card to show at any given point. This could be done any number of ways; I choose to keep it simple and change the visibility of the card face whenever the very edge of the card is being viewed. In the code below I look for a 90 degree angle in the tween cycle and use that opportunity to swap the visibility of my card faces. private function setSideVisibility():void{ if(card.rotationY >= 90){ cardBack.visible = true; }else if(card.rotationY < 90){ cardBack.visible = false; } } } } Wrapping Up and Using External SWFs So, for the most part this is a pretty simple class to write and implement. It could easily be modified to suit whatever need you may have. To wrap up I thought it might be useful to show you a quick example of how you would use external SWF files in the card flip and use an object other than the card itself to call the flip method. The full class for this example is in the resources zip file for this article so I will only go into some of the basic modifications to the class above that I made. Really, only two simple changes allow me to import external SWF files for use in the card flip. Take a look at the result below and scroll down to see the changes made: The first change was a simple one, we simply need to change the source our oEmbed Meta Tags to load the SWFs: [Embed(source='helloCardFront.swf')] public var CardFrontSWF:Class; [Embed(source='helloCardBack.swf')] public var CardBackSWF:Class; [Embed(source='flipButton.swf')] public var FlipButton:Class; The next change is just as simple, we just need change cfb and cbb to Sprites instead of Bitmaps: private var cfb:Sprite; private var cbb:Sprite; Again, the full version of the card flip using both SWFs and images is available in the resources zip for this article. It will be much easier to view them in your text editor in their full glory. Conclusion Well, that pretty much sums it up. Flash Player 10 looks like it is going to provide developers with a lot of new toys! As always, I would love to see any updates or creations you make using this class! Please shoot me a comment to show me your experiments and findings! Maikel Sibbald 12 June, 2008 at 6:47 pm I’m trying to build a simular thing in Flex. But my flexbuilder does not like this.transform.perspectiveProjection.projectionCenter = new Point(200,200); this.transform.perspectiveProjection.fieldOfView = 45; Very strange, it does take rotationY. I’m using 3.0.1.1844 Jim Freer 28 June, 2008 at 7:54 pm I don’t see any difference in behavior with or without the 2 lines: this.transform.perspectiveProjection.projectionCenter = new Point(200,200); this.transform.perspectiveProjection.fieldOfView = 45; I also compared my 2 compiled versions with your version and see no difference. Jim Freer 28 June, 2008 at 8:50 pm I want to apologize for my previous comment. I still don’t see a difference when I comment out the following lines: this.transform.perspectiveProjection.projectionCenter = new Point(200,200); this.transform.perspectiveProjection.fieldOfView = 45; However, I do see differences when I put more extreme numbers in their place. Your post has given me a clue on how to manipulate PerspectiveProjection for my own project. I have to admit I still don’t understand what I’m seeing. But I wanted to thank you for getting me moving again. Nate Chatellier 8 July, 2008 at 10:10 pm This could look a little better if the projected shadow had the same angle regardless of which side of the card was facing up. But, nice article nonetheless. BigAl 24 February, 2011 at 3:19 pm Nice Tutorial! Here’s slightly different one for creating cool 3D effects with AS3: Mapy 10 July, 2008 at 9:46 am Super extra Blog. It’s very exciting! Daniel 10 July, 2008 at 3:01 pm This is very cool. DO you still have the none 10 version handy? webdesign 15 July, 2008 at 1:21 pm Wow nice tutorial i love AS 3 !! thx for writing BigBoss 31 July, 2008 at 3:26 am This is very useful article.i am new at making flash . this article really helped me.I hope you will share more.. Thanks !! dai 3 September, 2008 at 12:40 pm this is crashing in FF3 ReferenceError: Error #1069: Property not found on flash.geom.Transform and there is no default value. at CardFlipSWF() ReferenceError: Error #1069: Property not found on flash.geom.Transform and there is no default value. at CardFlip() Abhi 3 September, 2008 at 5:14 pm I am just starting with AS3 so think the article will help me a lot. thanks for nice works Lance 7 December, 2008 at 11:31 pm Hi Ben, Thanks so much for this tutorial, it’s the greatest one out there! I have a question though, or even a bug… In your example, for the card back, you made it face the right direction by scaling it by (-1) with: cbb.scaleX = -1; While this works in this case, it doesn’t work with Flex UIComponents correctly, as they look distorted and some parts of them are cut off. I took your example and changed all of your sprites to UIComponents and your Bitmaps to some custom components to make better 3D transitions than the FxEffects in Flex and it works surprisingly well! However, the scaling by (-1) is messed up. And the interesting thing is, if I did “cbb.rotationY = 180”, it looks beautiful BUT my FPS goes down from 30 to 12 every time I flip from front to back! Do you have any idea how to get around this issue? If it’s going to slow down this much then making two sided planes is out in Flash 10. Thanks so much. Best, Lance Justin 9 January, 2009 at 7:14 pm Hi, I’ve posted another example using Senocular’s method of determining which side of the clip should be visible. It can be useful when perspective comes into play and just monitoring the values of rotationX Y and Z will not work. There’s also a class for creating double sided clips, might be useful to someone! Richard 13 January, 2009 at 5:33 pm Thanks for an informative article. I was surprised by one thing: I’ve never come across the ‘[SWF(…’ metatag before. I’ve scoured the documentation but I can’t see where I missed it. Is this undocumented, or is there some particular document that I have overlooked? Kiumars Zarrabi 2 February, 2009 at 6:18 pm Hello, Thank you for very cool example and your detail explanation of it. However, I have encountered some issues, and seeking help. The problems that occurred are: 1172: Definition flash.geom:PerspectiveProjection could not be found. When I type import flash.geom. I cannot even find PerspectiveProjection in the auto menu! 1119: Access of possibly undefined property perspectiveProjection through a reference with static type flash.geom:Transform. 1119: Access of possibly undefined property perspectiveProjection through a reference with static type flash.geom:Transform. 1119: Access of possibly undefined property rotationY through a reference with static type flash.display:Sprite. Richard S Davies 3 April, 2009 at 11:54 am Getting multiple errors in FF3 (PC) inverseSquared 3 June, 2009 at 4:03 pm To all of those getting errors on the perspectiveprojection the problem is, as stated within the third paragraph of the Adobe docs here (), that you cannot change the properties directly as shown. You must create a PerspectiveProjection object and THEN set it to the sprite’s transform properties. In all other respects, a great tutorial! var perspectiveCorr:PerspectiveProjection = new PerspectiveProjection(); perspectiveCorr.fieldOfView = 45; perspectiveCorr.projectionCenter = new Point(200,200); this.transform.perspectiveProjection = perspectiveCorr; Vimal Saifudin 7 September, 2009 at 12:49 pm How can make it such a way that it flips automatically instead of clicking the button,. I am new to flash.. pls help mrsanders 5 February, 2010 at 6:28 pm Very useful, thanks so much! devendra kumar 11 March, 2010 at 10:39 am Hi i want to use flip so i need sourcecode for that Abhimanyu Rana 16 April, 2010 at 2:30 pm Thank you very much. It is very helpful for me. Kathi Capron 1 July, 2010 at 2:49 pm Heya! Fantastic believed, but will this genuinely do the work? LucyVanderbuilt 20 February, 2012 at 2:55 pm The CardFlip.swf (with Ben’s butterfly business card) doesn’t seem to be working. Neither in the embed in the page above, nor when I download and try to run locally. If I click within the swf (or, more specifically, on the image of the business card), it does not flip. Did the latest version of Flash Player maybe break something? Something else I can check? The second example (CardFlipSWF.swf, with the “Hello my name is…”) works, but I’m really after the first example because it demonstrates flipping a two-sided sprite rather than a single-sided sprite with show-through… yes? (not sure, since it’s not working)
https://www.thetechlabs.com/tech-tutorials/flash/create-a-card-flip-effect-for-flash-player-10-using-actionscript-3/?replytocom=9856
CC-MAIN-2020-10
refinedweb
3,126
65.12
How can you add more elements to a given list? Use the append() method in Python. This tutorial shows you everything you need to know to help you master an essential method of the most fundamental container data type in the Python programming language.]. Related articles: Syntax You can call this method on each list object in Python. Here’s the syntax: list.append(element) Arguments Code Puzzle Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it? # Puzzle nums = [1, 2, 3] nums.append(nums[:]) print(len(nums)) # What's the output of this code snippet? You can check out the solution on the Finxter app. (I know it’s tricky!) Here’s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall: Examples Let’s dive into a few more examples: >>> lst = [2, 3] >>> lst.append(3) >>> lst.append([1,2]) >>> lst.append((3,4)) >>> lst [2, 3, 3, [1, 2], (3, 4)] You can see that the append() method also allows for other objects. But be careful: you cannot append multiple elements in one method call. This will only add one new element (even if this new element is a list by itself). Instead, to add multiple elements to your list, you need to call the append() method multiple times. Python List append() At The Beginning What if you want to use the append() method at the beginning: you want to “append” an element append() Multiple or All Elements But what if you want to append not one but multiple elements? Or even all elements of a given iterable. Can you do it with append()? Well, let’s try: >>> l = [1, 2, 3] >>> l.append([4, 5, 6]) >>> l [1, 2, 3, [4, 5, 6]] The answer is no—you cannot append multiple elements to a list by using the append() method. But you can use another method: the extend() method: >>> l = [1, 2, 3] >>> l.extend([1, 2, 3]) >>> l [1, 2, 3, 1, 2, 3] You call the extend() method on a list object. It takes an iterable as an input argument. Then, it adds all elements of the iterable to the list, in the order of their occurrence. List append() vs insert() The difference between the append() and the insert() method is the following: - the append(x)method adds new element xto the end of the list, and - the insert(i, x)method adds new element xat position iin the list. It shifts all subsequent elements one position to the right. Here’s an example showing both append() and insert() methods in action: >>> l = [1, 2, 3] >>> l.append(99) >>> l [1, 2, 3, 99] >>> l.insert(2, 42) >>> l [1, 2, 42, 3, 99] Both methods help you add new elements to the list. But you may ask: Which is faster, append() or insert()? All things being equal, the append() method is significantly faster than the insert() method. Here’s a small script that shows that the append() method has a huge performance advantage over the insert() method when creating a list with 100,000 elements. import time l1 = [] l2 = [] t1 = time.time() for i in range(100000): l1.append(i) t2 = time.time() for i in range(100000): l2.insert(0,i) t3 = time.time() print("append(): " + str(t2 - t1) + " seconds") print("insert(): " + str(t3 - t2) + " seconds") # OUTPUT: # append(): 0.015607357025146484 seconds # insert(): 1.5420396327972412 seconds The experiments were performed on my notebook with an Intel(R) Core(TM) i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM. Python List append() vs concaten append() If Not Exists A common question is the following: How can you add or append an element to a list, but only if it doesn’t already exist in the list? When ignoring any performance issues, the answer is simple: use an if condition in combination with the membership operation element in list and only append() the element if the result is False. append() Return New List If you use the lst.append(element) operation, you add the element to the existing list lst. But what if you want to create a new list where the element was added? The answer is simply to use the list concatenation operation lst + [element] which creates a new list each time it is used. The original list lst will not be affected by the list concatenation operation. Here’s an example that shows that the append() method only modifies an existing list: >>> lst_1 = [1, 2, 3] >>> lst_2 = lst_1.append(4) >>> lst_1 [1, 2, 3, 4] And here’s the example that shows how to create a new list as you add a new element 4 to a list: >>> lst_3 = [1, 2, 3] >>> lst_4 = lst_3 + [4] >>> lst_3 [1, 2, 3] By using the list concatenation operation, you can create a new list rather than appending the element to an existing list. Python List append() Time Complexity, Memory, and Efficiency Time Complexity: The append() method has constant time complexity O(1). Adding one element to the list requires only a constant number of operations—no matter the size of the list. Space Complexity: The append() method has constant space complexity O(1). The operation itself needs only a constant number of bytes for the involved temporary variables. The memory overhead does not depend on the size of the list. Note that the list itself does have linear space complexity: you need O(n) bytes to represent n elements in the list. Efficiency Considerations: The append() method is as efficient as possible. In terms of the asymptotic behavior of the time complexity, there’s no way to improve upon the append() method—even if you’d use other data structures such as sets or binary trees. However, if you need to add multiple elements to the list, you can get some constant factor improvements by using the extend() method rather than the append() method. The former takes an iterable as an argument so you can add many elements at once in a single batch. This is more efficient and can lead to 50% performance improvements in practical settings. If you’re interested in the most performant ways to add multiple elements to a list, you can see extensive performance tests in this tutorial on the Finxter blog. Python List append() at Index Do you want to append an element at a certain position? This is called insertion and you can do it with the list.insert(i, x) method that inserts element x at position i of the list. All subsequent elements will be shifted to the right (their index increases by one). The time complexity of the insert() method is O(1). Here’s an example: >>> lst = [99, 42, 101] >>> lst.insert(2, 7) >>> lst [99, 42, 7, 101] The code inserts element 7 at position 2 of the list. Element 101 previously held position 2 so it now holds position 3. If you want to insert an element and create a new list by doing so, I’d recommend to use Python slicing. Check out this in-depth blog tutorial that’ll show you everything you need to know about slicing. You can also get your free slicing book “Coffee Break Python Slicing”. Here’s the code that shows how to create a new list after inserting an element at a certain position: >>> lst = [33, 44, 55] >>> lst[:2] + [99] + lst[2:] [33, 44, 99, 55] Again, you’re using list concatenation to create a new list with element 99 inserted at position 2. Note that the slicing operations lst[:2] and lst[2:] create their own shallow copy of the list. Python List append() Error Actually, there isn’t a lot of things you can do wrong by using the append() method. 1) One common error happens when you assume that the append() method creates a new list. This is not the case: there’s no return value for the append() method. It simply appends an element to an existing list. 2) Another error can happen if you try to append an element to a list but the list is not yet created. Of course, you can only call the method if you properly initialized the list object. 3) Yet another error happens if you try to use the append() method with too many arguments. The append() method takes only one argument: the element to be appended. If you add another argument (like the position on which you’d like to append the element), you’ll get an error. exactly this purpose. Here’s an example: >>> lst = [4, 5] >>> lst.append(None) >>> lst.append(7) >>> lst [4, 5, None, 7] For comprehensibility, I have to say that it’s not possible to add an empty element to a list, simply because of the fact that there’s no such thing as an empty element in Python. Python List append() Thread Safe Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as append()) are actually thread safe. In other words: can you call the append(). Python List append() Sorted How to insert an element into a sorted list? Well, you shouldn’t use append() in the first place because the append operation cannot insert an element at the correct position. It only appends the element to the end of the list. Instead, you can use binary search and the list.insert(i,x) method to insert element x at position i in the list. Here’s the code for the binary search algorithm in Python:) Please find a more detailed discussion of the binary search algorithm at my tutorial on the Finxter blog. Python List append() Dictionary These are the different interpretations of using the append() method with a dictionary: - Append a dictionary to a list. - Append all key value pairs from a dictionary to a list. - Append an element to a list stored in a dictionary. - Add/Append a key value pair to a dictionary. Let’s explore them one by one: Append a dictionary to a list. A dictionary is a Python object. So you can simply add it to a list like you would any other element: >>> dic = {"hello": 0, "world":1} >>> lst = [1, 2, 3] >>> lst.append(dic) >>> lst [1, 2, 3, {'hello': 0, 'world': 1}] The fourth list element is the dictionary itself. Append all key value pairs from a dictionary to a list. Say, you’ve got a dictionary with (key, value) pairs. How can you add all of them to a given list? The answer is simple: use the extend() method with the dictionary method items(). >>> income = {"Alice": 100000, "Bob": 44000} >>> lst = [("Carl", 22000)] >>> lst.extend(income.items()) >>> lst [('Carl', 22000), ('Alice', 100000), ('Bob', 44000)] The items() method returns all key value pairs as tuples. You can master Python dictionaries by following my visual, ultimate guide on this blog. Append an element to a list stored in a dictionary. This one is easy: retrieve the list and call the append() method on it. Here’s how: >>> teams = {"A" : ["Alice", "Anna"], "B" : ["Bob", "Bernd"]} >>> teams["A"].append("Atilla") >>> teams["A"] ['Alice', 'Anna', 'Atilla'] As the list is an object, modifying this object (even if it’s “outside” the dictionary) will affect the object stored in the dictionary itself. Add/append a key value pair to a dictionary. How can you add a (key, value) pair to a dictionary? Simply use the operation dic[key] = value. Python List append() For Loop One Line You’re looking for a one-line for loop to add elements to a list? This is called list comprehension and I’ve written a detailed article about it on this blog. Here’s the quick example to add all elements from 0 to 9 to a list: >>> [i for i in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Where to Go From Here? The list.append(x) method adds element x to the end.
https://blog.finxter.com/python-list-append/
CC-MAIN-2021-43
refinedweb
2,044
72.87
Filter. I figure I might as well tell you where the source is first. I decided to use GitHub for this project… so it is hosted on GitHub here. Download it and have at it! MONADS MONADS MONADS! If Steve Ballmer were a functional programmer, he’d FOR SURE be screaming MONADS MONADS MONADS! I’ve discussed monads in the past (with a little less understanding than I have now :) ). Basically a parser (like what I’ve implemented) is like the IEnumerable monad in C#. There is a whole list of combinators you can use to define exactly what a parser does to arrive at a result. Intermediate results are stored as pairs of the parsed value and the string left to parse. I have defined a few simple combinators (I will talk about Or, When, and OrWhen specifically) that are useful. I’ve also defined some of the standard LINQ query operators… so you can easily use a parser as a LINQ query. As Erik Meijer says, “everything is a query!”. Parser Internals The parser has really 2 important internals, a delegate and a storage container for the result and “rest” string. Here’s the code for each. // generic delegate for getting result/restpublic delegate ParserResult<T> Parse<T>(string input);// class for holding the result and restpublic sealed class ParserResult<T>{public ParserResult(T parsed, string remaining){Parsed = parsed;Remaining = remaining;}public T Parsed { get; private set; }public string Remaining { get; private set; }} You’ll notice I’m using a generic… so you can pretty much parse anything here. The Parse delegate takes an input and returns a parser result. The parser’s job is to make sure everything is parsed correctly. This is in the ParserLib project of my source code. The Combinators Combinators in functional programming are kind of an awesome thing. The main operators are bind and return. Bind is implemented with Select, SelectMany and Then. These are really the important operators, but Or, When, and OrWhen are what I find particularly useful when dealing with constraints and possibilities in my URL to IQueryable configuration. Or is a combinator that takes 2 Parse delegates. If the first should return null (indication of failure) then the result of the Parse will be the result of the second delegate. When is a unary parser (takes only 1 parser) and takes a string predicate. If the predicate is satisfied by the input, then the result will be delegated to the Parse instance. Otherwise the parser fails and null is returned. This is especially useful in my implementation of String to IQueryable because I associate a beginning keyword to a parser. OrWhen is a hybrid of Or and When that I built to mainly chain my parsers together. OrWhen takes a string predicate (like When) and 2 parsers (like Or). If the result isn’t null for the first parser, then that is the result. Otherwise the string is tested against the predicate and fails if the predicate fails or returns the result of the parse if the string predicate passes. If you download the code, you will see these defined in the ParserLib project. I’m not going to show you the implementation for the sake of brevity. But I would recommend having a look. The Query Parser Ah now to the good stuff. QuerParser is it’s own separate project in my solution. I have defined what I call “ParserExpressions”, which mostly conform to the LINQ standard query operators. The expressions are take, skip, where, sort, and page (which isn’t a standard query operator). I will discuss why some of the other operators were not implemented in a minute. But you do have the option of extending the parser by creating your own operators. Here is the interface that all the expressions use. public interface IParserExpression<T>{IQueryable<T> Map(IQueryable<T> queriable);} That’s it. Just one method (plus a ToString… more on that in a bit). The expression has to be able to transform an IQueryable using the Map method. How this method works is up to the expression. For example, the take expression transforms the IQueryable by calling the Take method and passing an integer (which is passed in the constructor) to generate a new IQueryable. You will see how this is useful in a minute. It is important to note that the ParserExpression does not parse the string. They simply act as containers for state until the IQueryable is mapped upon. The parse delegate, as I said before, is the logic behind the parser. Let’s now have a look at the parse code. public class StringQueryParser<T>{private string expressions;public StringQueryParser(string exprs){expressions = exprs.ToLower();}protected Predicate<string> StartsWith(string test){return str => str.StartsWith(test);}protected virtual Parse<IParserExpression<T>> Parsers{get{return Parser.When(StartsWith(ParserConstants.ExpressionSeparator.ToString()), IgnoreSeparatorParser).OrWhen(StartsWith(ParserConstants.PageIndicator), PageParser).OrWhen(StartsWith(ParserConstants.SkipIndicator), SkipParser).OrWhen(StartsWith(ParserConstants.TakeIndicator), TakeParser).OrWhen(StartsWith(ParserConstants.SortIndicator), SortParser).Or(WhereParser);}}public IEnumerable<IParserExpression<T>> Parse(){if (string.IsNullOrEmpty(expressions))return new List<IParserExpression<T>>();return Parsers.Repeat().Invoke(expressions).Parsed.Where(x => x != null);}public IQueryable<T> Map(IQueryable<T> queriable){foreach (var parseExpr in Parse())queriable = parseExpr.Map(queriable);return queriable;}// the parsers have been removed for brevity. once// again, download the code for have a look at the// entire parser code......} As you’ll see I’ve removed the parsers. Just go download the code to look at the parser code. Those are generally unimportant for this post. I can go in-depth if there is a demand for it. I’ve implemented a Parsers property that returns a composite parser that encapsulates the logic to parse the string. If you were to override this class, you’d want to override the Parsers property to append your own parsers or just completely start anew. Each indicator (page, take, sort and skip) will be covered in the next section, but basically we filter an expression down to it’s parts and create the expression from there. You’ll have a better idea of how to form these expressions by the end. Don’t worry :) So really there’s no surprises here (other than repeat… that’s in ParserLib. Kind of intuitive… you parse until the input is empty). When all is said and done, the IQueryable is mapped through all the expressions generated by the string. Here’s how accomplish a parse in an ASP.NET MVC controller. public class MyController : Controller{....// option #1, instantiate a StringQueryParserpublic ActionResult List(string query){// replace with your data accessIQueryable<User> usersQueryable = Session.Linq<User>();// do the parsingvar parser = new StringQueryParser<User>(query);usersQueryable = parser.Map(usersQueryable);// manipulate and parse as neededreturn Json(usersQueryable.ToList());}// option #2, use the extension methodpublic ActionResult List2(string query){// replace with your data accessvar usersQueryable = Session.Linq<User>().Parse(query);// manipulate and parse as neededreturn Json(usersQueryable.ToList());}......} I personally prefer option 2. That’s a little neater, but both do the same thing. You will want to setup a “catch all” route in MVC that maps to this. How to form expressions At this point, I’ve been blabbering about the internals of the parser. Some of you probably don’t care… which is actually fine with me. The important part of this whole project is the real world application. Basically you will be passing a well-formed expression to your controllers that will manipulate the IQueryable accordingly. Here’s the low down on how to do this by string. Singular Expressions /skip-5/ skips the first 5 elements /take-4/ returns only 4 elements /take-all/ returns all elements /page-5-11/ returns a paged result on page 5 (1-based) with page size 11 /page-5/ returns a paged result on page 5, default page size is 10 in my library /sort-name/ applies an ascending sort on the name property /sort-desc-name/ applies a descending sort on the name property /sort-name,age,birthmonth/ applies an ascending sort on name property, then ascending sort on age property, then on birthmonth property /sort-desc-name,age,birthmonth/ applies a descending sort on the name property, then ascending sort on age property, then on birthmonth property /name-equals-jon/ applies a where name equals jon /age-greaterthan-4/ applies a greater than 4 where /name-not-null/ applies a name must not be null constraint For the where expression, there are a lot of combinators that we support (equals, like, not, greater than, less than, greater than or equal, and less than or equal). We also support null as a “keyword”. So don’t expect your name properties to be null or something… that would be interpreted as null by the parser and not “null” as in the string. Multiple Expressions It is particularly useful to chain these expressions together. Here’s some examples. Feel free to combine these however you’d like. /page-5/name-equals-jim/age-lessthan-90/age-greaterthanequal-4/ /skip-4/take-3/name-equals-kim/haschainsaw-equals-true/ /gender-equals-female/page-5-10/ The order is typically of no importance except for using skip and take together. It is a good idea to use a skip before a take. That’s just been my experience. You’ll notice in these examples (which are fictitious, by the way :)) that we support a lot of different types. Strings, int, double, float, enum, and more. In the future I’ll add an interceptor that you can parse where’s differently. How properties work When designing this solution, I had this idea that you might want to name a property differently or ignore a property. I have added two attributes (ParserIgnore and ParserPropertyName). The parser takes these into effect. If you pass the parser an ignored property then the constraint isn’t parsed. You can define a parser property name to a property and that name will be used in determining which property to apply a constraint. This avoids the issue of property name conflicts… you have to resolve those yourself using the property name attribute for the expected behavior to work when you have the same property name in different case. Also, it’s worth mentioning that everything is parsed in lower-case. So the case in your expressions are of no importance… it’ll just be changed to lower-case upon parsing. Using the generator Sometimes you don’t want to form these by hand… concatenation isn’t exactly useful when you’re using paged data, for example. Because of this, I’ve built a generator. Basically you’d pass a few IParserExpression’s to this generator and it’ll generate the string for the query for you. The generator uses the ToString method on each IParserExpression. It is important to note that you must override ToString for the generator to work on your custom expressions. You can take a look at the code yourself, but I thought I might show you an example of how to use this. ....<h2>My MVC Page</h2>....<a href="#<% new StringQueryGenerator<User>(new IParserExpression<User>[]{new WhereExpression<User>(u => u.Name, WhereCombinator.equals, "foo"),new PageExpression<User>(4, 10)}).Generate() %>...... This will generate a string like /name-equals-foo/page-4/ . Both where and sort have a constructor overload that you can pass in a property expression… so you don’t have to use the property name as a string. Conclusion Wow that was a long blog post :) I hope that you’ve seen that this is useful for ASP.NET MVC in particular and in an instance where a user can define their own query. There are many examples of this sort of thing on the web where people are using this approach to filter results based on a clean-looking query. I hope you check out the source code and let me know if you have any suggestions or comments on my implementation. And with that I say DEATH TO QUERY STRING FILTERING!
http://weblogs.asp.net/zowens/filter-iqueryable-by-string-for-asp-net-mvc
CC-MAIN-2015-32
refinedweb
2,007
56.76