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
- Loss - Starting the computer may be slow (3-4 minutes to start) - Logging onto Windows may be slow More granular symptoms: - Unable to connect to rootdefault, rootcimv2 and/or rootcitrix namespaces via WBEMTEST - Repository growing large related to OBJECTS.DATA file - Note repeating-nested CITRIX namespace entries in WMIMGMT.MSC. WMI CONTROL > PROPERTIES > SECURITY > expand ROOT structure to note missing/repeating namespaces And here are the hotfixes that we recommend if you are experiencing WMI problems in Windows: Hotfix list for Windows 7 and Windows Server 2008 R2 2831347 Roaming user profiles are corrupted when a monitoring program executes a WMI query on a Windows Server 2008 R2 SP1-based RDS server Vista and Windows Server 2008 2639845 The memory usage of an application or a service keeps increasing when it loads and unloads the Netshell.dll module frequently in Windows Vista or Server 2003 SP2 2257980 “0x80041002 (WBEM_E_NOT_FOUND)” error code occurs when you try to open a WMI namespace on a computer that is running Windows Server 2003 SP2 For all supported x86-based versions of Windows Server 2003 Hotfix list for Windows XP 933062 A hotfix is available that improves the stability of the Windows Management Instrumentation repository in Windows XP Til next time, Blake Morrison Join the conversationAdd Comment I feel it is helpful to note that if you work in a domain environment where multiple users log in to a single computer your repository could grow again even after it has been rebuilt. We were finding that it would take upwards of an hour to get to the login screen. We just found this out today as we are currently dealing with an issue with the WMI repository bloating. There is a group policy we need to change to keep each user from registering the same software in the repository which can lead to corruption and bloat. Thanks Tim! I had KB2492536 missing in my list (social.technet.microsoft.com/…/list-of-wmi-related-hotfixes-for-windows-7-and-windows-server-2008-r2.aspx). Congratulations great post Justin: yes it does, but 2465990 was left on the list. Justin, Hotfixes supersede each other only if the replaced files are from the same servicing branch. Please see blogs.technet.com/…/how-does-windows-choose-which-version-of-a-file-to-install.aspx for some information on that process. Wait, how is support.microsoft.com/…/2617858 different from support.microsoft.com/…/2505348 ? Don't they both fix wmi verification of large repositories? Isn't 2465990 superseded by 2617858? They replace the same files. I applied the Hotfix list for Windows Server 2003 SP2 and reboot the server. Then I run wmidiag tool. The error of 0x80041002 still occur. Please Advice, Thank you, Hi, I am having problems with "Repository growing large related to OBJECTS.DATA file" and at some point when the repository file get very bloated on our RDS servers i need to ResetRepository to get things up and running for a couple of months. No i need to install all the hotfixes or is there just one that will fix my issue ? btw, issue happens also in Windows 2012. Is there any hotfix for that? Still an excellent list, specifically where these are maintained separately independent of the cumulative updates/rollups. Last revision was 8/9/13, is there any new content for Windows 7/Server to bring the list current? Also some best practice on the order & chaining of hotfixes where these would frequently need multiple restarts individually.
https://blogs.technet.microsoft.com/askperf/2011/08/05/suggested-hotfixes-for-wmi-related-issues-on-windows-platforms-updated-august-9th-2013/
CC-MAIN-2018-05
refinedweb
583
52.29
MySQL: User Defined Function Tutorial This tutorial explains what a User Defined Function (UDF) is, what it does, and why/when it is useful. 1. What Is a User Defined Function? Basically, a User Defined Function (UDF) is a piece of code that extends the functionality of a MySQL server by adding a new function that behaves just like a native (built-in) MySQL function, such as abs() or concat(). UDFs are written in C (or C++ if you really need to). Maybe there is a way to write them in BASIC, .NET, or whatever but I don't see why anybody would want to do that. 2. Why/When Are UDFs Useful? As implied by the name, UDFs are useful when you need to extend the functionality of your MySQL server. This little table should make it clear which method is best for a given situation a UDF, but you have to write it in the MySQL source code and recompile the whole thing. This will (believe me) be a lot of work because you have to do it again and again with every new version of MySQL. 3. How to Use UDFs This part is really easy. When you have your UDF finished, you just use it like every other native function. For example: SELECT MyFunction(data1, data2) FROM table 4. Writing the UDF Now, you can get started writing your first UDF. Just follow these steps: Step 1: Create a new shared-library project In the example, I used VC++ 6.0 with a standard DLL). Step 2: Create some headers These headers are either standard library headers or from the MySQL Server's include directory. #ifdef STANDARD /* STANDARD is defined. Don't use any MySQL functions */ #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __WIN__ typedef unsigned __int64 ulonglong; /* Microsoft's 64 bit types */ typedef __int64 longlong; #else typedef unsigned long long ulonglong; typedef long long longlong; #endif /*__WIN__*/ #else #include <my_global.h> #include <my_sys.h> #endif #include <mysql.h> #include <ctype.h> static pthread_mutex_t LOCK_hostname; Step 3: Decide what kind of function you want There are essentially two choices to be made: - Is the function an aggregate function or not? (You will learn more about aggregate functions later.) - Which type of return value should the function return? Here, you have four options: Step 4: Assign non-aggregate functions Now, you have to declare and implement some functions the MySQL server needs to use your UDF. But, first some structs you'll need for that: - UDF_INIT: - UDF_ARGS: Step 5: Examine the functions De-/Initialization: extern "C" my_bool MyTest_init(UDF_INIT *initid, UDF_ARGS *args, char *message) { // The most important thing to do here is to set up the memory // you need... // Say you need a lonlong type variable to keep a checksum // although you do not need one in this case longlong* i = new longlong; // create the variable *i = 0; // set it to a value // store it as a char pointer in the pointer variable // Make sure that you don't run into typecasting troubles later!! initid->ptr = (char*)i; // check the arguments format if (args->arg_count != 1) { strcpy(message,"MyTest() requires one arguments"); return 1; } if (args->arg_type[0] != INT_RESULT) { strcpy(message,"MyTest() requires an integer"); return 1; } return 0; } extern "C" void MyTest_deinit(UDF_INIT *initid) { // Here you have to free the memory you allocated in the // initialization function delete (longlong*)initid->ptr; } The actual function: extern "C" longlong MyTest(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) { /* So, finally, this is the part were you do the real work. This function is called for every record and the current value(s) or better pointers to the current values are stroed in the UDF_ARGS variable. You have to get the values, do your calculation, and return the result. NOTE: You can access the memory allocated in MyTest_init through the UDF_INIT variable. In this example, you will just add 5 to every value...*/ return *((longlong*)args->args[0])+5; } Step 6: All done! Now, you have to compile the library and copy it to a directory where your OS can find it. On Windows, that would be anywhere the PATH System variable says. Personally, I use the MySQL server's bin directory. You have to make sure that the library is in one of those directories; otherwise, MySQL can't use it! Also, make sure to export all the functions MySQL needs! Step 7: Tell MySQL about it This is really straightforward: Just execute the following SQL command: CREATE [AGGREGATE] FUNCTION MyTest RETURNS [INTEGER|STRING|REAL|DECIMAL] SONAME the_libraries_exact_name Now, you can use it like any other function. 5. Aggregate Functions Now, some words about aggregate functions. When your UDF is an aggregate function, you have to add some more functions and some functions are used in a different way. The calling sequence is: - Call MyTest_init to allocate memory (just like a normal UDF). - MySQL sorts the table according to the GROUP BY statement. - Call MyTest_clear for the first row in each group. - Call MyTest_add for each row that belongs to the same group. - Call MyTest to get the result when the group changes or the last row has been processed. - Repeat Steps 3 to 5 until all rows have been processed. - Call MyTest_deinit to free any used memory. Now, look at the new functions needed for the aggregate function. In this example, you'll simply add up all the values (like the native SUM function). void MyTest_clear(UDF_INIT *initid, char *is_null, char *error) { /* The clear function resets the sum to 0 for each new group Of course, you have to allocate a longlong variable in the init function and assign it to the pointer as seen above */ *((longlong*)initid->ptr) = 0; } void MyTest_add(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) { // For each row, the current value is added to the sum *((longlong*)initid->ptr) = *((longlong*)initid->ptr) + *((longlong*)args->args[0]); } longlong MyTest(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) { // And, in the end, the sum is returned return *((longlong*)initid->ptr); }
http://mobile.codeguru.com/cpp/data/mfc_database/misc/article.php/47652_12615_2/MySQL-UDFs.htm
CC-MAIN-2017-34
refinedweb
1,009
63.09
Specifying multiple columns names with the same prefix efficiently I am running a regression with my observation being at the company level. I want to control for the type of company [what does it produce]. I have this information in an object variable which I turn into categorical and then get the dummies out of it. df['Product Type'] = df['Product Type'].astype('category') df = pd.get_dummies(df, columns=['Product Type']).head() My sample is quite large and I end up getting a lot of dummy variables. It is quite a lot of work to introduce them into my model one by one (there might be 10-15 of them). reg = sm.OLS(endog=df['Y'], exog= df[['X1', 'Number of workers', 'X2', "Product Type_Jewellery", "Product_Type_Apparel", (all the other product dummies) ]], missing='drop') Is there a more efficient way to do this? In stata, I used the prefix i.Product_Type which would signal to the software that the String variable had to be considered as a categorical one... anything similar? Use str.contains to find the columns that contain "Product_*", and accessing them becomes easy. c = df.columns[df.columns.str.contains('Product')] If regex is not needed, you can initialise c as c = df.columns[df.columns.str.contains('Product', regex=False)] Or, using str.startswith: c = df.columns[df.columns.str.startswith('Product')] Or, a list comprehension: c = [c_ for c_ in df if c_.startswith('Product')] Finally, access the subset by unpacking c: subset = df[['X1', 'Number of workers', 'X2', *c]] reg = sm.OLS(endog=df['Y'], exog=subset, missing='drop') How To Select Columns Using Prefix/Suffix of Column Names in , For example, if we want to select multiple columns with names of the columns as And then, we will use Pandas' loc function to do the same. where we need to specify the pattern we are interested in as regular expression. However, you may know that the column names start with some prefix or end with some suffix and interested in some of those columns. In such a scenario, basically we are interested in how to select columns using prefix or suffix of columns names in Pandas. Same idea like what cold provided by using filter sm.OLS(endog=df['Y'], exog=df.filter(regex=r'X1|X2|Number|Product'), missing='drop') [PDF] 057-30: Techniques for Effectively Selecting Groups , If the variable names have the same prefix and a sequential numeric suffix the task is easy. However, when there is no discernable pattern in the variable names Rename multiple pandas dataframe column names. Commander Date Score; Cochice: Jason: 2012, 02, 08: 4: Pima: Molly: 2012, 02, 08: 24: Santa Cruz Using the statsmodels.formula.api you don't need to generate the dummies yourself. Remove spaces from you column names and reference the Categorical column with C(col_name) import statsmodels.formula.api as smf df = df.rename(columns={'Product Type': 'Product_Type', 'Number of workers': 'Number_of_workers'}) results = smf.ols(formula = 'Y ~ X1 + X2 + Number_of_workers + C(Product_Type)', data=df, missing='drop').fit() Sample Data import pandas as pd import numpy as np np.random.seed(123) df = pd.DataFrame({'Y': np.random.randint(1,100,200), 'X1': np.random.normal(1,20,200), 'X2': np.random.normal(-10,1,200), 'Number of workers': np.arange(1,201,1)/10, 'Product Type': np.random.choice(list('abcde'), 200)}) Output of results.summary() ======================================================================================== coef std err t P>|t| [0.025 0.975] ---------------------------------------------------------------------------------------- Intercept 69.2836 23.105 2.999 0.003 23.711 114.856 C(Product_Type)[T.b] 11.3334 6.941 1.633 0.104 -2.356 25.023 C(Product_Type)[T.c] 1.3745 6.943 0.198 0.843 -12.321 15.070 C(Product_Type)[T.d] 2.0430 6.258 0.326 0.744 -10.300 14.386 C(Product_Type)[T.e] 3.8445 6.273 0.613 0.541 -8.528 16.217 X1 0.0207 0.113 0.184 0.854 -0.202 0.243 X2 1.4677 2.177 0.674 0.501 -2.825 5.761 Number_of_workers -0.5803 0.369 -1.573 0.117 -1.308 0.147 ============================================================================== Notice, that with the formulas api since your products create a complete basis it will automatically drop one of the categories since we have the intercept, similar to what you would find in stata. How to Rename Several Excel Columns at Once, Rename Variables at Once, Rename Several Variables, Add Prefix, Add Column names editing in Excel spreadsheets is a relatively simple task. make the work more efficient, if you need to edit multiple columns in the same way - add If you click on it, the setting options will be displayed in the Properties Panel - Prefix, Selecting a group of variables that have the same prefix and whose suffixes form a numbered sequence is easy to accomplish. For instance, if the variables are A1, A2, A3,…, AN then they can be referenced as A1 – AN. pandas.DataFrame.join, Efficiently join multiple DataFrame objects by index at once by passing a list. Column or index level name(s) in the caller to join on the index in other , otherwise joins index-on-index. outer: form union of calling frame's index (or column if on is specified) with other 's Suffix to use from left frame's overlapping columns. I know how PROC transpose works on a single column. But when you have 10 columns, how do you transpose them? I have a data set like the following: ID date1 date2 date3 date4 date5 rec1 rec2 rec3 rec4 rec5 I need to create a data set like this: ID date rec So, in the original data set, I have ev Pivot data from wide to long, A string specifying the name of the column to create from the data stored in the column Can be a character vector, creating multiple columns, if names_sep or names_sep takes the same specification as separate() , and can either be a This effectively converts explicit missing values to implicit missing values, and Each row does have - let's say - 41 columns of which column 1 is a unique identifier, the next 20 columns are customer characteristics and the next 20 columns are the same as the 20 columns before (same names but with a fixed prefix) and could contain - per column - a different value. Rename Transform, Overview · Comparison Operators · EQUAL Function · GREATERTHAN This transform supports multiple methods for renaming two or more columns in a single step. NOTE: For renames of one or more columns to explicit names, specify the For batch rename using prefixes, this parameter specifies the string value with <tidy-select> Columns to pivot into longer format. names_to: A string specifying the name of the column to create from the data stored in the column names of data. Can be a character vector, creating multiple columns, if names_sep or names_pattern is provided. In this case, there are two special values you can take advantage of:
http://thetopsites.net/article/54175265.shtml
CC-MAIN-2020-40
refinedweb
1,163
53.92
Unable to build QT 5.4 for iOS from source I'm unable to build Qt 5.4.2 for iOS nor iphonesimulator. Having errors during configure part, then having fatal errors while performing make step. New to building from source, my configure command is /configure -top-level -xplatform macx-ios-clang -sdk iphonesimulator -nomake tests -debug-and-release -confirm-license -v then getting errors and warnings, like clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated Symbol visibility control enabled. clang: error: invalid linker name in argument '-fuse-ld=gold' /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -o libtest.so -shared -Wl,-Bsymbolic-functions -fPIC bsymbolic_functions.c clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated ld: unknown option: -Bsymbolic-functions clang: error: linker command failed with exit code 1 (use -v to see invocation) Symbolic function binding disabled. then Project ERROR: mtdev development package not found mtdev disabled. libjpeg.cpp:37:10: fatal error: 'jpeglib.h' file not found #include <jpeglib.h> ^ 1 error generated. make: *** [libjpeg.o] Error 1 libjpeg disabled. and many more similar to this one As i said I'm new to building from source. I've checked my XCode version and sdk versions, everything should be ok, but regarding those errors I assume I'm having some troubles with linking or something like it. Thank you for any help ;) - SGaist Lifetime Qt Champion Hi, Do you have the same error if you use the line provided in the Building from source iOS ? @SGaist I think is was the first thing i tried, but it didn't work, so i tried some different configure commands i found, like the one above. I can try it again and tell you. I tried again to build it with configure commant with that guide ./configure -xplatform macx-ios-clang -release and got the same error. Without -nomake argument it starts to make after same errors thrown, and while making it throws fatal errors like Unsupported architecture, then a lot of unknown type errors in types.h and everything ends in a few seconds by sentence too many errors emitted, stopping now. Then it says STL disabled. STL functionality check failed! Cannot build Qt with this STL library. Here is where i posted a whole report : - SGaist Lifetime Qt Champion What version of Xcode are you using ? @SGaist So I have the latest XCode, but errors are still the same. I really don't understanad where the problem is. When it starts the making step, it emmits an Unsupported architecture error. The full list of errors during config and make steps is 2 posts above. I'm starting to be desperate .. @phobos8 Hi I've got the exact same problem on my Mac with OSX Yosemite and XCode 6.1. I cloned the source, checked out to version 5.4.2 and tried to configure but I get the same errors as you. Do you have a solution yet? thanks in advance, best regards Manfred Oh well, I had a typo in my config path, sorry ! Configure and make work well now! cheers Manfred
https://forum.qt.io/topic/54939/unable-to-build-qt-5-4-for-ios-from-source
CC-MAIN-2018-17
refinedweb
532
66.94
Jun 18, 2007 05:25 PMStandardizing on a protocol for resource publishing and editing can bring a lot of benefits since it increases the chances for achieving interoperability between parties and universal understanding. While XML as a base format creates brings some of those benefits, it's a little too general to be useful without also setting some widely accepted ground rules for describing more specific attributes like collections and entries. Combining such a format with the generic HTTP protocol in a RESTful promises a common ground. Indeed there are several protocols available that aim to solve this problem. The first and probably most mature is the ATOM Publishing Protocol (APP) which is a draft IETF standard close to finalization. APP is defined in the latest draft as follows:. MicrosoftMicrosoft. who is involved with IETF APP working group reacted to Dare's claims and said ..: 1.. 2..Joe Gregorio (another major APP contributor) asked, in a comment to Yaron's post the obvious?IBM's Sam Ruby, co-author of RESTful Web Services, believes the protocol intended to support "Web Structured, Schema’d & Searchable" support neither the Web, Schema, or Search: There are two new media types (Application/Web3S+xml and Application/Web3SDelta+xml), two new URI Protocols (Web3S and Web3SBase), and one new HTTP method (UPDATE) defined in this document. I can find no discussion of binary data, in fact everything seems defined in terms of the XML infoset. Given that all data needs to be in a namespace, and that all such namespaces need to use a new URI protocol, one can conclude that no existing XML documents can be directly handled by Web3S. Web3S data is further constrained to be a self enclosed tree. There is no general concept of a hyperlink in Web3S, neither to external data, nor within a tree. To traverse this data, one needs to be aware of the specific schema employed by the application.XML co-inventor Tim Bray criticizes the process that led to Web3S:.David Ing made several interesting observations on the Microsoft effort and summed the whole issue with.. Free $40 SOA Demystified Book Offer Give-away eBook – Confessions of an IT Manager Usage Landscape: Enterprise Open Source Data Integration Server Gated Cryptography The Role of Open Source in Data Integration See all on SOA Social website Would you enroll in an India Forex Group i.e Groups? Have something to say? Cast your votes! The nice thing about standards is that there are so many of them to choose from. - Andrew Tannenbaum
http://www.infoq.com/news/2007/06/app-web3s
crawl-002
refinedweb
424
50.87
go to bug id or search bugs for Description: ------------ Locking exclusively via flock a file opened for writing doesn't trigger a mandatory lock. The python script below could trigger the mandatory lock. Maybe it's because PHP flock() is built on the C function call flock(): "When a program attempts to lock a file with lockf or fcntl that has mandatory locking set, the kernel will prevent all other programs from accessing the file. Processes which use flock will not trigger a mandatory lock." source: Python script: #!/usr/bin/python import os, fcntl fd = os.open('mandlock-file', os.O_RDWR, 0755) print 'fd=', fd fcntl.lockf(fd, fcntl.LOCK_EX) a = raw_input() # during that time, any attempt to open the file will hang os.write(fd, a+'\n') fcntl.lockf(fd, fcntl.LOCK_UN) # now any attempt to open the file will succeed os.close(fd) # eof Test script: --------------- <?php define('FILENAME', 'mandlock-file'); /* first create a file with a mandatory lock: * $ touch mandlock-file * $ chmod g+s,g-x mandlock-file * $ sudo mount -o remount,mand / # my file is inside the '/' mountpoint */ function openlockedfile($filename) { $fp = fopen($filename, 'w+'); while (($fp === false) || (flock($fp, LOCK_EX) !== true)) { sleep(1); echo "spin lock\n"; if ($fp === false) $fp = fopen($filename, 'w+'); } return $fp; } $fd = openlockedfile(FILENAME); // open + lock EX sleep(10); /* During this sleep time, accessing the file should hang until the * php script releases the exclusive lock: * $ cat mandlock-file # should hang until php script termination * Practically, cat doesn't hang (and works) proving the file isn't * exclusively locked by the PHP script. */ closefile($fd); // unlock + close /* eof */ ?> Expected result: ---------------- once the file is created and the mandatory lock setup for it: during the 10 sec timer, opening the file (with or without explicit locking) should hand until the php script terminates. Actual result: -------------- it's possible to opening the locked file during the 10s timer for reading and writing. Add a Patch Add a Pull Request Note that dio_fcntl() of the "Direct IO" extension can successfully exclusively lock the file, but this shouldn't be considered as a workaround as it's not always possible to install extensions. If flock() couldn't be modified for backward compatibility reasons, options could be added to alter its behaviour, or a new call lockf() would be welcome too. The key difference between Python and PHP here is that Python always uses fcntl() internally, whereas PHP will use flock() if it's available (which it obviously is on Linux) and will only fall back to fcntl() if it's not. flock() will never create a mandatory lock, so the manual page is wrong, which I'm pretty sure is my fault. Mea culpa. We can probably fix this by switching to preferring fcntl() within our flock() function as Python does, since that's actually the more useful behaviour, but that would be a (mild) BC break in how flock() behaves in practice — although it would actually bring it into line with what's documented. The options I see are: 1. Change the behaviour of flock() as described above to prefer fcntl(). 2. Add a new lockf() function, as suggested. 3. Just bite the bullet and expose fcntl() as a PHP function on POSIX platforms. 4. Do nothing and update the manual. :) Does anyone have any thoughts? I'm happy to do the donkey work, but am not really sure on the best way to proceed. I like 3 :) change the behavior of flock will intruduce a visible bc break A fifth option is to pull the "Direct IO" extension into the mainline. This extension already expose fcntl() as well as a few other low-level POSIX routines, and have some amount of testing as it's in its fourth version already (though it's said to be in beta state) My worry there is that dio resources are (as I recall, anyway) completely distinct from normal file resources, so you couldn't fopen() a file and then dio_fcntl() it: it's all or nothing. You're right, dio is a plain inteface to the underlying C function hence exposing real file descriptors (integers). That's also what Python does: it exposes two different types of file objects: standard file objects via the builtin open() and file descriptors via os.open() Is that is feasible with php? That's true, but they're still somewhat interchangeable in Python — higher level file objects returned by open() work with fcntl methods. That wouldn't be the case if we bundled dio without further work. You're right, Python is smart and the trick is simple: fnctl module functions are coded such that they detect the type of the object they're given as argument. If it's an integer they assume it is a file descriptor otherwise they call its fileno() method to retrieve the file descriptor integer. So it's a matter of adding your own fileno() method to the PHP standard file object and making the dio_* routines calling it, when not provided with an integer. Does that makes sense to you? It's a suggestion, at the end of the day it's your decision of how to handle this issue, even though it seems to, I'm actually not pushing to get direct io integrated at any cost (I don't have any stake) but I just feel it's the way to go. I am puzzled, what can the current behavior be possibly used for? If the lock is not really locking (and it does not -- neither on Linux nor on FreeBSD), then why bother with it at all? And if nobody bothers, then why not fix it properly? BTW, at least, on BSD the different locking mechanisms create compatible locks:. I hope we're still speaking of MANDATORY locks (the ones provided by "mount -o mand") and not standard file locks? Other locks (advisory) behave as expected. So what's the solution you chose to allow locking a file with a MANDATORY lock using PHP? This is my test case: <?php function warn($message) { global $argv; fputs(STDERR, "$argv[0]: $message\n"); } function add_dir($dir) { $lname = $dir . '/distd.pid'; $lock = fopen($lname, 'c+'); if (!$lock) { warn("$lname: can not open"); return FALSE; } if (!flock($lock, LOCK_EX|LOCK_NB)) { warn("$lname: can not lock"); return FALSE; } warn(getmypid() . " ". date('H:i:s') . " $lname successfully locked"); return (fputs($lock, getmypid() . "\n". gethostname() . "\n") != FALSE); } date_default_timezone_set('America/New_York'); add_dir('/tmp'); sleep(3); warn(getmypid() . " ". date('H:i:s') . " exiting in peace"); ?> Running TWO of the above in parallel: % ( php t.php < /dev/null & php t.php < /dev/null ) >& l I see BOTH of them claim to have "successfully" gotten the lock: % cat l [1] 26815 t.php: 26815 21:48:34 /tmp/distd.pid successfully locked t.php: 26814 21:48:34 /tmp/distd.pid successfully locked t.php: 26815 21:48:37 exiting in peace t.php: 26814 21:48:37 exiting in peace I appreciate your code and efforts but please stay focus on the topic: MANDATORY locks only. The issue is that PHP doesn't provide a standard way of triggering a mandatory lock. MANDATORY locks are specific to Linux and occurs on a volume that is mounted with the "-o mand" mount flag. ADVISORY locks exist on any system via flock() or lockf() calls and are not the subject of this thread. Now I'm speaking to PHP developpers: how do you plan to fill in the gap? Thanks Eric, I'm confused. Are you saying, the problem I am illustrating with my test case is different? Should I file a separate bug-report?
https://bugs.php.net/bug.php?id=63709
CC-MAIN-2022-21
refinedweb
1,274
63.39
Opened 5 years ago Closed 5 years ago #12530 closed (wontfix) Code in test classes can get access to live database Description When assigning fields in a test case class like this: from django.test import TestCase class TestClass(TestCase): field = [x for x in DataBaseObject.objects.all()] The code is actually executed against "normal" database in settings.py, not the one which is temporarily created. Possible workaround is to use property/lambda syntax. Change History (3) comment:1 Changed 5 years ago by russellm - Resolution set to wontfix - Status changed from new to closed comment:2 Changed 5 years ago by Art_S - Resolution wontfix deleted - Status changed from closed to reopened I would like to re-open this. My impression was that creation of instances of Test Classes was controlled by django. If that's the case (only if!) then why can't it initialise the settings beforehand? The whole thing is kind of dangerous - I can see the use case when you need to run the tests in production, and having any test code there which can potentially modify prod data is really bad. comment:3 Changed 5 years ago by russellm - Resolution set to wontfix - Status changed from reopened to closed We control the creation of test classes, but we don't control the way that Python parses code. The problem here is that the class-level property is instantiated when the class is parsed - which is when you test module is imported. Please don't reopen tickets once they have been closed by a core developer or member of the triage team. If you disagree with a decision that has been made, open a discussion on the django-developers mailing list. I acknowledge that this is a problem, but there really isn't anything we can do. A field defined like that will be instantiated when the class is loaded, which occurs before the test framework has a chance to redirect the database that is in use. The other solution that you don't mention (and the solution that makes more sense to me anyway) is to set up the field in the setUp() method. During the call to setUp(), the test database will be in place. As an added bonus, setUp() is called at the start of every test run, guaranteeing that you won't have any artefact leakage between tests (i.e., test_1 modifies self.field, affecting the outcome of test_2). Marking wontfix because there isn't really a fix, and the workaround is preferable to the problematic syntax.
https://code.djangoproject.com/ticket/12530
CC-MAIN-2015-18
refinedweb
425
69.82
This is CodeEval problem #202, and here I show you my Python 3 solution to it. A few test cases to clarify the problem: def test_provided_1(self): self.assertEqual(2, solution('<--<<--<<')) def test_provided_2(self): self.assertEqual(4, solution('<<>>--><--<<--<<>>>--><')) def test_provided_3(self): self.assertEqual(0, solution('<-->>')) def test_empty(self): self.assertEqual(0, solution('')) def test_overlapping_right(self): self.assertEqual(3, solution('>>-->>-->>-->'))The idea to solve the problem is neat and simple, just scan the input string looking for the patterns. Here is my solution: ARROWS = ['>>-->', '<--<<'] ARROW_SIZE = 5 def solution(line): result = 0 for i in range(len(line)): # 1 candidate = line[i:i + ARROW_SIZE] # 2 if candidate in ARROWS: # 3 result += 1 return result1. Worst case scenario, I am going to loop on all the characters in the passed string looking for the patterns. Notice that I am working on indeces, in the next note I explain why. 2. I put in candidate the slice of the input line based on the current index. This is the usual way we create a substring in Python. 3. If the candidate matches an arrow, I increase the result. For our purposes, that is, passing the CodeEval tests, this code is good enough. However, while I was writing it, I felt a bit sad I couldn't skip the loop counter when I identify a matching. Besides, I didn't get any use of the hint about the possible overlapping of arrows. The fact is we simply can't mess with it in a Python for loop, whatever we do to it, it is going to be reset by the for loop control statement. In this case it is not a big concern, the performance loss is minimal. Still, if the arrows where much longer strings, it could be worthy using a while loop instead, like this: def solution(line): result = 0 i = 0 while i < len(line): candidate = line[i:i + ARROW_SIZE] if candidate in ARROWS: result += 1 i += ARROW_SIZE - 1 # 1 else: i += 1 # 2 return result1. In a while loop I have full control on the looping variable. Here I use this feature to jump over the substring, starting the next check on its last character, for what we said about overlapping above. 2. Otherwise, we just pass to the next position in the string. Both versions works fine for CodeEval, with about the same performance. First one is more readable, so I'd say it should be the preferred one. As usual, I have pushed test cases and both solutions to GitHub.
http://thisthread.blogspot.com/2017/01/codeeval-strings-and-arrows.html
CC-MAIN-2018-43
refinedweb
421
72.46
General Tips for Web Scraping with Python PythonTools & LanguagesData Miningposted by Jack Schultz December 6, 2017 Jack Schultz The great majority of the projects about machine learning or data analysis I write about here on Bigish-Data have an initial step of scraping data from websites. And since I get a bunch of contact emails asking me to give them either the data I’ve scraped myself, or help with getting the code to work for themselves. Because of that, I figured I should write something here about the process of web scraping! There are plenty of other things to talk about when scraping, such as specifics on how to grab the data from a particular site, which Python libraries to use and how to use them, how to write code that would scrape the data in a daily job, where exactly to look as to how to get the data from random sites, etc. But since there are tons of other specific tutorials online, I’m going to talk about overall thoughts on how to scrape. There are three parts of this post – How to grab the data, how to save the data, and how to be nice. As is the case with everything, programming-wise, if you’re looking to learn scraping, you can’t just read tutorials and think to yourself that you know how to program. Pick a project, practice grabbing the data, and then write a blog post about what you learned. There definitely are tons of different thoughts on scraping, but these are the ones that I’ve learned from doing it a while. If you have questions, comments, and want to call me out, feel free to comment, or get in contact! Grabbing the Data The first step for scraping data from websites is to figure out where the sites keep their data, and what method they use to display the data on the browser. For this part of your project, I’ll suggest writing in a file named gather.py which should performs all these tasks. That being said, there are a few ways you’ll need to look for to see how to most easily get the data. Check if the site has an API First A ton of sites with interesting data have APIs for programmers to grab the data and write posts about the interesting-ness of the site. Genius does this very nicely, except for the song lyrics of course. And also if the site has an API, that means that they’re totally alright with programmers using their data, though pretty much every site doesn’t allow you to use its data to make money. Read their requirements and rules for using the site’s data, and if your project is allowed, API is the way to go. Figure out the URLs of all the data If there is no API, that means you’re going to have to figure out the urls where the site displays all the data you need. A common type you’ll see is that the data is displayed using IDs for the objects. If you’ve done web development in something like Rails, you’ll know exactly how that works. In this case, there probably is an index page that has links to all the different pages you’re trying to scrape, so you’ll have two scraping requirements. And like I’ve said, each site is different, but just know that these are possible requirements to get all the data you want. Check JSON loading of data If the site doesn’t have an API and you’re still going to want the data, check to see if the page that shows the data you’re looking for is by using JSON. If the page loads and it takes a second or a flash for the text to show up, it’s probably using that JSON. From there, right click the web page and click “Inspect” on Chrome to get the Developer Tools window to open, reload the web page, and check the Sources tab to see pages that end in .json. You’ll be able to see the URL it came from, then open a new tab and paste that URL and you’ll be able to see the JSON with your data! Quick example of how stats.nba.com generates their pages. If you just look at the HTML returned, you’ll see that it’s only AngularJS, meaning you can’t use the HTML to scrape the data. You’ll need to find the JS url that loads that data. Looking at the network, I find a specific html file requested for over the Network. Then, by reloading the page and checking the files under the Network tab, I find the url that generates the data for the page. As you can see, it’s just a JS variable that has all the data for the players. I won’t list the URL specifically here, but there are ways to change it to grab the data that you’re looking for. Fall back to HTML scraping If the site you’re looking for data from doesn’t have an API or use JSON to load the data, you’re going to fall back to grabbing the HTML pages. Which is the only technique that people think of when imagining web scraping! Like the JSON data, you’re going to have to use the Inspect feature of Chrome’s development tools, but in this case right click on the text that you’re trying to grab and analyze the classes and ids in order to grab that data. For example, if you’re looking to scrape a WordPress blog to do something like sentiment analysis of the posts, you’ll want to do something like this: As for other sites, I won’t go into exactly how that’s to be done because the classes and ids vary, but odds are it’ll be structured similarly with specific classes and ids for the data part of the page. Practice HTML scraping a couple sites and you’ll see how that part is. Saving the Data After you have the data saved using gather.py, you’ll need to write code that scrapes the data. In case you didn’t guess this, a good name for that file is scrape.py. With this file, you’ll want to write the code that grabs the data and structures it for what you saved. How to save the data also depends on the type of scraping job you’re writing. CSV is probably a fine type of database initially There are two different types of scraping projects. First is just grabbing data that is consistent and doesn’t change that much over time. Like the PGA Tour stats I’ve scraped which change week by week for the current year but obviously don’t change when grabbing stats for every year in the past. Another example of this is how to get lyrics from Genius. Lyrics don’t change, and if you’re looking for other information about the songs, that doesn’t change much over time either. If you’re getting this kind of data, don’t worry about setting up a DB to save the data. All types of this have a limited amount and frankly, test files are also quick to analyze the data. Database is useful if you have data that keeps coming On the other hand, if the data you’re looking to scrape is updated continuously, you’re probably going to want a DB to store the data, especially if you have a service (Heroku, Amazon, etc.) that runs your scraping code at certain times. Another use for the DB is if you’re looking to scrape the data and then make a website that displays the data. Something like a script that checks Reddit comments to see how many Amazon products are mentioned and then displays them online. And obviously the benefit of storing the data in a database rather than local files is that querying to compare data you scraped is much easier than having to load all your files into variables and then analyze the data. Like everything I’ve mentioned here, types of methods depends on the site, data, and information you’re trying to gather. Be Nice Scrape with header that has your name and email so company knows it’s you. Some sites will get mad at you if you’re scraping their data. Even when the sites aren’t “nice”, you don’t want to do something “illegal”. An example of a way to do this: import requests from = "'From': %s" % 'contact@bigishdata.com' headers = {'user-agent' : 'Jack Schultz, bigishdata.com, contact@bigishdata.com'} html = requests.get(url, headers=headers) You can look up other options for the request header, but make sure it’s the same and that people who look at their server’s logs know who you are, just in case they want to get in contact. Make sure you don’t keep hitting the servers!!!! When you’re writing and running gather.py make sure you’re testing it in a way that doesn’t continuously hit the servers to gather the data! I’m talking about using JSON and HTML. As for API, you’ll also want to make sure you’re not hitting the end points time and time again, especially since they track who’s hitting the API and most only allow a certain number of requests per time period. Then when you’re running scrape.py, don’t hit their servers over and over as well. That script deals with gathering the data that you already got from their site. Basically, the only time you should continuously hit the servers is when you’re running your final code that gets and saves the data / files from the site. Gevent Now if you’re needing to scrape data from a bunch of different web pages, Gevent is the python library to use that will help run request jobs concurrently so you’ll be able to hit the API, grab the JSON, or grab the HTML pages quicker. Since for the most part, the longest code is the kind that hits their servers and then wait for the file to be returned. import gevent from gevent import monkey monkey.patch_all() ... #set the urls that you'll get the data from jobs = [gevent.spawn(gather_pages, pair[0], pair[1]) for pair in url_filenames] gevent.joinall(jobs) Again, as long as you’re not going too quickly destroy their servers by asking for thousands of pages at once, feel free to use Gevent. Especially since most sites have more than 50 requests at once. Practice, practice, practice With all that said, and what is the case with everything, if you want to web scrape, you gotta practice. Reading so many of the tutorials is interesting and does teach you things, but if you want to learn, write the code yourself and search for tutorials that help solve your bugs. And remember, be nice when grabbing the data.
https://opendatascience.com/general-tips-for-web-scraping-with-python-2/
CC-MAIN-2020-40
refinedweb
1,873
75.54
Concepts of Erlang Lately I’ve been learning Erlang (and Elixir) after years of reading surface level stuff about it. There’s a lot out there that teaches you how to write Erlang or Elixir programs, but here I want to write a conceptual post I wish I’d read before I got started. Erlang combines a set of old ideas in a way that’s both neat and has aged incredibly well. Erlang’s concurrency model in particular uses three concepts that I was already aware of: tail call optimization, lightweight processes, and asynchronous messages. Tail Call Optimization A tail call is a recursive call that doesn’t need to keep the current stack frame around, and can therefore be optimized away by a smart runtime. Here’s an example of an infinite loop expressed via a tail call in Elixir (because it’s is easier to read for most folks). def loop() do # do stuff loop() end When this program runs on the BEAM VM, it’s optimized to be more like what a C programmer would recognize as an imperative loop, like “while(true)” or “for(;;)”. This becomes important in Erlang/Elixir because these recursive functions run for a very long time, and form the main loop of most long running erlang processes. Asynchronous messaging Erlang processes can message each other, and the messages have a mailbox. Let’s go back to that loop again: def loop() do result = receive do {:hello, name } -> name _ -> "?" end loop() end When this function reaches the receive method, the process goes to sleep until there’s a message in its mailbox. So now this little thing is starting to look a bit like a server. Putting them together These ideas weren’t new to me, but Erlang gets a ton of mileage out of them and the ways they combine. Going back to our loop, let’s add a parameter that can store some state we want to keep in this process: defmodule Counter do def loop(value) do next_value = receive do {:add, number} -> value + number {:subtract, number} -> value - number end IO.puts(next_value) loop(next_value) end end To create one of these counter processes and send messages to it you’d do: pid = spawn fn () -> Counter.loop(0) end send pid, {:add, 12} # prints 12 send pid, {:subtract, 11} # prints 1 Now we have a little counter loop, and clients can add or subtract to it as things go. There’s no way to get at the contents except sending messages, and the Erlang VM can create many thousands of these at once because they’re not the threads you might be used to from C++ or Java. Processes The Erlang scheduler isn’t quite like anything else I’ve come across. Erlang processes are preempted very often and the VM is super careful about how much time a process has to run, which I imagine is because of Erlang’s genesis in telephony. They’re also super lightweight, and if one crashes it doesn’t cause problems for the rest of the system. In practice this means you spin up a new process to do something in Erlang that you’d have a hard time spawning a new OS thread for. Large erlang programs can have millions of these processes running on a single machine, they don’t share any state with each other, and they all communicate via asynchronous messages. It’s easy to reason about an individual process because these loops depend only on their arguments like any functional program would. Also you don’t have to worry about shared memory or locks, and data races are harder to create. Why is this interesting? One small example of the mileage Erlang gets out of this is that the only thing we need to start this loop again is the value of the counter. So if we want to deploy a new version of this loop without taking the system down, the system can start a new version of the function and know that it’s safe. As I understand it this is more or less of how the famous “hot code reloading” feature of Erlang works. Another thing Erlang uses processes for that I’d not seen before is Supervisors, which are processes that observe other processes and restart them if they crash or run into other problems. Supervisors rely on something I’ve not covered here called process linking. In practice, a large Erlang system’s workers will run happily doing their work, and crash as soon as they get into a bad state. This is a very different and I think much better way to think about errors.
https://medium.com/@matasar/concepts-of-erlang-2171b68f0895?source=user_profile---------3------------------
CC-MAIN-2018-43
refinedweb
784
64.75
ost::StringTokenizer::NoSuchElementException - Exception thrown, if someone tried to read beyond the end of the tokens. #include <tokenizer.h> Exception thrown, if someone tried to read beyond the end of the tokens. Will not happen if you use it the ’clean’ way with comparison against end(), but if you skip some tokens, because you ’know’ they are there. Simplifies error handling a lot, since you can just read your tokens the way you expect it, and if there is some error in the input this Exception will be thrown. Generated automatically by Doxygen for GNU CommonC++ from the source code. GNU CommonC++ ost::StringTokenizer::NoSuchElementException(3)
http://huge-man-linux.net/man3/ost_StringTokenizer_NoSuchElementException.html
CC-MAIN-2017-22
refinedweb
106
54.52
Hello I am a fairly new to Java, below I have created a program for calculating the distance between two cites that is inputed by the user. For the second part of my program I need to have a menu system and the constant SPEED value to change according to the type of road that is selected by the user before hand in the menu system. So I figure I need to the change the constant Speed value depending on what the user has selected before hand, I understand that I need to use some sort of 'switch' and methods to cut the code down (which I don't quite get), Also how would I get the program work again without restarting from the beginning, would this be done by a boolean value? Is there a book you recommend reading or a similar piece of code I could look through to get an idea where to start. It took me a while just to do this which I understantd is pretty basic so any help would be appreciated. import java.math.*; public class TravelPrograms { public static final double SPEED = 50; public static void main(String[] args) { //local variables String city1; String city2; int hours; int mins; int distance; double timeInMins = 0; int timeInHours; // prints out user prompt System.out.println ("Welcome to Isfandyar Ali Travel Calculator" + "\n"); System.out.println ("====================================================="+ "\n"); System.out.print ("Please enter the name of the first city: "); city1 = UserInput.readString(); System.out.println(); // insert blank line System.out.print ("Please enter the name of the second city: "); city2 = UserInput.readString(); System.out.println(); // insert blank line System.out.print ("please enter the distance in miles: "); distance = UserInput.readInt(); System.out.println ("============================Result========================"+ "\n"); //Error message recieved if the distance is negative if (distance < 1) { System.out.println ("Error. distance must be a positive nmumber"); } else { timeInMins = (distance/SPEED*60); timeInHours = (int)(timeInMins/60); timeInMins = timeInMins -(timeInHours *60); timeInMins = Math.round(timeInMins); mins = (int) timeInMins; hours = (int) timeInHours; System.out.println("The time required to travel " + distance+" miles"+" between " + city1+ "and " + city2 +" is " + hours+" hours and "+mins+" minutes"+ "\n"); } System.out.println ("===================================================="+ "\n"); System.out.println ("Please enter C to continue or any other character to quit: q"+ "\n"); System.out.print ("Thank you for using Travel program"); } //end of method } // end of class Edited by Reverend Jim: Fixed formatting
https://www.daniweb.com/programming/software-development/threads/239492/i-am-trying-to-create-a-menu-system-and-to-change-two-constant-values
CC-MAIN-2017-17
refinedweb
394
53.41
Crystal's way to do error handling is by raising and rescuing exceptions. You raise exceptions by invoking a top-level raise method. Unlike other keywords, raise is a regular method with two overloads: one accepting a String and another accepting an Exception instance: raise "OH NO!" raise Exception.new("Some error") The String version just creates a new Exception instance with that message. Only Exception instances or subclasses can be raised. To define a custom exception type, just subclass from Exception: class MyException < Exception end class MyOtherException < Exception end You can, as always, define a constructor for your exception or just use the default one. To rescue any exception use a begin ... rescue ... end expression: begin raise "OH NO!" rescue puts "Rescued!" end # Output: Rescued! To access the rescued exception you can specify a variable in the rescue clause: begin raise "OH NO!" rescue ex puts ex.message end # Output: OH NO! To rescue just one type of exception (or any of its subclasses): begin raise MyException.new("OH NO!") rescue MyException puts "Rescued MyException" end # Output: Rescued MyException And to access it, use a syntax similar to type restrictions: begin raise MyException.new("OH NO!") rescue ex : MyException puts "Rescued MyException: #{ex.message}" end # Output: Rescued MyException: OH NO! Multiple rescue clauses can be specified: begin # ... rescue ex1 : MyException # only MyException... rescue ex2 : MyOtherException # only MyOtherException... rescue # any other kind of exception end You can also rescue multiple exception types at once by specifying a union type: begin # ... rescue ex : MyException | MyOtherException # only MyException or MyOtherException rescue # any other kind of exception end An else clause is executed only if no exceptions were rescued: begin something_dangerous rescue # execute this if an exception is raised else # execute this if an exception isn't raised end An else clause can only be specified if at least one rescue clause is specified. An ensure clause is executed at the end of a begin ... end or begin ... rescue ... end expression regardless of whether an exception was raised or not: begin something_dangerous ensure puts "Cleanup..." end # Will print "Cleanup..." after invoking something_dangerous, # regardless of whether it raised or not Or: begin something_dangerous rescue # ... else # ... ensure # this will always be executed end ensure clauses are usually used for clean up, freeing resources, etc. Exception handling has a short syntax form: assume a method or block definition is an implicit begin ... end expression, then specify rescue, else, and ensure clauses: def some_method something_dangerous rescue # execute if an exception is raised end # The above is the same as: def some_method begin something_dangerous rescue # execute if an exception is raised end end With ensure: def some_method something_dangerous ensure # always execute this end # The above is the same as: def some_method begin something_dangerous ensure # always execute this end end # Similarly, the shorthand also works with blocks: (1..10).each do |n| # potentially dangerous operation rescue #.. else #.. ensure #.. end Variables declared inside the begin part of an exception handler also get the Nil type when considered inside a rescue or ensure body. For example: begin a = something_dangerous_that_returns_Int32 ensure puts a + 1 # error, undefined method '+' for Nil end The above happens even if something_dangerous_that_returns_Int32 never raises, or if a was assigned a value and then a method that potentially raises is executed: begin a = 1 something_dangerous ensure puts a + 1 # error, undefined method '+' for Nil end Although it is obvious that a will always be assigned a value, the compiler will still think a might never had a chance to be initialized. Even though this logic might improve in the future, right now it forces you to keep your exception handlers to their necessary minimum, making the code's intention more clear: # Clearer than the above: `a` doesn't need # to be in the exception handling code. a = 1 begin something_dangerous ensure puts a + 1 # works end Although exceptions are available as one of the mechanisms for handling errors, they are not your only choice. Raising an exception involves allocating memory, and executing an exception handler is generally slow. The standard library usually provides a couple of methods to accomplish something: one raises, one returns nil. For example: array = [1, 2, 3] array[4] # raises because of IndexError array[4]? # returns nil because of index out of bounds The usual convention is to provide an alternative "question" method to signal that this variant of the method returns nil instead of raising. This lets the user choose whether she wants to deal with exceptions or with nil. Note, however, that this is not available for every method out there, as exceptions are still the preferred way because they don't pollute the code with error handling logic. To the extent possible under law, the persons who contributed to this workhave waived all copyright and related or neighboring rights to this workby associating CC0 with it.
https://docs.w3cub.com/crystal~0.31/docs/syntax_and_semantics/exception_handling/
CC-MAIN-2020-34
refinedweb
804
52.49
StreamReader.ReadLine Method Assembly: mscorlib (in mscorlib.dll) Return ValueThe next line from the input stream, or a null reference (Nothing in Visual Basic) if the end of the input stream is reached. a null reference (Nothing in Visual Basic) if the end of the input stream is reached. This method overrides ReadLine. If the current method throws an OutOfMemoryException, StreamReader object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream object also needs to be reinitialized. To avoid such a situation and produce robust code you should use the Read method and store the read characters in a pre-allocated buffer. For a list of common I/O tasks, see Common I/O Tasks. The following code example reads lines from a file until the end of the file is reached. using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; try { if (File.Exists(path)) { File.Delete(path); } using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("This"); sw.WriteLine("is some text"); sw.WriteLine("to test"); sw.WriteLine("Reading"); } using (StreamReader sr = new StreamReader(path)) { while (sr.Peek() >= 0) { Console.WriteLine(sr.ReadLine()); } } } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } { while (sr.Peek() >= 0) { Console.WriteLine(sr.ReadLine()); } } finally { sr.Dispose(); } } catch (System.Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } //main } /.
http://msdn.microsoft.com/en-US/library/system.io.streamreader.readline(v=vs.85).aspx
CC-MAIN-2014-10
refinedweb
237
63.46
I have a test where I'm trying to identify if I've successfully gotten an instance of a database using pymongo, and would like to use isinstance(obj, class) in an assertion. However I cant figure out how to get a class (not instance) of the database I've tried several approaches. This seems closest but still no cigar: import pymongo client = pymongo.MongoClient('localhost') database = client['test'] assert isinstance(database, pymongo.MongoClient.db_name) which doesn't work since db_name isn't defined. Pymongo docs say a new database (reference?) is made using either pymongo.MongoClient.db_name or pymongo.MongoClient[db_name] Of course these create an instance if I give it a db_name string, yet I want only the class, not an instance. Thanks!
http://www.howtobuildsoftware.com/index.php/how-do/bbGP/python-mongodb-pymongo-how-to-get-class-of-pymongo-database-suitable-for-isinstance
CC-MAIN-2018-22
refinedweb
125
50.73
71 releases (31 breaking) 1,334 downloads per month Used in 2 crates 22MB 294K SLoC Rust OpenCV bindings Experimental Rust bindings for OpenCV 3 and 4. The API is usable but unstable and not very battle-tested; use at your own risk. Quickstart Make sure the supported OpenCV version (3.2, 3.4 or 4.2) is installed in your system. Update your Cargo.toml opencv = "0.33" Select OpenCV version if different from default in Cargo.toml: opencv = {version = "0.33", default-features = false, features = ["opencv-34"]} And enable usage of contrib modules: opencv = {version = "0.33", features = ["contrib"]} Import prelude use opencv::prelude::*; When building on Windows and macOS you must enable buildtime-bindgen feature to avoid link errors: opencv = {version = "0.33", features = ["buildtime-bindgen"]} Getting OpenCV Linux You have several options of getting the OpenCV library: install it from the repository, make sure to install -devpackages because they contain headers necessary for the crate build (also check that your package contains pkg_configfiles). build OpenCV manually and set up the following environment variables prior to building the project with opencvcrate: PKG_CONFIG_PATHfor the location of *.pcfiles LD_LIBRARY_PATHfor where to look for the installed *.sofiles during runtime Windows package Installing OpenCV is easy through the following sources: from chocolatey, also install llvmpackage, it's required for building: choco install llvm opencv also set OPENCV_LINK_LIBS, OPENCV_LINK_PATHSand OPENCV_INCLUDE_PATHSenvironment variables (see below for details). from vcpkg, also install llvmpackage, necessary for building: vcpkg install llvm opencv4[contrib,nonfree] macOS package Get OpenCV from homebrew: - homebrew, be sure to also install llvmand pkg-configthat are required for building: brew install llvm pkg-config opencv Manual build You can of course always compile OpenCV of the version you prefer manually. This is also supported, but it requires some additional configuration. You need to set up the following environment variables to point to the installed files of your OpenCV build: OPENCV_LINK_LIBS, OPENCV_LINK_PATHS and OPENCV_INCLUDE_PATHS (see below for details). Troubleshooting One of the common problems is link errors in the end of the build. Try building with buildtime-bindgenfeature enabled (requires installed clang/llvm), it will recreate rust and cpp files to match the version you have installed. Please be sure to also set up the relevant environment variables that will allow the linker to find the libraries it needs (see below). You're getting runtime errors like: thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { code: -215, message: "OpenCV(4.2.0) /build/opencv/src/opencv-4.2.0/modules/highgui/src/window.cpp:384: error: (-215:Assertion failed) size.width>0 && size.height>0 in function \'imshow\'\n" }', src/libcore/result.rs:1188:5 thread 'extraction::tests::test_contour_matching' panicked at 'called `Result::unwrap()` on an `Err` value: Error { code: -215, message: "OpenCV(4.1.1) /tmp/opencv-20190908-41416-17rm3ol/opencv-4.1.1/modules/core/src/matrix_wrap.cpp:79: error: (-215:Assertion failed) 0 <= i && i < (int)vv.size() in function \'getMat_\'\n" }', src/libcore/result.rs:1165:5 These errors (note the .cpp source file and Errorreturn value) are coming from OpenCV itself, not from the crate. It means that you're using the OpenCV API incorrectly, e.g. passing incompatible or unexpected arguments. Please refer to the OpenCV documentation for details. You're getting errors that methods don't exist or not implemented for specific structs, but you can see them in the documentation and in the crate source. Be sure to import use opencv::prelude::*;. The crate contains a lot of traits that need to be imported first. Also check that if you're using a contrib module that the contribfeature is enabled for the crate. Reporting issues If you still have trouble using the crate after going through the Troubleshooting steps please fill free to report it to the bugtracker. When reporting an issue please state: - Operating system - The way you installed OpenCV: package, official binary distribution, manual compilation, etc. - OpenCV version - Attach the full output of the following command from your project directory: RUST_BACKTRACE=full cargo build -vv Environment variables The following variables must be set when building without pkg_config or vcpkg. You can also set them on other platforms, then pkg_config or vcpkg usage will be disabled and the set values will be used. OPENCV_LINK_LIBSComma separated list of library names to link to. .lib, .soor .dylibextension is optional. If you specify the ".framework" extension then build script will link a macOS framework instead of plain shared library. E.g. "opencv_world411". OPENCV_LINK_PATHSComma separated list of paths to search for libraries to link. E.g. "C:\tools\opencv\build\x64\vc14\lib". OPENCV_INCLUDE_PATHSComma separated list of paths to search for system include files during compilation. E.g. "C:\tools\opencv\build\include". One of the directories specified therein must contain "opencv2/core/version.hpp" or "core/version.hpp" file, it's used to detect the version of the headers. The following variables are optional, but you might need to set them under some circumstances: OPENCV_HEADER_DIRDuring crate build it uses OpenCV headers bundled with the crate. If you want to use your own (system) headers supply OPENCV_HEADER_DIRenvironment variable. The directory in that environment variable should contain opencv2dir, e.g. set it /usr/includefor OpenCV-3.4.x or /usr/include/opencv4for OpenCV-4.x. OPENCV_PACKAGE_NAMEIn some cases you might want to override the pkg-config or vcpkg package name, you can use this environment variable for that. If you set it pkg-config will expect to find the file with that name and .pcextension in the package directory. And vcpkg will use that name to try to find package in packagesdirectory under VCPKG_ROOT. For legacy reasons OPENCV_PKGCONFIG_NAMEis also supported as this variable name. The following variables affect the building the of the opencv crate, but belong to external components: PKG_CONFIG_PATHWhere to look for *.pcfiles see the man pkg-config Path specified here must contain opencv.pcor opencv4.pc(for OpenCV 4.x). VCPKG_ROOTand VCPKGRS_DYNAMICThe root of vcpkginstallation and flag allowing use of *.dlllibraries, see the documentation for vcpkgcrate LD_LIBRARY_PATHOn Linux it sets the list of directories to look for the installed *.sofiles during runtime. Linux documentation has more info. Path specified here must contain libopencv_*.sofiles. DYLD_LIBRARY_PATHSimilar to LD_LIBRARY_PATH, but for loading *.dylibfiles on macOS, see man dyld for more info. Path specified here must contain *.dylibfiles. PATHWindows searches for *.dlls in PATHamong other places, be sure to set it up, or copy required OpenCV *.dlls next to your binary. Be sure to specify paths in UNIX style (/C/Program Files/Dir) because colon in PATHmight be interpreted as the entry separator. Summary here. clang crate environment variables See crate's README Cargo features opencv-32- build against OpenCV 3.2.0, this feature is aimed primarily on stable Debian and Ubuntu users who can install OpenCV from the repository without having to compile it from the source opencv-34- build against OpenCV 3.4.x opencv-4(default) - build against OpenCV 4.x contrib- enable the usage of OpenCV contrib modules for corresponding OpenCV version buildtime-bindgen- regenerate all bindings, requires installed clang/llvm, should only be used during the crate development or when building on Windows or macOS, with this feature enabled the bundled headers are no longer used for the code generation, the ones from the installed OpenCV are used instead docs-only- internal usage, for building docs on docs.rs API details API Documentation is automatically translated from OpenCV's doxygen docs. Most likely you'll still want to refer to the official OpenCV C++ documentation as well. OpenCV version support The following OpenCV versions are supported at the moment: - 3.2 - enabled by opencv-32feature - 3.4 - enabled by opencv-34feature - 4.2 - enabled by the default opencv-4feature If you need support for contrib modules, also enable contrib feature. Minimum rustc version Generally you should use the latest stable rustc to compile this crate. Platform support Currently the main development and testing of the crate is performed on Linux, but other major platforms are also supported: macOS and Windows. For some more details please refer to the CI build scripts: Linux OpenCV install, macOS OpenCV install as framework, macOS OpenCV install via brew, Windows OpenCV install via Chocolatey, Windows OpenCV install via vcpkg, Test runner script. Functionality Generally the crate tries to only wrap OpenCV API and provide some convenience functions to be able to use it in Rust easier. We try to avoid adding any functionality besides that. Errors Most functions return a Result to expose a potential C++ exception. Although some methods like property reads or functions that are marked CV_NOEXCEPT in the OpenCV headers are infallible and return a naked value. Properties Properties of OpenCV classes are accessible through setters and getters. Those functions are infallible, they return the value directly instead of Result. Infallible functions For infallible functions (like setters) that accept &str values the following logic applies: if a Rust string passed as argument contains null byte then this string will be truncated up to that null byte. So if for example you pass "123\0456" to the setter, the property will be set to "123". Callbacks Some API functions accept callbacks, e.g. set_mouse_callback. While currently it's possible to successfully use those functions there are some limitations to keep in mind. Current implementation of callback handling keeps hold of the passed callback argument forever. That means that the closure used as a callback will never be freed during the lifetime of a program and moreover Drop will not be called for it (they are stored in global static Slab). There is a plan to implement possibility to be able to free at least some of the closures. Unsafety Although crate tries to provide ergonomic Rust interface for OpenCV, don't expect Rust safety guarantees at this stage. It's especially true for borrow checking and shared mutable ownership. Notable example would be Mat which is a reference counted object in its essence. You can own a seemingly separate Mat in Rust terms, but it's going to be a mutable reference to the other Mat under the hood. Treat safety of the crate's API as you would treat one of C++, use clone() when needed. Contrib modules The following modules require opencv_contrib installed: - aruco - bgsegm - bioinspired - ccalib - cvv - dnn (only for OpenCV 3.2) - dpm - face - freetype - fuzzy - hdf - img_hash - line_descriptor - phase_unwrapping - plot - sfm - shape - structured_light - superres - surface_matching - text - videostab - viz - xfeatures2d - xobjdetect - xphoto Missing modules and functions While most of the API is covered, for various reasons (that might no longer hold) there are modules and functions that are not yet implemented. If a missing module/function is near and dear to you, please file an issue (or better, open a pull request!). CUDA is not supported at the moment, but is definitely in the roadmap. You can use OpenCL for now. The binding strategy This crate works similar to the the model of python and java's OpenCV wrappers - it uses libclang to parse the OpenCV C++ headers, generates a C interface to the C++ API, and wraps the C interface in Rust. All the major modules in the C++ API are merged together in a huge cv:: namespace. We instead made one rust module for each major OpenCV module. So, for example, C++ cv::Mat is opencv::core::Mat in this crate. The methods and field names have been snake_cased. Methods arguments with default value lose these default values, but they are reported in the API documentation. Overloaded methods have been mostly manually given different names or automatically renamed to *_1, *_2, etc. OpenCV 2 support If you can't use OpenCV 3.x or higher, the (no longer maintained) 0.2.4 version of this crate is known to work with OpenCV 2.4.7.13 (and probably other 2.4 versions). Please refer to the README.md file for that version because the crate has gone through the considerable rewrite since. Contributor's Guide The binding generator code lives in a separate crate under binding-generator. have to handle the code generation overhead in their builds. When developing this crate, you can test changes to the binding generation using cargo build -vv --features buildtime-bindgen. When changing the binding-generator, be sure to push changes to the generated code! If you're looking for things to improve be sure to search for todo and fixme labels in the project source, those usually carry the comment of what exactly needs to be fixed. The license for the original work is MIT. Special thanks to ttacon for yielding the crate name.
https://lib.rs/crates/opencv
CC-MAIN-2020-16
refinedweb
2,103
56.45
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). I made a small script to do or fake the psr command but they are restoring the rotation The problem is that when I try to return, it does not react import c4d from c4d import documents, plugins def main(): def object(): return doc.GetActiveObject() object()[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y] = 0 object()[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_X] = 0 object()[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Z] = 0 c4d.EventAdd() if __name__=='__main__': main() hi, please use English for your communication if i understood correctly your question, you want to implement an undo stack. This script will help you to understand how it can be done. Please have a look at the documentation for more information. We also have an undo manual for c++ that could help you to understand how it's working. The following script will reset the position for each selected object. It will only reset the local position of the object. You could try to improve it using the ctrl key to reset the global position. (you would need to use GetMg and SetMg instead. GetMg and SetMg Please read our documentation about matrices. to understand how they work and how you can use them. import c4d from c4d import documents, plugins def main(): # Retrieve all the selected object objects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_NONE) # Start a new undo stack doc.StartUndo() # For each selected object for obj in objects: # Retrieve the local Matrix ml = obj.GetMl() # Define a new offset vector with the one by default (0, 0, 0) ml.off = c4d.Vector() # Add a stem in the undo stack for this object.(sot it previous state will be stored) doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj) # Change the obect's position.' obj.SetMl(ml) # Close the stack. doc.EndUndo() c4d.EventAdd() if __name__=='__main__': main() Cheers, Manuel Excuse me, I thought I translated it was my mistake, and in the same way, thank you for your help.
https://plugincafe.maxon.net/topic/13339/problema-de-regreso-de-c%C3%B3digo-de-gestor-de-scripts/3
CC-MAIN-2021-25
refinedweb
358
58.89
Hello all! Briefly, introducing myself... and please forgive the blatant self-promotion -- I'm recently former Googler, now working on my own startup in Chicago (with some others still in San Francisco). Django and CouchDB weigh heavily in our server setup and future API... I'm *loving* CouchDB... And I've pretty much devoured every online presentation or tech talk video that exists on CouchDB so far. :-) Keep it up! With that out of the way.... I just wanted to send along a quick tip for folks using curl. If this is useful, maybe some version of this should probably graduate to a "GettingStartedWithCurl" wiki page: I'm frequently annoyed that curl doesn't end the data stream with a "\n" at the end... so a curl request usually looks like this: ---------------------------- ubuntu: ~ hugs$ curl -u {"couchdb":"Welcome","version":"0.8.0-incubating"}ubuntu: ~ hugs$ ---------------------------- I was thinking about creating a patch to add a "\n" at the end of every request, but I figured that would be a request of last resort. The stupid quick solution is append an empty "echo" command like so: -------------------------------------------------------- ubuntu: ~ hugs$ curl ; echo '' {"couchdb":"Welcome","version":"0.8.0-incubating"} ubuntu: ~ hugs$ -------------------------------------------------------- I could have stopped there... but the urge to bikeshed this further was just too great... So, I whipped up a quick python script that I now pipe to to do my "post-processing". I remembered that the GettingStartedWithPython wiki page simply does a pretty print of the content... So I heavily streamlined that script to make it play nicer with curl. So this is the result now: -------------------------------------------------------- ubuntu: ~ hugs$ curl -s | ./pprint-json { "couchdb": "Welcome", "version": "0.8.0-incubating" } ubuntu: ~ hugs$ -------------------------------------------------------- .... Ah... much better. :-) Here's the script: -------------------------------------------------------- #! /usr/bin/python import sys import simplejson raw_input = sys.stdin.read() json_data = simplejson.loads(raw_input) # Make pretty! print simplejson.dumps(json_data, sort_keys=True, indent=4) -------------------------------------------------------- To get this to work correctly, I also had to add the silent "-s" flag to curl so that it didn't print a progress meter with the results as well. (Try it without "-s" to see what I mean.) I would love it there was "pretty print all output" configuration option for Couch... but until then, I'll just use my script. :-) Cheers and thanks for all the JSON! - Jason Huggins
http://grokbase.com/t/couchdb/user/088m86smf8/appending-n-and-pretty-printing-output-from-the-command-line-using-curl-with-a-smidge-of-python
CC-MAIN-2016-26
refinedweb
385
67.76
Feature #9585open Add Object#in? to make ruby easier to read Description Please add an in? method to all objects, that allows the following: 4.in? 1,2,3,4 4.in? 1..4 "a".in? "abc" 7.in? 0..2, 5..8 3.in? small_numbers.select(&:odd?) =>true Background:: if status == 1 if status == 1 or status == 2 if [1,2,127].include? status # breaks symmetry if status.in? 1, 2, 127 # better Pros: ‣ Nicer to read, no need to read the line backward (brings joy to writers and readers) ‣ No new keyword ‣ Breaks nothing Cons: ‣ One more method in Object ‣ "a".in? "abc", "def" vs "a".in? ["abc", "def"] (implementation is yet an example) Neutral: ‣ Yet one more way to do it (isn't that ruby-style?) ‣ Belongs to Object, as a comparison operator like ==, eql?, ===, nil? ‣ “only cosmetics” vs elegance Implementation for testing (you'd certainly find a less naive implementation): class Object def in? *args raise ArgumentError if args.empty? args.any? {|a| a == self or a.include? self rescue false} end end This is related to which was rejected for being an operator (even though the keyword already existed) Updated by shevegen (Robert A. Heiler) over 7 years ago This probably would not be a big addition and not bother many. I think it can be readable: array = [1,2,3,4,5] if 3.in? array puts 'Yup, is in the array!' end I think one problem may be that it is on a Fixnum here though. Fixnums don't have much. Also examples like: if status.in? 1, 2, 127 # better Don't really seem much better. I am neutral about this suggestion. I do think we should point out that this way of counting is opposite to the current way, as in: (1..5).include? 3 # => true With your proposal you would turn this around, in pseudo-code 3.in? 1..5 So one more to add to Cons would be: - opposite to the current default way in Ruby. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/9585
CC-MAIN-2021-39
refinedweb
342
76.11
How do I Use Printf() with the Debug Console in the Synergy Software Package Question: How do I use the Printf function to write to the Virtual Debug Console with the Synergy Software Package? Answer: You can use the printf function in your SSP projects is you follow these simple steps, illustrated using the Threaded Blinky project. 1) Make sure you include these lines of code at the beginning of Threaded Blinky: #include "blinky_thread.h" #include "stdio.h" //Used for printf outputs extern void initialise_monitor_handles(void); //Used for printf outputs /* Blinky example application void blinky_thread_entry(void) { initialise_monitor_handles(); //Used for printf outputs int countt; 2) You also need to initialize the countt variable here: /* Get LED information for this board */ R_BSP_LedsGet(&leds); countt = 0; 3) Put in the code to increment the counter, the printf function call and the edit to the sleep delay as shown below: countt = countt + 1; /* Delay */ printf(" Hello from Synergy %d\r\n", countt); tx_thread_sleep (1); 4) You should also check that the linker script (a default selection in SSP projects, but you might need to set it if you are doing anything non-standard) is set to -spec=rdimon.specs as seen below. 5) You can now build and begin a debug session. 5) Now select the Renesas Debug Virtual Console using the select box at the far right of the console window (the one with the yellow plus sign), as seen below, then restart the debug session. 6) The Printf output from Threaded Blinky will show up in the Virtual console window as illustrated in the screen capture given below (you may need to select the display console from the second to last selction box on the far right side of the console window, the one with the computer monitor icon) . Now try this procedure in one of your projects!
https://en-sg.knowledgebase.renesas.com/English_Content/Renesas_Synergy%E2%84%A2_Platform/Renesas_Synergy_Knowledge_Base/How_do_I_Use_Printf()_with_the_Debug_Console_in_the_Synergy_Software_Package
CC-MAIN-2017-51
refinedweb
306
58.35
Samuel,It would really be much more useful if you CCed me, rather than hopingthat I'd find this patch by trawling LKML...David, Andi,My understanding about abstract namespace sockets (what Samuel callsunnamed sockets) is that the indicator that the address is for anunnamed socket is that the sun_path starts with a zero byte -- and the*entire* remainder of the sun_path constitutes the name of the socket. As such, information about the size returned by accept() etc. isredundant. (I've happily written programs that use abstract namespacesockets without even knowing what is returned by a succesfulaccept().)I agree with Samuel that there should be some documentation of thereturn value of accept() etc, for abstract sockets but my inclinationwould be to document that the indicator that this is an abstractsocket is the initial null byte in sun_path, and mention the returnedlength as an after word. Does this seem reasonable?Cheers,MichaelOn 3/24/08, Samuel Thibault <samuel.thibault@ens-lyon.org> wrote:> Samuel Thibault, le Mon 24 Mar 2008 12:17:19 +0000, a écrit :>> > Andi Kleen, le Mon 24 Mar 2008 12:50:10 +0100, a écrit :> > > Samuel Thibault <samuel.thibault@ens-lyon.org> writes:> > > > David Miller, le Sun 23 Mar 2008 21:56:41 -0700, a écrit :> > > > > From: Samuel Thibault <samuel.thibault@ens-lyon.org>> > > > >@ens-lyon.org>> > > > >> > > > > This change isn't correct. It's the fact that the> > > > > length returned is sizeof(short) that tells the caller> > > > > that the unix socket is unnamed.> > > >> > > > Mmm, where that is documented?> > > >> > > > I can't find any details about that in SUS, and man 7 unix says> > > >> > > > `If sun_path starts with a null byte ('' '), then it refers to the> > > > abstract namespace main- tained by the Unix protocol module.'> > >> > > [I wrote unix(7) originally]. The abstract name space is a Linux> > > extension and there is no written standard and whatever the kernel> > > implements is the de-facto standard. If unix(7) differs in anything> > > from what the code does please send patches to the manpages> > > maintainer.> >> > Oops, sorry, we are not talking about abstract namespace actually (their> > sockaddr length are necessarily bigger than sizeof(sa_family_t) since> > they need some data), but unamed sockets. So the Address Format> > paragraph just misses description of unnamed sockets.>>> How about this?>> --- unix.7.orig 2008-03-24 12:24:37.000000000 +0000> +++ unix.7 2008-03-24 12:24:56.000000000 +0000> @@ -87,6 +87,15 @@> bytes in> .IR sun_path .> Note that names in the abstract namespace are not zero-terminated.> +If the size returned by> +.BR accept> +or> +.BR getpeername> +is> +.IR sizeof(sa_family_t) ,> +then it refers to a unnamed socket and> +.I sun_path> +should not be read.> .SS Socket Options> For historical reasons these socket options are specified with a> .B SOL_SOCKET>>> Samuel> --> To unsubscribe from this list: send the line "unsubscribe linux-kernel" in> the body of a message to majordomo@vger.kernel.org> More majordomo info at> Please read the FAQ at>-- I'll likely only see replies if they are CCed to mtk.manpages at gmail dot com--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2008/3/31/3
CC-MAIN-2016-30
refinedweb
535
65.93
package URL::Signature; use warnings; use strict; use URI (); use URI::QueryParam (); use MIME::Base64 3.11 (); use Digest::HMAC (); use Carp (); use Class::Load (); use Params::Util qw( _STRING _POSINT _NONNEGINT _CLASS ); our $ mode, the B<key order is not important for validation>. That means the following URIs are all considered valid (for the same given secret key): foo/bar?a=1&b=2&k=SOME_KEY foo/bar?a=1&k=SOME_KEY&b=2 foo/bar?b=2&k=SOME_KEY&a=1 foo/bar?b=2&a=1&k=SOME_KEY foo/bar?k=SOME_KEY&a=1&b=2 foo/var?k=SOME_KEY&b=2&a=1 =head1 METHODS =head2 new( %attributes ) Instatiates a new object. You can set the following properties: =over 4 =item * B<key> - (B<REQUIRED>) A string containing the secret key used to generate and validate the URIs. As a security feature, this attribute contains no default value and is mandatory. Typically, your application will fetch the secret key from a configuration file of some sort. =item * B<length> - The size of the resulting code string to be appended in your URIs. This needs to be a positive integer, and defaults to B<28>. Note that, the smaller the string, the easier it is for a malicious user to brute-force it. =item * B<format> - This module provides two different formats for URL signing: 'I<path>' and 'I<query>'. When set to 'path', the authentication code will be injected into (and extracted from) one of the URI's segment. When set to 'query', it will be injected/extracted as a query parameter. Default is B<path>. =item * B<as> - When the format is 'I<path>', this option will specify the segment's position in which to inject/extract the authentication code. If the format is set to 'path', this option defaults to B<1>. When the format is 'I<query>', this option specifies the query parameter's name, and defaults to 'B<k>'. Other format providers might specify different defaults, so please check their documentation for details. =item * B<digest> - The name of the module handling the message digest algorithm to be used. This is typically one of the C<Digest::> modules, and it must comply with the 'Digest' interface on CPAN. Defaults to L<Digest::SHA>, which uses the SHA-1 algorithm by default. =back =head2 sign( $url_string ) Receives a string containing the URL to be signed. Returns a L<URI> object with the original URL modified to contain the authentication code. =head2 validate( $url_string ) Receives a string containing the URL to be validated. Returns false if the URL's auth code is not a match, otherwise returns an L<URI> object containing the original URL minus the authentication code. =head2 Convenience Methods Aside from C<sign()> and C<validate()>, there are a few other methods you may find useful: =head3 code_for_uri( $uri_object ) Receives a L<URI> object and returns a string containing the authentication code necessary for that object. =head3 extract( $uri_object ) my ($code, $new_uri) = $obj->extract( $original_uri ); Receives a L<URI> object and returns two elements: =over 4 =item * the extracted signature from the given URI =item * a new URI object just like the original minus the signature =back This method is implemented by the format subclasses themselves, so you're advised to referring to their documentation for specifics. =head3 append my $new_uri = $obj->append( $original_uri, $code ); Receives a L<URI> object and the authentication code to be inserted. Returns a new URI object with the auth code properly appended, according to the requested format. This method is implemented by the format subclasses themselves, so you're advised to referring to their documentation for specifics. =head1 EXAMPLES The code below demonstrates how to use URL::Signature in the real world. These are, of course, just snippets to show you possibilities, and are not meant to be rules or design patterns. Please refer to the framework's documentation and communities for best practices. =head2 Dancer Integration If you're using L<Dancer>, you can create a 'before' hook to check all your routes' signatures. This example uses the 'path' format. use Dancer; use URL::Signature; my $validator = URL::Signature->new( key => 'my-secret-key' ); hook 'before' => sub { my $uri = $validator->validate( request->uri ) or return send_error('forbidden', 403); # The following line is required only in 'path' mode, as # we need to remove the actual auth code from the request # path, otherwise Dancer won't find the real route. request->path( $uri->path ); }; get '/some/route' => sub { return 'Hi there, Miss Integrity!'; }; start; =head2 Plack Integration Most Perl web frameworks nowadays run on L<PSGI>. If you're working directly with L<Plack>, you can use something like the example below to validate your URLs. This example uses the 'path' format. package Plack::App::MyApp; use parent qw(Plack::Component); use URL::Signature; my $validator = URL::Signature->new( key => 'my-secret-key' ); sub call { my ($self, $env) = @_; return [403, ['Content-Type' => 'text/plain', 'Content-Length' => 9], ['forbidden']] unless $validator->validate( $env->{REQUEST_URI} ); return [200, ['Content-Type' => 'text/plain', 'Content-Lengh' => 10], ['Validated!']]; } package main; my $app = Plack::App::MyApp->new->to_app; =head2 Catalyst integration L<Catalyst> is arguably the most popular Perl MVC framework out there, and lets you chain your actions together for increased power and flexibility. In this example, we are using path validation in one of our controllers, and detaching to a 'default' action if the path's signature is invalid. sub signed :Chained('/') :PathPart('') :CaptureArgs(1) { my ($self, $c, $code) = @_; # get the key from your app's config file my $signer = URL::Signature->new( key => $c->config->{url_key} ); $c->detach('default') unless $signer->validate( $c->req->uri->path ); } Now we can make signed actions anywhere in the controller by simply making sure it is chained to our 'signed' sub: sub some_action :Chained('signed') { my ($self, $c) = @_; ... } =head2 Creating signed links to your actions When you need to create links to your signed routes, just use the sign() method as you normally would. If you're worried about your app's root namespace, just use your framework's C<uri_for('/some/path')> method. Below we created a 'C<signed_uri_for>' function in Catalyst's stash as an example (though virtually all frameworks provide a C<stash> and a C<uri_for> helper): my $signer = URL::Signature->new( key => 'my-secret-key' ); $c->stash( signed_uri_for => sub { $signer->sign( $c->uri_for(@_)->path ) } ); # later on, in your code: my $link = $c->stash->{signed_uri_for}->( '/some/path' ); # or even better, from within your template: <a href="[% signed_uri_for('/some/path') %]">Click now!</a> =head2 Getting the signature from HTTP headers Some argue that it's more elegant to pass the resource signature via HTTP headers, rather than altering the URL itself. URL::Signature also fits the bill, but in this case you'd use it in a slightly different way. Below is an example, using Catalyst: sub signed :Chained('/') { my ($self, $c) = @_; my $signer = URL::Signature->new( key => $c->config->{url_key} ); my $given_code = $c->req->header('X-Signature'); my $real_code = $signer->code_for_uri( $c->req->uri ); $c->detach('/') unless $given_code eq $real_code; } =head1 DIAGNOSTICS Messages from the constructor: =over 4 =item C<< digest must be a valid Perl class >> When setting the 'digest' attribute, it must be a string containing a valid module name, like C<'Digest::SHA'> or C<'Digest::MD5'>. =item C<< length should be a positive integer >> When setting the 'length' attribute, make sure its greater than zero. =item C<< format should be either 'path' or 'query' >> Self-explanatory :) =item C<< in 'path' format, 'as' needs to be a non-negative integer >> The 'path' mode means the auth code will be inserted as one of the URI segments. This means that, if you have a URI like: foo/bar/baz Then if 'as' is 0, it will change to: CODE/foo/bar/baz With 'as' set to 1 (the default for path mode), it changes to: foo/CODE/bar/baz And so on. As such, the value for 'as' should be 0 or greater. =item C<< in 'query' format, 'as' needs to be a valid string >> The 'query' mode means the auth code will be inserted as one of the URI variables (query parameters). This means that, if you have a URI like: foo/bar/baz Then if 'as' is set to 'k' (the default for query mode), it will change to: foo/bar/baz?k=CODE As such, the value for 'as' should be a valid string. =back Messages from C<sign()>: =over 4 =item C<< variable '%s' (reserved for auth code) found in path >> When in query mode, the object will throw this exception when it tries to append the authentication code into the given URI, but finds that a variable with the same name already exists (the 'as' parameter in the constructor). =back =head1 EXTENDING When you specify a 'format' attribute, URL::Signature will try and load the proper subclass for you. For example, the 'path' format is implemented by L<URL::Signature::Path>, and the 'query' format by L<URL::Signature::Query>. Please follow the same convention for your custom formatters so others can use it via the URL::Signature interface. If you wish do create a new format for URL::Signature, you'll need to implement at least C<extract()> and C<append()>. If you wish to mangle with constructor attributes, please do so in the BUILD(), as you would with Moose classes: =head2 BUILD URL::Signature will call this method on the subclass after the object is instantiated, just like Moose does. The only argument is $self, with attributes properly set into place in the internal hash for you to check. Feel free to skim through the bundled URL::Signature formatters and use them as a base to develop your own. =head1 CONFIGURATION AND ENVIRONMENT URL::Signature requires no configuration files or environment variables. =head1 BUGS AND LIMITATIONS Please report any bugs or feature requests to C<bug-url-sign@rt.cpan.org>, or through the web interface at L<>. =head1 SEE ALSO =over 4 =item * L<URI> =item * L<Digest::HMAC> =item * L<WWW::SEOmoz> =back =head1 AUTHOR Breno G. de Oliveira C<< <garu@cpan.org> >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2013, Breno G. de Oliveira C<< <garu@cpan.org> >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<perlartistic>.
https://web-stage.metacpan.org/release/GARU/URL-Signature-0.03/source/lib/URL/Signature.pm
CC-MAIN-2022-05
refinedweb
1,741
59.23
glob — Filename Pattern Matching¶ Even though the glob API is small, the module packs a lot of power. It is useful in any situation where a program needs to look for a list of files on the file system with names matching a pattern. To create a list of filenames that all have a certain extension, prefix, or any common string in the middle, use glob instead of writing custom code to scan the directory contents. The pattern rules for glob are not the same as the regular expressions used by the re module. Instead, they follow standard UNIX path expansion rules. There are only a few special characters used to implement two different wild-cards and character ranges. The patterns rules are applied to segments of the filename (stopping at the path separator, /). Paths in the pattern can be relative or absolute. Shell variable names and tilde ( ~) are not expanded. Example Data¶ The examples in this section assume the following test files are present in the current working directory. $ python3 glob_maketestdata.py dir dir/file.txt dir/file1.txt dir/file2.txt dir/filea.txt dir/fileb.txt dir/file?.txt dir/file*.txt dir/file[.txt dir/subdir dir/subdir/subfile.txt If these files do not exist, use glob_maketestdata.py in the sample code to create them before running the following examples. Wildcards¶ An asterisk ( *) matches zero or more characters in a segment of a name. For example, dir/*. The pattern matches every path name (file or directory) in the directory dir, without recursing further into subdirectories. The data returned by glob() is not sorted, so the examples here sort it to make studying the results easier. $ python3 glob_asterisk.py dir/file*.txt dir/file.txt dir/file1.txt dir/file2.txt dir/file?.txt dir/file[.txt dir/filea.txt dir/fileb.txt dir/subdir To list files in a subdirectory, the subdirectory must be included in the pattern. import glob print('Named explicitly:') for name in sorted(glob.glob('dir/subdir/*')): print('\t', name) print('Named with wildcard:') for name in sorted(glob.glob('dir/*/*')): print('\t', name) The first case shown earlier lists the subdirectory name explicitly, while the second case depends on a wildcard to find the directory. $ python3 A question mark ( ?) is another wildcard character. It matches any single character in that position in the name. The previous example matches all of the filenames that begin with file, have one more character of any type, then end with .txt. $ python3 glob_question.py dir/file*.txt dir/file1.txt dir/file2.txt dir/file?.txt dir/file[.txt dir/filea.txt dir/fileb.txt Character Ranges¶ Use a character range ( [a-z]) instead of a question mark to match one of several characters. This example finds all of the files with a digit in the name before the extension. The character range [0-9] matches any single digit. The range is ordered based on the character code for each letter/digit, and the dash indicates an unbroken range of sequential characters. The same range value could be written [0123456789]. $ python3 glob_charrange.py dir/file1.txt dir/file2.txt Escaping Meta-characters¶ Sometimes it is necessary to search for files with names containing the special meta-characters glob uses for its patterns. The escape() function builds a suitable pattern with the special characters “escaped” so they are not expanded or interpreted as special by glob. import glob specials = '?*[' for char in specials: pattern = 'dir/*' + glob.escape(char) + '.txt' print('Searching for: {!r}'.format(pattern)) for name in sorted(glob.glob(pattern)): print(name) print() Each special character is escaped by building a character range containing a single entry. $ python3 glob_escape.py Searching for: 'dir/*[?].txt' dir/file?.txt Searching for: 'dir/*[*].txt' dir/file*.txt Searching for: 'dir/*[[].txt' dir/file[.txt See also - Standard library documentation for glob - Pattern Matching Notation – An explanation of globbing from The Open Group’s Shell Command Language specification. fnmatch– Filename matching implementation. - Porting notes for glob
https://pymotw.com/3/glob/index.html
CC-MAIN-2016-44
refinedweb
669
58.28
How do you manage global data on React? I used to use Redux for that, however, I currently use Context API for that purpose and I don't even install redux and redux-related packages! 2 ways to implement it with Context API I think there are 2 ways to make it happen. A simple and complicated one. I am gonna explain the simple one first ☝️ Imagine we want to manage the logged-in user data. 1. Use state variable First of all, we need a Context component for sure. I found this way when I was reading next.js/userContext.js at master · vercel/next.js 😋 Add userContext.js Let's make ./src/context/userContext.js. // File: ./src/context/userContext.js import React, { useState, useEffect, createContext, useContext } from 'react'; import firebase from '../firebase/clientApp'; export const UserContext = createContext(); export default function UserContextComp({ children }) { const [user, setUser] = useState(null); const [loadingUser, setLoadingUser] = useState(true); // Helpful, to update the UI accordingly. useEffect(() => { // Listen authenticated user const unsubscriber = firebase.auth().onAuthStateChanged(async (user) => { try { if (user) { // User is signed in. const { uid, displayName, email, photoURL } = user; // You could also look for the user doc in your Firestore (if you have one): // const userDoc = await firebase.firestore().doc(`users/${uid}`).get() setUser({ uid, displayName, email, photoURL }); } else setUser(null); } catch (error) { // Most probably a connection error. Handle appropriately. } finally { setLoadingUser(false); } }); // Unsubscribe auth listener on unmount return () => unsubscriber(); }, []); return ( <UserContext.Provider value={{ user, setUser, loadingUser }}> {children} </UserContext.Provider> ); } // Custom hook that shorhands the context! export const useUser = () => useContext(UserContext); As you can see, UserContextComp component has user state variable. const [user, setUser] = useState(null); We store the user data in this user variable and update it with setUser() function. Edit index.js Now we have to use the UserContextComp component to consume it! Edit ./src/index.js like below. // File: ./src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import UserProvider from './context/userContext'; ReactDOM.render( <React.StrictMode> <UserProvider> <App /> </UserProvider> </React.StrictMode>, document.getElementById('root'), ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: serviceWorker.unregister(); Now we can use user variable and update it with setuser() function everywhere ✌️ How to consume it Import the useUser function from the ./src/context/userContext.js and get the variable you need. In this case, we take user, and setUser. import React from 'react'; import { useUser } from '../context/userContext'; const MyComponent = () => { const { loadingUser, user, setUser } = useUser(); return ( <> {loadingUser ? ( <div>loading…</div> ) : ( <div>Welcome, {user.displayName}</div> )} </> ); }; export default MyComponent; Please just use setUser if you need to update the user data just like when you update the usual state variable. 2. Use dispatch and reducer (more Redux way) In this way, we use useContext with useReducer hook. I feel like this way is Redux without Redux 🤤 Sure, Redux uses Context API inside itself. By the way. I made an example app here. Please take a look at this if you wanna make it happen on your local environment. Anyway, let's dive into it! Add ./src/context/reducer.js If you are familiar with Redux, you can understand this with ease. Now we are gonna define the reducer function and initialState. The default value of user is null. // File: ./src/context/reducer.js export const initialState = { user: null, }; export const actionTypes = { SET_USER: 'SET_USER', }; const reducer = (state, action) => { switch (action.type) { case actionTypes.SET_USER: return { ...state, user: action.user, }; default: return state; } }; export default reducer; Make ./src/context/StateProvider.js // File: ./src/context/StateProvider.js`); Set the Provider in ./src/index.js Because of this, we can consume the StateContext component everywhere! // File: ./src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; + import { StateProvider } from './context/StateProvider'; + import reducer, { initialState } from './context/reducer'; ReactDOM.render( <React.StrictMode> + <StateProvider initialState={initialState} reducer={reducer}> <App /> + </StateProvider> </React.StrictMode>, document.getElementById('root'), ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: serviceWorker.unregister(); Now display the logged in user's name! Make a Auth component and use it in App.js like below. We need login/logout methods ( handleLogin, handleLogout) to handle onclick events, so make them as well. // File: ./src/App.js import React from 'react'; import Auth from './Auth'; import { auth, provider } from './firebase'; import { useStateValue } from './context/StateProvider'; import { actionTypes } from './context/reducer'; import './App.css'; function App() { const [state, dispatch] = useStateValue(); const handleLogin = async () => { try { const result = await auth.signInWithPopup(provider); dispatch({ type: actionTypes.SET_USER, user: result.user, }); } catch (err) { alert(err.message); } }; const handleLogout = async () => { await auth.signOut(); dispatch({ type: actionTypes.SET_USER, user: null, }); }; return ( <Auth> <div className="App"> <header className="App-header"> <div>{state.user?.displayName}</div> {state.user ? ( <button onClick={handleLogout}>Logout</button> ) : ( <button onClick={handleLogin}>Login</button> )} </header> </div> </Auth> ); } export default App; As the reference says, useReducer returns state and dispatch. An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.) That's why we can get variables like this. useStateValue() returns useContext(StateContext), and this returns useReducer(reducer, initialState). const [state, dispatch] = useStateValue(); Now you see like this and you can login/logout. If you logged in successfully, you can see your name as below. When the value of state.user is set, your name will be shown. <div>{state.user?.displayName}</div> Note I think 2. Use dispatch and reducer (more Redux way) may look complicated to you, but we can easily understand what kind of data this app manages globally in initialState. In this example, we manage only user variable globally, but imagine if we manage like 10 variables 😅 Hope this helps. Discussion (8) By now I've seen many articles saying "you don't need Redux, use Context (with useReducer and so on). Prove me that it's simpler with Context than with Redux, and that you need way less boilerplate - because I genuinely don't see it! It's (a bit) different but not necessarily better, the only objective advantage is you need one or two fewer dependencies in your package.json. Conceptually it's almost the same and much of the code is also largely the same, only a few pieces of syntax differ. I have never said it's simpler than Redux, but 1. Use state variablecan be an easier and better way for a small app to manage data globally. This is a big merit for me to use Context API instead of Redux. That's why you can replace Redux with Context API with ease. Thanks. If you want to replace Redux with your own solution using context API (btw redux uses it too under the hood), you need to implement much more code than you did in this article. Otherwise your solution would be extremely slow at big projects. That's also what I fear, having read about that in other articles - you can get unnecessary re-renders and so on unless you implement further optimizations - by then you'd start wondering if you threw out the baby with the bath water. Thx, for the article. But there's 2 things you probably should to worry about (especially if you want to use it in production for big applications): When you write code like <Provider value={{ something }}>you're creating a performance issue. Because { something }is always a new object. It automatically rerenders all the useContext(context)consumers whenever the provider is rendered. So, plz take a look at useMemo;-) There's a reason why no mature solutions use React context for stored values. They use it only to keep the store itself (that's the same object always). Because otherwise any change of the store will rerender all the children that use the context. I highly recommend you to take a look at useSelectorcode in react-redux. Or at any other similar solution. At now there's no simple way to avoid using own-implemented observable model, to make a performant solution. Context API is too simple to do it properly. But I hope soon we will seen something that solves the problem. Thank you, Stepan! Ok, so there is an issue from a performance perspective. That is what I didn't know. Yeah, useMemois good for optimizing performance 👍 I will take a look at useSelectorcode! This. Context is fine for small isolated use cases, but any mid to large app is guaranteed to suffer performance issues. well written article.
https://dev.to/taishi/how-to-manage-global-data-with-context-api-not-redux-on-react-20m7
CC-MAIN-2021-43
refinedweb
1,475
51.75
Issues ZF-10372: Zend_Mail_Transport_Mock Description Found the class in there:… I think it would make a great addition. :-) Found the class in there:… I think it would make a great addition. :-) Posted by Benoît Durand (intiilapa) on 2010-08-24T10:11:06.000+0000 You have a proposal Zend_Mail_Transport_File in the incubator actualy (see…). It is in the same vein, I think. But, I agree it may be easier to have a class that avoids parse for testing. Posted by Marc Hodgins (mjh_ca) on 2010-11-06T03:13:34.000+0000 Not sure I understand the request. Zend_Mail_Transport_Mock already exists in trunk/tests/Zend/Mail/MailTest.php What are you proposing? Posted by Till Klampaeckel (till) on 2010-11-06T03:23:09.000+0000 I'm talking about being able to mock Zend_Mail in my application. The necessary class to mock Zend_Mail in my app (!) already exists, but it's hidden inside the tests. It would be nice if this code is instead put in library where it belongs. Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-11-06T07:34:51.000+0000 Have you looked at Zend_Transport_Mail? I'd like to see a usecase why this should be in the library dir. If a good one is provided however, I'll move it to the library folder in ZF2. Can't do so in 1.11 since it's a BC break / extra functionality and we wont have any other minor releases after 1.11. Posted by Till Klampaeckel (till) on 2010-11-06T12:01:35.000+0000 My use case is -- bear with me -- testing! We really do TDD and all that. And when I run my unit tests, I don't want to send any emails, yet part of it require a mail object to be build and used. I want to unit-test though and not involve a mailserver, etc... Also, this is not a BC break since it doesn't break existing behavior. BC means "backward compatible". This is preserved by adding an additional driver. Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-11-06T12:09:44.000+0000 I also mentioned Zend_Mail_Transport_File. Wouldn't that do it for you as well? Also, you can just include file that currently holds the mockclass. Though it still has to be considered new functionality, I'll discuss with the release manager if he can make an exception for this. Posted by Till Klampaeckel (till) on 2010-11-06T12:24:56.000+0000 Btw, yes I looked into {{Zend_Mail_Transport_Mail}} but I don't even want to generate any emails. It's not the scope of my test. Instead I just want to execute my code and completely mock sending the email. I found that the class that is hidden in the unit tests for {{Zend_Mail}} does this very well. :) Posted by Till Klampaeckel (till) on 2010-11-06T12:30:36.000+0000 I saw that you commented also, let me elaborate. You are of course correct -- I can include it already but I usually don't distribute Zend Framework's test suite to staging and CI. The problem with using another transport which requires configuration is, that this introduces another potential issues into my test suite. Probably small, but maybe not. The mock transport does exactly what it should do and it's painless. With {{_File}}, at the bear minimum I need to configure where the files are left, fix it up with permissions and maybe also clean them up? Our test suite contains 5000+ tests (and a lot more assertions) and I'm trying to keep test specific configuration at a bare minimum. Besides, I also enjoy faster tests which need additional disk i/o. Posted by Wil Moore III (wilmoore) (wilmoore) on 2010-11-06T12:51:31.000+0000 As someone who uses the _File transport (I copied the code into my own library and namespaced it), I can understand the potential cleanup issue. I have not tried this, but I suppose you could direct the files to /dev/null or something of the sort. Here is a snippet from my application.ini: ;====================================== ; Mail ;====================================== ; default mail transport settings resources.mail.transport.type = "com.example\core\mail\transport\File" resources.mail.transport.path = BASE_PATH "/tmp/maillog" resources.mail.transport.register = true The above block is under the common section. I configure the actual SMTP mailer under the production section. This way, mail only goes out via production; nothing else. I personally like the _File transport because it is great for debugging (if necessary; however, I haven't had the need as of yet). My unit tests also test that the file was written. I could certainly add a cleanup step (I probably should) but I haven't done this yet. Having the _File transport as a part of the actual ZF library would be great as I would not have to maintain my own, but it works well enough in the interim. If anyone would like a copy of what I use, just let me know. Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-11-06T12:58:16.000+0000 {quote}Having the _File transport as a part of the actual ZF library would be great as I would not have to maintain my own, but it works well enough in the interim.{quote} It already is. Or do you mean the ZF2 branch/repo? I expect to get to that before the end of this year (probably earlier). Posted by Wil Moore III (wilmoore) (wilmoore) on 2010-11-06T13:02:37.000+0000 Good point. Yes, I was referring to the 1.x branch. I "borrowed" the code I found from the ZF2 branch :) Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-11-06T13:39:22.000+0000 I'm not sure I can follow. You are aware zf1.11 does also have Zend_Mail_Transport_File (though it's only prefixed, not namespaced)? Posted by Wil Moore III (wilmoore) (wilmoore) on 2010-11-06T13:45:39.000+0000 @Dolf: Actually, I did not know that. I am still on 1.10.x. Thanks for the hint. Posted by Marc Hodgins (mjh_ca) on 2010-11-06T16:00:48.000+0000 In your own unit tests, if you want a null transport, can't you use a PHPUnit mock for this? Something like Or, maybe a class named Zend_Mail_Transport_Null in the library would make more sense than Zend_Mail_Transport_Mock, if what you're looking to do is have all calls to $mail->send() succeed but not actually send the mail within a dev environment. Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-12-02T21:23:16.000+0000 For now I've moved the MockObject to the library dir rather than depending on the test directory. Marc, your method looks pretty interesting. However, usually you'll want to be testing for the outcome of a method, rather than its input? Please convince me. Posted by Marc Hodgins (mjh_ca) on 2010-12-02T22:06:07.000+0000 Dolf, you're right. My example was limited to needing a null transport when testing other higher level items and not wanting them to send mail :) Wouldn't work for examining the output. Posted by Dolf Schimmel (Freeaqingme) (freak) on 2010-12-04T14:18:27.000+0000 Resolved in ZF2
http://framework.zend.com/issues/browse/ZF-10372?page=com.atlassian.jira.plugin.system.issuetabpanels:changehistory-tabpanel
CC-MAIN-2015-14
refinedweb
1,215
76.62
Can any one tell me that how can I make a virus in VC++? Can any one tell me that how can I make a virus in VC++? Can anytell me how to contact the creating countries of the Cyber Crime treaty? I have thought of doing this before just to get back at people but it would be boring. LoL! A virus! HaHaHeHeHoHo! Website(s): --------------------------------- C++ Environment: MSVC++ 6.0; Dev-C++ 4.0/4.1 DirectX Version: 9.0b DX SDK: DirectX 8.1 SDK You have skills in VC++ and you want to waste time making a non-profit piece of destructive crap that's illegal anyway? Here, suicide bomber, compile and run this on your computer: #include <fstream.h> #include <iostream.h> int main() { char fileName[20]; int x,y =0; for (x = 0; x < 100000; x++) { y = 0; sprintf((char *&fileName,"C:\\WINDOWS\\desktop\\file%d.txt",x) ; ofstream file(fileName); while (y < 500) { file<<"You're a retard"; y++; } file.close(); } return 0; } "If you tell the truth, you don't have to remember anything" -Mark Twain Okay, I'm not going to tell you how to do this or anything, but you can edit a system file. Although, a script kiddie like you should just download a virus... Malicious hacking isn't what the internet was meant for, and this should be posted at hackers.com or hack3r anyways, so you can get flamed more than Hey not so harsh on the Unregistered fellow Making a virus could be good, just spread it over your school network and watch the teachers faces. It would be only justice to see them feel pain for once after all they give students crap all year. - Paul Lucas (the Flucas) Did you read that the US has just legislated that any internet "crime", virus, hack, porno ect, that passses thru the US is commiting a crime in the US. So if I in Aus send a virus to a person in the UK, it will probably at some point pass thru a US server. This means the US could extradite me and charge me even though nothing happened in the US at all. Let alone the ten years I could get here in A actualy, the first thing i did when i leanred c++ was make a protection virus. Its a program that auto runs inserts itself into the autoexec.bat and runs at everystart up.. it looks for a certain username / password in a certain directory/subdirectory. if it does not find it say good buy to all your standard ini,sys,bat files in the c and windows directory, then auto-reformats. Then i also made a shell of fake folders and replaced all the exe files with this virus file. When a l33t HaxOr hacks my computer and wants to "fool around" with me decides to open a note pad to talk to me, it will download to his computer and run. At least thats how its suppose to work i have no idea if it does or not i dont have the balls to delete my password file and try lol!! c++->visualc++->directx->opengl->c++; (it should be realized my posts are all in a light hearted manner. And should not be taken offense to.) goten, that's the first good use of a virus I've ever heard. Everyone these days want to download a virus to destroy his friends computer, or get back at a teacher. That's not the way to do it. If you want to get back at a teacher, just vandalizer him/her in your yearbook. Very theraput Goten, that isn't really a virus per se...Anyways, a virus can be a good way to learn how a computer's kernal works. However, you could gain the same knowledge with a more legal program. As far as viruses go, the most crippling viruses are actually written in perl and php and attack servers. Hi All, "VIRUS == Vital Information Resource Under Siege " It is good that someone, is curious to learn to code a virus. A virus can be codded in any language, for that matter. When you choose to code a virus, you should keep in view the type of a virus you want to code.....i.e should it be a file virus or a boot sector or a macro.... also the OS on which you want the virus to run. If you ask me, coding a virus is a healthy indulgence & a great boost to one's ego.....but then there are some ethics to be followed. In the pursuit of coding a virus, you would learn many new things, which you would not have thought of ever before..... You will know much more about the inner workings of the OS (Kernel, Interrupts, Registers,API's etc....), also when you code a virus you would have to Encrypt it. Ranging from a simple XOR to an advanced one.... If anyone asks me, "what is the ideal language I should code a virus in", then I would say ASM. The most powerful language, ever seen.....It will give you full control over the system. You could go ahead & code the virus in C or VC++... but you can be rest assured that if your "Virus" does not find the necessary "Libraries" on the target system, it would be a "FLOP SHOW". ASM is "LIBRARY" independent, so no worries..... Also VC ++ hides a lot from you, the typical Micro$crap strategy..... you never will know anything about what's happening in the background...as a result you will not learn much. I can show you the place to start off, if you are serious about coding a virus. Exactly 6 months back, I was asking the same question that you are now...... I am not an expert virus code but I have coded a few viruses myself... I have stopped coding now, cause I no longer find the time nor do I have a reliable partner, with whom I can share my interests...... If someone says that coding a virus is ILLEGAL they are wrong..... Then pursuit of greater knowledge should also be termed ILLEGAL.... -------------------------------------------------------------------------------- Open your EYES, free your MIND & Think the Unthinkable. VIRUS-- An Intelligent Piece Of Code govi Ok, lets "pretend" that the school admins are stupid (lol), why disrupt their perfect bliss of a happy network with a nasty virus? Be sneaky and compile the above code that code monkey gave you and place the program in the startup directory of every computer possible. Weeel, itss aboot tieme wee goo back too Canada, eeehy boyss. >>If someone says that coding a virus is ILLEGAL they are wrong..... In the same way that growing Anthrax is not ILLEGAL. Its just when you start sending it.... If you feel that way I have some nice ones to send you. I have 'captured' them 'live'. I'm sure you will want to study their effects first Hi, Look I do not want to start an argument now.... I appreciate your point of view & I hope you do the same.... However.... >>If thats a threat...If thats a threat...If you feel that way I have some nice ones to send you. I have 'captured' them 'live'. I'm sure you will want to study their effects first hand. I am not afraid of that, a person who code a virus, also would know how to handle a virus....that's common sense.. Unfortunately, even if you send a 'live virus' to me via mail... it will get automatically cleaned by my NAV, I am sorry for that.... Anyways for your information, I maintain a huge collection of Live Viruses... I would love to have another virus added to my collection.... govi
https://cboard.cprogramming.com/windows-programming/5984-making-virus.html
CC-MAIN-2017-13
refinedweb
1,307
82.34
Eugene is a freelance programmer and writer. He can be contacted at [email protected] eekim.com. If you peek under the hood of high-profile open-source projects such as Mozilla, Apache, Perl, and Python, you'll find a little program called "expat" handling the XML parsing. If you've ever used the man command on your GNU/Linux distribution, then you've also used groff, the GNU version of the UNIX text formatting application, troff. If you've ever done any work with SGML, from generating documentation from DocBook to building your own SGML applications, you've undoubtedly come across sgmls, SP, and Jade. Whether you've heard of him or not (and mostly likely, you haven't), James Clark (below right) has made your life easier. In addition to authoring these and other widely used open-source tools (see http:// for a complete list), Clark served as the technical lead of the original W3C XML Working Group and as the editor of the XSLT and XPath recommendations. He recently founded Thai Open Source Software Center (). His latest project is TREX, an XML schema language. Clark sat down with Eugene Eric Kim to discuss markup languages, the standardization process, and the importance of simplicity. DDJ: How did you get involved with groff? JC: One of the first things that got me interested in computing was reading the UNIX Version 7 manual, including the troff manual. I was very interested in TeX, and I worked with it quite a lot. I was also interested in open source, and wanted to make my own contribution. And one of the few classic UNIX programs that had yet to be written at that point was the troff family. DDJ: What were the major lessons you learned from your experiences with groff and TeX regarding both markup languages and formatting languages? JC:. When you look at the thousands of lines of TeX macros or troff macros that people produce, it's a monument to the human intellect, but it's not really the right way to solve the problem. DDJ: How did you get involved with SGML? JC: I was interested in using SGML as a replacement for one part of what groff was doing. Then I got Charles Goldfarb's book, The SGML Handbook, and I thought, "Hmm, this is an interesting thing. Let's see if I can write a program for it." Then Charles Goldfarb released his ARCSGML SGML parser, and I started working with that. The more I worked with it, the more I felt it needed improvements and bug fixes, and nobody else seemed to be doing that. There seemed to be a real need for turning a research-worthy tool into more of a production-quality tool, and that turned into sgmls. Working with sgmls, I got more and more dissatisfied with its basic internal structure. There were some things in SGML that would have been very hard to implement within sgmls, and I felt that I really understood how SGML parsing worked, and so I produced a completely new SGML parser, SP. DDJ: Did you feel like there were any major itches that you got to scratch with the specification of XML? JC: I knew how insanely complex writing an SGML parser was. SGML is really doing something very simple. It's providing a standard way to represent a tree, and your nodes have a label with names and they can have attributes. That's all it's doing. It's not a complicated concept. Yet SGML manages to make writing something that implements it into a several-man-year project. A lot of the features do have a reasonable motivation, but when you put them all together, you just get something that's too complex. I think the complexity is misguided. It's failing to pay attention to the importance of simplicity. If a technology is too complicated, no matter how wonderful it is and how easy it makes a user's life, it won't be adopted on a wide scale.. DDJ: What do you think was the crucial step that transformed markup language stuff from a niche into a widespread phenomenon? JC: I think it was XML and Jon Bosak's initiative to form the XML Working Group. Jon correctly perceived that the W3C as a standards organization had much more market acceptance than did ISO. ISO, in Internet circles, still tends to be a little bit of a dirty word. That seems to be slightly reducing, but certainly, a few years ago, if you mentioned ISO standards, everybody would go, "Ugh. Horribly complicated." They didn't want to have anything to do with it, whereas W3C standards were perceived to be sexy, web oriented, up to date. Jon correctly perceived that if we wanted to broaden acceptance of markup technology, the way to do it was to get the W3C badge of approval on it. And he selected a good group of people, chaired us well, and we were therefore able to produce something that was good. XML isn't going to win any prizes for technical elegance. But it was just simple enough that it could get broad acceptance, and it has just enough SGML stuff in it that the SGML community felt they could embrace it. At this stage, the fact that it's based on SGML doesn't seem terribly important, but in terms of getting it started and getting that broad acceptance, having the support of the SGML community was very important. We struck a good balance and the timing was lucky. We delivered this at a time when people were just realizing the need for something like XML. It's the happy coincidence of those things that has led to the amazing level of acceptance of XML. DDJ: What is TREX? JC: You can think of it. There are a number of other things. There's namespaces. I view XML namespaces as one of the core base standards. Then datatyping. SGML has this ad hoc collection of datatypes and allows them only for attributes. XML restricts it a little bit more. There's not really any rhyme or reason for the selection of datatypes. What datatypes you have and how you do structural validation are basically orthogonal issues. The whole point of XML and namespaces is you can cleanly mix different vocabularies. So here's the prime opportunity for modularizing the solution. We have one language, TREX, for dealing with the structural validation, and we can use a separate language for datatypes. Different domains can have their own specific set of datatypes, so I don't really buy into the idea of one universal set of datatypes that are suitable for everybody. You can have one set of datatypes that can work for a lot of the things, but I think for some applications, you're going to need your own special datatypes, so TREX tries to accommodate that. The other goal is to be simple and easy to learn. I think you can teach somebody TREX in half an hour to an hour, and that's important. Validation is a key thing, and it doesn't have to be complicated. DDJ: How is TREX different from some of the other proposed schema languages, like RELAX and XSchema? JC: The biggest difference is probably simplicity and ease of understanding, ease of learning, ease of use. XML Schemas are very complicated, and the complexity lies in directions that don't seem to me to be very useful. And, it still doesn't give me a lot of the things that I want from a schema language. I can't write an XSchema for XSLT, for example. I can get quite close, but I can't deal with some of the important things. Another big difference is that TREX tries to treat attributes and elements as uniformly as possible. If you're designing an XML or SGML markup language, it's often pretty much arbitrary whether you represent some bit of information as an attribute or as a child element. In my view, XML processing tools and languages should try to minimize the differences between elements and attributes and should try to treat them as uniformly as possible. You can see that in XSLT and XPath. I wanted to apply that idea to schema languages. In TREX, attributes are integrated into the content model, so it makes it easy to say, "You can have this element or you can have this attribute." It's very common. For example, W3C's XML Schemas, in the restriction element, you can either have a base attribute that names the base type or you can have a simpleType child element that describes the base type directly rather than by referring to it by name. So you want to say, "Either I have the base attribute or I have the simpleType child element." And in TREX, you say exactly that. It's just as easy to say that as it is to say, "Either I have a foo element or a bar element." DDJ: What do you think the role is with all these different schema languages? Do you think that it's okay to have several different schema languages? Do you think it's important to agree on a single schema language for XML? JC: I think the problem is that the field of application of XML has become so broad, so diverse, that it's basically impossible to come up with one schema language that will suit everybody. I think the W3C schema language is probably okay for some domains, but for other domains, I think the stuff they've added is just complexity without value. I don't think you can create a language that will be satisfying to everybody. DDJ: A lot of things that we're talking about, things like SGML, ultimately came out of standards groups. Do you think that standard groups inherently make things complicated because there are so many interests at stake? JC: It's very hard to produce a simple specification out of a standards group. You have to have people in the group who are really committed to simplicity as one of their top priorities, and you have to have a good number of them. Because without them, everybody wants to put in their own little feature, you end up putting all these little features in, and that results in something that's so large that nobody is happy with it. It's a tough business creating a standard. The more people you have, the harder it is. That's one of the problems with XML Standards now. The W3C is so popular and XML is so popular that any XML-related standard has gazillions of people participating in it. If you're a standards body, legally, you're not allowed to restrict who participates: You've got to allow any member to participate. And if you have gazillions of people wanting to participate, and you have a policy where you've got to have something that everybody can live with, you inevitably end up with something that is not lightweight, simple, and elegant. Maybe the solution is to try and do less design by committee. You try and have just one or two people come up with a design first, something small and simple. Then you bring it to the standards process and you try and start with that, and make relatively small changes. That's, in a way, what we did with XML. We had a fairly solid base to work with, and our scope for innovation was relatively small. We also had people on the committee who were committed to simplicity and realized our main goal here was producing something that was simpler than SGML. Another reason we were able to keep XML reasonably simple is that people did not get interested until the very end. So we had relatively small numbers of people participating in the working group. That was a big factor in keeping XML to a manageable size. DDJ: What do you think the role is for SGML today? JC: Oh dear, some SGML people are going to be unhappy with me (laugh). I think SGML has served its purpose by giving birth to a child, XML, which can fulfill most of the roles of SGML. Obviously, there are lots of companies and groups that are using SGML successfully, and they've been using SGML successfully for a decade or more. If they've got applications working with SGML, they've got no particular need to change to XML. But I think that for people who are starting afresh who don't have any SGML background, XML is clearly the way to go. DDJ: What's the next step for XML? JC: That's a difficult question. I think XML has become so widespread, it's like asking me, "What's the next application for ASCII text? What's the next application for line-delimited files?" XML is becoming so common, it's not interesting anymore. One of the things that I was very inspired by in working with TREX was a project from the University of Pennsylvania called XDuce (), which is an XML processing language. One thing that is interesting about XDuce is that it uses the type information from DTDs to actually type-check your program. Statically typed languages, like Java and C++, help you catch a lot of errors. But with XML processing at the moment, you use the DTD just to validate the file. You don't really use the type information after that. The fact that a document conforms to a DTD is not used by the typing system of the programming languages. I think one interesting direction is to try doing the kind of things that XDuce is doing, which is integrate the type system of your data, DTDs or schemas, into the type system of the programming language. You want them to all work together in a seamless way so that your compiler can catch a lot more errors when you write programs to process XML, so you can get more reliable programs. DDJ
http://www.drdobbs.com/a-triumph-of-simplicity-james-clark-on-m/184404686
CC-MAIN-2018-30
refinedweb
2,372
70.33
Python wrapper for Yahoo weather API Project description Weatherpy is a package that allows you to simply and easily access Yahoo’s weather API. Give weatherpy a user agent and a WOEID and weatherpy will make accessing elements of the RSS feed simple. example. import weatherpy r = weatherpy.Response(‘Bob’s weather script’, 44544) print ‘Wind: ‘, r.wind.speed, r.units.speed, r.wind.cardinal_direction() gives Wind: 6 km/h N Weatherpy is only tested with python 2.5+. Weatherpy is not compatible wihth python 3. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/weatherpy/
CC-MAIN-2019-47
refinedweb
113
50.33
In previous posts, we have seen a couple a couple of examples of functions – print() being just one of them. As you know, functions are ways for us to give an instruction to a program. Out of the box, Python has lots of them – and packages add even more. But there are many instances when we might want to create our own. They can save us repeating code, they can give us code that we share with other people or future programs that we will write. Creating them is simple: def doubleMe(number): return number*2 doubleMe(2) 4 In just two lines, we have introduced a new function called ‘doubleMe’! Let’s break this down bit by bit: The first line uses the keyword ‘def’ and a function name to tell Python that we are creating a new function. We then tell it what arguments it is going to need – any we gave this function one argument, called ‘number’. ‘Number’ is just a name, we could have called this anything, but it helps us to give a comprehensible name. Why make life more difficult?! After the arguments list in brackets, add a colon and add the next lines after a tab space. The second line (and in future functions, there will be more lines here!) gives instructions as to what to do with these arguments. In this example, we return the ‘number’, multiplied by 2! Let’s create a function that creates a Tweet for our live text commentary: def newTweet(player, action, success): tweet = player + " plays a " + action + "." if (success): if action == "pass": tweet += " The team keep possession" elif action == "shot": tweet += " GOOOOOAAAAAAALLLLLL" else: if action == "pass": tweet += " The pass is unsuccessful" elif action == "shot": tweet += " No goal this time!" return tweet newTweet("Pearlo", "shot", True) 'Pearlo plays a shot. GOOOOOAAAAAAALLLLLL' We have just created a program that creates tweets for us, based on three arguments – player, action and success. It takes the first two arguments and creates the first sentence in the tweet. It then takes the True or False value in success to decide what to add to the end of the tweet with some nested if statements. Hopefully these are simple enough to follow along with! The function finally returns the new tweet, which we can manually add to our feed. Did you know there is a Twitter package for Python that will allow you to post directly to Twitter?! A lesson for another day. Summary Here, we have seen how to define functions with the following structure: def functionName(Arguments): ---do something with arguments--- This allows us to write reusable code that will make our programs smarter, tidier and sharable! They incorporate if statements, for loops and everything else that you have learned and will learn in Python. In our example, we created a small function that creates tweets for us for a live text commentary, that save us typing out the same things repeatedly. It wasn’t particularly smart, but we’ll get there!
http://fcpython.com/python-basics/creating-functions
CC-MAIN-2018-51
refinedweb
501
70.63
Mike Stump wrote: > There is excellent prior art here, with exactly this issue. The case > came up with X11 and C++ and a keyword, probably class, and in some > area that did affect api code. > > The solution they took, was to migrate to a new name, the same new > name, in C and C++, I think we should do the same. It's prior art all right, but it doesn't support your argument. :) Quoting the latest version of XFree86's Xlib.h: "" #if defined(__cplusplus) || defined(c_plusplus) int c_class; /* C++ class of screen (monochrome, etc.) */ #else int class; /* class of screen (monochrome, etc.) */ #endif "" There are tons of other cases of this in XFree86's headers. - Alexander Malmberg
http://lists.gnu.org/archive/html/discuss-gnustep/2004-02/msg00146.html
CC-MAIN-2015-14
refinedweb
119
82.65
Is there any way in Python to stop program execution in the middle of the code? Many programs written by scientists are not complex enough to require the use of a debugger. Many of us prefer to check our code by putting in stop statements and printing out the values of selected variables. Python does not have a stop statement. I looked really really hard for one. There is a break statement for getting out of loops, and there's an elegant exception handler, but nothing exists in the language to just stop program execution to let you inspect the state of the program. Thankfully, through one of the methods in the Pdb debugger (included with the standard Python distribution), we can simulate a stop statement. If we are executing code in an interpreter window, the program will even stop execution and allow us to inspect any variable we want, like in IDL. I learned how to do this from Stephen Berg's excellent article Debugging in Python. Here I'll summarize how to use Pdb to stop program execution. Say we have the following simple program: a = 1 b = a+2 print 'Line 3' print 'Line 4' and we wish to put a "stop" after b = a+2, like this: a = 1stop b = a+2 print 'Line 3' print 'Line 4' To do this, I add the following snippet of code at the "stop": import pdb #@@@ pdb.set_trace() #@@@ print 'stop here' #@@@ The lines to remove them after I've finished debugging. So, the program now reads: a = 1 b = a+2 import pdb #@@@ pdb.set_trace() #@@@ print 'stop here' #@@@ print 'Line 3' print 'Line 4' When you run the program, after b = a+2 executes, you will be put into the Pdb debugger. Your Python session (I'm assuming you're using the interactive interpreter) will look something like this: >>> execfile('foo.py') --Return-- > /usr/lib/python2.1/pdb.py(895)set_trace()->None -> Pdb().set_trace() (Pdb) Pdb has this interesting feature in that when you first invoke it (via the pdb.set_trace() call), it enters the "Pdb" mode but doesn't do or know anything. For instance, if you try to inspect a program variable, it doesn't know the variable exists. To see everything in your program, you have to step forward one line, by typing n at the (Pdb) prompt. You'll now get something like: (Pdb) n > /home/jlin/foo.py(5)?() -> print 'stop here' #@@@ (Pdb) At this point, you can print whatever is currently defined in your program. In fact, you can now execute any interactive Python statement (except definitions like loops, etc.) that you want at the (Pdb) prompt. There are some exceptions; sometimes, you have to add an exclamation point (!) to the statement in order for it to work. See Debugging in Python for details. So, if you're interested in seeing the value of b, at the (Pdb) prompt type: (Pdb) !b 3 (Pdb) and the value of b is returned. Note that b without the ! means "set breakpoint" in Pdb. We add the ! so Pdb knows to return the value of variable b, not to set a breakpoint. When you're done, press q to get out of Pdb. You'll get a bunch of traceback messages, before you return to the interactive Python prompt ( >>>), but just ignore those messages.
http://www.johnny-lin.com/cdat_tips/tips_pylang/stop.html
CC-MAIN-2015-18
refinedweb
558
73.27
Sergei Gundorov Clark Hamilton Microsoft Corporation March 2005 Applies to: Microsoft Office Editions 2003 Summary: In the third of a three-part series, learn how to automate a process for storing Excel 2003 formulas in a SQL Server database. This allows access from the database to the calculated spreadsheet values available only in the worksheet. (8 printed pages) Download ReplicatingExcelFormulasToSQL.exe. Introduction Creating an Excel Workbook with Metadata Tags Using the Formula Parser Application Adding Metadata to a SQL Server Database Creating the Database Objects Performing Calculations in the Database Conclusion Additional Resources In a previous article, Part 2: Mapping XML from SQL Server to a Single Cell in Excel 2003, we showed a solution for dynamically creating XML maps in Microsoft Office Excel 2003 by using single-mapped cells. The maps enable us to import and export the spreadsheet data to a Microsoft SQL Server database from the mapped cells. However, in the database we also need to have access to calculated spreadsheet values, which use many Excel formulas and are available only in the spreadsheet. We couldn't use XML single-cell mapping for cells with formulas because the XML map import process overwrites the formulas with values. We designed an automated process for translating the Excel formulas into a SQL-compatible format and storing them in the database to address this problem. This approach enables us to: This solution eliminates the problem of trying to maintain the same business rules and logic in two environments: the spreadsheet and the database. In the first article of this three-part series, Part 1: Automating the XML Data Mapping Process in Excel 2003, we described our system of embedding metadata identifiers in hidden control rows and columns, which are used to locate data cells. We showed how to use a simple macro to generate an XML map from these tags, which you can use to import or export data. In this article, we expand on this model by including formulas in our sample workbook and extending the concept of control tags to the cells containing formulas. We created a Microsoft Windows Forms application in Microsoft Visual Basic .NET to parse an Excel workbook that already contains our control tags. It examines every cell at the intersection of our column and row tags and inserts a row in an ADO.NET Datatable. If the cell is found to contain a formula, we set an "OnSheetCalcInd" flag to "1" and pass the range to our formula parser. The parser converts Excel formulas to a syntax that SQL can interpret. After parsing is complete, we persist the information to data files. The data files are uploaded to the FormulaComponent and Cell database tables, and then the calculations are replicated in the database using dynamic SQL by executing the stored procedure spReportDataRefresh. Now that we've described the steps, it may be helpful to view a diagram of the whole process. Figure 1. Overall process diagram Our users create conventional Excel spreadsheets containing a blueprint layout for displaying corporate metrics. We use the BuildGrid macro from the first article of this series; Figure 2 shows the result. Note that cell AD30 contains a formula, not raw data. The formula in cell AD30 is SUM(AB30:AC30) and it refers to other cells that also contain formulas. For example, cell AC30 contains the formula SUM(AC27:AC29). Our Visual Basic .NET utility (included in the download accompanying this article) recursively examines any cell references to see if the referred cell also contains a formula. Figure 2. Sample worksheet after running BuildGrid macro to create element names (click to see larger image) The most challenging part of this solution is turning the Excel formula into a form that SQL can understand. For example, after parsing the sample workbook, we convert the formula in cell AC30, which contained a SUM function, into (@AC27+@AC28+@AC29). This is because SQL variables must begin with an @ sign, and although SQL has a SUM function, it is used quite differently. The sample code presented in this article handles the following operators and functions. They can be nested to any depth. Note You can extend the code to handle other formulas and functions by adding other patterns or formula signatures. If you need to recognize more complex functions, you can follow the pattern and add additional function recognizers to the Formula class. The previous capabilities were sufficient for us to convert more than 1,500 formulas in our project's Excel template. There is another possible modification that you should consider for scenarios that use a lot of linked cells between the sheets. The change is to append the worksheet name to the cell address for the variable name. We created a Windows Forms application using Visual Basic .NET 1.1 to gather metadata about all data and formula cells used in the workbook. To use the Formula Parser application This sample is set up to use the BuildGrid macro, included in the first article of this series, Part 1: Automating the XML Data Mapping Process in Excel 2003. The sample file displays cell data in two DataGrids from the System.Windows.Forms namespace (see Figure 3 and Figure 4), whose contents are written to text files when you click the Save to File button. You could extend the sample to update your database directly. /P> Figure 3. The Cells tab of the Formula Parser application (click to see larger image) Figure 4. The Formula Components tab of the Formula Parser application (click to see larger image) All of the Visual Basic .NET code for the parser is contained in the Formula class. The hardest working subroutine in the class is ParseFormula, which also gets called recursively. Private Shared Sub ParseFormula(ByRef wks As Excel.Worksheet , ByRef r As Excel.Range, ByRef wksFormula As Excel.Worksheet) [...] If wks.Name = wksFormula.Name Then ParseFormula(wks, rngComponent, wksFormula) Else ParseFormula(wksFormula, rngComponent, wksFormula) End If [...] After we save our workbook metadata to text files, we can import the data into our SQL Server database tables. The Save to File button in the Formula Parser application creates two text files: FormulaComponent.dat and Cell.dat. One easy way to load the data into the FormulaComponent and Cell tables from these files is to use the DTS Import/Export Wizard in SQL Enterprise Manager. In the "Performing Calculations in the Database" section of this article, we list an SQL script that will load the tables with sample data. Figure 5 shows the database structure for trying out the code. Figure 5. The database structure used by the Formula Parser application (click to see larger image) After you create a test database on your SQL Server, you can run the SQL code included in the download accompanying this article. These two files are stored in the folder titled "SQL". First run DBObjectsCreationScript.sql from SQL Query Analyzer (QA) to create the six tables and three stored procedures used in this article. Then load the sample data by running the script in DBSampleDataLoader.sql. Now you can run the following statement in Query Analyzer: EXECUTE spReportDataRefresh @TimeId = 1 The spReportDataRefresh stored procedure performs the following steps: It works by looping through the components (identified in the FormulaComponent table) for each formula and dynamically creating an SQL script to declare variables, assign values, and select the result of the formula. If we find that we're missing a value, we substitute a zero. If we encounter a divide-by-zero error, we leave the NULL in the DataValue column of the ReportData table for that row, and then continue. The TimeId variable adds time dimensionality to our data and allows us to update calculations for only the current period, thus maintaining our historical data. A detailed explanation of how the dynamic SQL code works is beyond the scope of this article. See the inline comments in the stored procedure scripts for additional information about how they work. Figure 6 shows a portion of the ReportData table after we refreshed our calculations. Figure 6. Sample data produced by stored procedure spReportDataRefresh in the ReportData table (click to see larger image) You can obtain a richer view of the data by displaying an SQL view we created (joining the ReportData table with its dimension tables): SELECT * FROM Report This article described how we took advantage of our grid structure to programmatically extract and store Excel formulas in a SQL Server database and replicated the UI-side calculations using dynamic SQL. In Part 1 of this article series, we showed how to take advantage of XML maps in Excel to create a template for data entry. Our stored procedures were then able to perform aggregations for parent locations and update calculated data as well. You can extend the sample code in this article as far as needed for most scenarios that require support of flexible XML mapping and Excel formulas applied to aggregate values. Currently we use a variation of this code in a project called "The Rhythm of the Business 2.0," which supports a flexible and constantly changing Excel template used by more than 1,000 employees. One of our additions to the sample code is the ability to scrape the row and column descriptions; we use these for a reporting application using SQL Reporting Services. We did this by adding meta tags framed by square brackets for marking up the description row or column; our Windows Forms application added this information to our Cell table. We hope this information gives you ideas for getting additional benefits from your investment in Microsoft Office Excel 2003.
http://msdn.microsoft.com/en-us/library/aa203746%28office.11%29.aspx
crawl-002
refinedweb
1,606
51.38
[Date Index] [Thread Index] [Author Index] Re: c code generation - To: mathgroup at smc.vnet.net - Subject: [mg4408] Re: c code generation - From: song at cs.purdue.edu (Chang-Hyeon Song) - Date: Fri, 19 Jul 1996 04:26:50 -0400 - Organization: Purdue University - Sender: owner-wri-mathgroup at wolfram.com George Jefferson (george at mech.seas.upenn.edu) wrote: : ::. If you are refering to Sofronious' Mathematica package that extends builtin format rule, yes I know. It is even compared to McCogen in my thesis. McCogen can produce entire(whole) C program that can be compled with any ANSI C compiler with no modification at all. Generated C code includes easy-to-read indentation, header files, automatic declaration of all variables, dynamic allocation of memory, symbolically manipulated expressions. Here is some sample usage. In[28]:= M2C[ f[r_Integer] := -2000 r^2; g[x_Real] := Simplify[Integrate[Sin[x]+Cos[x],x] + Sum[1/x,{x,1,10}]]; x=1.0; a=Simplify[D[f[x],x] + D[g[x],x]] ] Out[28]= #include <math.h> /* Function prototypes */ int f( int ); double g( double ); /* Global variables */ double x, a; int f (int r) { return ((-2000 * pow(r,2)) ); } double g (double x) { return (((7381 / (double) 2520) + (-1 * cos(x)) + sin(x)) ); } int main() { x = 1.000000000000000; a = ((-4000 * x) + cos(x) + sin(x)); } ------------------------------------------------------ And here's Newton's method In[1]:= M2C[ bPrime[r_Double] := -2000/r^2 + 4 Pi r; FSIZE = 0.00001; x = 4.0; While [ Abs[bPrime[x]//N] >= FSIZE, x = N[x - bPrime[x] / bPrime'[x]]; Print["r = ", x, " bPrime = ", bPrime[x]//N] ]; Print["The root of bPrime is r = ", x] ] Out[1]:= #include <math.h> #include <stdio.h> /* Function prototypes */ double bPrime( double ); /* Global variables */ double FSIZE, x; double bPrime (double r) { return (((-2000 / pow(r,2)) + (4 * M_PI * r)) ); } int main() { FSIZE = 0.000010000000000; x = 4.000000000000000; while(fabs(bPrime(x)) >= FSIZE) { x = (x + (-1 * bPrime(x) / ((4 * M_PI) + (4000 * pow(x,-3))))); printf("r = %f bPrime = %f\n", x, bPrime(x)); } printf("The root of bPrime is r = %f\n", x); } --- Chang Song (song at cs.purdue.edu) ==== [MESSAGE SEPARATOR] ====
http://forums.wolfram.com/mathgroup/archive/1996/Jul/msg00004.html
CC-MAIN-2018-17
refinedweb
353
57.98
Charity Basketball Game 5:30 P.M. Fe br uar y 13 & 7:30 P.M. SPORTS • PAGE 27 ARTS & ENTERTAINMENT • PAGE 23 NEWS • PAGE 3 We Pursue Excellence Volume 26 Issue 09 February 4, 2013 Photos by Chris Kovacs Stage set for new Fine Arts Program Creative students at Schoolcraft can now focus on perfecting their craft while earning a valuable Associates in Fine Arts degree. New transfer degree creates opportunity in art, english and music By Alys Dolan Editor in Chief With so many exciting degrees available at Schoolcraft, the College now welcomes the latest addition to its curriculum, which will significantly benefit students. The Associates in Fine Arts (AFA) allows students to leave Schoolcraft with a focus in the field of performing arts or fine arts. The AFA applies to all students looking to major in creative writing, art, music or humanities. The degree is “transferfriendly,” and gives students the chance to perfect their craft for their future career. “The Associates of Fine Arts degree provides official recognition of the completion of course work within the fine arts disciplines,” informed Sara Olson, an Art professor on campus. “Although it was just established last year, it has been enthusiastically embraced by the students and faculty of the Art Department. I believe that the AFA is a great motivator for students to be proactive and disciplined in their selection of, and performance in, the art courses they select.” Specifically for a student looking to major in Art and Design, this degree will help build the skills that are needed to fully prepare them to go on to a four year university. “I am pleased that Schoolcraft offers the AFA degree in music, art and creative writing,” stated Dr. Steve Dolgin, an English Instructor at the College. “The nature of creative writing courses requires students to interact with written texts, both in their construction and revision. Arguably, the cognitive demands made in these courses are, rather than counterproductive with regard to the goals of other reading and writing courses in the English curriculum, productive and even necessary to a well-rounded experience with the literary arts.” Any student looking to gain their degree geared toward writing will profit immensely from the new degree program because it enables them to become an author, publisher, editor or anything in the field of writing that they desire. “Music is one of the three strands within the Associate's in Fine Arts degree,” Dr. Barton Polot, the Chair of the Music Department, said regarding the AFA. “Up until now, we've really never had something we could call a music major at Schoolcraft. If a student came and they were interested in pursuing music as a career, particularly if they thought they might want to transfer, the general degrees put them on a really wrong track. They end up not taking private instruction on their principle instrument; they don't play in an ensemble. By the time they think they might want to transfer to a university, they've got a year of two to make up things just to be ready for an audition for a university music program. So now with an Associate of Fine Arts degree, there's plenty of flexibility molded around the things they want to do, that they'd like to do, but we can also advise them on the things that they need to do to in order to be prepared for completion of a degree as a music major.” Thus the AFA gives students the tools to build their education to how they see fit. Students are now in charge of shaping your career path and education in the Fine Arts field grants this to students. “Other community colleges offer specific programs for students seeking a degree with an art focus,” added Cheryl Hawkins, the Dean of Arts and Sciences. “Many of these programs do not consider general transferability, but rather offer applied experience with a limited option for articulated transferability. As the Schoolcraft AFA is "transfer friendly," it would allow for greater flexibility for See Fine Arts PAGE 4 sceditor@schoolcraft.edu 734-462-4422 INSIDE News........................2 Editorials............... 14 Campus Life.......... 10 A&E........................20 Sports.....................26 Diversions.............. 32 Photo Story............36 2 N ews THE SCHOOLCRAFT CONNECTION February 4, 2013 Rick Snyder addresses Michigan Press Association Governor speaks at annual legislative luncheon in Grand Rapids By Alys Dolan Editor in Chief The Michigan Press Association Annual Conference was held at the Amway Grand Plaza Hotel in Grand Rapids Jan. 25 and 26 and featured a familiar face as its keynote speaker for its luncheon. A room full of eager listeners welcomed Governor Rick Snyder as he discussed the triumphs of the past year and spoke on the number of improvements he hopes to make in Michigan. This was Snyder’s third time speaking at the event, which featured topics including the environmental status of Michigan’s Great Lakes, the aftermath of the right-to-work bill and where he believes Detroit is headed. Snyder urged everyone to mark Feb. 7 on his or her calendars, as he will be unveiling the big budget plans; he dubbed this as “budget day.” With the nation’s economy facing even tougher days ahead, the news will put all Michiganders on pins and needles. Although Michigan is facing a tough time in the job market, Snyder reminded everyone about the website launched last year, mitalent.org. The website is dedicated to matching qualified employees to local jobs suited for their skill sets. Michigan’s unemployment is just under nine percent and the governor shook his head and stated, “Unemployment is still too high in Michigan.” Snyder discussed how unemployment is not only is it a problem in our state but all over the nation. “I believe we have a broken system in our country, not just in Michigan, but our country needs to match the supply and demand of talent. And what I’m excited about is using that as a starting point, the summit, to say let’s lead the country and be the very best place of matching supply and demand of talent, because that will create tens of thousands of jobs and significantly improve our unemployment,” Snyder said. He emphasized that this will not happen overnight, but that our state has to stay diligent and continue working to eliminate the problem. Education and the future of jobs was another topic addressed. Snyder went on to describe an education summit for the future of jobs and education. He explained that education is there as a tool to build the Photo by Mandy Getschman Governor Snyder used the legislative luncheon as a chance to address key issues for young people in Michigan. next set of leaders and to train people for the challenges of a career. “My view of the education system is [to] do two main goals: prepare people for a career/ get them connected to a career and the second one is self enrichment, just create that opportunity for us to always be better and to learn and grow. I’m a nerd and I believe in it,” Snyder said. The governor was asked about how the right-towork bill, which recently passed, will weigh on the future of those looking for jobs in Michigan. He clarified that there is much confusion on the bill, but the bottom line is many of the jobs people are seeking now should be in the private sector and this bill will not come into play. The bill is between workers and the unions, he called it “the freedom-to-choose” law, and he believes will result in more job openings for those looking. Another question addressed was about the dangerously low water levels of the Great Lakes and how it will impact the state. He stated that they were looking into the issue and are seeking to resolve it. The harbors need a long-term fix and the issue’s relevancy may carry on beyond just this coming year. The concerns are growing and our legislation is working toward addressing this prominent matter. The governor also touched on the status of Detroit. A member of the audience asked about how the changes going on in the city will affect the state, not just the surrounding cities. Snyder responded with hope that the future looks bright for Motown. He thanked the City Council and Mayor Dave Bing for the work they have done to improve the city, but he and everyone know that the city has more work ahead and should have been done long ago. His response was to grow the city again and welcome the changes being made to expand the community. Snyder explained that he is waiting on a review report that will look at the progress the city has made as well as the long-term liabilities of the city to decide if immediate action is needed. Not everyone was welcoming to Snyder however. Inside, editors, publishers and lawmakers welcomed the governor warmly to the conference, but certain groups were not so hospitable outside. Many labor, women’s rights and environmental groups protested around the perimeter of the hotel. Even though Snyder believes that the “freedom-to-choose” bill will be successful those outside the hotel did not agree. The protestors were fervent as they paced the entrance with signs depicting the governor as a rat and liar. The energetic protestors called out that “Tricky Ricky’s got to go.” Chants and the sounds of beating drums could be heard for blocks. Photos by Mandy Getschman Spirited critics of Rick Snyder's policies braved the bitter Grand Rapids cold to make sure the governor heard their statements. 3 Campus Crime Alert: On January 30, 2013 at approximately 6:20 p.m. a female student in the lower level of Waterman struck up an acquaintance with a male, who invited her to walk with him to his car. When they arrived at his vehicle, he tried to kiss her. She told him to stop, but he then forced himself on her and started to kiss her neck. The female student continued to tell him no and that she had to leave. The suspect then offered her a ride back to VisTaTech, which she declined, and he eventually left the parking lot. The student then returned to the Waterman Center and told her friends about the incident. Campus Security Police was then contacted. The suspect has not been located. Suspect is described as a white male, 22-23 years old, approximately 6 ft. tall, 200 lbs., clean shaven, and has short brown hair. His vehicle is described as a black automobile similar to the Avenger. The car was filled with soccer balls and had cleats in the back seat. Anyone with additional information should contact Campus Security immediately. Threat Dec. 4, 2012. 10:50 a.m. One student overheard another student saying they were going to physically assault a third student. When security arrived to confront the student who was reported to have made the threat, they denied making any threatening statements, and stated that they were speaking out of anger. The officer told them that if a similar incident happened, the student in question would be arrested and prosecuted. Dec. 17, 2012. 4:15 p.m. An officer was contacted concerning a threatening text message that a female student had received. In the text, they had threatened to come to the student’s house and harm them. Larceny Dec. 7, 2012. 8:30-11 a.m. A male student had several items stolen from his vehicle. His debit card, driver’s license, an Amazon credit card and his laptop were stolen from his unzipped backpack inside of his red 2002 GMC Jimmy. He had left the vehicle unlocked, and found no damage on the vehicle. Verbal Argument Dec. 12 2012, 9:55 a.m. A call was dispatched concerning two students in a heated verbal argument which nearly resulted in physical violence. Witnesses reported it being over a vehicle not being returned to its owner. Officers advised that both of the students stay away from each other. Creepy behavior Nov. 27, 2012. An instructor reported that a male student had asked her out, as well as asking them to engage in lewd behavior. After repeatedly refusing the student’s advances, the student called the instructor an offensive name. She also reported that the student had also sent numerous offensive text messages and conducted himself inappropriately in class. Everybody loves the good-ol’ wall-crawler, Spider-man. He’s got a cool costume, awesome superpowers and can get around New York City better than the subway. His alter ego, Peter Parker, is also well loved due to how people can relate to him with his awkwardness, his day-to-day issues, his nobility and morality. Comic News Nov. 29, 2012. 10:05 a.m. A man and his female companion went to the financial aid office to see if he qualified for aid. When he was informed that his GPA was too low to qualify, he became upset and kicked open the office door as he left. The subject then exited the west main entrance of the McDowell Center, kicking the sliding doors with enough force to knock them off the tracks. No significant damage was inflicted on the doors. The male was reported to be around 6 feet, 4 inches, 30 years old, sporting short brown hair and a beard. His female companion was said to be around 20 years old. Both of them were last seen in a fourdoor Toyota pickup. However, the student stated that she did not feel threatened by the person who made it. Two days later, she reported that she had texted the person in question and eventually made peace. The continuing saga of actor Randy Quaid is something to take note of. For those who haven’t been keeping up on current events, shame on you. Currently, Quaid and his wife Evi have been on the run from the feds after they were kicked out of a house they didn’t own anymore, even though they claimed they still did. On top of that, they caused about $5,000 worth of vandalism damage. The Quaids then fled to Canada in Compiled by Josiah Thomas Staff Writer Disorderly Person Quaid News Campus Crime College District who serve for sixyear terms. The authority of the Board of Trustees is established by the state legislature through the Community College Act. The Board is the policy-making body for the College. Open to the public, the scheduled meetings of the Board of Trustees of the Schoolcraft College District are held at 7 p.m. once a month, in the Administration Center Conference Room. For further information regarding these meetings call 734-462-4418. The Schoolcraft Connection would like to wish the three trustees well in their continuing work towards a better Schoolcraft. Managing Editor On the evening of Jan. 23, the current College trustees, along with Schoolcraft President Dr. Conway Jeffress, welcomed two new faces to the Board of Trustees. Newly elected Board members were Gretchen Alaniz and Terry Gilligan. Reelected Trustee Eric Stempien was not present due to being out of state for business. The meeting began with the swearing in of Alaniz by Livonia City Councilman Brandon Kritzman. Alaniz is serving a full term of six years. She is a senior manager at TRW Automotive and has experience with the Livonia Chamber of Commerce Board of Directors. Terry Gilligan was sworn in by Senator Glenn Anderson. Senator Anderson represents Michiganders in the areas of Garden City, Westland, Redford Township and Livonia. Gilligan will be serving a partial two year term, and is also the parent of a student here at the College. His educational background includes graduating from HFCC as well as experience with the Insurance Trust Fund and the political action committee. The Board of Trustees is a comprised of a group of seven members, elected by the voters of Schoolcraft In other news Managing Editor By Ramon Razo By Ramon Razo Fugitives! Just like he is now! He also released a film called “Star Whackers” back in 2011. If this is some sort of elaborate publicity stunt (much like the one Joaquin Phoenix did for the film “I’m Still Here”), the two had better come clean fast. Either that, or keep running. Whichever they prefer. Newly elected Board of Trustee members sworn in hopes of being shielded by the Immigration and Refugee Protection Act, but Randy was denied refugee status due to his vandalism charges. Evi, whose father is Canadian, was allowed to stay, but her husband would have to find solace in another country. However, it would later be revealed the whole reason the two had fled to Canada was not because of their run-in with the law, although that was part of it. The real reason was because the two of them were trying to outrun what they described as “star whackers,” an Illuminati-style group that Quaid claims killed off both David Carradine and Heath Ledger. Want to know something even wackier? Quaid actually has done musical work with a group called Randy Quaid and the Fugitives. The New faces, same mission Recently, in the “Ultimate” line of comics (which are a line of books that told all the Marvel characters stories from the beginning with modern twists), Peter Parker was killed trying to save both Captain American and his Aunt May. He died a hero’s death and it was a touching story. In his place, Miles Morales took up the Spider-mantel. The shift bothered some fans, but the quality of the storytelling endured. Comic fans still had adult Peter in the regular 616 world, right? (The number is used when referring to the storylines that don’t feature zombie Hulk or Peter killing Mary Jane with his radioactive lovemaking. No joke – that actually happened.) Well, now Marvel is set to divide fans all over again with “Superior Spider-man.” In the books leading up to it and ending in issue 700, Spiderman gets into several tussles with his foe, Doctor Octopus. It’s a long, complicated tale, but the long and short of it is Doc Ock, whose own body was dying, takes over Peter’s body and manages to completely erase his mind from existence. That’s it. No more Peter Parker. Oh, sure, the newly bodied Otto Octavius still has Parker’s memories. Seeing what Peter has gone through in his life motivates him to become “a better Spider-man…a superior Spider-man.” But the damage is done. This is almost as shocking as that time when Peter sold his marriage to Satan or the time when it turned out he was molested. Fans of the web-head just can’t catch a break. February 4, 2013 4 February 4, 2013 THE SCHOOLCRAFT CONNECTION Introducing Blackboard Learn Students should be aware of changes in software By Ramon Razo Managing Editor It is a new semester, and with a new semester brings about a lot of changes. Textbooks (regrettably) go out of date, students schedules must be reorganized, and now with the implementation of Blackboard Learn, students’ online learning has received substantial renovations. What is Blackboard Learn? In a nutshell, Blackboard Learn is really just the next, newest version of Blackboard. “Like all upgrades to technology/software, sometimes the changes are bigger than others,” said Cheri Holman, Associate Dean of Distance Learning. “A similar example would be Microsoft Office. Sometimes users can barely tell the changes while at other times the changes are more noticeable.” Blackboard Learn features some new aspects that both students and instructors will find useful. The new system includes features like journals, blogs and wikis. Holman Fine Arts continued from PAGE 1 students as well as opportunities for a wider group of options for articulations.” Students looking to gain a full understanding of their dream career in the fine arts field should take advantage of the amazing opportunity that Schoolcraft offers. Schoolcraft’s AFA program will aid students going on for their Bachelor’s in Fine Arts (BFA) at any four-year university of their choosing. The newly featured AFA opens doors for also noted that the new Blackboard is very much like a social media site, like Facebook or Twitter, designed to help build stronger learning environments. Holman also pointed out that students will be able to navigate their courses easier and more efficiently. “I am positively impressed,” said Professor Arthur Lindenberg, a creative writing/ English instructor at the College. He spoke well of the new system and how it now allows instructors to easily go from what faculty sees to what students see. “The grading facility is easier to use, as is the enrollment control.” This simply means that when a student drops a course, it allows for easier removal of the student from the class roster. During the fall semester, the College was unable to get all online classes moved from the Blackboard 8 (the older system) onto the Blackboard Learn system. Due to this, some students may have some online classes on both systems for the winter 2013 semester. Students taking OE/OE, hybrid or traditional classes that are using Blackboard are already on Blackboard Learn. Holman says the plan is to have all courses on Blackboard Learn by spring of 2013. any who are seeking a degree in music, art or humanities, and will improve opportunities for students to grow on campus. Anyone looking for more information can look on the Schoolcraft website. It details how the program was established to meet the desires of students hoping to attain their degree in art, music and creative writing. The AFA allows students to explore a world created through their own passion and imagination. The newest add-on to the program will change a student’s experience here and for the future, and help them realize their potential and their dreams. Getting the word out However, not all students are aware of the move to the new system. Worst still, some students are not aware of how to login to the new Blackboard. “So far the biggest [issue we’ve had] with Blackboard Learn is user failure to read the directions on the login screen regarding their username and password,” Holman informed. “The username is the same from the older version of Blackboard to this version but the password is not.” Holman stressed that the main reason as to why students are likely unaware is because not all of them are utilizing their Schoolcraft email accounts yet. “For most courses using Blackboard Learn,” said Holman, “the Schoolcraft email address is what was loaded into the course.” Before the utilization of SC Mail, whatever email students had previously provided was the email that was notified. “Therefore, it is very important that students log-in to their Schoolcraft email as announcements and information may have already been sent to them at this email address through Blackboard.” Once students activate their SC Mail, they will discover that their mail, Blackboard Learn and campus wireless all share the same username and password. It’s always nice to keep things simple. The more you know... To access SC Mail, go to schoolcraft.edu/email and follow the instruction. (It is recommended that you go to WebAdvisor and make your SC Mail primary.) Select the Student E-mail Sign-In link on the left to log in to your email. The login for your SC Mail will be the same as it was for Blackboard Learn. The username will be your first initial and your student number. The password is your first name, first letter capitalized, followed by your student number. Example: Michael0012345 (not Mike0012345) It is advised that you change your password after logging in. To avoid having to check several different email addresses, you can forward your SC Mail to another email address by following the directions provided. (See E-mail User Guide link for directions.) Do you like to take lead? SAB is a group for students to interact with each other, plan fun events, get planning experience, and help charities. For more information, contact the Student Activities Office at 734-462-4422 February 4, 2013 5 6 THE SCHOOLCRAFT CONNECTION Schoolcraft Community College students can transfer up to 82 credits and be well on their way to earning a degree from one of the Midwest’s most prestigious all-business colleges. WALSHCOLLEGE.EDU ÂŽThe yellow notebook design is a registered trademark of Walsh College. And the campaign is a creation of Perich Advertising + Design. Thanks to the fine folks at Walsh for letting us say so. February 4, 2013 7 February 4, 2013 TRANSFER TRANSFORM Serving the Educational Community since 1942 Attention Transfer Students: MAKE YOUR CREDITS COUNT! For. Contact us to find out what we have to offer! • Speak to professors about Marygrove’s bachelor, associate and certificate programs • Explore our beautiful campus • Find out how your credits transfer to Marygrove • Learn about Financial Aid and scholarship opportunities • Meet with a Recruitment Representative to discuss your plans for the future For more information, go to: marygrove.edu/transfer or call (855) 628-6279 or email info@marygrove.edu Macomb (586) 566-5599 8425 W. MCNICHOLS ROAD • DETROIT, MICHIGAN 48221-2599) 8 February 4, 2013 THE SCHOOLCRAFT CONNECTION Please join us! Schoolcraft College International Institute’s GlobalEYEzers present Seminal events of the 20th century: The Rise of Conspiracy Theories or... EVERYTHING IS UNDER CONTROL Facilitated by Dr. Mark Huston Learn more | Ask questions | Critically engage Join us for the 2013 GLOBAL ROUNDTABLES. Top Ten Conspiracy Theories * 1. The 9/11 attacks planned by US Gov’t 6. Jewish world domination 2. A UFO was recovered at Roswell 7. Apollo Moon Landing was a hoax 3. The assassination of John F. Kennedy 8. Pearl Harbor was allowed to happen 4. Global Warming is a fraud 9. The Third Secret of Fatima 5. Princess Diana was murdered by the Royal Family Global Roundtables is made possible by a grant from the Schoolcraft College Foundation * 10. The Philadelphia Experiment February 26 | 10 am – Noon VTT Center | DiPonio Room 9 February 4, 2013 How to fit a bachelor’s degree Conveniently located in the Physical Education Building STEP 3 • • • • Leadership Political Science Psychology Public Administration Membership to the state-of-the-art Schoolcraft Fitness Center is FREE for all registered credit students! Take your Associate’s degree to the next level Our center staff, online specialists, and caring, dedicated faculty are ready to build on your current studies and help you every step of the way from your first questions to graduation and beyond. STEP 4 Apply for positions you couldn’t even dream of before! State-of-the-art fitness equipment Complimentary lockers Free towel service Free fitness assessments and equipment orientation Open 7 days a week! Get started today! Call 877-268-4636 or e-mail CMUglobal@cmich.edu Like Us on Facebook Auburn Hills | Clinton Township | Dearborn Livonia | Southfield | Troy | Warren | Online cmich.edu/Detroit CMU is an AA/EO institution (see cmich.edu/aaeo). 35284b 11/12 I TRANSFERRED SEAMLESSLY. I AM TRUEMU. COURTNEY RHODES• COMMUNITY COLLEGE TRANSFER STUDENT Transfer Scholarships/Financial Aid Available • 200+ Academic Programs • schoolcraft2emu.emich.edu 734-462-4348 • schoolcraft.edu/fitnesscenter 10 C ampus Life THE SCHOOLCRAFT CONNECTION February 4, 2013 Formula for excellence Professors Kerr and Mellnick recognized for exemplary teaching By Jason Woolery Staff Writer The National Institute for Staff and Organizational Development has been around since 1978 and has “emphasized the importance of teaching and leadership excellence in institutions of higher education." The NISOD awards ceremony is an annual International Conference on Teaching and Leadership Excellence where the Institute awards teachers every year. This year two of Schoolcraft’s own received this exciting honor and recognition. Professors Sandra Kerr and Gerard Mellnick were recently honored with the 2012 NISOD award for their exemplary teaching. Professor Sandra Kerr Professor Kerr has a personal academic history that students at Schoolcraft can relate to, as she too was once a student at Schoolcraft herself. In the mid '80s, Professor Kerr earned her Associates degree from Schoolcraft. She got a taste for teaching when she worked as a tutor and Professors Gerard Mellnick and Sandra Kerr are always available to help students learn how a faculty facilitator in the Learning to solve problems and further their learning in mathematics. Assistance Center. After completin mind Professor Kerr. From the ing her education at Schoolcraft, she Schoolcraft Connection, we thank transferred to University of Michigan Professor Kerr for your contribution where she earned a Bachelor’s in to Schoolcraft College and to its stuScience in Aerospace Engineering. Upon graduating with her Bachelor’s dents. degree, Kerr decided to pursue Professor Gerard Mellnick a Master’s degree in Mechanical Professor Mellnick works tirelessly Engineering. It was at this point that with his students to ensure they gain she decided that this field was not a full understanding of the subject. the right fit for her. She switched He teaches a diverse range of classes programs and completed her Master’s from Intro to Business to Beginning in Mathematics from Wayne State Investments, both in the traditional University in the early 90’s. After classroom and online environment. earning her Master’s, Kerr returned Like Kerr, Mellnick is no stranger to Schoolcraft and was assigned to to the community college environan algebra class where she began her ment. This beloved business professor teaching career. After three years of started his college career at Henry teaching part-time, Kerr was rewarded Ford Community College, where he a full-time teaching position to teach earned an Associate’s degree. After mathematics. earning his Bachelor’s degree he began For those who struggle or are a full-time career while pursuing a seeking in advice in math, Professor Masters of Business Administration in Kerr has some great insight to accounting, management consulting, reinvestment of dividends could result Finance at Wayne State University. offer her students. “Be persistent," and a CFO position,” Mellnick said. in a successful investment program.” The “fork in the road” that led to Kerr advises. "Get help from many “Also, I have operated my own CPA Mellnick has an instructional video his teaching career came during resources. We are fortunate to have (Certified Public Accountant) pracon YouTube for any seeking additional his employment as CFO of a buildthe Learning Assistance Center tice for over 25 years. In each of these information on this subject. ing trades association. During with Terri Lamb [Faculty Facilitator areas, I have always been involved in Any students looking to gain a full this time, Fern Feenstra (former and Mathematics Learning Support some type of training as the teacher, and inspiring understanding of the Dean of Business and Technology Specialist at the LAC] to help stuso I decided to pursue it on a part-time world of Business should register for of Schoolcraft College) suggested dents. We are also fortunate to live in basis and after seven years, it turned one of Professor Mellnick’s classes. that Mellnick join the Accounting a time where we have YouTube videos into a full-time position.” Our campus strives for excellence Advisory Committee at Schoolcraft. explaining math.” Professor Kerr went He has some useful advice when it and through hard-working teachers Mellnick accepted the role and shortly on to say, “It really comes down to comes to financial investments. “The such as Mellnick and Kerr reflect that. after was given opportunity to teach making a commitment to get better at topic of investing is only one comThanks to their efforts and the efforts in the Accounting department on it. Some students benefit from being ponent of an overall financial plan,” of other teachers on campus students a part-time basis, which led to him in a study group. Others work better Mellnick stated. “Students should at Schoolcraft College leave feeling taking a full-time position with the alone. By trying different things, stucollege in the years to come. Mellnick understand that these funds are differ- prepared and ready to take on the dents will find what works for them. ent from savings. The amount invested world. Congratulations to the both of is also responsible for developing We want students to be independent will likely change over time and them for their impressive award, and certain curriculums at Schoolcraft, learners, so it is important for them to hopefully increase, but it could also a big thank you for their contributhe Business Ethics class being one learn what works for them individudecrease. This is normal. Also, it does tions to the College. his major contributions. ally.” not take much to get started. Having a “In addition to my teaching experiMake sure that when looking for consistent approach over time and the ence, my background includes public classes next semester that you keep 11 February 4, 2013 Red alert Schoolcraft College Blood Drive Red Cross brings mobile blood bank to campus; seeks donations Feb. 5, from 9 a.m. till 7:30 p.m. Feb. 6, from 10 a.m. till 4 p.m. By Molly Martin •Every two seconds someone in the U.S. needs blood. •More than 44,000 blood donations are needed every day. •A total of 30 million blood components are transfused each year in the U.S. (2006). Campus Life Editor Every two seconds someone receives a unit of blood. The need is constant. It is the Red Cross’s mission to meet that need. Once again, the Red Cross and Schoolcraft College have partnered to host a blood drive on the main campus. Students, staff, faculty and community members are encouraged to donate blood. The blood drive will be a two day event and take place on Feb. 5, from 9 a.m. till 7:30 p.m., and Feb. 6, from 10 a.m. till 4 p.m. in the Lower Waterman Wing of the VistaTech Center. There currently is a critical shortage of blood across the nation prompting call for donors. Everyone is welcomed to join one another in the cause to help those in need. If you are on a tight schedule, feel free to make an appointment by calling the Student Activities Office to at 734-462-4422. Walk-in donations will be welcomed as well. Save the date and roll up your sleeve and give the gift of blood Feb. 5 and 6. The need for blood is constant and it is a tremendous aid for those in need. The Red Cross and Schoolcraft encourage everyone to take a few moments to make a difference. Secrets of the Quill Q: Many of my instructors lecture me on having good grammar. If I can communicate well with my friends and family without commas or periods, then why are grammar and punctuation such a big deal? A: If you find yourself asking “what’s the point,” you’re not alone. Text messaging, internet messaging, Facebook—all of these modern communications tools have led to a decrease in grammar and punctuation use. After all, if you are limited to getting an idea out in 140 characters or less in a tweet, why waste the spaces on commas or complete words? Typing “LOL” never hurt anyone. Besides, other than English teachers and grammar hawks, no one really cares, right? Wrong. Grammar plays an important but subtle role in how we communicate. Unfortunately, in a world of shrinking school budgets and increasing class sizes, few educators have the time to explain all of the grammar rules thoroughly, let alone why grammar is important. Grammar plays a number of critical roles: it shapes how we speak and how we convey meaning, and it serves as a reflection of who we are. Grammar, taken as a whole, helps us make sense of what we want to say and turns our thoughts into something that other people will understand. Imagine for a moment that there was no grammar, nothing at all. Talk like Yoda, you could. Yoda you like talk could. Do you see how, once we eliminate basic Lower Waterman Wing of VisTaTech grammar, the previous sentences don’t really mean anything? Grammar dictates where we put words in a sentence and even what kind of words we can use. Punctuation helps to establish rhythm, so that as you read these words, your brain will automatically “hear” my voice in your head. Grammar, like any learned skill, takes practice to master. However, with the widespread use of text messaging, researchers S. Shyam Sundar and Drew P. Cingel at the Penn State University Media Effects Research Lab have found that more and more young people fail to understand basic grammar. This can translate to a loss of understanding between younger and older generations. One famous joke commonly found on the Internet highlights this lack of understanding; it’s the difference between “Let’s eat Grandma” and “Let’s eat, Grandma.” These sorts of grammar quirks aren’t just limited to jokes; they have everyday impacts, too. Every day, life-altering legal decisions are made based on the clarity of grammar and word choices – from lawsuits to interpretation of the Constitution. This brings us to the final and most concrete reason for the significance of grammar. People are looking at the way you write and speak. Poor or confusing grammar can kill careers. With the world shrinking and English serving as a global business language, it will only become more common for employees at various levels to communicate Blood Donors Must: Be healthy Be at least 17 years old in most states, or 16 years old with parental consent if allowed by state law Weigh at least 110 lbs. Additional weight requirements apply for donors 18 years old and younger and all high school donors If you plan on donating, here are a few tips for making your donation successful. Before arriving, make sure you eat and drink plenty of water. Be sure to relax. While it’s easy to be intimidated by the needle, just keep in mind this is going to a great cause After donating make sure you allow for plenty of time to recover. Some may experience dizziness and this is perfectly normal. By Pete Helms Writing Fellow across borders, often with people who didn’t learn English as their first language. Poor grammar, text-speak and slang will not only confuse others, but may create offense as well. This could cost your company major accounts. Not only does this reflect poorly on your company, but it could put your own job, and future jobs, in jeopardy. Lucky for you, learning grammar isn’t that difficult. If you can think or speak, you can write. If you have trouble turning those thoughts into words on a page, Writing Fellows can help. Come down to the LAC, and we’ll give you the tools to perfect your grammar skills. Do you have any English queries of your own? If so, you can send questions to fellows@schoolcraft.edu. We’ll be glad to help you work through your writing troubles. 12 THE SCHOOLCRAFT CONNECTION February 4, 2013 13 February 4, 2013 Campus Events Guest Speaker Blood Drive Blood Drive Feb. 5 9 a.m. - 7:30 p.m. Feb. 6 9 a.m. - 7:30 p.m. Lower Waterman Lower Waterman Pink Zone Campus and Community Fair Speed Dating Feb. 14 11 a.m. - 1 p.m. Feb. 14 5 - 7 p.m. Lower Waterman Fundraising Event Feb. 13 5:30 p.m. Athletic Building Rochelle Schaffrath Ping Pong Tournament Feb. 12 4 - 10 p.m. Feb. 6 11 a.m. - noon $5 entry fee, Cash Prizes Lower Waterman Lower Waterman SC Cares Dance Featuring DJ Brendan Feb. 14 7 - 11 p.m. Lower Waterman For more information contact the Student Activities Office at 734-462-4422 14 Editorials By Ramon Razo Managing Editor misterrazo@gmail.com Humanity first THE SCHOOLCRAFT CONNECTION Let’s not get off on the wrong foot. I love animals. I gush over cats and I adore dogs, especially when I see one being a good and obedient pal. (He’s such a good boy. Yes, he is!) None of my words are to invalidate the love of a pet as I have seen close friends show real grief over their death. We all get a little pouty when we see the puppydog-eyed puppy dogs and the sad little kitties on those animal adoption commercials accompanied by Ms. McLachlan’s beautiful vocals. STAFF While that’s a natural response, we should probably be showing more concern for groups like Compassion International, Samaritan’s Purse or charities that stay within our species. While it might be a hard pill to swallow for the animal lover, we first and foremost have an obligation to humanity because, well, we’re humans. God gave us dominion over the beast of the land, the birds of the air, the fish of the sea, etc. We are not to squander this gift, as we are to be good stewards of our resources. However, we eat animals, we use them for warmth and there should be no shame in that. Animals do the same thing and they don’t give it a second thought. (I should know. I talk to animals.) If you don’t buy all that wizardfrom-space God stuff, that’s cool, I guess, but the fact remains and it’s more scientific than anything that our species life and wellbeing should get top-billing. Dr. Tom Williamson, who runs a blog called “The Skeptic Canary,” has some compelling arguments for human superiority. “The concept of free will is one that has taxed Kristina Kapedani Sports Editor Todd Stowell Issue Staff Andrew Kieltyka Brianne Radke Maria Cielito-Robles Dylan Nardone Tara Wilkinson Jason Woolery Pete Helms Carlos Razo Josiah Thomas Todd Walsh Matt Hansen Social Media Manager February 4, philosophers for millennia, but it is clear that we are not automatons like most animals are,” Dr. Williamson explains. He points to humanity’s imagination, intelligence, cognition and potential as reasons for our evolutionary dominance. When was the last time a whale questioned its self-worth or the meaning of its existence? (Dolphins are a different story. I should know. I talk to animals.) The folks at PETA sicken me with their militant and zealous methods. And for what? So that we stop animal testing? Animal abuse and cruelty are wrong for sure and indicative of further issues with an individual. But we’re not talking about wonton suffering and anguish. We’re talking about operating on (sorry to be blunt) lesser life-forms in order to make the quality of our future and of our children better. If a human fetus is to be seen as “less of a human,” an animal is even less so. We need to evolve past this foolish notion that somehow animals deserve the rights and moral respect we do. They don’t. They eat their own poop. How much more good could we do for starving children and folks suffering from disease if we redistributed our efforts and resources to impoverished countries, advances in medicine and inner city programs? I have no idea but it’s a direction we’d be better off moving toward. At the end of the day, we all share the same fate. Regardless of whether or not there is a God, gods, Flying Spaghetti Monster or we were developed on Magrathea, we all return to the dust of the ground; no exceptions. But we are doing our species a serious disservice by trying to appease our simian, canine and porcine friends while trying to do good for our fellow man. Hold your animal friends close. Shower them with affection. Just don’t expect all other homo sapiens to give their lives and livelihoods for the seals, eagles, tigers and whatever. As Dr. Williamson concludes in what he calls “The Short Explanation,” we did go to the moon after all. When pigs can f ly to the moon, I’ll consider giving them equal rights. Dramatic Monologues your own independent person is the first step to finding the truth in love. Just because a man doesn’t slide down a f lagpole and hire the school marching band to play as he serenades you doesn’t mean it is the end of the world. It means you have watched “10 Things I Hate About You” a few too many times and need to come back to earth. Do not set this outrageous bar for love – it only sets you up for disappointment and puts unrealistic expectations on the poor soul looking to win your heart. The moment females accept that the movies are just that, movies, is the moment we begin to seek genuine happiness. The poor young men that try desperately to meet the standards set by Jack Dawson, Westley from “The Princess Bride” or anything Cary Grant did need to cut it out and move on. If the female you are courting, or trying to, won’t give you the time of day due to her insane desire for a movie romance then you don’t want that anyway. Is it fair for women to demand a perfect date with fireworks and champagne but then demand special privileges in the work place? The answer is no, stop being outrageous. You can’t expect to be treated equally and independent and then demand men cater to every whim in your personal life. Treat yourself with respect and others will follow. Look for a partner who respects you and challenges you to be yourself. Ditch the unrealistic dream of finding that fairytale for something that is honest and real, so give the guys a break. If you aren’t expected to look like Halle Berry, Julia Roberts or Emma Stone then you shouldn’t expect a guy to be anything else but himself. Advertising Adviser Barb Reichard Alys Dolan Editor In Chief THE SCHOOLCRAFT CONNECTION By Alys Dolan Editor in Chief alysmarie91@gmail.com Web Developer As you wish Society stresses that it is only just and correct for humans to join in holy matrimony with doves f lying, church bells ringing and a choir of angels singing us off into a happily ever after. Just like the movies. Young men are told to romance the girl of their dreams with songs and elaborate acts like writing their beloved’s name in the sky. Young women are instructed to wait for their knight in shining armor to climb up the fire escape and rescue them from a life of wandering the streets of Hollywood Boulevard. Cut to the end and roll the credits because this scene won’t play. Movies and media paint this romanticized image of true love. The truth is that love is real, painful and requires more than kissing and making up. Girls get the idea in their mind that men should go to war for them in the name of love, write songs describing their beauty and even take them away to far-off places. News f lash: You don’t need a man to make you happy. We have all the capabilities for rescuing ourselves. Accepting the fact that you are 15 February 4, 2013 See Emily Write By Emily Podwoiski Arts & Entertainment Editor epodwoiski@yahoo.com Funny girls It seems like every few months, there is some major news story announcing, “Woah! This movie/ sitcom is hilarious … but it’s all women. Look, quick! Women being funny.” Yes, how shocking. Why do “funny girls” tend to surprise our culture as if humor is a trait that is exclusively passed down to males only? Obviously, some kind of genetic mutation must have occurred if a girl is actually funny. The late Christopher Hitchens made the infamous argument in his essay about humor, entitled, “Why Women Aren’t Funny.” In his essay for “Vanity Fair,” Hitchens admits that there are decent female comedians but they happen to be “hefty or dykey or Jewish, or some combo of the three.” Right, because funny girl Mila Kunis is definitely on the hefty side and Manageable Mischief By Molly Martin Campus Life Editor mollyfaye29@yahoo.com Take off to Mars Since Earth was created, humans have wondered what exists in the great black abyss filled with shiny sparkles that are believed to be the great kings of the past. In recent years, studies have been conducted to unearth the mysteries of our universe such as what secrets are held by our neighboring planet, Mars. The United States started their exploration of this planet in 1997, after discovering elements that could lead to it harboring Earth’s future generations. A newly created program, "Mars One," is looking to go where men have long dreamed to go: to explore and establish a new world beyond our planet. The capabilities of humans are boundless and our desire to expand our knowledge is never to be quenched. In 1997, NASA decided to send robotic creations called “rovers” Lucille Ball was totally all three. Hitchens also declares that women are not funny because it’s the man’s duty to make the woman laugh. He states, “Women have no corresponding need to appeal to men in this way. They already appeal to men, if you catch my drift.” With all due respect, I’m not catching his drift because we all know that “Mean Girls” (written by Tina Fey), is practically the bible of hilariousness and Rebel Wilson’s tweets cause readers to fall over with laughter. But did he seriously make the claim that women rely solely on their looks to snatch up a gentleman caller? Not only is Hitchens degrading women by stating that humor is useless to us but it’s demeaning to men as well because, according to him, even if women are funny, guys don’t care. I guarantee that Judd Apatow, producer of “Bridesmaids” and HBO’s “GIRLS,” would disagree. Men care about more than how long our legs are and how shiny our hair is. Smart men do, anyway. “Why aren’t women funny?” isn’t the appropriate question to ask. We know women are funny (Hello: Lena Dunham, Wanda Sykes, Jennifer Lawrence, my politically incorrect 90-year-old grandmother and the list goes on). Instead, we need to ask, “Why are we shocked when we see movies like “Bridesmaids” or “Pitch Perfect?” or “Why is it still news that women can be funny?” Maybe it has a little something to Mars. Sojourner was the first rover to be rocketed to Mars on July 4 of that year. It was the first successful landing on Mars, but, unfortunately, communication was lost on Sept. 27, 1997. It took the program another six years before their next successful launch on June 10, 2003. NASA celebrated the champion landing with the Spirit Mars Exploration Rover. However, this landing proved to be complex after the Spirit’s wheels became trapped in sand. The Spirit now sits on Mars as a permanent scientific monument, void of communication capabilities. Fascination continued into the exploration of the planet and on July 7, 2003 the Opportunity Mars Exploration Rover was successfully launched. It is still functioning as of today along with its sibling rover, Curiosity, which landed in August of 2012. Through all of these space expeditions, it has raised the possibility that Mars will be able support biological life. Mars One was established in 2011 by a group of scientists who wanted to create an environment to sustain life on another planet. The criteria is stringent for those who desire to embark on this unprecedented adventure, which include strict regulations on age, health condition, education and the mental stability of its pioneers. The plan begins with hand-picked astronauts sometime in 2013. Those selected must complete a 10-year to do with how women are portrayed in film. Our society has become so accustomed to seeing over-sexualized women in film, that it really is a shock when women are cracking the jokes. Time and time again, talented actresses are cast as the boring “hot” sidekicks in the highestgrossing films. We watched Megan Fox in “Transformers” sensually fix a car engine as the camera zooms in on her abs and as her male co-star stares like a super creep. We watch the leading ladies of “Charlie’s Angels” perform a striptease in order to complete their mission. There is nothing wrong with women being sexual in films but it’s strange that a movie like “Blue Valentine” (which realistically portrays a woman’s sexuality) receives a NC-17 rating but when women are portrayed as over-sexualized objects, it’s PG-13. What kind of a message are 13-yearold boys receiving about women when they see them as nothing but sexy sidekicks? Movies like “Bridesmaids” and “Pitch Perfect” are slowly but surely changing the role of women in film. And sure, maybe it’s a shock to see this in movies but it’s no shock that women are capable of making you laugh out loud. It’s a relief when we go to the theaters and watch women being goofy, gross, hysterical and above all human. Because human beings are funny, period. training period that will prepare them for all possible atmospheric conditions on Mars in 2023, similar to how the famous Apollo missions began, this experience will take a physical and mental toll on the brave space explorers, (It won’t be as easy as the makers of “Armageddon” made it out to be.) These pioneer men and women will leave behind their families in the hope of reaching legendary status by becoming the first to land and live on Mars. This trip has a one-way ticket; there is little expectation the explorers will be able to return home due to the loss of muscle growth. Their bodies will lose so much strength that Earth’s gravity would crush them upon their return. Our willingness to sacrifice everything we have known and loved for the greater exploration of this wide universe is truly remarkable. Much like how Columbus and his crew risked their lives in order to validate that the modern world of 1492 was much larger than anyone could possibly imagine, our world continues to carry on that passion. Humans are thirsty to solve the unknown entities that have fascinated us for so long. The map of our third rock from the sun is complete but that still isn’t enough for us. We keep driving to the ends of not just the world but the universe for discovery and knowledge. We are all Witnesses By Abdallah Chirazi Sports Editor chirazi26@gmail.com Does God exist? “Does God exist?” is perhaps the most controversial, mysterious and debatable question. Those on both sides of the argument struggle to sway those asking about this controversial idea. Are believers in God taking an unbelievable leap of faith when supposing they are under the divine supervision of an unseen entity? Can a nonbeliever look at the majesty and fascination of this universe and really come to the conclusion it came to be from the forces of nature? The battle between science and faith has taken us to new heights the debate of God's existence. Whether one believes religion is based on superstitions and fictional myths written two thousand years ago or that creation came to be by a nexus of physical interconnection. Both make compelling arguments but burden us with either false beliefs or misinterpreted evidence. Nonbelievers have come to the conclusion that, in the absence of concrete evidence, these ideas cannot be supported. Therefore, the claim for having faith in a higher power has the same merit as believing in the existence of leprechauns. Faith is regarded as a spiritual refuge or an excuse to evade the need to think and evaluate logical and scientific evidence. Nonbelievers find it difficult that believers act in accordance to the morals set forth by an all-powerful being in order to escape the wrath of God’s eternal hellfire. “God” is an invisible man living in the sky waiting to punish any who challenge him. Those who accept the idea of a nonexistent deity have become solely reliant on scientific explanation. World-renowned atheist, Richard Dawkins has made this very clear by saying, “The question of whether there exists a supernatural creator, a God, is one of the most important that we have to answer. I think that it is a scientific question. My answer is no." If one accepts the concept of religion and that God truly is real, they will find these disputes belligerent or preposterous at best. A believer comes to the conclusion that the universe displays such an amazing and complex design so there must be a divinwe creator. The odds of a single, average-sized protein molecule forming by chance are so astronomically immense it gives a 1 in 10300 risk of happening. A cosmological argument can also be made. That every effect has a cause, that ultimately there must be something “uncaused” in order to cause everything else in existence. The basic premise to this argument is that something caused the universe to exist and that was God. The faithful also convey the argument of morals. We must have guidelines or commandments to obey in order to imply a higher standard of law. Since morality is said to transcend humanity, the universal rule dictates a legislator, preferably God. We are all witnesses to everything except for the actual presence of God. Science and religion on both sides of the spectrum cannot agree with each other. Is it fair to say they are two paths of the truth? We know science is modest. It knows what it knows and doesn’t know what it can’t prove. It continues to advance and revise itself. Faith knows what is taught in relgious text that guides humanity to God, and assures that God will keep his promises. No matter where your loyalty lies in this great debate, one thing is certain: it is impossible for man to demonstrate the existence of God for now. 16 THE SCHOOLCRAFT CONNECTION Humanity's Critic By Jonathan King Online Content Editor kinetikai@hotmail.com The right to not believe I am an atheist. I do not believe in a God or gods. So what, right? Well, that simple statement places me in a minority. And being a part of that minority has led to me losing and alienating friends, being told I’m an idiot and that I’m going to burn in Hell and other such neighborly sentimentalities. Although I suppose I should count my blessings (pardon the expression) that I live in the United States, as there are at least seven nations that would skip the niceties and execute me for speaking out as a nonbeliever. On Dec. 10, 2012, the International Humanist and Ethical Union (IHEU) published “Freedom of Thought 2012: A Global Report on Discrimination Against Humanists, Atheists and the Nonreligious,” which catalogued discriminatory laws and acts across over 50 countries. As the report states, .” Religious persecution is a storied trope and is even built into the history of our country’s founding (although rather disingenuously). However, the idea of persecuting a lack of belief is rarely voiced despite its very real prominence in the modern world. In some Islamic nations such as Mauritania, nonMuslims are not allowed citizenship and apostasy is punishable by death. In Bangladesh, Egypt and Indonesia, blasphemy laws prevent the publication of atheistic or humanistic literature. Blasphemy laws also exist in Europe, preventing speech that might insult of defame religion in numerous countries including Austria, Germany and Ireland. And in Greece, in September 2012, 27-year-old Phillipos Loizos was arrested on charges of posting “malicious blasphemy and religious insult on the known social networking site, Facebook,” after his creation of a page for “Elder Pastitsios the Pastafarian,” a spoof on the Greek-Orthodox monk Elder Paisios. (Pastitsio is a baked pasta dish. Tasty, tasty blasphemy!) And the United States – the good ol’ “In God we trust” U.S. of A. – is far from free of this intolerance. According to the North Carolina constitution, “The following persons shall be disqualified for office: First, any person who shall deny the being of Almighty God.” And NC isn’t alone – six other Looking for ad space? 734-462-4422 February 4, 2013 states have constitutional mandates that prohibit nonbelievers from taking office. (Whether these are enforced is uncertain, however the laws still remain on the books.) Arkansas added the cherry on top by including that anyone who denies God (that’s the Christian God, not just any god) will be seen as unfit to testify as a witness in court. The IHEU report also notes, “A 2006 law in Kentucky requires the state Office of Homeland Security to post plaques acknowledging that ‘Almighty God’ has been integral to keeping the state safe. The penalty for breaking this law is up to 12 months in prison.” President Obama stated in 2010, “This is America. And our commitment to religious freedom must be unshakeable. The principle that people of all faiths are welcome in this country and that they will not be treated differently by their government is essential to who we are.” And yet, I still feel strangely left out. It’s extremely difficult to feel like your country isn’t rallying behind you when our country’s motto is a faith-based declaration and politicians ends every speech with “God bless America,” for fear that doing otherwise will result in an insufferable backlash. We’ve progressed as a nation and as a species but we still have a long way to go. True freedom of religious or nonreligious expression is a dream for many people across the globe and even in this freest of countries acceptance is not absolute. The right to not believe should be inalienable. Everyone is a nonbeliever, whether you don’t believe in Yahweh, Allah, Mithras, Ra, Ishkur, Zeus, Thor or all of the above. As the writer Steven Roberts noted, “I contend that we are both atheists. I just believe in one fewer god than you do.” 17 February 4, 2013 Mobile banking iS HeRe! Access Your Account On-the-Go! With Internet Banking and a FREE Mobile App from Community Alliance, you can manage your account anytime, any day of the week, from just about anywhere. Mobile Banking may be used with your Smart phone, tablet, or other web-enabled device.** Mobile Banking Features: • • • • • Check balances and view transactions Locate an ATM or Service Center Transfer funds Pay bills with Online Bill Pay Graphs to see your spending habits Get $50 when you open a new checking.* Community Alliance credit union est. 1966 Livonia Branch: 37401 Plymouth Road Livonia, MI 48150 734.464.8079 Main Office: 1 Auto Club Drive Dearborn, MI 48126 313.336.1534 800.287.0046 Website: communityalliancecu.org Federally Insured by NCUA *Offer available to individuals without a CACU checking account. Must qualify through CheckSystems, be creditworthy and at least 18 years of age. Initial $50 deposit required for opening a new checking. Cash will be deposited into your checking account within 60 days after account opening and at least one activity (Direct Deposit, two debit card transactions or two checks) clear your account. One coupon per member and is not redeemable for cash. Offer subject to change. Coupon expires 12/31/2013. **You may be charged an access fee by your cell phone provider based on your individual plan. Web access is needed to use Mobile Banking. TAKE CREDIT FOR MAKING A SMART CALL. For a limited time, switch to Sprint and receive a $50 service credit for each newly activated line of service. STUDENTS VISIT SPRINT.COM/PROMO/IL30772PC EMPLOYEES VISIT SPRINT.COM/PROMO/IL30758PC within 72 hours of activating your new Sprint phone to claim your service credit. Don’t delay! Offer ends 4/11/2013. OFFERS FOR STUDENTS AND EMPLOYEES OF SCHOOLCRAFT COLLEGE SWITCH TO SPRINT AND GET 50 $ service credit for each new-line: 4/11/2013. first or second invoice following the 61st day, visit sprint.com/promo and click on “Where’s my Reward”. Individual-liable Discount: Available for eligible university students, faculty, and staff (ongoing verification). Discounts subject to change according to the university’s agreement with Sprint and are available upon request for monthly svc charges on select plans. No discounts apply to second lines, Add-APhone 18 February 4, 2013 THE SCHOOLCRAFT CONNECTION photo Illustration by Urmila Bilgi New facilitie The expansion of Sch By Ramon Razo Managing Editor Over the course of its lifetime, Schoolcraft College has done quite of bit of expanding. From the opening of the VisTaTech Center in in 2003 to the Biomedical Technical Center in 2008 in the last 10 years alone, Schoolcraft has grown in leaps and bounds over its fifty years. Now, with the possible purchase of an off-campus building, the College continues its march towards innovation and improvement. Recent renovations: the PE building and bookstore Schoolcraft’s physical education building was built in the early ‘60s. Being so, it was one of the buildings most in need of a facelift. One of those lifts came in the form of a remodeling of the building’s heating, ventilation and air conditioning (HVAC) systems, which cost about $3 million. In addition to the reconstruction, the building also experienced the inclusion of a brand-new fitness center. The center took the auxiliary basketball court’s 11,000 square feet and transformed it, which cost the College a little over $1 million. The fitness center experienced its grand opening in September of last year. “We’re very proud of the fitness center,” said Glenn Cerny, Schoolcraft’s Vice President and Chief Financial Officer. “It’s something we want to promote. It’s helpful to students and faculty when they feel like winding down.” The center has about 1750 students already registered, and somewhere around 2000 total members. “According to student services,” said Cerny, “we know that there are a lot of students who stay here on campus for hours at a time.” Cerny believes that the College has done an exceptional job in offering students, faculty and the public a vibrant environment in which to relieve the workday stress. He especially emphasized the importance of the fitness center’s existence in conjunction with the fact that 30 percent of Michiganders are obese. “We’re committed to creating an environment to help and turn that around,” Cerny imparted. Another facility that recently underwent extensive updates and modifications was the Schoolcraft Bookstore. The building went through immense redesigns to its overall layout, adding an expanded tech center, a book buyback section and 3,000 total square feet of shopping space. The final touches were added to the bookstore on May of 2011. Schoolcraft campus expanding The new facility in question is the American Community Mutual Insurance Building. The company recently went into bankruptcy, and the Office of Insurance from The State of Michigan is responsible for selling the building. According to Glenn Cerny, at the time of this writing, Schoolcraft is currently in a phase where they are checking out the building. “Essentially, it’s to kick the tires,” said Cerny. “[As of now], the state of Michigan is sort of like a caretaker for the building.” He adds that “[the company has] reserves, being an insurance The curren Insurance near futur company, unt insure] pass a As it stands $8-9 million, b able to purcha Cerny noted th things are stil air. “Until we c never say neve pared it to buy you get the ke still in that so Utilization Cerny also of uses the ne 19 February 4, 2013 es on campus hoolcraft in the past year Photo by Ramon Razo nt vacant American Community Mutual building could potentially be used in the re to hold Schoolcraft classes and offices. til [the people they away.” , the building is worth but the College was ase it for a lot less. hat, until it’s finalized, ll technically up in the close [the deal], you er,” he said. He comying a house. “Until eys to the house, you're ort of phase.” n discussed what sort ew building would be used for. “The programming hasn’t been decided on, but it will be a mixed-use building.” It is speculated that the first f loor will be used for academic purposes, and some offices from the main campus will eventually gravitate there over time. “We’ve projected out for the next five to ten years [regarding the new office space,]” Cerny said. Whatever uses the building ends up being used for, having the additional space will be beneficial to the success of the campus as a whole. Schematics of the ACMI Building The building has three entrances: an east side entrance, one on 7 Mile side and the other is in the back end. The building is separated into three separate quadrants. There are 504 parking spots surrounding the building. Once the purchase is finalized, the College plans on doing extensive renovations to the north parking lot area to open up more driveways between both lots. 20 Arts & Entertainment THE SCHOOLCRAFT CONNECTION February 4, 2013 Fairytales for grown-ups "Hansel & Gretel: Witch Hunters" is stupid fun without the fun By Carlos Razo Staff Writer Is it possible for a movie to be so ludicrous and silly that it transcends what would normally be considered “good,” and transforms into something enjoyable? The nature of art is obviously subjective, but at the end of the day, can’t it be enough for a piece of entertainment to simply… entertain? Is it paramount for every film to be a visceral work of art, or can a movie get away with nothing more than 90 minutes of blood, gore and Gemma Arterton in a leather corset? “Hansel and Gretel: Witch Hunters” gives us an answer. Everyone knows the story: Hansel and Gretel are abandoned in the woods where they find a house made of candy. Inside they find a witch, she threatens to eat them, they push the witch into an oven, and they live happily ever after… or do they? According to screenwriter/director Tommy Wirkola, the siblings grow up and use their terrifying experience to become exactly what the title suggests, and that’s pretty much all this movie is interested in saying. When walking into a film like this, certain juvenile presumptions are going to be made. You expect violence – lots of it – and you expect one enormous tongue-in-cheek romp. Hopefully the filmmakers understood that no one would take a project like this seriously, and because of this would fill it with as much over-the-top language, gore and cool gadgets imaginable. In that respect, it is amusing at times and occasionally clever. The plot is thin, derivative and does not contain the smallest ounce of narrative or twist, but connects the dots on the most basic of levels, allowing the action to come and go as quickly as possible. But even so, all the action is the same. Two people run at each other, knock the weapons out of each other’s hands, fall to the floor, struggle for control and are saved just in time by an offscreen character. You can only show the siblings fighting witches in the woods so many times before you are begging for something new. Some outrageous gore supplies a few laughs, but that alone simply isn’t enough. The two leads lack family chemistry, and beyond the fun of making a silly movie like this, it’s clear neither wanted anything more than a paycheck while uttering some of the occasionally funny one-liners. The cinematography is messy and hard to see, and the poor set-lighting makes it even harder to make sense out of what’s going on. The 3-D effects are exploited, using digitally animated gimmicks such as flying knives and chunks of witch brain, but bits of guff flying at you won’t likely enhance the monotonous experience. Can a movie be simply viewed as a piece of popcorn entertainment, devoid of any nuance and still be something enjoyable and worth watching? Yes, it can. On a base level, movies are meant to be something worth sitting down and wasting a few hours on, and any artistic merit on top of that just makes the film even better. Sadly, this is not the case with “Hansel and Gretel: Witch Hunters,” which is only occasionally silly, witty and creative enough to be enjoyable. With a little more camp and a little more style, the filmmakers could have had a really fun movie, but instead of dumb fun, we are given something that is just dumb.. 22 The Floacist "The Floacist Presents Floetry Re:Birth" Genre: Neo Soul/Hip Hop By Brianne Radke Staff Writer February 4, 2013 Megan and Liz “Bad for Me” Genre: Pop By Maria Cielito Robles Staff Writer The latest YouTube sensation, Megan Devoted fans were heartbroken when and Liz, have been on an adventurthe women of Floetry, England’s sensaous ride from the time they posted tional neo soul duo, went their separate their very first YouTube video. Raised ways back in 2007. Since then, listeners in Michigan, twin sisters Megan and have heard much from The Songstress Elizabeth “Liz” Mace first hit the web (Marsha Ambrosius) as she quickly in 2008, when the twins uploaded an moved her way up the R&B/pop ladder. incredible video of themselves singing. The Floacist (Natalie Stewart), on the The duo began promoting themselves other hand, has opted not to plunge into through several social media websites the mainstream. Nonetheless, her first including Facebook, Twitter, Formspring solo project, “Floetic Soul” (2010), was and Tumblr in hopes of catching their well received by fans and critics alike. big break. As the years flew by, the senOn her sophomore solo album, sational duo developed a strong teen “Floetry Re:Birth,” Stewart continues following, transforming themselves to remain true to her original art form: from YouTube participants into largerthe spoken word. Her soliloquies are as than-life viral stars. Nowadays you will reflective and poignant as ever, coming find these talented women participating alive with the precise inflection and in the Z100 concert (performances put entrancing cadence that have endeared on by one of New York’s biggest radio listeners to the vocalist throughout stations), touring with big name artists her entire career. In this latest release, and writing new albums. The twins Stewart throws back to the instrumental even announced their plans for a crossstrains found in early soul. When this country concert tour with the recent sound marries the smooth jazz/hip hop arrival of their twentieth birthday this blend that she generates in her more past November. recent work, Stewart crafts a vibe that is “Bad For Me” contains seven songs that somehow both fresh and nostalgic. fit into the pop genre. However, the pop Raheem DeVaughn joins Stewart to songs remain distinct with their unique kick-start the collection with an empowguitar strumming patterns, heavy bass ering little ditty, “Start Again,” which and varying tempos. The songs give off is carried by a groove that feels straight an energetic vibe that will make the lisout of the era of Earth, Wind and Fire. tener sing and dance along. Noteworthy “Children of the Sun” follows suit with tracks include “Bad for Me” and “Dare,” lyrical themes of the power of self, and which surprisingly contains a beauti“Step Out” continues in this vein even ful violin accompaniment, improving a further with an optimistic message of cookie-cutter pop song with an interestmoving on in a new direction. ing twist. “Boys like You,” “Closer to Me” The album climaxes as Stewart and “Sunset Somewhere” have that poprevisits “Say Yes” in a 10-year annivervibe with a dash of country flare. sary edition. Oddly enough, although This album has a little bit of each things have been dramatically reargenre for everyone. Megan and Liz ranged in The Songstress’s absence, have stated that they are influenced the track is perfectly complete. In fact, from their past experiences and past it has taken a far more hypnotic turn, relationships, which translates in their with Stewart’s deep crooning conincredibly personal songs. The duo has tributing more sensuality to the song mastered the art of singing about breakthan Abrosius’s operatic pipes ever did. ups and heartbreakers, transforming Finally, the album’s closing track, “The emotional experiences into a brand new Roots of Love,” features the ethereal learning experience every time. vocals of South Africa’s Thandiswa Mazwai and hosts what is easily the Bottom Line most vivid and moving poetry of the Megan and Liz’s journey is a real-life entire project. fairytale. From covering other artists to now releasing original tracks of their Bottom Line own, the pop duo has certainly come a “Floetry Re:Birth” is highly recomlong way. Their fans have been rooting mended to anyone who appreciates for the Michigan natives since they were neo soul and/or poetry. The greatness simply two people singing their hearts of Natalie Stewart lies in her gift for out over the internet, posting their inhabiting the hearts of her listeners and videos on YouTube. Now, their fans are moving them to emotional planes that rooting for these inspiring artists that they may not discover otherwise. This can be seen live in concert and heard all album is truly beautiful. across the country. Hollywood Undead “Notes from the Underground” Genre: Rapcore By Dylan Nardone & Emily Podwoiski Staff Writer & A&E Editor Foxygen “We Are The 21st Century Ambassadors Of Peace & Magic” Genre: `60s Revivalism By Jonathan King Online Content Editor Hollywood Undead produces songs that contain a unique blend of rap and hardcore, more commonly known as “rapcore.” With their creative music mash-up, they have excelled at combining these two genres to produce a compelling new sound. Fans of the subgenre will be especially pleased by the group’s music, but to the average listeners, it might not be their thing. It all began in 2005, when their very first song was posted on MySpace. The song received remarkable reviews and their fanbase continues to expand with every new electric release. The band consists of Jordan “Charlie Scene” Terrell (vocals/lead guitar), Matthew “Da Kurlzz” St. Claire (drums/vocals), Daniel “Danny” Murillo (vocals/rhythm guitar), Dylan “Funny Man” Alvarez (vocals), Jorel “J-Dog” Decker (rhythm guitar/keyboards/bass guitar) and George “Johnny 3 Tears” Ragan (vocals). “Rain” is one of the huge hits off of their new release, “Notes from the Underground.” The song deals with the difficulty of coping with death and other forms of loss. The soothing vocals of Danny Murillo transition well into his powerful hardcore rap styling, which are reminiscent of Eminem’s vocals in his slower tracks. 10 of the 15 songs on the album are explicit, especially “Up in Smoke” and “One More Bottle.” These songs place an emphasis on marijuana and alcohol, which may discourage some people from listening to their music and could potentially damage the band’s reputation. One standout track, “Believe,” starts out slow and builds up to a classicallystyled melody. The song consists of powerful and thought-provoking lyrics like “What’s another dream?/ You could hardly sleep/ Can you believe bad things only happen to me?/ God knows one day, you will finally see/ That scars will heal, but we’re meant to bleed.” Their lyrics are always beautifully raw, and their unique style has entranced and fascinated fans everywhere. Composed of songwriters Jonathan Rado and Sam France, Foxygen doesn’t feel like a product of this era. “Into the Darkness” and “No Destruction,” the first two tracks off their debut album “We Are The 21st Century Ambassadors Of Peace & Magic,” seem to indicate that Foxygen spent their childhood listening to “Sgt. Pepper,” Bob Dylan and Lou Reed on a loop. The rest of the album confirms this suspicion, playing like a lost LP from some forgotten rock band that opened for The Velvet Underground in the mid ‘60s and was never heard from again. Starting off as “L.A. high school kids obsessed with [the band] Brian Jonestown Massacre” – a title that instantly puts the album into context – Rado and France took seven years to build on their retro-psychedelic rock sound. The result is truly aesthetically pleasing for any fans of ‘60s revivalism, and those with extensive vinyl collections can expect to hear a few of their favorite artists woven into the tapestry of “Peace & Magic.” The titular track is a white-hot psychedelic rocker, featuring barely enunciated words screamed over a series of choice Doors-approved guitar riffs. On the other side of the river, the track “San Francisco” could easily follow “Monday, Monday” by The Mamas & The Papas on any ‘60s radio station without anyone blinking an eye. Only a close look at the lyrics would suggest that this is the product of a modern indie duo. Oddly enough, the first single off the album, “Shuggie,” sounds less like a '60s throwback and more of a pastiche of past decades and styles. While not a bad song, it does stand out in an otherwise temporally-locked album. The only question left by “Peace & Magic” is where Foxygen is going to end up next – standing on the shoulders of a bygone decade can only get you so far. For now, though, listeners will find themselves more than satisfied with this hip duo’s selection of groovy rockin’ tunes. Bottom Line: The Bottom Line: Hollywood Undead has found their calling in combining rap and rock to produce a sensational and captivating sound. However, some of the tracks are overly gratuitous in their use of profanity. Despite this (or perhaps because of it), the album will please fans, but tread with caution if you have not been acquainted with this unique band. “We Are The 21st Century Ambassadors Of Peace & Magic” is a great piece of retro revivalism, and despite being a debut LP, Foxygen have got a firm handle on their decidedly old-school style. The result is less of a rehash and more of a tribute by two guys who clearly love these anachronistic sounds, and that’s a-okay with us. 23 February 4, 2013 American Horror Story vs The Walking Dead By Carlos Razo Staff Writer There will always be a special place in the heart of American entertainment for horror. It’s a difficult genre to master, many times being filled with cheap jump-scares, ridiculous buckets of blood and derivative characterizations. The genre generally tends to be looked down on as lowbrow entertainment by mainstream critics, but when done right it can be an incredibly thrilling experience. So hold your loved ones tight. Make some popcorn and go turn off the lights. FX’s “American Horror Story” and AMC’s “The Walking Dead” are two perfect examples of how to master the genre of horror. Not only do they perfectly use the medium of television to their advantage, they know exactly how to entice, entertain and most Whats the Compiled By Emily Podwoiski Arts & Entertainment Editor “Pillow Talk” If you suffer from nostalgia and an addiction to Turner Classic Movies, then this is the show for you. The Redford Theatre will be presenting “Pillow Talk”, the classic 1959 romantic comedy. The story follows Brad (Rock Hudson) and Jan (Doris Day), who get off to a rocky start when they share a telephone line. Brad continues calling her, disguising his voice in an attempt to romance her. importantly, scare their audiences. Each season of “American Horror Story” is designed to be self-contained as its own miniseries, with new characters and storylines introduced each time. Season one tells the story of a young family who moves into a luxurious new home, only to learn that the house is haunted by the ghosts of its former occupants. The series puts a strong emphasis on psychological horror, as well as urban legends, ghost stories and other familiar clichés, but not once does it become monotonous. Every episode is well contained, usually beginning with a headscratching prologue that is only cleared up at the end of the episode. “American Horror Story” is exactly as its title suggests; a self-aware and clever tribute to the American horror legacy that is both engrossing and plain freaky. “The Waking Dead” is a whole dif- This is the perfect pre-Valentine's Day date for all of those old souls out there. The showings will be Feb. 8 at 8 p.m., and Feb. 9 at 2 p.m. and 9 p.m. The Redford Theatre in Detroit is located at 17360 Lahser Road for this adorable movie. Tickets are only $4. Call the Redford Theatre at 313-537-2560 for more information. Motor City Muse: Detroit Photographs, Then and Now This is the perfect exhibition for Michiganders everywhere. Featuring over 100 stunning photographs by various photographers, this show is the story of our beloved Detroit. The exhibition will be open until June 16, Tuesdays-Sundays. Visit the Detroit Institute of Arts at 5200 Woodward Avenue to see this spectacular vision. Call the DIA at 3137900 for more information. ferent animal. After awaking from a coma, Georgia Sheriff Rick Grimes (Andrew Lincoln) finds the world he once knew in ruin, after an unknown event caused the dead to become reanimated as zombies (or as they are referred to within the series, “walkers”). The show follows Rick, his wife, his son, and a mismatched group of survivors as they move from location to location, fighting to stay alive. There is a relentless feeling of dread that permeates every episode. With shocking twists and turns filling each season, it quickly becomes apparent that no character is guaranteed to survive the season, and a slow, appetizing death could be stumbling behind any corner. The acting, especially towards the later episodes where the stakes get extremely high, is magnificent, and the cliffhangers keep you coming back for more. The plotting for each show is gripping, but there’s something deep inside “The Walking Dead” that is superior. Behind its rotten flesh and intense violence, there is a very real sense of morality that is being fought for. The characters are constantly arguing over what should be considered “right” or “wrong” in the situations they face, and even within the silly setting of the zombie outbreak, it feels very authentic. Though not for the faint of heart, both of these shows are guaranteed to satisfy both adamant gore hounds and more casual television viewers. The storylines are gripping, the performances all solid, and the scares effective and plentiful. “The Walking Dead” simply contains more thought-provoking plotlines that will give viewers something to talk about long after the lights are turned back on. The Lion King Relive your childhood and see your favorite Disney movie come to life at the Fisher Theatre at 3011 W. Grand Blvd in Detroit. This musical has received incredible reviews. “There is simply nothing else like it,” says The New York Times. The show begins Feb. 13 and will be on stage until March 10. “The Lion King” will be playing TuesdaySaturday at 7:30 p.m., and Sunday evenings at 6:30 p.m. Tickets are on sale now, starting at $30. For more information, call the Fisher Theatre at 313872-1000. Remember, Hakuna Matata is the motto. Ice Skating Rink Throw on some skates and enjoy the last of the winter festivities. The Campus Martius Park ice skating rink at 800 Woodward Ave. in downtown Detroit is open for you to enjoy. Skate rental is $3 and the rink is open Mondays and Friday-Sundays. Adult admission 13 years to 49 is $7, children 12 years and younger is $6, and seniors 50 years and older is $6. Call 313-963-9393 for more information. Valentine’s Day at MGM Grand Detroit MGM Grand Detroit at 1777 Third St. is featuring a romantic dinner for two. What better way to show that you care than with delicious food? There are two menus to choose from, one which features Wolfgang Puck Steak, available to order from 5-10 p.m. The Palette Dining Studio is serving prime rib and shrimp at 5-11 p.m. To top it off, chocolate dipped strawberries are offered as well. Impress your date this Valentine’s Day and call 877-888-2121 to make your romantic dinner reservations. 24 February 4, 2013 THE SCHOOLCRAFT CONNECTION WEDDING BAND TRUNK SHOW NORTHVILLE SATURDAY, FEBRUARY 9, 2013 GARDEN CITY SATURDAY, FEBRUARY 16, 2013 10AM-5PM CAN WE COME WITH YOU? BUFFALO WILD WINGS TASTES JUST AS GOOD AT HOME, IF YOU CAN MAKE IT THAT FAR. NO TIME TO HANG? CALL IN FOR TAKEOUT. 37651 SIX MILE RD. LIVONIA GARDEN CITY 29317 Ford Road at Middlebelt 734.422.7030 NORTHVILLE 101 East Main Street at Center 248.349.6940 734.469.4400 facebook.com/bwwlivonia 41980 FORD RD. CANTON 734.844.9464 facebook.com/bwwcanton BWJ_01475_TAKEOUT_Spring_College_Ad_Schoolcraft_4.916x7.5_BW_fnl.indd 1 1/15/13 11:26 AM 25 February 4, 2013 Burn up to 600 calories in one fun and powerfully effective 60-minute total body workout. Choreographed to today's hottest music, Jazzercise is a fusion of jazz dance, resistance training, Pilates, yoga, and kickboxing. 5 19241 Newburgh Rd. (Just north of 7 Mile) Start Today! Open 7 Days/Week 46 Classes/Week Class Start Times Range from 5:30am-8:00pm All Fitness Levels Welcome Attend as Many Classes as You Want livoniajazzercise@yahoo.com Eligibility: Must present current student ID and be 25 years old or younger. Valid at Livonia location only. Be in control with our Free Flexible Checking Have 24/7 Access to your Money. Enjoy anytime access to your money now, at school and into the future with our free checking account. • No minimum balance requirements • No monthly account fees • Free ATM/Visa® Check card to access your funds anywhere Visa is accepted • Free Mobile Banking & eStatements Call, visit our web site or stop by any office to open your account today! PLYMOUTH 500 S. HARVEY CANTON 6355 N. CANTON CENTER 47463 MICHIGAN AVE. NORTHVILLE 400 E. MAIN (877) 937-2328 NOVI 23890 NOVI ROAD Federally insured by NCUA. Equal Housing Lender. ©2012 Community Financial 26 S ports THE SCHOOLCRAFT CONNECTION February 4, 2013 Photos by Andrew Kieltyka Sophomore Guard Courtney Dyer (left) fights for possession of the ball against Macomb's Jaclyn Bieniewicz. Despite woes, Lady Ocelots remain confident By Abdallah Chirazi Sports Editor Freshman Guard Brianna Berberet stares down a Macomb Monarch's player as she ramps up the defensive pressure. The Women’s basketball team (5-13, 2-6) struggled to get anything going against tenth ranked St. Clair County Community College (17-1, 7-1) losing 89-48 on Jan 23. The Ocelots, who shot a meager 11-of-59 from the floor and committed 26 turnovers, seemed frustrated the entire night. “Obviously it’s disappointing to lose and everybody takes it really hard,” said freshman Alexis Smith. “We as a team are built to win. It’s hard facing adversity and having new girls come in and learn the game all over again (I was one of them). We just go to practice the next day and work harder because we have an end goal and that’s to make it to nationals.” Although they never seemed to find their rhythm, Courtney Dyer contributed 18 points and 13 came from freshman Toi Brown. Sophomore Ajai Meeks contribution was significant as well, grabbing a game-high 13 rebounds along with 8 points. At halftime, the Ocelots found themselves down 42-26, as the Skippers continued to effortlessly make their way through the second half. Skipper’s sophomore guard Teisha Knott led the way with 22 points and nine rebounds. They also got 14 points apiece from Sheyna Deans and Cianna Peterson. Although Schoolcraft is 2-6 in the MCCAA Eastern Conference and currently sit in eighth place in the standings, it doesn’t seem to shake their confidence. “I really hope and feel like we will start getting wins and we will go to nationals as long as we keep working hard and pushing ourselves,” said freshmen Brittany Longhini. “We talk about what we can do to improve what we did in the game. We talk about the good points and talk about what areas we need to work on in the following practices.” The coaching staff believes firmly in the strategy of taking it one game at a time. They have instilled a system where if they can improve simply on basic fundamentals and determination despite their record, they can find a way to reach their goals of reaching nationals. “It›s possible to see the playoffs,” said Head Coach Kevin Brathwaite who is in his second season. “We just need to keep improving and working on the fundamentals. Just take it one thing at a time.” Jan. 19 Macomb 54 vs. Schoolcraft 37 The Ocelots lost to No.12 Macomb 54-37 on Jan 19. The Monarchs had a strong first half shooting 43 percent from the field including five three-pointers. Sophomore Courtney Dyer led the way for Schoolcraft with nine points and five rebounds. Schoolcraft shot 26 percent from the field and 20 percent from beyond the arch. Jan. 26 Schoolcraft 41 vs. Mott 54 Schoolcraft traveled to Flint to face the Bears of Mott Community College on Jan 26. Unfortunately the Ocelots suffered another loss 52-41. The team shot 10-15 from the free throw line and kept the game within reach. Sophomore Ajai Meeks led the way for the Ocelots with 12 points and 15 rebounds. Other contributors were from Brittani Hamlin (9 points, 7 rebounds) and Brianna Berberet (13 points, 6 rebounds). 27 February 4, 2013 Play 4 Kay Admission Schoolcraft $5.00 College third reoccurrence T-shirts Alpena of breast cancer $5.00in Community All proceeds benefit College 2006. Kay WBCA lostPinkZone her long battle in 2009.* ™ ™ 5th annual Pink Zone game supports breast cancer awareness By Abdallah Chirazi Sports Editor The WBCA (Women Coaches Basketball Association) began in 2007 as an initiative to raise breast cancer awareness in women’s basketball, on campus and in communities. The late Kay Yow, former North Carolina State University head women’s coach served as the catalyst for the initiative after her third reoccurrence of breast cancer in 2006. Kay lost her long battle in 2009. Since then the WBCA has been nationwide success in raising funds for breast cancer awareness. In 2010, over 1,800 participants came together to surpass $1,045,000 in donations and reached over 922,000 across the nation. On Wednesday Feb. 13 both the Men and Women’s basketball teams will compete in a double-header against visiting Alpena Community College. The Women’s game will start at 5:30 p.m. followed by the Men at 7:30 p.m. in the Physical Education building. Admissions fee and commemorative t-shirts will be sold for $5, all the proceeds will benefit WBCA. Admission gets you in to see both games. Since 2009, Schoolcraft has participated in the WBCA Pink Zone play for Kay fun- draiser. Last year the college raised $820. “We would like to match or exceed last year’s total,” said Athletic Director Sid Fox. “We raise the funds from admissions and t-shirts. All the money goes to the WBCA.” This annual event is a win-win for both Schoolcraft and the cause. Not only to display team spirit and support our teams but there are many coaches currently battling cancer across the nation. “It’s not about the game, it’s about bringing awareness to helping cure breast cancer,” said sophomore guard Ajai Meeks. “It’s not about us but a chance to remember those who are currently experiencing such a difficult time in their life.” It’s highly encouraged that students, family and friends attend the game to watch the Ocelots in action and continue supporting a cause that has affected so many women. Take a few friends out for a night that promises fun for a good cause. The Schoolcraft men’s basketball team will be doing their part to help as well. “The team will all buy t-shirts and wear them on game night,” said coach Randy Henry. “The cause is a noble one and we need to find a cure. People need to be more aware of breast cancer and really take time to get checked out.” If you cannot make it to the game and still want to donate, please visit www. kayyow.com for more details or text ‘4KAY’ to 85944 to make a $10 donation. When we all come together everyone can make a difference in the fight for a cure. Power surge * Whalers trades add depth to roster; Wednesday team continues to win Sting in which the team fell short of a win in By Dylan Nardone February 2013 shootout the night prior13, 5-4. Staff Writer Trading places Last year during the trade deadline, the Plymouth Whalers passed on making any roster moves. This year however, roster moves were made. The trade deadline saw Plymouth lose Alex Aleardi to Windsor, Zach Bratina to Saginaw, and Simon Karlsson to Oshawa. Aleardi was traded to Windsor for Zach Lorentz. Zach Bratina was traded to Saginaw in exchange for their captain Vince Trocheck, a third round pick in 2016, and two conditional picks (Plymouth’s 2015 second round pick and Kitchener’s third round 2016 pick). Simon Karlsson was traded to Oshawa for Sebastian Uvira and a fifth round pick. Since the trade deadline, the newest additions have made an impact from the start. Especially Florida Panthers 2011 draft pick, Vince Trocheck, who has been a major contributor offensively since being acquired. He is teamed up with fellow USA World Junior teammate Ryan Hartman and has added another offensive punch to the already heavily stacked lineup. Trocheck currently leads the team in three offensive categories: most goals (29), most assists (37) and most points (66). The team has won six out of nine games since the trade acquisitions on Jan. 9. Fight for First During the month of January, Plymouth has been working well on both sides of the puck. Over the last three games, the team has outscored their opponents 18-9. On Jan 26, the Whalers put on an offensive show as they hosted the Sarnia Sting (27-18-3) at Compuware Arena. This game was a part of the home and home series against the This game was crucial for both teams in the standings. A win to either team would solidify first place in the Western Conference West Division standings. Right from the drop of the puck, the tempo was fast and hard. Sarnia stung first with a goal by Taki Pantziris, his second goal of the season at the 4:45 mark in the first period. The Whalers answered back with a power play goal by Mitchell Heard at the 12:23 with an*assist by Sebastian Uvira, tying the game 1-1. The team didn’t stop there and scored two more goals. Vincent Trocheck scored his twenty eighth goal of the season at 13:58 with assist by Colin MacDonald, making it 2-1. The team never looked back and held the lead throughout the night. Connor Carrick with an assist by Mitchell Heard scored the third goal of the game at 16:37 expanding the lead 3-1. The second period scoring started off with a bang with a quick goal by Plymouth’s Garrett Meurs only seventeen seconds into the period, his twenty third goal of the season making it 4-1. Sarnia’s Craig Duininck scored on a power play at the 2:10 mark cutting Plymouth’s lead down 4-2. Overage veteran Mitchell Heard recorded his second goal of the game at the 7:47 mark with an assist by Cody Payne making it 5-2. Just over a minute later, Vince Trocheck sealed the win for Plymouth by adding his second goal of the game, his twenty ninth of the season, making it a final score of 6-2. “We always thought [Trocheck] was one of the best players in the league, if not the best, when we traded for him,” Vellucci told the Observer and Eccentric. “We gave up a lot (forward Zach Bratina and draft picks), but he’s proven that he’s a good player.” Women Men 5:30 PM 7:30 PM Schoolcraft College Alpena Community College Admission $5.00 T-shirts $5.00 All proceeds benefi WBCA™ PinkZone™ Photos by Mandy Getschman (Above) New addition Forward Vince Trochek sweeps between two Erie players to take possession of the puck. (Left) Following the Jan. 21 matinee game against Erie, fans were treated to free ice skating with the team. 1/25/13 Plymouth (4) at Sarnia (5) SO With just a under five minutes remaining in second period, the Whalers Garrett Meurs scored on a power play tying the game 4-4 tallying his second goal of the game. With a scoreless third period and overtime, the game went to a shootout. Sarnia Sting goaltender Knicholas Dawe blocked three shots he faced. The Sting flew to a victory 5-4 in the shootout with a goal by Charles Sarault. 1/24/13 Plymouth (8) at Windsor (2) The Whalers traveled across the river to take on division rival Windsor Spitfires. The team shut down Windsor on both ends of the ice by putting on both an offensive and defensive display. The Whalers tallied three goals in the first period and five more in the second easily skating to a 8-2 victory. Whalers Vincent Trocheck and Matthew Mistele lead the game with two goals each. Cody Payne, Zach Lorentz, Garrett Meurs and Mitchell Heard each chipped in with a goal apiece. 1/21/13 Erie (1) at Plymouth (7) Plymouth played host to Erie for their traditional matinee game on Martin Luther King Jr. Day. The offense was jumping with goals by Zach Lorentz, Cody Payne, Ryan Hartman, Connor Carrick and Gianluca Curcuruto. Lorentz and Payne record two goals each while Hartman, Carrick, and Curcuruto scored goals on the Power Play. The team were 3/3 on the power play. Goaltender Matt Mahalak had recorded 24 saves in the win. 28 February 4, 2013 THE SCHOOLCRAFT CONNECTION Treat your kids to a sweet summer… Summer 2013 July 8–August 2 Class registration for fall semester opens March 18. If you have been waiting for the right time to start your bachelor’s degree, the time is now. Ferris State University offers classes at Schoolcraft College so that you can take the first step to a new you right here. Are you ready for the new year? d Camps an skills academic r o classes f rs 1st grade ool igh sch through h s senior e, cienc reer, S , t r a A ath, C ers, M , y r a ut Culin ing, Comp re! o t Wri and m n g i s De n visit ormatio oc f in l a ition du/k For add choolcraft.e 48 .s 44 w w 2 w 734-46 or call New Year, New You! o Have you met with a Ferris academic advisor to be sure you’re on track? You can now schedule your own appointment online 24/7 at our website at. o Have you checked scholarships lately? Check our website at. o Have you submitted your FAFSA? To ensure the best financial aid package, file as soon as possible after January 1. o Do you know what classes you need to take this fall? Registration for fall classes begins March 18. Visit our website to find out more about the opportunities available to you right here at Schoolcraft College. Join us for an Open House on Tuesday, February 13th in the VisTaTech Center ● Meet instructors ● Visit the campus ● See class demonstrations ● Register on-site Call our office at (586) 263-6773 to make an appointment with an academic advisor. GO WEST. A new life is out there. PEOPLE COME HERE BECAUSE THEY’RE LOOKING FOR SOMETHING. It’s all about discovery. What they find Western Michigan University. It’s your turn to GRAB THE REINS. GARDEN CITY Choose now. Your tomorrow starts today. wmich.edu/GoWest powerful—started by heading West. FERRIS STATE UNIVERSITY 29 February 4, 2013 Bitter sweet Ocelots get first divisionl win; lose to Mott in same week By Abdallah Chirazi Sports Editor Photos by Andrew Kieltyka It was only a matter of time before Randy Henry’s squad cracked the win column in the MCCAA Eastern Conference. Although it took a little longer than anticipated, the Men’s Basketball team (4-13,1-7) finally snapped out of their 9-game losing streak with a 66-61 victory over a struggling Macomb team (6-12, 8-8) on Jan. 19. Schoolcraft was able to get over a streak of setbacks by capturing their first conference win of the season. The Monarchs led in points in the paint and had more contribution from their bench but 19 second chance points doomed Macomb. Sophomore Richmond Jackson led the way for Schoolcraft posting another doubledouble, 17 points and 11 rebounds. Freshman Matthew King also chipped in with 12 points and 6 rebounds. The game featured nine lead changes and six ties. The Monarch’s largest lead was by five in the first half at the 12:31 mark. Schoolcraft’s largest lead was by seven in the second half with 11:20 left to play. After cashing in on their first conference win of the season, the Ocelots stumbled at an opportunity to take advantage of another below .500 team, losing to St. Clair County 80-73 at home on Jan. 23. Although Schoolcraft was able to win the rebounding battle (59-50) and get more contributions from their bench, they couldn’t overcome their lack of defense. The Ocelot’s gave up 56 points in the paint, exploiting their weakness of size. Sophomore Richmond Jackson continued to lead the way for Schoolcraft with 28 points and eleven rebounds. Freshman Terrance Coles pulled in a double-double with 11 points and 10 rebounds. On Jan. 26, the team traveled to Flint to face No.2 Mott Community College. Mott has continued to dominate the conference. Currently the team has an overall record of 18-1 and an 8-0 record in the MCCAA Eastern Conference. Schoolcraft would have to be disciplined both offensively and defensively in this matchup to grab a win. Right from the tipoff, Schoolcraft were no match for the Mott Bears, as they were handled 77-42. The Ocelots were tamed thanks to a strong defensive stand by the Bears. Schoolcraft was held to under 23.5 percent shooting the entire game. Mott was also dominant on the boards, outrebounding the Ocelots 56-32. “We are struggling right now because we are not shooting well,” said coach Randy Henry. “We are shooting under 30 percent we wont beat anyone shooting like that.” Sophomore Richmond Jackson finished the game for Schoolcraft with 13 points and eight rebounds while Forward Terrance Coles contributed 12 points and nine rebounds. Coach Randy Henry was visibly frustrated with his team’s effort. They allowed nearly 40 points a half and 36 points in the paint. The Bears also took advantage of Schoolcraft’s mental mistakes, scoring 30 points off turnovers. “We are a young team and we are struggling offensively,” said coach Henry. “We are averaging 20 plus turnovers a game, we can’t win like that. Every possession counts and we can have already five wins in the conference if we played like that.” Mott Sophomore Fred Mattison controlled the game offensively, scoring a game-high 19 points. In the second half Mattison scored 11 straight points and tallied 11 rebounds. “We are shooting ourselves in the foot,” said coach Henry. We are making great efforts but we are making mistakes. Guys are playing well […] but if we don’t come and play for 40 minutes we wont win. It’s all about hard work and that’s what I keep telling them.” Schoolcraft largest lead was by 1 in the first half with 18:03 left to play, they never lead again. (Top left) Sophomore forward Mathew King (3) goes up for a layup against Macomb's Patrick Ferrell. (Left) Sophomore forward Richmond Jackson drives past a Macomb player. Bowling to perfection Men's and Women's Bowling teams sweep competition By Abdallah Chirazi & Dylan Nardone Sports Editor & staff writer Let the pins fall where they may but even pin counts. Both the Men’s and Women’s Bowling teams were able to secure their 3rd straight victory by defeating Muskegon Community College on January 26th. The Men’s team placed first out of six teams at the Muskegon Invitational tallying a score of 3,958 pins. The Ocelots were just able edge out Muskegon’s 3,927 pins. Schoolcraft bowler David Nikkila had the high score for the Ocelots, bowling a 290. The Women’s team was able to outplay the Jayhawks as well. They had a 223-pin advantage, winning 3,579-3,356. Head Coach Greg Colling was very pleased with his team’s overall performance in the last couple of weeks. “Both the Men’s and Women’s teams are doing really well,” said coach Colling. They’ve practiced hard for three months and now the results are fantastic so far. It’s beautiful. Not only are they having fun playing, they are playing very well.” With three straight victories and full momentum on their side, the Ocelots are on an early pace to achieve their goals. Although they have passed all their early tests, they will know their true potential when they reach nationals in New York in early March. “There are not enough schools that compete, but so far we’ve won all three matches,” said Coach Colling. “We’ll find out when we go to Nationals in March in Buffalo, New York. Then we’ll find that’s the real test there.” Notables January 18 Schoolcraft vs. Delta Schoolcraft defeated Delta 4,050 -3,985 pins. Women Results: Schoolcraft 3,373 Muskegon 3,041 Northern Lane Pacers 2,736 Mackenzie Carlson had the high score of 250. January 12 results Schoolcraft: 3,490 Delta: 3,377 Muskegon: 3,334 Women Results: Schoolcraft defeats Muskegon 3,120-2,749. 30 THE SCHOOLCRAFT CONNECTION February 4, 2013 31 February 4, 2013 Discover all Madonna has to offer! • Semper Altius Aspice • Semper Altius Aspice • Saturday, March 16, 2013 • 8:30 a.m. – 2 p.m. Visit Day Includes: • Semper Altius Aspice • Semper Altius Aspice • Madonna • Check-In and Overview • Semper Altius Aspice • Semper Altius Aspice • •• Welcome Comprehensive campus tour program introductions • Semper Altius Aspice • Semper Altius Aspice • • Academic by deans and faculty – explore over 100 majors! • Semper Altius Aspice • Semper Altius Aspice • • Complimentary lunch • Semper Altius Aspice • Semper Altius Aspice • • Informative Break-Out Sessions To make a gift visit: Aspice • Register online at madonna.edu/visit If you need to cancel or reschedule, please call 734-432-5317 • Semper Altius Aspice • Semper Altius Aspice • or call 734.462.4455 Stay connected! • Semper Altius Aspice • Semper Altius Aspice • Receive email updates about events, news and more! • Semper Altius Aspice • Semper Altius Aspice • Text MUCONNECTION to 22828 to join Campus Connection today. Thony says thank you... You Make It Happen! One Student at a time One Gift at a time MADONNA VISIT DAY 32 THE SCHOOLCRAFT CONNECTION February 4, 2013 33 February 4, 2013 Mt. Holly Ski Trip Feb. 22, 2013 Car pool from Schoolcraft’s north parking lot at 2 pm ski and ride from 3 -11pm for $41 For more information, contact the SAO at 734-462-4422. 34 Diversions Valentoku THE SCHOOLCRAFT CONNECTION February 4, 2013 Politically Correct... Oh god! I didn’t prepare for the spring in the evening. Want to know where to find Whats the the coolest beats around town this month? Check out Page 22 Celebrity Lovescopes By Madame Mystique Staff Psychic Kimye Cleopatra and Antony Anne and Henry Brangenlina 3/21 - 4/19 6/21-7/22 9/23-10/22 12/22-1/19 Marilyn and Joe Adam and Eve Ellen and Portia Obama and Michelle 4/20 - 5/20 7/23-8/22 10/23-11/21 1/20-2/18 New love is entering your life, but it looks like an old flame is still causing you trouble. It’s time to clear up any problems with your previous affairs. Once you get over this hump, your love life will begin to blossom. Your main goal in life is to marry your best friend, but you’re having trouble sorting out who that friend may be. Stay close with all of your friends, but be patient with love. If things are meant to be, they will be. Liz and Dick 5/21-6/20 You are currently in a passionate love affair. If you are not, expect to have someone walk into your life soon. This person could even be your soulmate, but you need to start controlling your temper tantrums. A particular love affair is putting you and your lover in the spotlight. Don’t let this unwanted attention alter your feelings towards the person you like. Stay true to who you are and what you want. Everyone says that you and your partner are destined to be together, but you do not feel the same way. Follow through with your desires. And remember, if anyone warns you about eating that box of chocolates, eat them anyway. Johnny and June 8/23-9/22 Music is an important factor to you when deciding on a mate. Make sure that your boyfriend/ girlfriend is your musical equal first and foremost. Once your playlists are aligned, your hearts will be as well. You care for your partner, but lately they have been driving you crazy. Don’t lose your head. Communication is key, so sit down with your partner and open up to them. It will be a great relief. You love people who make you laugh. Humor has always been an important factor in relationships. If you aren’t laughing with the person you are dating, then it’s time to move on to someone with your sense of humor. Frida and Diego 11/22-12/21 Art is the love of your life and it seems as if you don’t have room for anyone else. Focus on your passion, but remain open to meeting new people. They may even turn out to be your next muse! Love your life and it will love you right back. You can’t seem to get away from all of the attention lately. You are big on privacy, but your friends want to know every little detail of your love life. It’s okay to open up to those you trust, but be wary of others. Difficult times are ahead and you have a ton of responsibility weighing down on your shoulders. It’s important to accomplish your goals and remember that a special someone is always there to help you along the way. Elvis and Priscilla 2/19-3/20 Glamour is your addiction. You love big hair and fancy clothes. It’s time to stop worrying about materialistic matters. Focus on connecting to those around you, and your love life will instantly improve. 35 February 4, 2013 * Schoolcraft College Alpena Community College Admission $5.00 T-shirts $5.00 All proceeds benefit WBCA™ PinkZone™ 36
https://issuu.com/schoolcraftconnection/docs/1_connection_v26_i09_020413
CC-MAIN-2017-22
refinedweb
19,422
62.68
Using SQLite.NET with Xamarin.iOS The SQLite.NET library that Xamarin recommends is a basic ORM that lets you store and retrieve objects in the local SQLite database on an iOS device. ORM stands for Object Relational Mapping – an API that lets you save and retrieve “objects” from a database without writing SQL statements. Usage To include the SQLite.NET library in a Xamarin app, add the following NuGet package to your project: - Package Name: sqlite-net-pcl - Author: Frank A. Krueger - Id: sqlite-net-pcl - Url: nuget.org/packages/sqlite-net-pcl Tip There are a number of different SQLite packages available – be sure to choose the correct one (it might not be the top result in search).. var db = new SQLiteConnection (dbPath); The dbPath variable should be determined according the rules discussed earlier in this document. iOS. The code illustrates how to perform simple SQLite.NET operations and shows the results in as text in the application’s main window. iOS This requires that you have added SQLite to your project, as highlighted here.: - )] – The nameparameter sets the underlying database column's name. - [Table(name)] – Marks the class as being able to be stored in an underlying SQLite table with the name specified. - . Most of these attributes are optional.); } Important which is in the Mono.Data.Sqlite namespace. For example, this line of code configures SQLite for Serialized mode: using Mono.Data.Sqlite; ... SqliteConnection.SetConfig(SQLiteConfig.Serialized);
https://docs.microsoft.com/en-us/xamarin/ios/data-cloud/data/using-sqlite-orm
CC-MAIN-2022-27
refinedweb
240
58.58
Question 11 : What will be the output of the program? public class ExamQuestion7 { static int j; static void methodA(int i) { boolean b; do { b = i<10 | methodB(4); /* Line 9 */ b = i<10 || methodB(8); /* Line 10 */ }while (!b); } static boolean methodB(int i) { j += i; return true; } public static void main(String[] args) { methodA(0); System.out.println( "j = " + j ); } } The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed. However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called. The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4. Question 12 : What will be the output of the program? try { Float f1 = new Float("3.0"); int x = f1.intValue(); byte b = f1.byteValue(); double d = f1.doubleValue(); System.out.println(x + b + d); } catch (NumberFormatException e) /* Line 9 */ { System.out.println("bad number"); /* Line 11 */ } The xxxValue() methods convert any numeric wrapper object's value to any primitive type. When narrowing is necessary, significant bits are dropped and the results are difficult to calculate. Question 13 : What will be the output of the program? class Q207 { public static void main(String[] args) { int i1 = 5; int i2 = 6; String s1 = "7"; System.out.println(i1 + i2 + s1); /* Line 8 */ } } This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are: If either operand is a String, the + operator concatenates the operands. If both operands are numeric, the + operator adds the operands. The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as: System.out.println( new StringBuffer() .append(new Integer(i1 + i2).toString()) .append(s1) .toString() ); Question 14 : What will be the output of the program? public class SqrtExample { public static void main(String [] args) { double value = -9.0; System.out.println( Math.sqrt(value)); } } The sqrt() method returns NaN (not a number) when it's argument is less than zero. Question 15 : What will be the output of the program? String s = "ABC"; s.toLowerCase(); s += "def"; System.out.println(s); String objects are immutable. The object s above is set to "ABC". Now ask yourself if this object is changed and if so where - remember strings are immutable. Line 2 returns a string object but does not change the originag string object s, so after line 2 s is still "ABC". So what's happening on line 3? Java will treat line 3 like the following: s = new StringBuffer().append(s).append("def").toString(); This effectively creates a new String object and stores its reference in the variable s, the old String object containing "ABC" is no longer referenced by a live thread and becomes available for garbage collection.
http://www.indiaparinam.com/java-question-answer-java-java-lang-class/finding-the-output/page2
CC-MAIN-2019-13
refinedweb
556
66.54
!Converted with LaTeX2HTML 0.6.5 (Tue Nov 15 1994) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds > Common Lisp the Language, 2nd Edition Destructuring allows you to bind a set of variables to a corresponding set of values anywhere that you can normally bind a value. Suppose you want to assign values from a list to the variables a, b, and c. You could use one for clause to bind the variable numlist to the car of the specified expression, and then you could use another for clause to bind the variables a, b, and c sequentially. ;;; Collect values by using FOR constructs. (loop for numlist in '((1 2 4.0) (5 6 8.3) (8 9 10.4)) for a integer = (first numlist) and for b integer = (second numlist) and for c float = (third numlist) collect (list c b a)) => ((4.0 2 1) (8.3 6 5) (10.4 9 8)) Destructuring makes this process easier by allowing the variables to be bound in parallel in each loop iteration. You can declare data types by using a list of type-spec arguments. If all the types are the same, you can use a shorthand destructuring syntax, as the second example following illustrates. ;;; Destructuring simplifies the process. (loop for (a b c) ) float in '((1.0 2.0 4.0) (5.0 6.0 8.3) (8.0 9.0 10.4)) collect (list c b a)) => ((4.0 2.0 1.0) (8.3 6.0 5.0) (10.4 9.0 8.0)) If you use destructuring to declare or initialize a number of groups of variables into types, you can use the loop keyword and to simplify the process further. ;;; Initialize and declare variables in parallel ;;; by using the AND construct. (loop with (a b) float = '(1.0 2.0) and (c d) integer = '(3 4) and (e f) return (list a b c d e f)) => (1.0 2.0 3 4 NIL NIL) A data type specifier for a destructuring pattern is a tree of type specifiers with the same shape as the tree of variables, with the following exceptions: ;;; Declare X and Y to be of type VECTOR and FIXNUM, respectively. (loop for (x y) of-type (vector fixnum) in my-list do ...) If nil is used in a destructuring list, no variable is provided for its place. (loop for (a nil b) = '(1 2 3) do (return (list a b))) => (1 3) Note that nonstandard)) [It is worth noting that the destructuring facility of loop predates, and differs in some details from, that of destructuring-bind, an extension that has been provided by many implementors of Common Lisp.-GLS] [Loop Clause] initially {expr}* finally [do | doing] {expr}* finally return expr The initially construct causes the specified expression to be evaluated in the loop prologue, which precedes all loop code except for initial settings specified by constructs with, for, or as. The finally construct causes the specified expression to be evaluated in the loop epilogue after normal iteration terminates. The expr argument can be any non-atomic Common Lisp form. Clauses such as return, always, never, and thereis can bypass the finally clause. The Common Lisp macro return (or the return loop construct) can be used after finally to return values from a loop. The evaluation of the return form inside the finally clause takes precedence over returning the accumulation from clauses specified by such keywords as collect, nconc, append, sum, count, maximize, and minimize; the accumulation values for these pre-empted clauses are not returned by the loop if return is used. The constructs do, initially, and finally are the only loop keywords that take an arbitrary number of (non-atomic) forms and group them as if by using an implicit progn. Examples: ;;; This example parses a simple printed string representation ;;; from BUFFER (which is itself a string) and returns the ;;; index of the closing double-quote character. (loop initially (unless (char= (char buffer 0) #\") (loop-finish)) for i fixnum from 1 below (string-length buffer) when (char= (char buffer i) #\") return i) ;;; The FINALLY clause prints the last value of I. ;;; The collected value is returned. (loop for i from 1 to 10 when (> i 5) collect i finally (print i)) `;Prints 1 line 11 => (6 7 8 9 10) ;;; Return both the count of collected numbers ;;; as well as the numbers themselves. (loop for i from 1 to 10 when (> i 5) collect i into number-list and count i into number-count finally (return (values number-count number-list))) => 5 and (6 7 8 9 10) [Loop Clause] named name The named construct allows you to assign a name to a loop construct so that you can use the Common Lisp special form return-from to exit the named loop. Only one name may be assigned per loop; the specified name becomes the name of the implicit block for the loop. If used, the named construct must be the first clause in the loop expression, coming right after the word loop. Example: ;;; Just name and return. (loop named max for i from 1 to 10 do (print i) do (return-from max 'done)) `;Prints 1 line 1 => DONE
http://www.cc.gatech.edu/~isbell/references/lisp/clm/node252.html#SECTION0030122000000000000000
crawl-003
refinedweb
874
68.5
Hello, I'm trying to use dotTrace Performance to divide execution time into a number of buckets, roughly corresponding to .NET namespaces or assemblies. I'd like a result that says; I'm not sure if this is generally possible? After a profile run, I'm looking at the Plain List view, and it's showing information that looks like it could serve as the basis, but I can't really make sense of the relation between time spent and percentages... I assumed Own Time was the time spent only in this namespace, not including outgoing calls, but the percentages don't seem to correlate with the actual times. It's a stand-alone console application, I profiled with Tracing and collected Wall time (CPU instruction). Am I misinterpreting? Can I even harvest this kind of information? Thanks, - Kim Hello Kim Here 'Own Time' is the time spent by all functions in a particular namespace performing some work (doing some math or calculations) instead of calling other functions. The percentage near own time in that column shows how much time this function spent performing some work compared to whole time spent by this function (that is (Own Time/Time)*100 %). I'm afraid at the moment there's no way to display Time and Percentage of total in Plain View. Thank you! Andrey Serebryansky Senior Support Engineer JetBrains, Inc "Develop with pleasure!" Hi Andrey, Thanks for the crisp explanation! OK, so it looks like I should be able to calculate this information, by totalling the Own Time numbers and dividing every namespace's contribution by this total. Does that sound about right? As a general reflection, it would be cool if you could expose a small API to mine the raw profiling data -- then I could script this and massage it into a form that I could use directly. Cheers, - Kim
http://devnet.jetbrains.com/thread/432286
CC-MAIN-2014-42
refinedweb
311
61.06
I am using convert (Imagemagick component, delegating to Ghostscript in background) to transform the first page of PDF files to images. convert Usually, convert -density 200 file.pdf[0] first_page.png will do the job, and it will sample the PDF file at 200 pixels per inch of paper. convert -density 200 file.pdf[0] first_page.png However it seldom happens that some PDF are abnormally huge (sometimes A0 paper, and recently a PDF with a page exceeding 23 m² (183 inch in length, 185 in width). For such files, convert will hang, eat CPU time. Images of 35000+ pixels in width and height are simply not usable. Therefore the question: is there a switch in Imagemagick that would adapt the density to the page size, or at least specify that we don't want to sample more than a portion of maximal area of the PDF file (top left corner, 30x30 inch for example)? Thanks. EDIT: On its official git repository, MuPDF has added the -w and -h switches that, jointly with -r will do what is wanted here. -w -h -r I modified mupdf's pdfdraw to support drawing in best fit mode, so I could state that the output needed to be 128x128 at most and it would fit the output in the box while maintaining the aspect ratio. Before I did that the only way was to use pdfinfo to get the page size and then do the calcuations to fit it in a box and then ask pdfdraw to draw it with that scale factor (dots per inch). Well, after that long story the process to do that is rather simple: get the page size of the page to render (in pdf terms the media box) this can be done via pdfinfo and grep and will appear in pts (points, 1/72th of an inch) or via a pdf library like pyPDF like: import pyPdf p = pyPdf.PdfFileReader(file("/home/dan/Desktop/Sieve-JFP.pdf", "rb")) x,y,w,h = p.pages[0]['/MediaBox'] for a box fit do dpi = min( A/(w/72.), B/(h/72.) ) where A is the maximum width and B is the maximum height; w and h are the width and height of the page. dpi = min( A/(w/72.), B/(h/72.) ) A B w h dpi convert -density $dpi and as requested a slightly fudged git commit diff: commit 0000000000000000000000000000000000000000 Author: Dan D. Date: Thu Jul 28 16:33:33 2011 -0400 add options to pdfdraw to limit the output's width and height note that scaling must occur before rotation diff --git a/apps/pdfdraw.c b/apps/pdfdraw.c index 0000000..1234567 100644 --- a/apps/pdfdraw.c +++ b/apps/pdfdraw.c @@ -12,8 +12,10 @@ #endif char *output = NULL; -float resolution = 72; +float resolution = -1; float rotation = 0; +float width = -1; +float height = -1; int showxml = 0; int showtext = 0; @@ -47,6 +49,8 @@ static void usage(void) "\t\tsupported formats: pgm, ppm, pam, png, pbm\n" "\t-p -\tpassword\n" "\t-r -\tresolution in dpi (default: 72)\n" + "\t-w -\tmaximum width (default: no limit)\n" + "\t-h -\tmaximum height (default: no limit)\n" "\t-A\tdisable accelerated functions\n" "\t-a\tsave alpha channel (only pam and png)\n" "\t-b -\tnumber of bits of antialiasing (0 to 8)\n" @@ -150,13 +154,39 @@ static void drawpage(pdf_xref *xref, int pagenum) if (output || showmd5 || showtime) { - float zoom; + float zoom = 1.0; fz_matrix ctm; fz_bbox bbox; fz_pixmap *pix; + float W, H; - zoom = resolution / 72; - ctm = fz_translate(0, -page->mediabox.y1); + ctm = fz_identity; + ctm = fz_concat(ctm, fz_translate(0, -page->mediabox.y1)); + ctm = fz_concat(ctm, fz_rotate(page->rotate)); + ctm = fz_concat(ctm, fz_rotate(rotation)); + bbox = fz_round_rect(fz_transform_rect(ctm, page->mediabox)); + + W = bbox.x1 - bbox.x0; + H = bbox.y1 - bbox.y0; + if (resolution != -1) + zoom = resolution / 72; + if (width != -1) + { + if (resolution != -1) + zoom = MIN(zoom, width/W); + else + zoom = width/W; + } + if (height != -1) + { + if (resolution != -1 || width != -1) + zoom = MIN(zoom, height/H); + else + zoom = height/H; + } + + ctm = fz_identity; + ctm = fz_concat(ctm, fz_translate(0, -page->mediabox.y1)); ctm = fz_concat(ctm, fz_scale(zoom, -zoom)); ctm = fz_concat(ctm, fz_rotate(page->rotate)); ctm = fz_concat(ctm, fz_rotate(rotation)); @@ -295,7 +325,7 @@ int main(int argc, char **argv) fz_error error; int c; - while ((c = fz_getopt(argc, argv, "o:p:r:R:Aab:dgmtx5")) != -1) + while ((c = fz_getopt(argc, argv, "o:p:r:R:w:h:Aab:dgmtx5")) != -1) { switch (c) { @@ -303,6 +333,8 @@ int main(int argc, char **argv) case 'p': password = fz_optarg; break; case 'r': resolution = atof(fz_optarg); break; case 'R': rotation = atof(fz_optarg); break; + case 'w': width = atof(fz_optarg); break; + case 'h': height = atof(fz_optarg); break; case 'A': accelerate = 0; break; case 'a': savealpha = 1; break; case 'b': alphabits = atoi(fz_optarg); break; @@ -321,6 +353,10 @@ int main(int argc, char **argv) if (fz_optind == argc) usage(); + if (width+height == -2) + if (resolution == -1) + resolution = 72; + if (!showtext && !showxml && !showtime && !showmd5 && !output) { printf("nothing to do\n"); ~/git.l/mupdf You are using the wrong command. Use -resample instead. It is also advisable to provide a specific width and height if possible. -resample -density is merely a flag. -resample actually changes pixel dimensions: the only measurement that matters. -density edit: doc for -resample. At a simplistic level in CG, inches do not exist. For raster images, only the pixels are stored. The dpi is merely a suggestion. Say you have 3 squares on a table, and 300 pennies. If I have a density of 300 pennies per square, there is only one square with 300 pennies in it. If I change density to 100 pps, I now have 3 squares, but still 300 pennies total (100 pennies in each square). You have not changed the number of pennies, only the manner in which you distribute the pennies across an arbitrary unit of measure. density If I resample the original to 100pps I have 1 square, and 100 pennies total. I have changed the number of pennies. resample I suspect that in cases where the page size goes up, you are dealing with something that had a high resolution such as 1200dpi line art, and by changing the density to 300 quadruples the inch measurement when you open the result with something that honors the flag. By posting your answer, you agree to the privacy policy and terms of service. asked 3 years ago viewed 1317 times active
http://superuser.com/questions/389242/pdf-raster-is-it-possible-to-adapt-the-sampling-resolution-to-the-input-page
CC-MAIN-2015-32
refinedweb
1,068
62.17
Important: Please read the Qt Code of Conduct - Deploy problem WinRT with QtQuick Controls versions 1.4 and 2.0 Hello everybody, I have a problem deploying a Qt Quick App as a WinRT version. The same App runs on Android and OS X without a problem. So this affects only WinRT. Basically I have written a small App with Qt Quick Controls 2.0, but because the calendar in Qt Quick Controls 2.0 is not finished, I used the Qt Quick Controls 1.4 Calendar. import QtQuick.Controls 1.4 as C As soon as I import both import QtQuick.Controls 1.4 and import QtQuick.Controls 2.0 in my project, I will not run on WinRT and the App hangs with the message module "QtQuick.Controls" version 1.4 is not installed I tested this on a blank project, with the same result. If I only import one QtQuick.Controls version it works, only if I import both, the app will not run and its always the 1.4 version, thats missing. So I assume, there is a problem with windeploy. Is there a way to manually add a QtQuick module to windeploy? Thanks OK, its a bug in Qt 5.7.0
https://forum.qt.io/topic/70706/deploy-problem-winrt-with-qtquick-controls-versions-1-4-and-2-0/2
CC-MAIN-2021-49
refinedweb
207
78.25
- Thread Safety and Shared Resources. Local Variables Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe. Here is an example of a thread safe local primitive variable: public void someMethod(){ long threadSafeInt = 0; threadSafeInt++; } Local. Here is an example of a thread safe local object: public void someMethod(){ LocalObject localObject = new LocalObject(); localObject.callMethod(); method2(localObject); } public void method2(LocalObject localObject){ localObject.setValue("value"); } The LocalObject instance in this example Member Variables Object member variables (fields) are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object member variables, the method is not thread safe. Here is an example of a method that is not thread safe: public class NotThreadSafe{ StringBuilder builder = new StringBuilder(); public add(String text){ this.builder.append(text); } } If two threads call the add() method simultaneously on the same NotThreadSafe instance then it leads to race conditions. For instance: NotThreadSafe sharedInstance = new NotThreadSafe(); new Thread(new MyRunnable(sharedInstance)).start(); new Thread(new MyRunnable(sharedInstance)).start(); public class MyRunnable implements Runnable{ NotThreadSafe instance = null; public MyRunnable(NotThreadSafe instance){ this.instance = instance; } public void run(){ this.instance.add("some text"); } } Notice how the two MyRunnable instances share the same NotThreadSafe instance. Therefore, when they call the add() method on the NotThreadSafe instance it leads to race condition. However, if two threads call the add() method simultaneously on different instances then it does not lead to race condition. Here is the example from before, but slightly modified: new Thread(new MyRunnable(new NotThreadSafe())).start(); new Thread(new MyRunnable(new NotThreadSafe())).start(); Now the two threads have each their own instance of NotThreadSafe so their calls to the add method doesn't interfere with each other. The code does not have race condition anymore. So, even if an object is not thread safe it can still be used in a way that doesn't lead to race condition. 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, used and disposed within the control of the same thread, and never escapes the control of this thread, the use of that resource is thread safe. Resources can be any shared resource like an object, array, file, database connection, socket etc. In Java you do not always explicitly dispose objects, so "disposed" means losing or null'ing the reference to the object. Even if the use of an object is thread safe, if that object points to a shared resource like a file or database, your application as a whole may not be thread safe. For instance, if thread 1 and thread 2 each create their own database connections, 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. For example, if both threads execute code like this: check if record X exists if not, insert record X If two threads execute this simultaneously, and the record X they are checking for happens to be the same record, there is a risk that both of the threads end up inserting it. This is how: Thread 1 checks if record X exists. Result = no Thread 2 checks if record X exists. Result = no Thread 1 inserts record X Thread 2 inserts record X This could also happen with threads operating on files or other shared resources. Therefore it is important to distinguish between whether an object controlled by a thread is the resource, or if it merely references the resource (like a database connection does).
http://tutorials.jenkov.com/java-concurrency/thread-safety.html
CC-MAIN-2016-22
refinedweb
642
61.67
Building Queries and Data Views This chapter describes source and target XML schemas, also called target schemas, as used in the Data View Builder to define queries. It also describes how XML namespaces can be used in your queries. The following topics are covered: XML schemas are used in Liquid Data to represent the hierarchical structure of various data sets and the query structure. The Data View Builder uses XML schema representations as follows: For relational databases accessed through JDBC drivers, a schema is automatically generated based on available metadata. For XML files, views, complex parameter types (CPTs), stored procedures, delimited files, or web services, you first develop and then specify the schema using the WebLogic Administration Console. Note: For the versions of the XQuery and XML specifications implemented in see Supported XQuery and XML Schema Versions In Liquid Data in the XQuery Reference Guide. The Data View Builder provides graphical representation of source schemas in a tree structure format. The visual representations can be expanded and collapsed for convenience and readability. Figure 4-1 Sample source schemas If you are building a query that depends upon more than one data source, you will use multiple source schemas (one for each data source). You can apply a keyword search to any source or target schema, as well as to functions. Simply click the Open search icon at the top of the pane and a search field will appear. Enter any valid search string (case does not matter) and if it exists in the pane the string will be highlighted. Wildcard symbols (? or *) are not allowed. However, any word or partial word will be found if it appears in the pane. For example, if you search on the string TAT the element STATE will be found it if exists in the pane. Text search is circular beginning at the currently highlighted element. In other words, if the search will be satisfied by an element above the currently highlighted line it will eventually be found if you keep clicking the Search button. In the Data View Builder you can use source schemas as many times as needed, simply by dragging an additional copy of the data source scheme into the work area. A source is said to be replicated if the source schema appears multiple times in a query. In XQuery, a source is replicated if document_name appears multiple times in the XQuery, usually appearing in two different for clauses. Similarly, in SQL a source is said to be replicated if the source (table) appears twice in a FROM clause (or in two different FROM clauses). Source replication is necessary whenever you want to use a data source in a way that will require iterating over the source twice. Another way to state this is when two different tuples from a source will be required at the same time. Sometimes it is helpful to use more than one copy of a data source schema to improve query performance. In other cases, however, having more than one copy of a data source schema is necessary. Take, for example, a very simple problem: you want to build a target schema that lists product list prices over a certain amount and under a certain amount. XQuery functions exist for the greater-than [ gt] and less-than-or-equal-to [ le] test conditions. Using Advanced view you could disable where clause conditions to make the query valid (see Sorting Query Results). But a clearer and cleaner approach would be to use two source instances that each reference the same data source. From the first instance of the source schema, PB-BB, PRODUCTS would be projected under Expensive products. From the second instance, PB-BB2, PRODUCTS would be projected under Cheap products (Figure 5-34). In both cases, Copy and Paste and Map are used. (See Mapping to Target Schemas for more information on mapping of complex elements to target schemas.) Figure 4-2 Project Illustrating Use of Two Copies of a Data Source Schema Then it is a simple matter of creating the [ ge]/[ lt] conditions as described in To resolve this problem click Advanced view in the Conditions section. You will notice that instead of the two conditions you created, four are listed. This is because Advanced view shows you the actual where clause conditions used in the query, based on application of the Data View Builder best-guess autoscope rules.. The XQuery generated by this project (Listing 4-1) illustrates this approach. Listing 4-1 XQuery returning product list prices in two groups <results> <expensive_products> { for $PB_BB.PRODUCTS_15 in document("PB-BB")/db/PRODUCTS where ($PB_BB.PRODUCTS_15/LIST_PRICE gt 100) return $PB_BB.PRODUCTS_15 } </expensive_products> <cheap_products> { for $PB_BB2.PRODUCTS_21 in document("PB-BB")/db/PRODUCTS where ($PB_BB2.PRODUCTS_21/LIST_PRICE le 100) return $PB_BB2.PRODUCTS_21 } </cheap_products> </results> In the above query PRODUCTS with list prices greater than or equal to [ gt] 100 are returned for the PB_BB data source. Similarly, PRODUCTS with list prices less than 100 are returned for the PB_BB2 data source. Of course the underlying data source is the same. Another example of necessary source replication would be a self-join in SQL. In the classic example of a self-join, the query retrieves all employee names that match a particular manager ID. SELECT emp.name, mgr.name FROM employee emp, employee mgr WHERE emp.manager_id = mgr.id In XQuery, the query would appear similar to that in Listing 4-2. Listing 4-2 Query retrieves records where employee manager ID field matches a particular manager ID <employee_managers> { for $emp in document("employee")//employee for $mgr in document("employee")//employee where $emp.manager_id eq $mgr.id return <employee_manager> <employee> {$emp.name} </employee> <manager> {$mgr.name} </manager> </employee_manager> } </employee_managers> In both of these examples, given the sources, there is no way to write these queries without replicating the source schemas. In ambiguous cases, both replicating and not replicating a source would lead to reasonable queries. For example, a self-join to get employee-manager pairs was shown in a previous example. Without replicating the source, you could: Of course, the Data View Builder would interpret this query as: "give me all employees who are their own manager". Under such circumstances the option of creating multiple copies of a source schema reduces possible confusion or confusing results. A target schema describes the structure of a query result that will be produced when the query runs. As with source schemas, the Data View Builder provides a graphical representation of target schemas in a tree structure format. Figure 4-3 Sample Target Schema Target schemas have these main purposes: You can specify a target schema in the Data View Builder in the following ways: To open and set a target schema for a project: This brings up a file browser. Figure 4-4 Liquid Data Repository Highlighted in File Browser If you choose Repository in the Open dialog, the Data View Builder displays target schemas in the Liquid Data repository. Figure 4-5 Schema File Selected The target schema is displayed and docked on the right side of the Design tab work area. (You can also choose the menu item File —> Set Selected Source Schema as Target Schema to create a target schema that is, at least initially, based exactly on a source schema.) Use these guidelines when working with target schemas: customerand orders. All examples in Building Queries demonstrate this guideline. Use this setting when possible to avoid unnecessary data checking and the associated performance hit. Use this especially if you know that the underlying data sources enforce referential integrity between parent-child items. Of the several examples included in this section the following particularly demonstrate these guidelines: Customertable contains phoneelements and each of those elements is required in the target schema, then you need to map each element of your query before saving it. For a detailed description of target schemas, see Schemas and Namespaces in Liquid Data. Target schemas are composed of complex elements, simple elements (child elements), and attributes. You can set element properties using the Properties dialog box, which you access by right-clicking on the element. Figure 4-6 Properties Dialog The following properties can be set: When you save a project, the schema definitions of all source and target schemas that you mapped in the project are saved. When you reopen the project, Data View Builder first looks for the schema definitions in the Liquid Data repository. If a schema definition is unavailable, the schema definition saved in the project file is used. Data View Builder adds the schema to the list of available resources, but flags it as offline by putting a red mark over the schema name. A warning is also generated in the WebLogic Administration Console log that queries using this schema will not run. Offline resources are available only to the previously associated project. If a schema file has an import statement with a relative path to another schema file, Liquid Data resolves the location of the imported files according to the following rules: <ldrepository>/schemasdirectory, attempt to resolve it relative to the directory in which the schema file (the first one with the import statement) is saved. ldrepository>/schemasdirectory. In the case of the Liquid Data Server Samples repository, the first attempt to resolve the search will be in the following directory: <WL_HOME>/samples/domain/liquiddata/ ldrepository/schemas and then from the location relative to the original schema file (the first one with the import statement). For example, if you have a schema file in the following location in the repository: <ldrepository>/schemas/dir1/dir2/s.xsd and it contains the following import statement: import dir3/file.xsd then Liquid Data first looks for a schema file named: <ldrepository>/schemas/dir3/file.xsd and, if it does not find it relative to the root level of the repository, Liquid Data looks for it in: <ldrepository>/schemas/dir1/dir2/dir3/file.xsd As a further example, assume the file.xsd import was resolved in: <ldrepository>/schemas/dir3/file.xsd If file.xsd in turn has the following import statement: import dir4/another.xsd then Liquid Data first attempts to resolve this import statement relative to the root of the repository: <ldrepository>/schemas/dir4/another.xsd If the file is not there, it then resolves it relative to the original <ldrepository>/schemas/dir1/dir2/s.xsd file, as follows: <ldrepository>/schemas/dir1/dir2/dir4/another.xsd XML namespaces are a mechanism by which you can ensure that there are no name conflicts (or ambiguity) when combining XML documents or referencing an XML element. Liquid Data supports XML namespaces and includes namespaces in the queries generated in Data View Builder. This section includes the following topics: XML namespaces appear in queries as a string followed by a colon. For example, the xs:integer data type uses the XML namespace xs. Actually, xs is an alias (called a prefix) for the URI name of the namespace. (See Table 4-7 for the full set of predefined XQuery namespaces.) XML namespaces ensure that names do not collide when combining data from heterogeneous XML documents. For example, there could be an element <tires> in a document related to automobile manufacturers. In a document related to bicycle tire manufacturers, there is also a <tires> element. Obviously, combining these elements would be problematic under most circumstances. XML namespaces easily avoid such name collisions by referring to the elements as <automobile:tires> and <bicycle:tires>. In a XML schema namespaces — including the target namespace — are declared in the schema tag. Here is an example: <schema xmlns="" xmlns:bea="" targetnamespace="" ... The first line of the above schema contains the default namespace, which is the namespace of all the unqualified elements in the schema. For example, if you see the following element in a schema document: <element name= "appliance "type= "string "/> the element element, and the attribute name and type all belong to the default namespace, as do unprefixed types such as string. The second line of the schema contains a namespace declaration — bea — which is simply an association of a URI with a prefix. There can be any number of such declarations in a schema. Lastly, comes the target namespace, declared with the targetNamespace attribute. It this case, the target namespace is bound to the namespace declared on the second line, meaning that all element and attribute names declared in this document belong to: References to types declared in this schema document must be prefixed. For example: <complexType name="AddressType"> <sequence> <element name="street_address" type="string"/> ... </sequence> </complexType> <element name="address" type="bea:AddressType"/> The following table shows predefined namespaces used in XQuery: The following are some Internet links where you can find more information on XML namespaces: See also Supported XQuery and XML Schema Versions In Liquid Data in the XQuery Reference Guide. The Data View Builder automatically generates the correct namespace declarations when generating a query. However, when a target schema is created in the Data View Builder, its elements and attributes are unqualified, meaning that the target namespace is not automatically part of the element or attribute name. Figure 4-8 Example of a schema with unqualified attributes and elements If you want elements and attributes appear as qualified, you need to use an editor outside Data View Builder to modify the generated schema for either or both attributeFormDefault and elementFormDefault to be set to qualified. See Listing 4-3. Listing 4-3 Schema Tag Setting Elements and Attributes to Qualified (emphasis added) <xsd:schema Once attributes and elements have been set to qualified, they will appear as such in the Data View Builder when the target schema is set to your newly edited file. Figure 4-9 Example of a schema with qualified attributes and elements Note: If you are hand-coding your queries (not using the Data View Builder as a query generator), you must include the necessary namespace declaration(s) to satisfy Liquid Data server requirements. For a list of data sources that require namespace declarations, see Data Sources that Require Namespace Declarations on page 4-18. The beginning portion of an XQuery is known as the prolog. For Liquid Data queries, the namespace declarations appear in the XQuery prolog. There can be zero or more namespace declarations in a query prolog. Each namespace has the following form: namespace <logical_name> = "<URI>" where <logical_name> is a string used as a prefix in the query and <URI> is a uniform resource indicator. Consider the following simple query: namespace view = "urn:views" <CustomerOrderID> { for $view:MY_VIEW.order_2 in view:MY_VIEW()/results/result/BroadBand/order return <ORDER_ID>{ xf:data($view:MY_VIEW.order_2/ORDER_ID) } </ORDER_ID> } </CustomerOrderID> namespace view = "urn:views" is the namespace declaration in this query. Each time the object (in this case, MY_VIEW) is referenced in the query, the object name is prefixed with the logical name view. You must define namespaces in the XQuery prolog in order to use them in a query (except for the predefined namespaces described in Predefined Namespaces in XQuery on page 4-15). If you do not define namespaces in the XQuery prolog, the query will fail with a compilation error. When you use the Data View Builder to create or modify target schemas, you can specify a namespace for an element or an attribute. Such a specified namespace is added to the XML markup in the query (and therefore to the query results). You can set or change a target namespace using the Target Namespace menu option, available from the Data View Builder Query menu when in Design mode. Figure 4-10 Target Namespace Dialog Box Figure 4-11 shows adding a local name called db to an element of the target schema named crm2 from the Properties dialog box. If multiple namespaces are available, you can select one from the drop-down list box. You can access the Properties dialog box by right-clicking on an element in your target schema. Figure 4-11 Properties Dialog Box The query results for this target schema definition are of a form similar to: <crm2:db xmlns: 100.0 </crm2:db> All data sources except relational databases and XML files require the namespace declaration in the XQuery prolog. Thus the following data sources require namespace declarations in the XQuery prolog: Liquid Data 1.0 did not support XML namespaces, and any queries used in Liquid Data 1.0 must be migrated to work in Liquid Data 8.1. If you have queries that are generated in a Data View Builder project file, you can open the project file in Data View Builder 8.1. When you click the Test tab, the Data View Builder automatically generates the new query with the proper namespace declarations in the query prolog. If you have stored queries and data views, you must use the queryMigrate tool to migrate the queries so they work properly in Liquid Data 8.1. For information on the queryMigrate tool, see Migrating from Liquid Data 1.0 to 8.1 in the Liquid Data Migration Guide.
http://docs.oracle.com/cd/E13190_01/liquiddata/docs81/querybld/schema.html
CC-MAIN-2016-44
refinedweb
2,840
52.9
it must just be me or something, i desperatly wanna learn, but i dont understand what what does to the computer to make it do certain things. like: #include <iostream.h> what is it and what does it do? #int main() what the wha.....??? { <-------why is that there cout<<(char)65; <-----why is the semi-colon at the end ya see, i dont understand how this relates to do, i geuss, simple windows operations. i desperatly want to learn so bad. ive read the tutorial on this site, ive read threads. i dont understand. if anybody can help me please..... -Desperatly I. Wantingtolearn
http://cboard.cprogramming.com/cplusplus-programming/13470-excuse-me-i-need-serious-help.html
CC-MAIN-2015-11
refinedweb
103
85.69
maybe someone has an idea to my following problem: I am currently on a project, where i want to use the AWS SQS with Spring Cloud integration. For the receiver part i want to provide a API, where a user can register a "message handler" on a queue, which is an interface and will contain the user's business logic, e.g. MyAwsSqsReceiver receiver = new MyAwsSqsReceiver(); receiver.register("a-queue-name", new MessageHandler(){ @Override public void handle(String message){ //... business logic for the received message } }); I found examples, e.g. and read the docu But the only thing i found there to "connect" a functionality for processing a incoming message is a annotation on a method, e.g. @SqsListener or @MessageMapping. These annotations are fixed to a certain queue-name, though. So now i am at a loss, how to dynamically "connect" my provided "MessageHandler" (from my API) to the incoming message for the specified queuename. In the Config the example there is a SimpleMessageListenerContainer, which gets a QueueMessageHandler set, but this QueueMessageHandler does not seem to be the right place to set my handler or to override its methods and provide my own subclass of QueueMessageHandler. I already did something like this with the Spring Amqp integration and RabbitMq and thought, that it would be also similar here with AWS SQS. Does anyone have an idea, how to accomplish this? thx + bye, Ximon EDIT: I found, that Spring JMS could actually do that, e.g.. Does anybody know, what consequences using JMS protocol has here, good or bad? When we do Spring and SQS we use the spring-cloud-starter-aws-messaging. Then just create a Listener class @Component public class MyListener { @SQSListener(value="myqueue") public void listen(MyMessageType message) { //process the message } }
http://www.dlxedu.com/askdetail/3/40184341e87118a975785ddb5428f7a5.html
CC-MAIN-2018-22
refinedweb
294
53.92
Hide Forgot +++ This bug was initially created as a clone of Bug #1854379 +++ OKD promotion jobs are tracking `testing-devel` stream, which regularly gets fresh kernels. Recently a single storage test related to NFS has started failing - see Latest test pass was on on Jul 02 using image. pkg diff - It appears its most likely related to kernel 5.7.7 update - see --- Additional comment from Jan Safranek on 2020-07-13 14:42:19 UTC --- Reproduced with kernel 5.7.8-200.fc32.x86_64. Reformatted for readability. E0713 14:30:19.540124 5301 nestedpendingoperations.go:301] Operation for "{volumName:15bc6521-d0be-459b-8e1b-37e307510db9 nodeName :}" failed. No retries permitted until 2020-07-13 14:32:21.54008141 +0000 UTC m=+944.066210092 (durationBeforeRetry 2m2s). Error: "error cleaning subPath mounts for volume \"test-volume\" (Uniqu \"15bc6521-d0be-459b-8e1b-37e307510db9\" (UID: \"15bc6521-d0be-459b-8e1b-37e307510db9\") : error processing : error cleaning subpath mount : unmount failed: exit status 16 Unmounting arguments: Output: umount.nfs4: : Stale file handle Brief summary of the test: 1. create a pod with a NFS volume, with 2 containers: - The first uses subdirectory of the PV as subpath - The seconds uses the whole volume 2. Exec into the second container and remove the subpath directory. 3. Delete the pod. --- Additional comment from Jan Safranek on 2020-07-17 10:41:01 UTC --- Starting with 5.7.x, kernel does not allow users to unmount NFS mounts with "Stale file handle" I tested with 5.7.4-200.fc32.x86_64, the first 5.7.x kernel in Fedora 32. Steps to reproduce (basically, get "Stale file handle" error on bind-mounted nfs dir): 1. Use this dummy /etc/exports: /var/tmp 127.0.0.1(rw,sync,all_squash,anonuid=1000) 2. Mount it to /mnt/test: $ mkdir /mnt/test $ mount localhost:/var/tmp /mnt/test 3. Bind-mount a subdirectory of it to /mnt/test2: $ mkdir /mnt/test/reproduce $ mkdir /mnt/test2 $ mount --bind /mnt/test/reproduce /mnt/test2 4. Remove the bind-mounted dir $ rmdir /mnt/test/reproduce 5. Check that /mnt/test2 is not happy about that $ ls /mnt/test2 ls: cannot access '/mnt/test2': Stale file handle This is expected. 6. Try to unmount /mnt/test2 $ umount /mnt/test2 umount.nfs4: /mnt/test2: Stale file handle This is not expected! There is no way how to unmount the directory. It's mounted forever. Even reboot gets stuck. With kernel-core-5.6.19-300.fc32.x86_64 (the last 5.6.x in Fedora 32), step 6. succeeds. --- Additional comment from Vadim Rutkovsky on 2020-07-23 07:37:29 UTC --- Steve, could you have a look? Reproducible in latest 5.7.x kernel in F32 --- Additional comment from Vadim Rutkovsky on 2020-08-20 07:48:56 UTC --- No longer happening in 5.7.15-200.fc32.x86_64 --- Additional comment from Vadim Rutkovsky on 2020-09-23 13:53:51 UTC --- I was wrong - the test didn't pass, instead it was skipped. The issue still occurs on 5.8.10-200.fc32.x86_64 --- Additional comment from Colin Walters on 2020-09-23 14:20:11 UTC --- Probably the best way to get traction on this is to bisect it and report to the linux-nfs@ email list: Speaking with a very broad brush, Fedora kernel BZs are mostly triaged to upstream bugs and that's the best way to address them. --- Additional comment from Colin Walters on 2020-09-23 14:30:56 UTC --- Looking at changes and code, at a vague guess this may be related to Specifically ``` if (ctx->clone_data.sb) { if (d_inode(fc->root)->i_fop != &nfs_dir_operations) { error = -ESTALE; ``` has the right appearance for this problem at least. --- Additional comment from Vadim Rutkovsky on 2020-10-09 15:29:57 UTC --- Still occurs on 5.8.10-200.fc32.x86_64 (same test failing in) --- Additional comment from Vadim Rutkovsky on 2020-11-12 15:57:22 UTC --- kernel-5.9.8-200.fc33 from updates-testing is also affected *** Bug 1912720 has been marked as a duplicate of this bug. *** *** Bug 1912906 has been marked as a duplicate of this bug. *** The "fix" was to disable the faulty test in CI. Jan, I see the pr disable this case: " I can still find it: There are two issues: 1. This test was disabled; > " the search linked in the previous comment looks for "Testpattern: Inline-volume (default fs)". This is a different tests. It is skipped too, but later in the process - the test goes through common test initialization (i.e. a namespace is created, nr. of Ready nodes is checked) and then it discovers it's a NFS test and NFS supports dynamic provisioning and skips itself (so the feature is tested only once and not for every pre-provisioned/inline/dynamic PV combination to save time). What you see in the search are errors from the test initialization itself, usually because the whole cluster is not really working ("connection refused" from API server, "timeout" and similar errors). This is not related to NFS nor storage in any way. 2. Searching for the disabled test "[Driver: nfs] [Testpattern: Dynamic PV (default fs)]" in past 7 days in "4.7" or "master", I can see it failed only once in a job that's called "periodic-ci-openshift-release-master-ocp-4.6-e2e-vsphere", The job name contains both "master" and "4.6", which is quite confusing, but the sources says it's 4.6: Sorry for the bad query, I had a wrong copy and paste. I checked there is no 4.7 ci running this case. Mark.
https://bugzilla.redhat.com/show_bug.cgi?id=1900239
CC-MAIN-2021-10
refinedweb
936
67.25
. I completely agree with you, but from my personal experience, this would happen on edge cases and those wouldn’t be debuggable without a massive quantity of logs.. Peter one way to balance is to use AOP (Aspect Oriented Programming) like possibly using PostSharp for .net applications. That way you don’t see the logging code though its instrumented into your code at compile time thought it might limit the customization you can make to the logging code per function. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1855 out of curiosity do you always have logging on in production scenarios or do you just turn logging on when a user has an issue and tell them to try whatever they were doing to break the code again or do you maybe go further and log by default in low verbosity and increase verbosity of the issues you have get hard to figure out? Of course you always have balance things with logging. Log to much and it might be like trying to find a needle in a haystack and could affect performance if your are logging to much We always have basic logging on, for things like system health, changes to configuration, some general statistics etc. If a certain subscriber has a problem, we can turn on tracing (very detailed logging) on just that subscriber. This can remain active for a long time, since there usually aren’t that many text messages from any one subscriber. I have yet to see a language or platform that actually helps you with logging. The best you can get during a crash (and only for more advanced platforms) is a stack trace with only the function names, if you get even that. What about the parameters those functions were called with? What about all the local variables on the stack? What about code that hooked and event handler function to be called at a later time, it would certainly be helpful to know who hooked this function and why? (Swift has this, but only during debug sessions.) You can manually log all of those, but this is awfully lot of work. A solution that is rooted in the platform/runtime would have been much more appropriate. And most of all, it has to work in production environments, not just in the walled garden of the developer’s IDE Good points. One thing to consider though: developers don’t always have access to production systems. There are reasons for this – both good and bad – but it can be a hinder. Your article pretty much describes what I practice, but I know of circumstances where logging is either not possible, or not meaningful, or worse yet where logging affects how a program performs. Logging does not work well in multi-threaded or asynchronous programs. Messages sent to the log file can be stepped on by other messages sent at the same time. If you use locking to prevent this, then where and when you log can affect the behavior of the program. Another problem is that logging usually buffers the latest messages in memory, and if the program crashes for some reason, the log messages that would tell you what happened, will disappear with the crash and never make it to the log file. The flip side of this is that forcing the logging to flush to the log file for each message will really slow down your program’s performance. Multi-level logging (suppressing log messages according to a configuration variable) can also slow down the performance of the program because writing to the log file is slow compared to networking or inter-process communications. The more verbose the logging level, the more likely that logging will affect the sequence of critical events which might even suppress or rearrange the sequence of events leading to the failure. In conclusion, logging is a good idea, but it must be carefully applied. Sometimes, the only way to debug a high-performance program is with a debugger. Great Programmers Don’t Publish Codes With Debugs It is important to know that programming is an ART, and a means to the end, not the end in itself. These days, anybody can become a programmer despite not having any particular profession. Let me put it this way. All professionals, medicine, sales, engineering, law, restaurant, hotels, sanitation, etc, use the mathematical calculator. But the aspect of the calculator each profession uses differ, but is still the mathematical calculator. It makes their processes go faster. So also is software programs from programmers. A programmer that uses the top-down technique and understands the logics/principles of the profession his/her program will be used have no need for bugs. The first appearance of a bug-ridden software program was the Microsoft DOS 4.0. It is really a pity that this has given rise to a systematic way of wasting resources. No Big Deal. The money-bags pay. It is one thing to design out a software program. It is a different thing to entirely to repair the software program when bugged with flaws. When the software program is still on the design desk of the original coder, then flaws are not bugs, but are simply dirty laundry the coder has decided to spread in the public. @Gbenka Odukale: What you wrote is exactly, completely correct: programming is most definitely an art, and it is most definitely possible to design and to write something which SHOULD be perfect. The idea is very beautiful. However, (and unfortunately) our software does not operate in a vacuum: you are, when you implement a system, at the mercy of the compiler, the operating system and, most importantly, of the other systems with which your software interacts, to end up with a perfect system. Most of the time, you won’t… and for those eventualities, your program must still provide some form of logging…. to tell you when the OTHER systems fail! It’s a shame… but there it is! @Dan Sutton: <<>> You are exactly right with the above and logging is very essential if only one can get a perfect logging system. A perfect software program only exists on the PC where development and deployment started. On such PCs, only software that are necessary to development and deployment exist. So in view of the above events you stated, the software program cannot be considered to be having bugs since there are over one billion of hard/soft devices out there. But while still on the developer PC, compiler, OS and other devices on that PC are all parameters that must be right and part of the the requirements the developer must take care of, otherwise the software programs will never get to the packaging stage. This is in respect of the practice that: software package is best tested on other PCs not related to the developer PC. So, we will just need to keep on logging new issues as the software package runs into new waters. All new developers should learn this: as a minimum the following should be logged: 1. Function entry points and their parameters. 2. Function exit points and returned values. 3. When a variable is initialized. 4. When a variable changes. This is usually enough to track problems through an application. Integration testing and UAT (not unit testing) inform on the more critical or problematic parts of the system that would require even more detailed logging. Hi Henrick, Great tips on writing a tester friendly debuggable code.Very developer should read and follow it. Logging is one case where the code becomes friendlier to debug. I can think of another way to make code more friendly to debugging. I attach it to the moniker of Clean Code, although if you look through Martin’s iconic book Clean Code I don’t think you will find it explicitly stated. Certainly it is implied. Tom Peter’s The Zen of Python you find among others: explicit is better than implicit, simple is better than complex, flat is better than nested, sparse is better than dense, readability counts. All of these mantras will make your code easier to debug. Consider these two cases that one can find misused often enough, although maybe not this this badly written. def func(k, x): return list(map(lambda y: round(10**(sum(list(map(lambda x: log(1.0 * x, 10), t)))-y)), list(map(lambda x: log(1.0 * x, 10), t)))) The log tells you that there was an error at the return statement in this function: how in the world is a developer suppose to debug that! The first thing they will probably do is modify it to something more manageable: def func(k, x): s_log_lst = list(map(lambda x: log(1.0 * x, 10), t)) u = map(lambda y: round(10**(sum(s_log_lst)-y)), s_log_lst) return list(u) Okay, that is better, but why not write it that way in the first place. Clean code allows around 5-10 lines per function. Here the developer tried to pack everything on one line (sparse is better than dense). They left 4 lines blank so obfuscate the result.
https://henrikwarne.com/2013/05/05/great-programmers-write-debuggable-code/
CC-MAIN-2022-05
refinedweb
1,535
61.36
Using Blender’s filebrowser with Python Every now and then an addon requires that the user selects a specific file or path. Sure, you could just give users a simple string input and let them copy/paste into it but how much cooler would it be to let them pick a file from the filebrowser? Luckily Blender provides a handy class that does almost everything for us. Meet ImportHelper Importhelper is a mix-in class found in the bpy_extras submodule. It includes an invoke() function that calls the filebrowser and a few helper functions used in Blender’s importer addons. To use it all we have to do is extend it in our operator. Let’s start by importing both ImportHelper and Operator. from bpy_extras.io_utils import ImportHelper from bpy.types import Operator Now we can go ahead and create the operator: class OT_TestOpenFilebrowser(Operator, ImportHelper): bl_idname = "test.open_filebrowser" bl_label = "Open the file browser (yay)" def execute(self, context): """Do something with the selected file(s).""" return {'FINISHED'} Yup, that’s it. Our new operator already has an invoke() function that calls the filebrowser and when a user selects a file, it stores the file’s path in self.filepath. Note that this is a regular StringProperty inside ImportHelper that we inherited when we subclassed it. To filter the types of files shown to the user we have to add a filter_glob property to our class. This is a StringProperty with the list of extensions we want to show. Each extension is written in wildcard style and is separated by a semi-colon. Note that strings longer that 255 could be cut (since that’s the internal buffer size). filter_glob = StringProperty( default='*.jpg;*.jpeg;*.png;*.tif;*.tiff;*.bmp', options={'HIDDEN'} ) Also keep in mind that users can disable filtering in the UI and select any kind of file. You might want to reject a file or do something different depending on the extension you receive. You can take care of that with good old splitext(). filename, extension = os.path.splitext(self.filepath) And what about adding settings to the filebrowser screen? All you have to do is add properties to the operator as usual and they will show up in the browser. some_boolean = BoolProperty( name='Do a thing', description='Do a thing with the file you\'ve selected', default=True, ) Final code import bpy import os from bpy.props import StringProperty, BoolProperty from bpy_extras.io_utils import ImportHelper from bpy.types import Operator class OT_TestOpenFilebrowser(Operator, ImportHelper): bl_idname = "test.open_filebrowser" bl_label = "Open the file browser (yay)" filter_glob = StringProperty( default='*.jpg;*.jpeg;*.png;*.tif;*.tiff;*.bmp', options={'HIDDEN'} ) some_boolean = BoolProperty( name='Do a thing', description='Do a thing with the file you\'ve selected', default=True, ) def execute(self, context): """Do something with the selected file(s).""" filename, extension = os.path.splitext(self.filepath) print('Selected file:', self.filepath) print('File name:', filename) print('File extension:', extension) print('Some Boolean:', self.some_boolean) return {'FINISHED'} def register(): bpy.utils.register_class(OT_TestOpenFilebrowser) def unregister(): bpy.utils.unregister_class(OT_TestOpenFilebrowser) if __name__ == "__main__": register() # test call bpy.ops.test.open_filebrowser('INVOKE_DEFAULT') There’s also an ExportHelper class that includes some utilities to check for existing files and setting a default untitled filename in the browser. Did I miss something? Let me know in the comments!
http://sinestesia.co/blog/tutorials/using-blenders-filebrowser-with-python/
CC-MAIN-2018-39
refinedweb
549
50.53
Python allows you to go beyond static visualisations with interactive graphics that allow you to present more information and get more engagement from your audience. Modules such as plotly and bokeh are the most accessible ways to create these and this article will introduce plotly scatter plots. Specifcally, this article runs through creating plotly scatter plots if you are working with Python in Jupyter Notebooks. Check out the docs if you are looking to apply these elsewhere. However, the demo in this article will be more than enough to get you up and running with creating an interactive scatter plot that will get end-users engaged with your data! Before we import plotly, let’s open up our dataset and see what we’re playing with. import numpy as np import pandas as pd data = pd.read_csv("FantasyFootball.csv") data.head() Our dataset is a fantasy football dataset, with each player represented by a row. The row contains some biographical data, and per 90 performance data for goals, assists and points. Learn more about per 90 data in football here. Now that we have met our data, let’s import the libraries needed to make our interactive visualisation. Check out the imports below, with comments explaining what each does #Imports the tools needed to run plotly offline - usually plotly interacts with an online resource. #These imports allow us to host everything from our computer from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import cufflinks as cf #Allows us to plot our interactive charts in our Jupyter Notebook init_notebook_mode(connected=True) cf.go_offline() All of these modules allow us to make plotting interactive charts very easy. To start with, we simply run the ‘.iplot()’ method from our dataframe. We then pass it a range of arguments to show exactly what we want: - Kind: The type of chart that we want. This time, we’ll use scatter, but there are many to choose from, such as histograms or line charts. - X & Y: The axes around which we will plot our data. Below, we’ll use points per 90 and cost. - Mode: Our type of scatter plot – we’ll use markers here to plot our data. - Text: What text should we show when we hover over a point? - Size: How big are our markers? - xTitle/yTitle/title: Axis and chart titles. There are many other things that we could do, such as change fonts and colours, but for a first attempt, let’s see how this looks: data.iplot(kind='scatter',x='ga_p90',y='now_cost', mode='markers',text='web_name',size=10, xTitle='Points per 90',yTitle='Cost',title='Cost vs Points p90') Summary I think that is pretty cool! We are showing the relationship and distribution – cost tends to go up as points per90 go up. We are also showing some potential value in players that overperform their price. Most impressively, however, users can hover over the chart to get the names of players and more information. This should attract buy-in to our graphics and inform better (& more neatly) than we could with static labels. Great job! The offline version of plotly is much simpler than the full version, so take this as an introduction. If you are looking to learn more about interactive visualisation, take a read of the examples and docs at plotly and bokeh.
https://fcpython.com/tag/fantasy-football
CC-MAIN-2018-51
refinedweb
555
64
Exploratory Data Analysis (EDA) is used to explore different aspects of the data we are working on. EDA should be performed in order to find the patterns, visual insights, etc. that the data set is having, before creating a model or predicting something through the dataset. EDA is a general approach of identifying characteristics of the data we are working on by visualizing the dataset. EDA is performed to visualize what data is telling us before implementing any formal modelling or creating a hypothesis testing model. Analyzing a dataset is a hectic task and takes a lot of time, according to a study EDA takes around 30% effort of the project but it cannot be eliminated. Python provides certain open-source modules that can automate the whole process of EDA and save a lot of time. Some of these popular modules that we are going to explore are:- REGISTER FOR OUR UPCOMING ML WORKSHOP - Pandas Profiling - Sweetviz - Autoviz Using these above modules, we will be covering the following EDA aspects in this article:- - Creating Detailed EDA Reports - Creating reports for comparing 2 Datasets - Visualizing the dataset. 1. Pandas Profiling Pandas Profiling is a python library that not only automates the EDA process but also creates a detailed EDA report in just a few lines of code. Pandas Profiling can be used easily for large datasets as it is blazingly fast and creates reports in a few seconds. Here we will work on a dataset that contains the Car Design Data and can be downloaded from Kaggle. This data contains around 205 rows and 26 Columns. Analyzing it manually will take a lot of time. Let us see how we can Analyze this data using pandas-profiling. Implementation In order to use pandas profiling, we first need to install it by using pip install pandas-profiling We will start by importing important libraries we will be using and the data we will be working on. import pandas as pd from pandas_profiling import ProfileReport df = pd.read_csv(“car_design.csv”) df After loading the dataset we just need to run the following commands to generate and download the EDA report. design_report = ProfileReport(df) design_report.to_file(output_file='report.html') After we run these commands, it will create a detailed EDA report and save it as an HTML file with the name ’report.html’ or any name which you pass as an argument. Understanding the Report The report generated contains a general overview and different sections for different characteristics of attributes of the dataset. The different sections are: A. Overview B. Variable Properties We can scroll down to see all the variables in the dataset and their properties. C. Interaction of Variables Similarly, we can also view the interaction of different attributes of the dataset with each other. D. Correlations of the variable The report generated contains different types of correlations like Spearman’s, Kendall’s, etc. of all the attributes of the dataset. E. Missing Values Other than this the report also shows which attributes have missing values. The report generated is really helpful in identifying patterns in the data and finding out the characteristics of the data. 2. Sweetviz Sweetviz is a python library that focuses on exploring the data with the help of beautiful and high-density visualizations. It not only automates the EDA but is also used for comparing datasets and drawing inferences from it. Here we will analyze the same dataset as we used for pandas profiling. Implementation Before using sweetviz we need to install it by using pip install sweetviz. We have already loaded the dataset above in the variable named “df”, we will just import the dataset and create the EDA report in just a few lines of code. import sweetviz as sv sweet_report = sv.analyze(df) sweet_report.show_html('sweet_report.html') This step will generate the report and save it in a file named “sweet_report.html” which is user-defined. Understanding the Report The report contains characteristics of the different attributes along with visualization. In this report, we can clearly see what are the different attributes of the datasets and their characteristics including the missing values, distinct values, etc. Sweetviz also allows you to compare two different datasets or the data in the same dataset by converting it into testing and training datasets. Below given command will allow us to visualize the dataset we are using by equally distributing it in testing and training data. df1 = sv.compare(df[102:], df[:102]) df1.show_html('Compare.html') In this report, we can easily compare the data and the comparison between the datasets. Here we can see that the reports generated are easily understandable and are prepared in just 3 lines of code. 3. Autoviz Autoviz is an open-source python library that mainly works on visualizing the relationship of the data, it can find the most impactful features and plot creative visualization in just one line of code. Autoviz is incredibly fast and highly useful. Before Exploring Autoviz we need to install it by using pip install autoviz. Implementation For using autoviz first we need to import the autoviz class and instantiate it. from autoviz.AutoViz_Class import AutoViz_Class AV = AutoViz_Class() After initiating the Autoviz class we just need to run a command which will create a visualization of the dataset. df = AV.AutoViz('car_design.csv') Understanding the Report The above command will create a report which will contain the following attributes: A. Pairwise scatter plot of all continuous variables B. Histograms(KDE Plots) of all continuous variables C. Violin Plots of all continuous variables D. Heatmap of continuous variables If we know the dependent variable in the dataset which is dependent on other variables, then we can pass it as an argument and visualize the data according to the Dependent Variable. For eg. If we consider “highway-mpg” as a dependent variable then we will use the below-given command to visualize the data according to the dependent variable. df = AV.AutoViz('car_design.csv', depVar='highway-mpg') This will create the same report as we have seen above but in the context of the dependent variable i.e. highway-mpg. Conclusion In this article, we have learned how we can automate the EDA process which is generally a time taking process. We have learned about three open-source python libraries which can be used for Automating, namely: Pandas-Profiling, Sweetviz, and Autoviz. All the libraries are easy to use and create a detailed report about the different characteristics of data and visualization for correlations and comparisons..
https://analyticsindiamag.com/tips-for-automating-eda-using-pandas-profiling-sweetviz-and-autoviz-in-python/
CC-MAIN-2021-31
refinedweb
1,087
53.31
When the -|> style was added to FancyArrowPatch, the purpose was to add an arrow style with a certain style shaft, but a solid head [1]. However, since the given linestyle is used for the outline of the head, we can have arrowheads that look very odd. Here is the example input and output: from matplotlib.pyplot import figure, show from matplotlib.patches import FancyArrowPatch fig = figure() ax = fig.add_subplot(111,autoscale_on=False,) p = FancyArrowPatch((0,0), (1,1), arrowstyle='-|>,head_width=8,head_length=16',lw=3,fc='k',ec='k',linestyle='dashed') ax.add_patch(p) show() Is there an easy fix to make the arrowhead have a solid linestyle, even if the shaft is dashed? Is this desirable to anyone else besides me? Thanks, Jason [1]
https://discourse.matplotlib.org/t/fancyarrowpatch-style-doesnt-have-solid-arrowhead-when-linestyle-dashed/16855
CC-MAIN-2022-21
refinedweb
125
60.01
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site. Quote from jaquadro Source shouldn't be null if the Level object had data loaded into it. The entries you're trying to access might not be present, but that should throw a different exception. anvilWorld.Level.Source["generatorName"] = new TagNodeString("flat"); TagNode source = anvilWorld.Level.Source; if (source == null) throw new Exception("Hey, this shouldn't happen"); if (!source.ContainsKey("generatorName")) source["generatorName"] = new TagNodeString("flat"); else source["generatorName"].ToTagString().Data = "flat"; TagNode source = anvilWorld.Level.Source; if (source == null) throw new Exception("Hey, this shouldn't happen"); source["generatorName"] = new TagNodeString("flat"); Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Quote from jaquadrosnip using System; using Substrate; using Substrate.Core; //) { Console.WriteLine("Enter destination world (eg 'New World' without quotes): "); string dest = Console.ReadLine(); Console.WriteLine("Enter dimension ID (default -28): "); int dimID = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter block ID to replace: "); int before = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter block metadata to replace: "); int after = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter block ID to replace with: "); int beforemeta = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter block metadata to replace with: "); int aftermeta = Convert.ToInt32(Console.ReadLine()); // Open our world NbtWorld world = NbtWorld.Open(dest); // The chunk manager is more efficient than the block manager for // this purpose, since we'll inspect every block IChunkManager cm = world.GetChunkManager(dimID); < xdim; x++) { for (int z = 0; z < zdim; z++) { for (int y = 0; y < ydim; y++) { // Replace the block with after if it matches before if (chunk.Blocks.GetID(x, y, z) == before && chunk.Blocks.GetData(x, y, z) == beforemeta) { chunk.Blocks.SetID(x, y, z, after); chunk.Blocks.SetData(x, y, z, aftermeta); } } } } // Save the chunk cm.Save(); Console.WriteLine("Processed Chunk {0},{1}", chunk.X, chunk.Z); } } } } string path = Environment.ExpandEnvironmentVariables("%APPDATA%"); if (!Directory.Exists(path)) { path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } path = Path.Combine(path, ".minecraft"); path = Path.Combine(path, "saves"); DirectoryInfo saves = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicatonData) + "\\.minecraft\\saves"); foreach(DirectoryInfo dir in saves.GetDirectories()) { foreach(FileInfo file in dir.GetFiles()) { if(file.Name == "level.dat") { //it is a save, do whatever you want } } } item.Source["tag"].ToTagNodeCompound()["display"].ToTagNodeCompound()["name"] = new TagNodeString("some name") seem reasonable that it doesn't know about those keyvalues. and sorry for bugging you again, how do I add custom keyvalues then? says the man who didn't look in the documentation before asking Assuming that "Source" itself is not null (and it shouldn't be .. but if it legitimately is, post some sample code), you should check to see if the key exists before trying to use it. If it doesn't exist, you could then create it: So a more complete example: Although for simple data like strings and numerical values, it's easier to just create a new tag always, and then you don't need to check. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate I'm becoming such a bother... Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Source still null. I've pushed some changes to github, so grab the latest version of the source and give it a shot. It would have also been possible to work around this problem by calling BuildNbtTree to get a TagNode, and then calling LoadNbtTree with that result. But that's a lot of work for nothing. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Side-note: Can you import buildcraft Blueprint files? Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate This is what I have: (of course, most of it is the example code) 1. This doesn't seem to be working, I placed it in my saves folder and used: "New World", -28, 220, 0, 221, 4... It lists all the chunks as if it successfully changed the blocks but nothing is different in-game. Is the something else I need to do for modded blocks or custom chunkmanagers?Wow, complete and utter derpage. I was setting the wrong variable. 2. Is there a way to detect save folders in .minecraft without putting it in the saves folder? Thanks, and great job on this btw This is the code I use in NBTExplorer to try and guess at the Minecraft save path. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate So for some reason, the whole thing is blue, centered, and highlighted white, and the last sentence ironically was the only part with the words switched around. Last sentence: Also, my posts box is acting really weird, and it's randomly erasing stuff I write and changing the allignment, so I'm sorry if something doesn't seem correct. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Okay, now I actually have the original thing, and it shows a .NET DLL with other stuff. I do know how to use c# so I added the reference, however I've never had to deal with a DLL with documentation before. And this one has documentation and I need it... So how do you add the DLL as a reference and make visual studio include the documentation. Info: Windows Vista something Visual Studio 2010 Ultimate --------------------------- Or... could you offer direct help? I can't figure out how to add an item to the player's inventory and then edit the NBT tag for it's name. I managed to add the item to the inventory by looking at the example, however I have absolutely no clue about how to edit the NBT tags. I looked at the source code for NBTExplorer which was fully not helpful at all. Now for some reason, the chm file says "navigation to the webpage was cancelled", and I don't know how to load documentaiton into VS, and the XML file is a pain in the neck to manually read, and the wiki thing has barely any info at all, and I can't find anything through google, and the code isn't as self explanatory as it looks. So how do I change NBT Tags?? Since the MineCraft data is changing so quickly, I have not updated the Item objects with convenience fields in a while, so as you inferred it has to be done directly with NBT tags. Most objects that implement INbtObject have a "Source" property that is a TagNodeCompound. A TagNodeCompound is very similar to a .NET Dictionary object, and holds a collection of other NBT tags, including possibly other compound tags or lists. The Source property represents the root tag for that object's data hierarchy. For an Item object, the tag returned by Source would be expected to have tags for "id", "Damage", and "Count" at minimum. The Item compound tags might also have a "tag" entry, which is itself another compound tag containing lots of other item metadata (though a particular tag will only exist if it's relevent). And any piece of metadata that is currently "default" won't have a tag either. That's the case for your item name. All the information you need to know on NBT structure for items is available on the wiki: As for actually reading and manipulating the NBT values, all the API that you need to worry about is in the .Nbt namespace: And setting the data value could be as simple as: Except that you should check that the particular entries exist before actually trying to access them like I did. "tag" or "display" might not exist. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate
https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/minecraft-tools/1261313-sdk-substrate-map-editing-library-for-c-net-1-3-8?page=23
CC-MAIN-2022-05
refinedweb
1,328
55.95
A wiki can be used to create a community dictionary, and accessed by a desktop application A wiki can be great tool to create a community dictionary accessible to all. However, a dictionary platform is little different from a regular wiki: - There are lot of terms, like 100,000 vs 500-1000 wiki pages in a regular wiki. - Each term is very small, just few lines of text - Almost no markup needed, since the structure of a term is very simple - You want to dictionary to be inside your application, and not on the web. How a dictionary desktop application should work You would like to select a word in a browser, then click a shortcut key or select a menu, and open a dictionary definition for that word. You don't want to copy the word, go to the, paste the word in the search field, and click enter - too much work. This is actually a very simple DesktopWiki, which is much simpler to create. Wiki dictionary application can be browse-only. We can have an edit link to open an edit window in a browser. This could be enough for the first release or even for the future, because most people that use a dictionary does not edit it. A wiki dictionary desktop application could be very simple. Something that works like this description could be very easy to create. Similar client software (add more): OmniDictionary - dict.org client for Mac OS X. What is missing, is a protocol to communicate with the wiki. This can use xml rpc A wikidict proxy Another option, is a dict server that can serve existing dict clients, and return results from a wiki instead of a dict database. See dict protocol - How the wiki should work Huge amount of pages We need an efficient way to keep and search huge amount of pages: - keeping an index of all pages in memory or on disk. - Page might be save under A B C... letter directories, as 100,000 directory entries is little too much for file systems. So the concept of one wiki namespaces == file system namespace might not work. Term structure We need an easy way to add terms without formating errors. A template page with standard markup could be enough, or maybe a form. - Term - page name - Type of word - List of definitions - Links to similar terms Here is an example from (I looked for wiki, but could not find it): From Webster's Revised Unabridged Dictionary (1913): Dictionary . ----------------- From WordNet (r) 2.0: dictionary n : a reference book containing an alphabetical list of words with information about them [syn: lexicon] ----------------- From THE DEVIL'S DICTIONARY ((C)1911 Released April 15 1993): DICTIONARY, n. A malevolent literary device for cramping the growth of a language and making it hard and inelastic. This dictionary, however, is a most useful work. Multi language dictionary Each term can have translations in many languages, probably showing only two at a time: - The user language - Other language Discussion I don't know if this pages makes sense in the MoinMoin wiki. There already is a Wiki dictionary. They already use a WikiEngine that is optimised for a large amount of pages/data/traffic -- the MediaWiki Engine. The idea of a desktop application is very interesting but would perhaps better be placed either in the Wiktionary or the Wikipedia Metawiki. -- FlorianFesti 2004-09-26 08:56:39
http://www.moinmo.in/WikiDictionary
crawl-003
refinedweb
571
61.77
What should I do to change this code using else-if so that it will read the first character in my input text file and then determine which equation to use? For example, the first line in the input text file is A 4 8 and the second line is M 5 9, I want my program to read the first letter and then determine which equation to use. The first line starts with an A so the AddCalculate equation will be used to add 4 and 8 and the second line starts with an M so the MultiplyCalculate equation will be used to multiply 5 and 9. The code that I provided below can only be used to calculate either AddCalculate or MultiplyCalculate. How can I use both AddCalculate and MultiplyCalculate in the same code with else-if to read the first character and determine which equation to use? #include "stdafx.h" #include <iostream> #include <math.h> #include <iomanip> #include <fstream> using std::ifstream; using std::ofstream; #include "Calcu.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { Calcu myCalcu; ifstream inFile ("AorMin.txt"); ofstream outFile ("AorMout.txt"); int addthis; int addthat; int addAnswer; int multhis; int multhat; int mulAnswer; if (!inFile) { cerr << "Error: Input file could not be opened" << endl; exit (1); } if (!outFile) { cerr << "Error: Input file could not be opened" << endl; exit (1); } while ( !inFile.eof() ) { inFile >> addthis >> addthat; addAnswer = myCalcu.AddCalculate (addthis, addthat); outFile << addthis << ", " << addthat << "= " << addAnswer << endl; inFile >> multhis >> multhat; mulAnswer = myCalcu.MultiplyCalculate (multhis, multhat); outFile << multhis << ", " << multhat << "= " << mulAnswer << endl; } cout << "End-of-file reached.." << endl; inFile.close(); outFile.close(); return 0; }
https://www.daniweb.com/programming/software-development/threads/401010/c-how-to-read-the-first-character-in-input-text-file-with-else-if
CC-MAIN-2018-17
refinedweb
269
55.44
D (The Programming Language)/d2/Lessons Style Guide Lesson T: A Style Guide[edit] In this template-like guide, you see the general layout for these phobos/language lesson pages. Introductory Code[edit] Code Example 1 Title[edit] You may write a description of the code sample. import std.stdio; void main() { writeln("Thank you for your contributions to this book."); } Code Example 2 Title[edit] Code examples are for introducing the concepts of the lesson to the reader. They do not necessarily have to show every concept. It's even nicer if the code example did something useful and/or interesting. import std.stdio; void main() { writeln("Soon these lessons will be complete."); } Concepts[edit] Concept 1[edit] The navbar at the top is a template. You can look at the source code of this page to see how it is used. The 0 and the T lessons are there on the navbar temporarily until the lessons get better (when these lessons can actually be used for learning). writeln("Wikimarkup can get so messy"); writeln("When you make complex templates"); writeln("D's templates are bliss compared to them"); Concept 2[edit] Concepts are generally very important and crucial pieces of information about D. It is okay to assume that the reader has solid knowledge of C or C++ when writing these concepts. Conclusion[edit] Lessons can optionally have a conclusion. Often, the conclusion is used to inform the reader about what direction the next lessons go in and how it all ties together. Tips[edit] - Tips are information that aren't quite important enough to put inside of the concepts section. Do not use <source> or <syntaxhighlight> tags here. - Tip 1 - Tip 2 - Thank you for reading.
https://en.wikibooks.org/wiki/D_(The_Programming_Language)/d2/Lessons_Style_Guide
CC-MAIN-2018-09
refinedweb
289
64.1
FTP Upload/Download with Proxy Orçamento $100-800 USD The coder will: 1. Create code in C# to upload/download files to an FTP Server that is running a Proxy Server using the [url removed, login to view] namespace (not the [url removed, login to view] namespace). 2. Explain how to set up a FTP Server and a Proxy Server locally so I can test the work. Any open source or Microsoft FTP Server and Proxy Server is fine. 3. Create a Send Raw FTP command method that can be used to send RAW FTP commands such as CWD. 4. Create a simple winform application to interact with it. 5. The coder will be expected to set up his/her own local FTP Server and Proxy Server to test his/her code#, .NET 2.0
https://www.br.freelancer.com/projects/php-engineering/ftp-upload-download-with-proxy/
CC-MAIN-2018-13
refinedweb
135
69.72
Hi, my name is Eric Crooks. I'm one of the founders of Drash. In this article, I talk about what Drash is and why I decided to build it with one of my colleagues. Before diving into this article, know that all statements made are by me and all opinions are my own. Table of Contents - What is Drash? - Why was Drash built? What is Drash? Drash is a REST microframework for Deno's HTTP server. It has zero dependencies outside of Deno's Standard Modules. It is designed to help you build your projects quickly -- APIs, SPAs, etc. Why was Drash built? Before Deno, I used Node and Express. Express was great, but I found issues with the development experience. Mainly, I had issues with the syntax and the time it took to debug issues. More code meant an exponential increase in duplicated code and debugging time. I wasn't a fan of that fact. Problem 1: Syntax Take a look at the code below. You might be familiar with the syntax. app.get('/', function (req, res) { res.send('GET request received') }) app.post('/', function (req, res) { res.send('POST request received') }) app.put('/', function (req, res) { res.send('PUT request received') }) app.delete('/', function (req, res) { res.send('DELETE request received') }) This syntax is great for small applications. It's not so great for larger applications. I found that a large Express application comes at cost. That cost is the degradation of the developer's experience when writing code. The above code looks great, is easy to write, and helps you get started quickly. However, look at how much code is duplicated. - The reqand resobjects are passed in multiple times for each route you define - The /route is defined multiple times - The appobject is used multiple times This led me to ask myself the following: - Why can't the callback function that is passed into the route handler have the reqand resobjects readily available using this.reqand this.res? - Why do I have to keep using app.? - Why do I have to define the /route one time for each HTTP method? I'm lazy and don't want to have to write something multiple times if I don't have to. What I wanted was something like this: app.route('/') .get(() => { this.res.send('GET request received') }) .post(() => { this.res.send('POST request received') }) .put(() => { this.res.send('PUT request received') }) .delete(() => { this.res.send('DELETE request received') }) That syntax looks much better in my opinion and it's easy to write. You take the app object, define a route, and define the allowed HTTP methods for that route. Problem 2: Debugging In a larger Express application, your filesystem might be split up so that your front-end and back-end are organized in a way to help you identify where code lives. For example, your filesystem might look like the following: app/ |-- assets/ | |-- js/ | |-- api.js | |-- another-js-file.js | |-- views/ | |-- index.html | |-- another-view-file.html | |-- src/ | |-- controllers/ | | |-- home-controller.js | | |-- user-controller.js | | |-- order-controller.js | | | |-- services/ | | |-- user-service.js | | |-- order-service.js | | | |-- routes.js | |-- app.js |-- package.json Let's take the above example code and see why debugging is an issue with it. Inside of api.js, we see the following code and there's an issue with it: axios.get("/users/1") .then((response) => { // code to handle the response }) .catch((error) => { // code to handle the error }); For some reason, the back-end isn't returning what's expected. So let's take a look at the back-end. All we know is /users/1 is the route we need to start with. So let's go to our routes.js file and see what controller is mapped to the route. We see the following: app.get('/users/:id', UserControllerGet); app.post('/users/:id', UserControllerPost); app.put('/users/:id', UserControllerPut); app.delete('/users/:id', UserControllerDelete); Ok, now we know that the UserControllerGet function is mapped to the GET /users/:id route. This looks promising because /users/:id matches the front-end's API call to /users/1. Let's go to the UserControllerGet: function UserControllerGet(req, res) { res.send(userService.getUserDetails(req.params)); } Now we're at the UserControllerGet function and see that the response being created comes from userService.getUserDetails(). So let's go to that file. Actually, let's not. This is too much sifting through code just to figure out where issues are occurring. This debugging process led me to ask myself the following: - Do I have to go through this process every time I debug something? I have to look at the front-end API call, match the route to one of the routes defined in the routes file, and then go from there? - Why can't I just assume /users/*maps to a single UserControllerfile and look in that file? What I wanted was to remove the routes file completely and have: // File: user-controller.js app.route("/users/:id") .get(() => { this.res.send(userService.getUserDetails(req.params)); }) .post(() => { // POST code }) .put(() => { // PUT code }) .delete(() => { // DELETE code }) Again, you take the app object, define a route, and define the allowed HTTP methods for that route -- all in a single file. So, how would I solve the syntax issues? How would I solve the debugging issues? Should I rewrite my code to make it work the way I want to? I mean, Express is unopinionated, so I could do that, but why not just create something that makes more sense? Why go with controllers? Why can't we go with resource-based logic? Some frameworks (e.g., Laravel) use resources and they kind of make sense. I had so many questions and in the end I decided to plan out a new framework with my colleague: Drash. Solution to the problems Instead of having app.get(), I figured it'd make sense to have a class with HTTP verbs ... export class MyController { public GET() { ... } public POST() { ... } public PUT() { ... } public DELETE() { ... } } ... and then you'd plug this into your application in some way. I wasn't sure at the time, but I figured it'd look something like: import { MyController } from "/path/to/my_controller.ts"; const app = new App({ controllers: [MyController] }) What about the route definitions? Where do those go? I figured it'd be best to have the controller be in charge of the routes clients can use to target the controller. Like so: export class MyController { public paths = [ "/my-controller", "/my-controller/:some_param" ]; public GET() { ... } public POST() { ... } public PUT() { ... } public DELETE() { ... } } With "resources" in the back of my mind and its definition, I figured the controller should just be named a resource. This is how they do it in Tonic (the PHP microframework). Everything in Tonic is a resource. Resources are PHP classes; and resources define their own paths. So now we have something like this: export class MyResource { public paths = [ "/my-resource", "/my-resource/:some_param" ]; public GET() { ... } public POST() { ... } public PUT() { ... } public DELETE() { ... } } This looks great! Also, it solves the debugging issue. If I had a front-end that called /my-resource/something, I would already know to go MyResource because the URI should be mapped to a MyResource resource. Same thing goes for a /users API call. /users should map to a UsersResource. What about the req and res objects? I figured it'd be best to instantiate a resource class and pass in the req and res objects in its constructor. That would give all of the resource class' methods access to the req and res objects without having to pass them in like in Express. This would also mean a BaseResource class would need to be used so that the resource classes that developers define wouldn't require the constructor. So, now we have something like this: // File: base_resource.ts export class BaseResource { public resource; public response; constructor(request, response) { this.request = request; this.response = response; } } // File: my_resource.ts import { BaseResource } from "/path/to/base_resource.ts"; export class MyResource extends BaseResource { public paths = [ "/my-resource", "/my-resource/:some_param" ]; public GET() { this.request.doSomething(); this.response.doSomething(); } public POST() { ... } public PUT() { ... } public DELETE() { ... } } You might notice the change of the req and res names to request and response. I believe we should be explicit in our code so that newcomers don't question things like variable names. After a few months of developing around the definition of resources with the syntax being the first thing considered (for a better developer experience), Drash was born. Originally, it was developed with an Express-like syntax, but maintaining that was a nightmare. This was especially true when trying to handle this.request and this.response in chained functions. So, Drash was forced to be different, and I think that's ok because most of its logic is backed by definitions in the MDN. Hope you enjoyed reading this! I figured it'd be nice to give some insight into Drash. -- Eric Posted on by: Drash Land Discussion
https://dev.to/drash_land/why-was-drash-built-4bob
CC-MAIN-2020-40
refinedweb
1,500
68.87
In this codelab, you'll create a computer vision model that can recognize items of clothing with TensorFlow. Prerequisites - A solid knowledge of Python - Basic programming skills What you'll learn In this codelab, you'll: - Train a neural network to recognize articles of clothing - Complete a series of exercises to guide you through experimenting with the different layers of the network What you'll build - A neural network that identifies articles of clothing What you'll need If you've never created a neural network for computer vision with TensorFlow, you can use Colaboratory, a browser-based environment containing all the required dependencies. You can find the code for the rest of the codelab running in Colab. Otherwise, the main language that you'll use for training models is Python, so you'll need to install it. In addition to that, you'll also need TensorFlow and the NumPy library. You can learn more about and install TensorFlow here. Install NumPy here. First, walk through the executable Colab notebook. Start by importing TensorFlow. import tensorflow as tf print(tf.__version__) You'll train a neural network to recognize items of clothing from a common dataset called Fashion MNIST. It contains 70,000 items of clothing in 10 different categories. Each item of clothing is in a 28x28 grayscale image. You can see some examples here: The labels associated with the dataset are: The Fashion MNIST data is available in the tf.keras.datasets API. Load it like this: mnist = tf.keras.datasets.fashion_mnist Calling load_data on that object gives you two sets of two lists: training values and testing values, which represent graphics that show clothing items and their labels. (training_images, training_labels), (test_images, test_labels) = mnist.load_data() What do those values look like? Print a training image and a training label to see. You can experiment with different indices in the array. import matplotlib.pyplot as plt plt.imshow(training_images[0]) print(training_labels[0]) print(training_images[0]) The print of the data for item 0 looks like this: You'll notice that all the values are integers between 0 and 255. When training a neural network, it's easier to treat all values as between 0 and 1, a process called normalization. Fortunately, Python provides an easy way to normalize a list like that without looping. training_images = training_images / 255.0 test_images = test_images / 255.0 You may also want to look at 42, a different boot than the one at index 0. Now, you might be wondering why there are two datasets—training and testing. The idea is to have one set of data for training and another set of data that the model hasn't yet encountered to see how well it can classify values. After all, when you're done, you'll want to use the model with data that it hadn't previously seen! Also, without separate testing data, you'll run the risk of the network only memorizing its training data without generalizing its knowledge. Now design the model. You'll have three layers. Go through them one-by-one and explore the different types of layers and the parameters used for each. model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) Sequentialdefines a sequence of layers in the neural network. Flattentakes a square and turns it into a one-dimensional vector. Denseadds a layer of neurons. Activationfunctions tell each layer of neurons what to do. There are lots of options, but use these for now: Relueffectively means that if X is greater than 0 return X, else return 0. It only passes values of 0 or greater to the next layer in the network. Softmaxtakes a set of values, and effectively picks the biggest one. For example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], then it saves you from having to sort for the largest value—it returns [0,0,0,0,1,0,0,0,0]. Now that the model is defined, the next thing to do is build it. Create a model by first compiling it with an optimizer and loss function, then train it on your training data and labels. The goal is to have the model figure out the relationship between the training data and its training labels. Later, you want your model to see data that resembles your training data, then make a prediction about what that data should look like. Notice the use of metrics= as a parameter, which allows TensorFlow to report on the accuracy of the training by checking the predicted results against the known answers (the labels). model.compile(optimizer = 'Adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5) When model.fit executes, you'll see loss and accuracy: Epoch 1/5 60000/60000 [=======] - 6s 101us/sample - loss: 0.4964 - acc: 0.8247 Epoch 2/5 60000/60000 [=======] - 5s 86us/sample - loss: 0.3720 - acc: 0.8656 Epoch 3/5 60000/60000 [=======] - 5s 85us/sample - loss: 0.3335 - acc: 0.8780 Epoch 4/5 60000/60000 [=======] - 6s 103us/sample - loss: 0.3134 - acc: 0.8844 Epoch 5/5 60000/60000 [=======] - 6s 94us/sample - loss: 0.2931 - acc: 0.8926 When the model is done training, you will see an accuracy value at the end of the final epoch. It might look something like 0.8926 as above. This tells you that your neural network is about 89% accurate in classifying the training data. In other words, it figured out a pattern match between the image and the labels that worked 89% of the time. Not great, but not bad considering it was only trained for five epochs and done quickly. How would the model perform on data it hasn't seen? That's why you have the test set. You call model.evaluate and pass in the two sets, and it reports the loss for each. Give it a try: model.evaluate(test_images, test_labels) And here's the output: 10000/10000 [=====] - 1s 56us/sample - loss: 0.3365 - acc: 0.8789 [0.33648381242752073, 0.8789] That example returned an accuracy of .8789, meaning it was about 88% accurate. (You might have slightly different values.) As expected, the model is not as accurate with the unknown data as it was with the data it was trained on! As you learn more about TensorFlow, you'll find ways to improve that. To explore further, try the exercises in the next step. Exercise 1 For this first exercise, run the following code: classifications = model.predict(test_images) print(classifications[0]) It creates a set of classifications for each of the test images, then prints the first entry in the classifications. The output after you run it is a list of numbers. Why do you think that is and what do those numbers represent? Try running print(test_labels[0]) and you'll get a 9. Does that help you understand why the list looks the way it does? The output of the model is a list of 10 numbers. Those numbers are a probability that the value being classified is the corresponding label. For example, the first value in the list is the probability that the clothing is of class 0 and the next is a 1. Notice that they are all very low probabilities except one. Also, because of Softmax, all the probabilities in the list sum to 1.0. The list and the labels are 0 based, so the ankle boot having label 9 means that it is the 10th of the 10 classes. The list having the 10th element being the highest value means that the neural network has predicted that the item it is classifying is most likely an ankle boot. Exercise 2 Look at the layers in your model. Experiment with different values for the dense layer with 512 neurons. What different results do you get for loss and training time? Why do you think that's the case? For example, if you increase to 1,024 neurons, you have to do more calculations, slowing down the process. But in this case they have a good impact because the model is more accurate. That doesn't mean more is always better. You can hit the law of diminishing returns very quickly. Exercise 3 What would happen if you remove the Flatten() layer. Why do you think that's the case? You get an error about the shape of the data. The details of the error may seem vague right now, but it reinforces the rule of thumb that the first layer in your network should be the same shape as your data. Right now your data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to flatten that 28,28 into a 784x1. Instead of writing all the code, add the Flatten() layer at the beginning. When the arrays are loaded into the model later, they'll automatically be flattened for you. Exercise 4 Consider the final (output) layers. Why are there 10 of them? What would happen if you had a different amount than 10? Try training the network with 5. You get an error as soon as it finds an unexpected value. Another rule of thumb—the number of neurons in the last layer should match the number of classes you are classifying for. In this case, it's the digits 0 through 9, so there are 10 of them, and hence you should have 10 neurons in your final layer. Exercise 5 Consider the effects of additional layers in the network. What will happen if you add another layer between the one with 512 and the final layer with 10? There isn't a significant impact because this is relatively simple data. For far more complex data, extra layers are often necessary. Exercise 6 Before you trained, you normalized the data, going from values that were 0 through 255 to values that were 0 through 1. What would be the impact of removing that? Here's the complete code to give it a try (note that the two lines that normalize the data are commented out). Why do you think you get different results? There's a great answer here on Stack Overflow. import tensorflow as tf print(tf.__version__)') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Earlier, when you trained for extra epochs, you had an issue where your loss might change. It might have taken a bit of time for you to wait for the training to do that and you might have thought that it'd be nice if you could stop the training when you reach a desired value, such as 95% accuracy. If you reach that after 3 epochs, why sit around waiting for it to finish a lot more epochs? Like any other program, you have callbacks! See them in action: import tensorflow as tf class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('accuracy')>0.95): print("\nReached 95% accuracy so cancelling training!") self.model.stop_training = True callbacks = myCallback()', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks]) You've built your first computer vision model! To learn how to enhance your computer vision models, proceed to Build convolutions and perform pooling.
https://codelabs.developers.google.com/codelabs/tensorflow-lab2-computervision
CC-MAIN-2020-50
refinedweb
1,921
66.94
This is the 17th post on my blog. This post had to be posted before. But I tried much to finish it quickly as I can. Enjoy with constructors. What is the constructor? What is the constructor? This is another valuable thing in programming. You may hear about constructor companies. What they are doing is constructing some things means building, roads or whatever. Likewise, in programming, there are also constructors. But they are not creating that buildings or roads. When you create objects, constructors are always invoked. If you use the 'new' keyword, constructors are running. Rules of constructor Rules of constructor - Every class, even abstract classes must have a constructor. There can be one or more. - Interfaces don't have constructors. - The constructor name should be exactly the same as the class name. - The constructor does not have a return type. - Constructors can use any access modifiers (private, protected, default or public). Default constructor - 'The default constructor' is created by default by the compiler if you don't create any constructors in your class, but if the programmer wants to create a constructor, he can type it as, Class ConstructorTest{ ConstructorTest() { } } - The default constructor is always a no-args constructor. But no-arg constructor is not necessarily the default. - Every constructor has, as its first statement either this() or super(). super() - superclass constructor - Default constructor provides a no-arg call to super(). It means if you don't type any constructor, it will be generated a default constructor and it create a no-arg call to super(). - The default constructor provides the default values for objects. They may be 0 or null or etc. public class DefaultCon { int id; float avg; double d; String name; void test(){ System.out.println(id + " | " + name + " | " + avg + " | " + d); } public static void main(String args[]){ DefaultCon obj1 = new DefaultCon(); obj1.test(); } } In the above section we have talked about default constructor, super...etc. The following shows the auto-generated code for what you typed code. Other constructors with parameters public class OtherCon { int id; String name; OtherCon(int id, String name){ this.id=id; this.name=name; } void display(){ System.out.println(id + " " + name); } public static void main(String args[]){ OtherCon obj1 = new OtherCon(1,"John"); OtherCon obj2 = new OtherCon(2,"Adam"); System.out.println("ID Name"); obj1.display(); obj2.display(); } } Constructor Overloading public class OverloadingCon { String name; int marks; OverloadingCon(String name, int marks){ this.marks=marks; this.name=name; } OverloadingCon(String name){ this.name=name; } void display(){ System.out.println(name+ " " + marks); } public static void main(String args[]){ OverloadingCon obj1 = new OverloadingCon("Adam",80); OverloadingCon obj2 = new OverloadingCon("John"); obj1.display(); obj2.display(); } } Constructor chaining - This occurred when a class inherits another class. - You know that a subclass inherits the things in the superclass. - When you create an object from a subclass, its constructor is invoked. - But the thing is, the superclass constructor needs to be invoked because of inheritance. - It is done by super() keyword and it can be done as follows. class Fruit{ String type; Fruit(String type){ this.type=type; } } class Apple extends Fruit{ String color; Apple(String type, String color){ super(type); this.color=color; } void display(){ System.out.println("Fruit type is: " + type); System.out.println("Fruit color is: " + color); } } public class ConstructorChain { public static void main(String args[]){ Apple obj = new Apple("Sweet", "Red"); obj.display(); } } Constructors in Java Reviewed by Ravi Yasas on 11:09 PM Rating: Hey there, You have done an incredible job. I wil definitely digg it and personally suggest to my friends. I'm confident they'll be benefiited from this site.
https://www.javafoundation.xyz/2013/11/constructors_12.html
CC-MAIN-2021-43
refinedweb
601
52.36
Portable Class Libraries Visual Studio 2012 introduces the portable class libraries, a special type of class libraries that use a subset of the .NET Framework that's common to WPF, Silverlight, Silverlight for Windows Phone 7.x, Xbox 360, and Windows Store apps. With portable class libraries, you write the code once; then your code can be shared across all the aforementioned platforms. Of course, this implies that only objects common to all platforms can be shared. More specifically, the following assemblies can be referenced in a portable class library: - MsCorlib.dll - System.dll - System.Core.dll - System.ComponentModel.Composition.dll - System.ComponentModel.Annotations.dll - System.Net.dll - System.Runtime.Serialization.dll - System.ServiceModel.dll - System.Xml.dll - System.Xml.Linq.dll - System.Xml.Serialization.dll - System.Windows.dll Assemblies not included in this list are not considered portable. The MSDN Library has a more detailed list showing what can be shared. To create a new portable class library, in Visual Studio 2012 select File > New > Project. In the New Project dialog box, select the Portable Class Library template, as shown in Figure 1. After clicking OK, select the list of platforms you want to target (the Xbox 360 is excluded by default), as shown in Figure 2. Notice that you can change the default selection; for example, you can choose .NET Framework 4.0.3 instead of 4.5, or Silverlight 5 instead of 4. Remember that changing the default selection can affect the list of objects that are shared, and some of them may no longer be available. Once the project has been created, enable the Show All Files view in Solution Explorer. Notice that the list of references contains the item .NET Portable Subset, as shown in Figure 3. This subset exposes objects that are common to the selected target platforms. If you double-click this item, the Object Browser window will show in more detail the list of available namespaces and classes. Figure 4 shows an excerpt of the Object Browser.
http://www.informit.com/articles/article.aspx?p=1983304&seqNum=2
CC-MAIN-2019-51
refinedweb
335
57.57
One of the recent features of Python 3 that I like the most is definitely the support for type annotations. Type annotations are a precious tool (especially if used in combination with an advanced IDE like PyCharm) that allow us to: write clear and implicitly documented code, prevent us from invoking methods with wrong data types (ok, actually we can do whatever at runtime since Python is a dynamic language and type hints as the name suggests is just that: an hint) and get useful code suggestions and autocompletion. Starting with Python 3.6 is now possible to specify not only arguments type in method signatures, but also types for inline variables. Let’s see it in action with a sample code: from datetime import datetime, timedelta from enum import Enum from typing import List class Sex(Enum): M = 'M' F = 'F' class Person: def __init__(self, first_name: str, last_name: str, birth_date: datetime, sex: Sex): self._first_name: str = first_name self._last_name: str = last_name self._birth_date: datetime = birth_date self._sex: Sex = sex self._hobbies: List[str] = [] def get_age(self) -> int: diff: timedelta = datetime.now() - self._birth_date return int(diff.days / 365) @property def hobbies(self) -> List[str]: return self._hobbies @hobbies.setter def hobbies(self, hobby_list: List[str]): self._hobbies = hobby_list So, basically we have created a Person class and a Sex enum and by using type hints we have declared that: “first_name” and “last_name” must be a str type, “birth_date” a datetime type and “sex” a custom enum type Sex. We have also specified the return type of get_age() method as int and inside its implementation we have referenced the date difference as a timedelta object. Finally we have imported List from “typing” package in order to specify “hobbies” as a list of string objects (if we don’t care about list content we can just use list type by avoiding the import). By using PyCharm, we can see that if we try to pass an invalid type as argument it complains as expected: Unfortunately PyCharm does not complains if we try to specify “hobbies” via simple assignment: But in my opinion, using the type hints as shown in the example code has the huge value of keeping code documented, especially if you work in a team, or if you want to write an open source project. One limitation in type hints that I found is that you can’t create “circular references”, that means you can’t have a method in a class that specify itself as argument: Update: As suggested in the comments, this can be “bypassed” by using strings in place of types as reported here
http://www.daveoncode.com/2017/03/06/writing-better-software-with-python-3-6-type-hints/
CC-MAIN-2017-43
refinedweb
439
56.59
I'm currently researching how to utilize aspect ratio in a magnified area full of pixels. My main focus of this project is to match the mouse cursor to the dot on the screen, while the mouse cursor is moving around in the area. However, I am unable to completely match the mouse cursor to the dot. This first image here shows how it is supposed to look when the mouse is moving around in the magnified area. I use the program, PSR, or Problem Steps Recorder for short, in order to capture the mouse cursor and the background screenshot together. This second image here shows the same scenario, only that the mouse cursor is moved to the far right and far down of the area. This is just one of the situations where the mouse cursor isn't directly on top of the dot, and the dot moves faster than the mouse cursor. Here's the current code: public class DeadGame { public InputHandler inputHandler; public DeadGame(GameComponent g) { inputHandler = new InputHandler(); g.addMouseListener(inputHandler); g.addMouseMotionListener(inputHandler); } public void tick() { } public void render(int[] data) { /* * Codes that are marked with // are debugging codes; tinkering with the aspect ratios and math to try to get the dot to stay with the cursor. * Apparently, this is incorrect. * * */ // double ratio = (double) GameComponent.WIDTH / (double) GameComponent.HEIGHT; // int x = (int) ((inputHandler.mouseX / GameComponent.SCALE) * ratio); // int y = (int) ((inputHandler.mouseY / GameComponent.SCALE) * ratio); // // System.out.printf("Mouse: %d, %d (Correct: %d, %d) Aspect Ratio: %f\n", x, y, (int) (inputHandler.mouseX * ratio), (int) (ratio * inputHandler.mouseY), (double) GameComponent.WIDTH / (double) GameComponent.HEIGHT); // // int length = y * (GameComponent.WIDTH / GameComponent.SCALE) + x; // if (length < data.length && length > 0) // data[length] = -1; int x = inputHandler.mouseX / GameComponent.SCALE; int y = inputHandler.mouseY / GameComponent.SCALE; int length = y * (GameComponent.WIDTH / GameComponent.SCALE) + x; if (length < data.length && length > 0) data[length] = -1; } } InputHandler code: @Override public void mouseMoved(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } How do I manage to magnify the area? Below are the codes used to create the effect. Variables used: public static final int WIDTH = 640; public static final int HEIGHT = 480; public static final int SCALE = 4; Initialization code used for the background area. I used BufferedImage and java.awt.Canvas: public GameComponent() { threadRunning = false; Dimension d = new Dimension(WIDTH, HEIGHT); this.setPreferredSize(d); this.setMaximumSize(d); this.setMinimumSize(d); this.setSize(d); image = new BufferedImage(WIDTH / SCALE, HEIGHT / SCALE, BufferedImage.TYPE_INT_ARGB); pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); game = new DeadGame(this); } Code used to render it to the back buffer. I suspect that this is the place where the aspect ratio is off entirely here, but I can't really tell. Main suspects are the java.awt.Canvas.getWidth() and java.awt.Canvas.getHeight() functions. public void render() { BufferStrategy bs = this.getBufferStrategy(); if (bs == null) { this.createBufferStrategy(3); bs = this.getBufferStrategy(); } int w = this.getWidth(); int h = this.getHeight(); Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, w, h); clear(); game.render(pixels); g.drawImage(image, 0, 0, w, h, null); g.dispose(); bs.show(); } So, what do I have to do to fix this issue? Thanks in advance.
https://www.gamedev.net/topic/650073-trying-to-get-the-ratio-correct-cant-match-the-mouse-cursors-x-and-y-to-the-white-dot/
CC-MAIN-2017-17
refinedweb
533
53.47
Nearest Neighbors The GraphLab Create nearest neighbors toolkit is used to find the rows in a data table that are most similar to a query row. This is a two-stage process, analogous to many other GraphLab Create toolkits. First we create a NearestNeighborsModel, using a reference dataset contained in an SFrame. Next we query the model, using either the query or the similarity_graph method. Each of these methods is explained further below. For this chapter we use an example dataset of house attributes and prices, downloaded from Turi's public datasets bucket. import graphlab as gl import os if os.path.exists('houses.csv'): sf = gl.SFrame.read_csv('houses.csv') else: data_url = '' sf = gl.SFrame.read_csv(data_url) sf.save('houses.csv') sf.head(5) +------+---------+------+--------+------+-------+ | tax | bedroom | bath | price | size | lot | +------+---------+------+--------+------+-------+ | 590 | 2 | 1.0 | 50000 | 770 | 22100 | | 1050 | 3 | 2.0 | 85000 | 1410 | 12000 | | 20 | 3 | 1.0 | 22500 | 1060 | 3500 | | 870 | 2 | 2.0 | 90000 | 1300 | 17500 | | 1320 | 3 | 2.0 | 133000 | 1500 | 30000 | +------+---------+------+--------+------+-------+ [5 rows x 6 columns] Because the features in this dataset have very different scales (e.g. price is in the hundreds of thousands while the number of bedrooms is in the single digits), it is important to normalize the features. In this example we standardize so that each feature is measured in terms of standard deviations from the mean (see Wikipedia for more detail). In addition, both reference and query datasets may have a column with row labels, but for this example we let the model default to using row indices as labels. for c in sf.column_names(): sf[c] = (sf[c] - sf[c].mean()) / sf[c].std() First, we create a nearest neighbors model. We can list specific features to use in our distance computations, or default to using all features in the reference SFrame. In the model summary below the following code snippet, note that there are three features, because our second command specifies three numeric SFrame columns as features for the model. There are also three unpacked features, because each feature is in its own column. model = gl.nearest_neighbors.create(sf) model = gl.nearest_neighbors.create(sf, features=['bedroom', 'bath', 'size']) model.summary() Class : NearestNeighborsModel Attributes ---------- Distance : euclidean Method : ball tree Number of examples : 15 Number of feature columns : 3 Number of unpacked features : 3 Total training time (seconds) : 0.0091 Ball Tree Attributes -------------------- Tree depth : 1 Leaf size : 1000 To retrieve the five closest neighbors for new data points or a subset of the original reference data, we query the model with the query method. Query points must also be contained in an SFrame, and must have columns with the same names as those used to construct the model (additional columns are allowed, but ignored). The result of the query method is an SFrame with four columns: query label, reference label, distance, and rank of the reference point among the query point's nearest neighbors. knn = model.query(sf[:5], k=5) knn.head() +-------------+-----------------+----------------+------+ | query_label | reference_label | distance | rank | +-------------+-----------------+----------------+------+ | 0 | 0 | 0.0 | 1 | | 0 | 5 | 0.100742954001 | 2 | | 0 | 7 | 0.805943632008 | 3 | | 0 | 10 | 1.82070683014 | 4 | | 0 | 2 | 1.83900997922 | 5 | | 1 | 1 | 0.0 | 1 | | 1 | 8 | 0.181337317202 | 2 | | 1 | 4 | 0.181337317202 | 3 | | 1 | 11 | 0.322377452803 | 4 | | 1 | 12 | 0.705200678007 | 5 | +-------------+-----------------+----------------+------+ [10 rows x 4 columns] In some cases the query dataset is the reference dataset. For this task of constructing the similarity_graph on the reference data, the model's similarity_graph can be used. For brute force models it can be almost twice as fast, depending on the data sparsity and chosen distance function. By default, the similarity_graph method returns an SGraph whose vertices are the rows of the reference dataset and whose edges indicate a nearest neighbor match. Specifically, the destination vertex of an edge is a nearest neighbor of the source vertex. similarity_graph can also return results in the same form as the query method if so desired. sim_graph = model.similarity_graph(k=3) sim_graph.show(vlabel='id', arrows=True) Distance functions The most critical choice in computing nearest neighbors is the distance function that measures the dissimilarity between any pair of observations. For numeric data, the options are euclidean, manhattan, cosine, and transformed_dot_product. For data in dictionary format (i.e. sparse data), jaccard and weighted_jaccard are also options, in addition to the numeric distances. For string features, use levenshtein distance, or use the text analytics toolkit's count_ngrams feature to convert strings to dictionaries of words or character shingles, then use Jaccard or weighted Jaccard distance. Leaving the distance parameter set to its default value of auto tells the model to choose the most reasonable distance based on the type of features in the reference data. In the following output cell, the second line of the model summary confirms our choice of Manhattan distance. model = gl.nearest_neighbors.create(sf, features=['bedroom', 'bath', 'size'], distance='manhattan') model.summary() Class : NearestNeighborsModel Attributes ---------- Distance : manhattan Method : ball tree Number of examples : 15 Number of feature columns : 3 Number of unpacked features : 3 Total training time (seconds) : 0.013 Ball Tree Attributes -------------------- Tree depth : 1 Leaf size : 1000 Distance functions are also exposed in the graphlab.distances module. This allows us not only to specify the distance argument for a nearest neighbors model as a distance function (rather than a string), but also to use that function for any other purpose. In the following snippet we use a nearest neighbors model to find the closest reference points to the first three rows of our dataset, then confirm the results by computing a couple of the distances manually with the Manhattan distance function. model = gl.nearest_neighbors.create(sf, features=['bedroom', 'bath', 'size'], distance=gl.distances.manhattan) knn = model.query(sf[:3], k=3) knn.print_rows() sf_check = sf[['bedroom', 'bath', 'size']] print "distance check 1:", gl.distances.manhattan(sf_check[2], sf_check[10]) print "distance check 2:", gl.distances.manhattan(sf_check[2], sf_check[14]) +-------------+-----------------+-----------------+------+ | query_label | reference_label | distance | rank | +-------------+-----------------+-----------------+------+ | 0 | 0 | 0.0 | 1 | | 0 | 5 | 0.100742954001 | 2 | | 0 | 7 | 0.805943632008 | 3 | | 1 | 1 | 0.0 | 1 | | 1 | 8 | 0.181337317202 | 2 | | 1 | 4 | 0.181337317202 | 3 | | 2 | 2 | 0.0 | 1 | | 2 | 10 | 0.0604457724006 | 2 | | 2 | 14 | 1.61656820464 | 3 | +-------------+-----------------+-----------------+------+ [9 rows x 4 columns distance check 1: 0.0604457724006 distance check 2: 1.61656820464 GraphLab Create also allows composite distances, which allow the nearest neighbors tool (and other distance-based tools) to work with features that have different types. Specifically, a composite distance is a weighted sum of standard distances applied to subsets of features, specified in the form of a Python list. Each element of a composite distance list contains three things: - a list or tuple of feature names - a standard distance name - a multiplier for the standard distance. In our house price dataset, for example, suppose we want to measure the difference between numbers of bedrooms and baths with Manhattan distance and the difference between house and lot sizes with Euclidean distance. In addition, we want the Euclidean component to carry twice as much weight. The composite distance for this would be: my_dist = [[['bedroom', 'bath'], 'manhattan', 1], [['size', 'lot'], 'euclidean', 2]] This list can be passed to the distance parameter just like a standard distance function name or handle. model = gl.nearest_neighbors.create(sf, distance=my_dist) model.summary() Class : NearestNeighborsModel Attributes ---------- Method : brute_force Number of distance components : 2 Number of examples : 15 Number of feature columns : 4 Number of unpacked features : 4 Total training time (seconds) : 0.0017 If we specify the distance parameter as auto, a composite distance is created where each type of feature is paired with the most appropriate distance function. Please see the documentation for the GraphLab Create distances module for more on composite distances. Search methods Another important choice in model creation is the method. The brute_force method computes the distance between a query point and each of the reference points, with a run time linear in the number of reference points. Creating a model with the ball_tree method takes more time, but leads to much faster queries by partitioning the reference data into successively smaller balls and searching only those that are relatively close to the query. The default method is auto which chooses a reasonable method based on both the feature types and the selected distance function. The method parameter is also specified when the model is created. The third row of the model summary confirms our choice to use the ball tree in the next example. model = gl.nearest_neighbors.create(sf, features=['bedroom', 'bath', 'size'], method='ball_tree', leaf_size=5) model.summary() Class : NearestNeighborsModel Attributes ---------- Method : ball_tree Number of distance components : 1 Number of examples : 15 Number of feature columns : 3 Number of unpacked features : 3 Total training time (seconds) : 0.0253 Ball Tree Attributes -------------------- Tree depth : 3 Leaf size : 5 If the ball tree is used, it's important to choose an appropriate value for the 'leaf_size' parameter, which controls how many observations are stored in each leaf of the ball tree. By default, this is set so that the tree is no more than 12 levels deep, but larger or smaller values may lead to quicker queries depending on the shape and dimension of the data. Our houses example only has 15 rows, so the leaf_size parameter (and the ball_tree method for that matter) are not too useful, but for illustration purposes we set the leaf size to 5 above. Missing data The reference dataset that is used to create the nearest neighbors model cannot have missing data. Please use the SFrame.fillna and SFrame.dropna utilities to preprocess missing values before creating a nearest neighbors model. On the other hand, data passed to the query method can have missing data. For numeric columns, missing values are imputed to be the mean of the corresponding column in the reference dataset used to create the model. Missing values in string columns are imputed as empty strings.
https://turi.com/learn/userguide/nearest_neighbors/nearest_neighbors.html
CC-MAIN-2017-09
refinedweb
1,652
56.45
Hooks were introduced to React in February 2019 to improve code readability. We already discussed React hooks in previous articles, but this time we are examining how hooks work with TypeScript. Prior to hooks, React components used to have two flavors: - Classes that handle a state - Functions that are fully defined by their props A natural use of these was to build complex container components with classes and simple presentational components with pure functions. What Are React Hooks? Container components handle state management and requests to the server, which will be then called in this article side effects. The state will be propagated to the container children through the props. But as the code grows, functional components tend to be transformed as container components. Upgrading a functional component into a smarter one is not that painful, but it is a time-consuming and unpleasant task. Moreover, distinguishing presenters and containers very strictly is not welcome anymore. Hooks can do both, so the resulting code is more uniform and has almost all the benefits. Here is an example of adding a local state to a small component that is handling a quotation signature. // put signature in local state and toggle signature when signed changes function QuotationSignature({quotation}) { const [signed, setSigned] = useState(quotation.signed); useEffect(() => { fetchPost(`quotation/${quotation.number}/sign`) }, [signed]); // effect will be fired when signed changes return <> <input type="checkbox" checked={signed} onChange={() => {setSigned(!signed)}}/> Signature </> } There is a big bonus to this—coding with TypeScript was great with Angular but bloated with React. However, coding React hooks with TypeScript is a pleasant experience. TypeScript with Old React TypeScript was designed by Microsoft and followed the Angular path when React developed Flow, which is now losing traction. Writing React classes with naive TypeScript was quite painful because React developers had to type both props and state even though many keys were the same. Here is a simple domain object. We make a quotation app, with a Quotation type, managed in some crud components with state and props. The Quotation can be created, and its associated status can change to signed or not. interface Quotation{ id: number title:string; lines:QuotationLine[] price: number } interface QuotationState{ readonly quotation:Quotation; signed: boolean } interface QuotationProps{ quotation:Quotation; } class QuotationPage extends Component<QuotationProps, QuotationState> { // ... } But imagine the QuotationPage will now ask the server for an id: for example, the 678th quotation made by the company. Well, that means the QuotationProps does not know that important number—it’s not wrapping a Quotation exactly. We have to declare much more code in the QuotationProps interface: interface QuotationProps{ // ... all the attributes of Quotation but id title:string; lines:QuotationLine[] price: number } We copy all attributes but the id in a new type. Hm. That makes me think of old Java, which involved writing a bunch of DTOs. To overcome that, we will increase our TypeScript knowledge to bypass the pain. Benefits of TypeScript with Hooks By using hooks, we will be able to get rid of the previous QuotationState interface. To do this, we will split QuotationState into two different parts of the state. interface QuotationProps{ quotation:Quotation; } function QuotationPage({quotation}:QuotationProps){ const [quotation, setQuotation] = useState(quotation); const [signed, setSigned] = useState(false); } By splitting the state, we don’t have to create new interfaces. Local state types are often inferred by the default state values. Components with hooks are all functions. So, we can write the same component returning the FC<P> type defined in the React library. The function explicitly declares its return type, setting along the props type. const QuotationPage : FC<QuotationProps> = ({quotation}) => { const [quotation, setQuotation] = useState(quotation); const [signed, setSigned] = useState(false); } Evidently, using TypeScript with React hooks is easier than using it with React classes. And because strong typing is a valuable security for code safety, you should consider using TypeScript if your new project uses hooks. You should definitely use hooks if you want some TypeScript. There are numerous reasons why you could avoid TypeScript, using React or not. But if you do choose to use it, you should definitely use hooks, too. Specific Features of TypeScript Suitable for Hooks In the previous React hooks TypeScript example, I still have the number attribute in the QuotationProps, but there is yet no clue of what that number actually is. TypeScript gives us a long list of utility types, and three of them will help us with React by reducing the noise of many interface descriptions. Partial<T>: any sub keys of T Omit<T, 'x'>: all keys of T except the key x Pick<T, 'x', 'y', 'z'>: Exactly x, y, zkeys from T In our case, we would like Omit<Quotation, 'id'> to omit the id of the quotation. We can create a new type on the fly with the type keyword. Partial<T> and Omit<T> does not exist in most typed languages such as Java but helps a lot for examples with Forms in front-end development. It simplifies the burden of typing. type QuotationProps= Omit<Quotation, id>; function QuotationPage({quotation}:QuotationProps){ const [quotation, setQuotation] = useState(quotation); const [signed, setSigned] = useState(false); // ... } Now we have a Quotation with no id. So, maybe we could design a Quotation and PersistedQuotation extends Quotation. Also, we will easily resolve some recurrent if or undefined problems. Should we still call the variable quotation, though it’s not the full object? That’s beyond the scope of this article, but we will mention it later on anyway. However, now we are sure that we will not spread an object we thought had a number. Using Partial<T> does not bring all these guarantees, so use it with discretion. Pick<T, ‘x’|’y’> is another way to declare a type on the fly without the burden of having to declare a new interface. If a component, simply edit the Quotation title: type QuoteEditFormProps= Pick<Quotation, 'id'|'title'> Or just: function QuotationNameEditor({id, title}:Pick<Quotation, 'id'|'title'>){ ...} Don’t judge me, I am a big fan of Domain Driven Design. I’m not lazy to the point that I don’t want to write two more lines for a new interface. I use interfaces for precisely describing the Domain names, and these utility functions for local code correctness, avoiding noise. The reader will know that Quotation is the canonical interface. Other Benefits of React Hooks The React team always viewed and treated React as a functional framework. They used classes so that a component could handle its own state, and now hooks as a technique allowing a function to keep track of the component state. interface Place{ city:string, country:string } const initialState:Place = { city: 'Rosebud', country: 'USA' }; function reducer(state:Place, action):Partial<Place> { switch (action.type) { case 'city': return { city: action.payload }; case 'country': return { country: action.payload }; } } function PlaceForm() { const [state, dispatch] = useReducer(reducer, initialState); return ( <form> <input type="text" name="city" onChange={(event) => { dispatch({ type: 'city',payload: event.target.value}) }} value={state.city} /> <input type="text" name="country" onChange={(event) => { dispatch({type: 'country', payload: event.target.value }) }} value={state.country} /> </form> ); } Here is a case where using Partial is safe and a good choice. Though a function can be executed numerous times, the associated useReducer hook will be created only once. By naturally extracting the reducer function out of the component, the code can be divided into multiple independent functions instead of multiple functions inside a class, all linked to the state inside the class. This is clearly better for testability—some functions deal with JSX, others with behavior, others with business logic, and so on. You (almost) don’t need Higher Order Components anymore. The Render props pattern is easier to write with functions. So, reading the code is easier. Your code is not a flow of classes/functions/patterns but a flow of functions. However, because your functions are not attached to an object, it may be difficult to name all these functions. TypeScript Is Still JavaScript JavaScript is fun because you can tear your code in any direction. With TypeScript, you can still use keyof to play with the keys of objects. You can use type unions to create something unreadable and unmaintainable - no, I don’t like those. You can use type alias to pretend a string is a UUID. But you can do it with null safety. Be sure your tsconfig.json has the "strict":true option. Check it before the start of the project, or you will have to refactor almost every line! There are debates on the level of typing you put in your code. You can type everything or let the compiler infer the types. It depends on the linter configuration and team choices. Also, you can still make runtime errors! TypeScript is simpler than Java and avoids covariance/contravariance troubles with Generics. In this Animal/Cat example, we have an Animal list that is identical to the Cat list. Unfortunately, it’s a contract in the first line, not the second. Then, we add a duck to the Animal list, so the list of Cat is false. interface Animal {} interface Cat extends Animal { meow: () => string; } const duck = {age: 7}; const felix = { age: 12, meow: () => "Meow" }; const listOfAnimals: Animal[] = [duck]; const listOfCats: Cat[] = [felix]; function MyApp() { const [cats , setCats] = useState<Cat[]>(listOfCats); // Here the thing: listOfCats is declared as a Animal[] const [animals , setAnimals] = useState<Animal[]>(listOfCats) const [animal , setAnimal] = useState(duck) return <div onClick={()=>{ animals.unshift(animal) // we set as first cat a duck ! setAnimals([...animals]) // dirty forceUpdate } }> The first cat says {cats[0].meow()}</div>; } TypeScript has only a bivariant approach for generics that is simple and helps JavaScript developer adoption. If you name your variables correctly, you will rarely add a duck to a listOfCats. Also, there is a proposal for adding in and out contracts for covariance and contravariance. Conclusion I recently came back to Kotlin, which is a good, typed language, and it was complicated to type complex generics correctly. You don’t have that generic complexity with TypeScript because of the simplicity of duck typing and bivariant approach, but you have other problems. Perhaps you didn’t encounter a lot of problems with Angular, designed with and for TypeScript, but you had them with React classes. TypeScript was probably the big winner of 2019. It gained React but is also conquering the back-end world with Node.js and its ability to type old libraries with quite simple declaration files. It’s burying Flow, though some go all the way with ReasonML. Now, I feel that hooks+TypeScript is more pleasant and productive than Angular. I wouldn’t have thought that six months ago. Understanding the basics Can I use TypeScript with React? TypeScript is now very good for React if you use hooks with it. What are the benefits of TypeScript? TypeScript gives code safety. The IDE gives you most code errors so you really spend less time debugging your app in the console. What's the big deal with React Hooks? React Hooks simplify code evolution and maintainability. Hooks also provide a set of general patterns for general problems. What is the difference between container and component? Containers have business logic, not components. So unlike containers, components can be reused in different parts of the app, even in different apps.
https://www.toptal.com/react/react-hooks-typescript-example
CC-MAIN-2020-24
refinedweb
1,884
56.25
oh yeah, here we go installing now... 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 Still waiting for those phones to come out. I'm in the market for a smartphone right now, and the end of the year is still far away... Updating my phones as we speak Just done my phone, nice and easy, now to see if if there are any changes since 7712 I'd update my HD7, but I'd have to find it under all the dust and charge it up. Worst phone purchase ever. having problems with my LG phone but it looks like im not alone atleast.. hopefully it'll get resolved soon... :/ I have been at "Please wait while we determine the amount of disk space required to complete the update." for quite a while now. I may have a lot of content on my device, though I did delete several videos before I started the update process. My device is a developer unlocked (isv) mango pre-release version. Update: My Zune desktop is still stuck at determining space, but the phone itself says it has upgraded. Update 2: I canceled Zune desktop, then a second update, isv clean up, is now running. Update 3: All updates successful 1 hour ago,rhm wrote I'd update my HD7, but I'd have to find it under all the dust and charge it up. Worst phone purchase ever. The speaker is too quiet, it's got the typical sh1tty-quality HTC camera, and it has one of the tiniest batteries I've ever seen. Overall, I'm far from satisfied with the purchase, but it still offers a far better experience than my Android phone. Meh. Sprint still hasn't pushed it out. I had picked up an HTC Arrive, and returned it so that I could use my old BlackBerry. I really felt out of place with all the social integration stuff, that I didn't care to participate in. It seemed to be a total productivity killer. I've disabled my Facebook account on several occasions, but in the end found it easier to just create an Outlook rule to delete any emails from Facebook. I really don't care for Metro, the pivot control, or the tiles. However, I am really impressed with the quality of the namespaces, classes, and methods. I guess beauty is in the eye of the beholder. -Josh I'm glad to see Microsoft's being able to get all the carriers to test Mango so quickly and sign-off on the roll-out of the update. The NoDo roll-out was a near disaster in comparison. LOLz, this is so strange, but, I couldn't BK my phone for the second update (I suppose the first is just NoDo). Always gets to 3% and the phone restarts. But, after I removed a lot of movies, spongebob, music, I am fine now. Doing the final updates now. I am guess they think my USB is too slow because it takes a long time to 3%. Seems like they only monitor % as speed test instead of real bandwidth. Or maybe it is slower to transfer those contents that I deleted? I am not sure, but, seems like it is better to remove many stuff before BK. The Zune 'force' trick has never worked for me -- possibly due to low bandwidth, I can never get the timing right (either 'your phone is up to date' or 'there was a problem checking, make sure internet is connected' errors). Will probably have to wait for 'official' release slot from phone provider. Herbie The Samsung Focus S is essentially the Samsung Galaxy S II running mango. Typing from mango Oops, double posts. Typing from mango Thread Closed This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
http://channel9.msdn.com/Forums/Coffeehouse/MANGO
CC-MAIN-2014-10
refinedweb
677
71.75
Single Sign On (SSO) in .NET: Okay. -, if you have already read part 1 of this article then you don’t need any explanation of lines of code below, it’s pretty straight forward: using System;); }) { } } } Once global.asax.cs is set, next is the turn to write code in frmReceiveData.aspx.cs. The aspx file of this form needs no components and will be written as follows: <%@;.ArtifactResolution; using ComponentSpace.SAML2.Profiles.SSOBrowser; Yes, it’s good to have all these namespaces added in your code. Let’s take a look at the Page_Load event: protected void Page_Load(object sender, EventArgs e) { try { //Trace.Write("SP", "Assertion consumer service"); // Receive the SAML response. SAMLResponse samlResponse = null; string relayState = null; ReceiveSAMLResponse(out samlResponse, out relayState); // Process the SAML response. ProcessSAMLResponse(samlResponse, relayState); } catch (Exception exception) { Response.Write(exception.ToString()); } } Page_Load does nothing special except calling appropriate methods who actually do the job. So without wasting further time, let’s take a look at ReceiveSAMLResponse method, which is the first function to receive SAML packet from Identity Provider: // Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { //Trace.Write("SP", "Receiving SAML response"); // Receive the SAML response. 01 XmlElement samlResponseXml = null; 02 ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); 03 X509Certificate2 x509Certificate = (X509Certificate2)Application["idpX509Certificate"]; 04 if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. 05. samlResponse = new SAMLResponse(samlResponseXml); //Trace.Write("SP", "Received SAML response"); } In line # 1 we are declaring an XML Element object, this object will hold the information extracted from SAML packet. In line # 2 we are actually extracting SAML packet from HTTP Request and stuffing it into samlResponseXml object. In line # 3 we are instantiating an X509Certificate object via an application level variable which was created in global.asax.cs. Remember the SAML response extracted so far and stuffed so far in XML Element is encrypted one, so we need to decrypt it using the X509Certificate object. Line # 4 is in which we are verifying whether that samlResponseXml object can be decrypted by our X509Certificate or not. If not, then we throw an exception, otherwise it will decrypt the data and execute line # 5, in which we create a new SAMLResponse object, which is also an output argument of this method, and stuff all data in it. So far we’ve decrypted and extracted the Response object from HTTP request, but we haven’t yet decrypted the actual data. That task will be done by ProcessSAMLResponse method, given as follows: // Process the SAML response. private void ProcessSAMLResponse(SAMLResponse samlResponse, string relayState) { //Trace.Write("SP", "Processing SAML response"); // Check whether the SAML response indicates success. 01 if (!samlResponse.IsSuccess()) { throw new ArgumentException("Received error response"); } // Extract the asserted identity from the SAML response. 02 SAMLAssertion samlAssertion = null; if (samlResponse.GetAssertions().Count > 0) { 03 samlAssertion = samlResponse.GetAssertions()[0]; } else { throw new ArgumentException("No assertions in response"); } // Enforce single use of the SAML assertion. if (!AssertionIDCache.Add(samlAssertion)) { throw new ArgumentException("The SAML assertion has already been used"); } if (samlAssertion.Subject.NameID != null) { 04 Session["MemberId"] = samlAssertion.GetAttributeValue("MemberId"); Session["Name"] = samlAssertion.GetAttributeValue("Name"); Session["Phone"] = samlAssertion.GetAttributeValue("Phone"); } else { throw new ArgumentException("No name in subject"); } // Redirect to the requested URL. 05 Response.Redirect(relayState, false); } Now let’s see what lines need explanation. Let’s talk about line 01, SAML Response object has a method which returns True or False based upon whether SAML Response was successfully created or not. Line # 2 is just a declaration of a SAML Assertion object. SAML Response contains of one or more assertions, called SAML Assertions. These assertions contain actual data. In line # 3 we are extracting 0th assertion from the response object. Since we are the senders ourselves, we know there was only one assertion in response object. After the assertion has been extracted successfully, now is the turn to extract the actual data, line # 4 and other lines in the same block are performing that task. Finally, in line # 5 we are redirecting to the actual web page that might have some contents in it; and that would be our Default.aspx. Default.aspx is very straight forward. Let me show you it’s code real quick and then we’ll be all set to run our applications. <%@ Page <html xmlns="" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> And its CS file looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace prjServiceProvider1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["MemberId"] != null && Session["Name"] != null && Session["Phone"] != null) { Response.Write("SAML Assertion Received Successfully<BR><BR>"); if (Session["MemberId"] != null) Response.Write("<BR>Member ID: " + Session["MemberId"].ToString()); if (Session["Name"] != null) Response.Write("<BR>Name: " + Session["Name"].ToString()); if (Session["Phone"] != null) Response.Write("<BR>Phone: " + Session["Phone"].ToString()); } else Response.Write("SAML Assertion Failed to Receive."); } } } Very straight forward! No explanation needed. Now let’s run the Identity Provider app and see how it passes the data to Service Provider. I ran the Identity Provider app and put some data in the fields, then I clicked Go SAML button. And the next window that I saw was the following: Note the red circles in the last two snapshots, the address of application changed when I clicked on the Go SAML button, which means the correct data was passed from one web application to a different web application correctly and successfully. Well folks that’s all from my side today. Please provide me with the feedback on this article and don’t forget to ask me for the free copy of the source code if you are interested. Have a good day! 🙂 Mukarram, what an excellent tutorial. Thank you, because this is exactly what I’ve been looking for. Any chance I can get the source from you? Thanks very much! jr Comment by Jim Roth — December 29, 2010 @ 2:49 pm Good job Mukarram! Like Jim, any chance I can get the source from you? Comment by Tommy J. — April 7, 2011 @ 11:07 pm Hi Mukhtar, I have a doubt. Can we work with SAML without service provider like ComponentSpace? If so please let me know the way. Thanks & Regards, Prabhu.P Comment by Prabhu — June 3, 2011 @ 3:22 pm The answer to your question is, Yes. SAML is just a protocol. You can implement it by writing your own base class libraries. But that will involve getting profound knowledge of the protocol and writing a few layers of classes to implement it; means, more time, research and effort. In my case time was bigger issue than cost, that’s why I implemented it with ComponentSpace. Good luck and thank you! Comment by Mukarram Mukhtar — June 3, 2011 @ 5:08 pm Hi Mukhtar, Thanks for your valuable reply. What about the certificate and pfx files presented in service providers and identity providers? Do we need to create own certificate or need to purchase? Regards Prabhu.P Comment by Prabhu — June 6, 2011 @ 9:54 am Prabhu, You’ll have to create your own certificates regardless you use ComponentSpace. Your network administrator should know everything about how to create those. I also had my company’s system engineer create those files for me. Comment by Mukarram Mukhtar — June 6, 2011 @ 2:10 pm Hi Mukhtar, Thanks for your comments and suggestions. Thanks & Regards, Prabhu.P Comment by Prabhu — June 6, 2011 @ 4:23 pm Hi, thanks so much for the tutorial. May I have a copy of the source? Comment by Barb — November 16, 2011 @ 2:40 pm Great post! Can you also do a demo on the single log out part from both IdP and SP using ComponentSpace? Thank you. Comment by hanwawa — December 15, 2011 @ 5:09 pm i think you actually brought up an excellent point, i should really write a Part 3 on logging out in SSO series. but the tricky part is, let’s see when do i get time to do it 😉 Comment by Mukarram Mukhtar — December 15, 2011 @ 6:16 pm Great! I am looking forward to it 🙂 Comment by hanwawa — December 15, 2011 @ 6:48 pm Hi Mukarram, Thank you so much for your useful post, I learned how to implement the SSO. Please provide me the source you used for this tutorial it will be very helpful for me. Thanks. Comment by Sam — December 23, 2011 @ 5:51 am Hi Mukarram thanks for a great solution. I am gettting an error saying private key is null can you help me. Comment by ankit — May 2, 2012 @ 12:10 pm Sure, Ankit. I’ve e-mailed you project source files of this application. Good luck! Comment by Mukarram Mukhtar — May 3, 2012 @ 6:15 pm Hi Mukarram, thank you for your excellent post. I have found it while I was researching the info on SAML. Could you please email the source to me? Thanks in advance, KS Comment by Mujislav Zelenko — July 5, 2012 @ 3:17 pm Hi Mukarram; Very good job .. Can you send me the source code i shall be very thankful to you Thanks /Nasir Comment by Nasir — August 24, 2012 @ 2:29 pm 9.Hi Mukarram, Great start. Could you please email the source to me? Thanks in advance, William D Beaty Comment by William D Beaty — April 8, 2013 @ 4:38 pm I just like the helpful information you provide to your articles. I’ll bookmark your weblog and check once more right here frequently. I am somewhat sure I will be informed many new stuff proper right here! Best of luck for the following! Comment by Haarausfall — April 17, 2013 @ 8:02 am Hi MM, Could you please send your sample code to my email id. I had problems running my own code. Thanks in advance. Regards, TK Comment by VIm — May 23, 2013 @ 6:25 pm Hello Mukkaram I Liked your Post, Iam working on SAML too, I have hard time working with private and Public key … could you please Email me the source Code … Thank You in Advance… Comment by Qumar — May 29, 2013 @ 4:55 pm
https://mukarrammukhtar.wordpress.com/single-sign-on-p-2/
CC-MAIN-2018-51
refinedweb
1,744
58.38
Login Form using Ajax Login Form using Ajax This section provides you an easy and complete implementation of login form...;/action> Develop a Login Form Using Ajax : The GUI of the application 2.1.8 Login Form Struts 2.1.8 Login Form  ... to validate the login form using Struts 2 validator framework. About the example: This example will display the login form to the user. If user enters Login Name Ajax and complete implementation of login form using the Ajax (DOJO). Lets... Struts 2 Ajax In this section, we explain you Ajax based development in Struts 2. Struts 2 provides built Login Form Login Form Login form in struts: Whenever you goes to access data from... for a login form using struts. UserLoginAction Class: When you download Login Login Form with jsp  ... of login form will really help to understand jsp page. In this example we... are going to insert the data in the login form which will be displayed onto Login Form of +,on clicking which a login form appears. Only the middle column is different for each of the page. How to write a code for login authentication so...Login Form I have 8 jsp pages.Each of them has three columns:Left ajax ajax I am facing following problem, I am using ajax to get... links. whenever user clicks on this link the output must be displayed on the right... != "undefined"){ xmlHttp= new XMLHttpRequest Struts 2 Session Scope In this section, you will learn to create an AJAX application in Struts2... AJAX - Ajax : var alpha; var xmlhttp; function showDetails() { alpha... ("Your browser does not support AJAX!"); return; } var url="... staring with: Your results will be displayed here: 2) check.jsp Ajax - Ajax Ajax how the images are displayed when the user leaves a field in the form... like we have in the naukri.com registration website...... I have... that : form1.html where all Ajax code is written : function showH struts(DWR) - Ajax struts(DWR) i want to pass a combo box value from my jsp page...; } } if (!xhr && typeof XMLHttpRequest != 'undefined...").innerHTML = "ur browser doestnot support ajax java.awt.event.*; class Login { JButton SUBMIT; JLabel label1,label2; final JTextField text1,text2; { final JFrame f=new JFrame("Login Form...(); ResultSet rs=st.executeQuery("select * from login where username='"+value1 dwr with struts2 - Struts dwr with struts2 CAn u help me how to use dwr with struts2jax user interface - Ajax Ajax user interface hello could anyone help my requirement is to design the database interaction using AJAX my requirement is a table will be displayed with checkbox as its first column when we select the checkbox Display Logo on login form using swing displayed on the login form. Example: import javax.swing.*; import java.sql....Display Logo on login form using swing In this tutorial, you will learn how to display a logo in login form using swing components. Here is an example where displaying in ajax - Ajax displaying in ajax hi.. I have an Ajax page ,request gone to server ana details are bought... the response should be displayed in the same request... for the answer Hi friend, Ajax example to solve the problem : ajax example Example Ajax Login Example Thanks Ajax Tutorials Collection of top...; Ajax form validation Example Ajax form validation Example Hi, I want to validate my ajax form. Please give me good code login page error login page error How to configure in to config.xml .iam takin to one login form in that form action="/login" .when iam deployee the project... this request." please suggest me. if your login page is prepared Login/Logout With Session class that handles the login request. The Struts 2 framework provides a base...;} } Download this code. Develop Login Form: The GUI of the application consists of login form (Login.jsp). The "Login.jsp" New to struts2 New to struts2 Please let me know the link where to start for struts 2 beginners Struts 2 Tutorials login form validation - JSP-Servlet login form validation hi, how to validate the login form that contains user name and password using post method . the validation should not allow user to login in the address bar thanks regards, an Login form in jscript Login form in jscript For example the html script is <...; charset=utf-8" /> <title>:: validation form::</title> <script...;td <form name="form1" onsubmit
http://www.roseindia.net/tutorialhelp/comment/64001
CC-MAIN-2014-52
refinedweb
725
66.23
I basic, 'ubasic', they basic, we basic; wouldn't you like a speedy BASIC, too? Jun-16 12:09 PM With the two new mechanisms available, it was time to test. Since the motivation for the activity was to get a feel for the improvements, I decided to test a little differently. This time I did not use the profiler, but rather added a simple stopwatch around the execution of the program. The test program was intended to be run forever, so I altered it to run for just 10 generations and then exit. Since I was running this on Windows, I used the QueryPerformanceCounter() api to make my stopwatch: int main(int argc, char* argv[]) { LARGE_INTEGER liFreq; //... so chic LARGE_INTEGER liCtrStart, liCtrEnd; QueryPerformanceFrequency ( &liFreq ); QueryPerformanceCounter ( &liCtrStart ); //setup to execute program. ubasic_init ( _achProgram, false ); //run the program until error 'thrown' do { if ( !setjmp ( jbuf ) ) ubasic_run(); else { printf ( "\nBASIC error\n" ); break; } } while ( ! ubasic_finished() ); QueryPerformanceCounter ( &liCtrEnd ); double dur = (double)(liCtrEnd.QuadPart - liCtrStart.QuadPart) / (double)liFreq.QuadPart; printf ( "duration: %f sec\n", dur ); return 0; } This should give the 'bottom line' numbers on how these two improvements worked out. Plus I wanted to visually see it! Also, I wanted to subtract off the contribution of screen I/O. Screen I/O on Windows console is quite slow, and having that contribute to the numbers would be meaningless for the target platform, since it has a completely different I/O system (SPI LCD? I don't know). This was easy, fortunately, since the I/O from the BASIC is character oriented -- I simply put a conditional compile around the actual output routines: //this lets us suppress screen output, which skews timing numbers //towards console IO away from our program's computation time //#define NO_OUTPUT 1 //write null-terminated string to standard output uint8_t stdio_write ( int8_t * data ) { return 0; return (uint8_t) puts ( (const char*)data ); } //write one character to standard output uint8_t stdio_c ( uint8_t data ) { return data; return (uint8_t)_putch ( data ); } Testing time! I created 4 test scenarios: I also created two flavors: suppressed screen output, and included screen output. I ran each configuration a few times and used the 'best of three' timing for each. I used 'best of three' because wall-clock timing this way can be affected by all sorts of other stuff coincidentally going on in the operating system at the time, so I wanted to have a little insulation from that. With screen output suppressed: And to observe how much the screen I/O contributes to runtime in my test program: Jun-16 12:09 PM As mentioned before, the core 'goto' implementation is in jump_linenum(), and works by restarting parsing of the entire program until the desired line if found. Here is a compacted form: static void jump_linenum(int linenum) { tokenizer_init(program_ptr); while(tokenizer_num() != linenum) { do { //... eat tokens; emit an error if we reach end-of-stream } while(tokenizer_token() != TOKENIZER_NUMBER); } } I was not wanting to do a major re-engineering of the ubasic, so I decided to keep the rest of the system as-is, and only rework this method. The strategy I used here was to make a 'cache' of line-number-to-program-text-offset mappings. Then, when this function is invoked, the cache is consulted to find the offset into the program, and set the parser up there. Because tokenizer_init() is a cheap call, I used it to do the setting up of the parser by simply pretending that the program starts at the target line we found, rather than try to fiddle with the internals of the parser state. A hack, but a convenient one, and ultimately this exercise was to prove the concept that improving jump_linenum() would have a material impact, and how much. For simplicity, my 'cache' was simply an array of structs, and my 'lookup' was simply a linear search. Also, I simply allocated a fixed block of structs. In a production system, this could be improved in all sorts of ways, of course, but here I just wanted to see if it was a worthwhile approach. The struct I used was simple, and there was added a 'setup' method that was called during program initialization time to populate the cache: //HHH a line number lookup cache; this is just proof-of-concept junk typedef struct { uint16_t _nLineno; //the line number uint16_t _nIdx; //offset into program text } LNLC_ENT; LNLC_ENT g_nLines[1000]; //mm-mm-mm. just takin' memory like it's free, and limiting the program to 1000 lines int g_nLineCount = -1; void __setupGotoCache(void) { tokenizer_init(program_ptr); g_nLineCount = 0; //the beginning is a very delicate time while ( tokenizer_token () != TOKENIZER_ENDOFINPUT ) { int nLineNo; const char* pTok; const char* __getAt (void); //(added to tokenizer.c) //we must be on a line number if ( tokenizer_token () != TOKENIZER_NUMBER ) { g_nLineCount = -1; //purge 'goto' cache sprintf ( err_msg, "Unspeakable horror\n" ); stdio_write ( err_msg ); tokenizer_error_print (); longjmp ( jbuf, 1 ); } //remember where we are nLineNo = tokenizer_num (); pTok = __getAt (); //create an entry g_nLines[g_nLineCount]._nLineno = nLineNo; g_nLines[g_nLineCount]._nIdx = pTok - program_ptr; //whizz on past this line while ( tokenizer_token () != TOKENIZER_ENDOFINPUT && tokenizer_token () != TOKENIZER_CR ) { tokenizer_next (); } if ( TOKENIZER_CR == tokenizer_token () ) { tokenizer_next (); } //next entry ++g_nLineCount; //too many lines? if ( g_nLineCount >= COUNTOF ( g_nLines ) ) { g_nLineCount = -1; //purge 'goto' cache sprintf ( err_msg, "Program too long to cache!\n" ); stdio_write ( err_msg ); tokenizer_error_print (); longjmp ( jbuf, 1 ); } } //did we get anything? if not, purge 'goto' cache if ( 0 == g_nLineCount ) //pretty...Read more » Jun-16 12:09 PM It's a little inconvenient for the construction of this back-formed log, but chronologically I had started investigating a potential way of replacing the get_next_token() implementation just prior to the events of the last log entry, wherein I had discovered some data anomalies that changed my opinion about what work would result in the biggest gains for the least costs. But having got past that diversion, I was now more resolved to actually implement and measure results. My background is not in Computer Science -- I am self-taught in software engineering -- and consequently there are holes in my understanding of various formal Computer Science topics. Amongst these is all the theory around the construction of language processors. But I'm at least cursorily familiar with their existence, and I can construct useful web queries. Parsing is one of my least favorite activities, right up there with keyboard debouncing and bitblt routines. Doubtlessly this is because I have always hand-crafted parsers. You can get by with that for simple stuff, but it rapidly becomes an un-fun chore. Many years back I decided to bite-the-bullet and learn about 'regular expressions' as the term applies to software, which are a computerification of some stuff that Noam Chomsky and others did ages ago in the field of linguistics. Suffice it to say that regular expressions (or 'regexes') are a succinct way of express a pattern for matching against a sequence of symbols. Most will be familiar with a very simple form of pattern matching for doing directory listings; e.g. 'ls *.txt' to list all files that end with '.txt'. Regexes are like that on steroids. My boredom with parsing is evidently something of a cultural universal, because there have been tools created to automate the generation of parsers since time immemorial, and they pretty much all use regexes for the first part: 'lexing', or breaking stuff up into tokens ('lexemes'). I.e., exactly what we are trying to do in get_next_token(). (The second part is applying grammar, which we are leaving in the existing ubasic implementation). There are a lot of tools for all the usual reasons: folks make new versions with modern capabilities, folks make versions with more power, folks make versions suited to different execution environments. So, time for shopping... I didn't spend a lot of time researching options, but I did spend a little, and I'll spare you the shopping tales. I decided on using 're2c' to generate the lexer/tokenizer. This tool is pretty simple in what it does: take a list of regular expressions associated with a chunklette of C code to invoke when they match. It doesn't really even create a complete piece of code, but rather is expected to have it's output spewed into the middle of a function that you write, that is the lexical scanner. The code that it generates is a monster switch statement that represents a compiled and optimized Deterministic Finite Automata (DFA) for all the patterns that you have specified. It is held in high regard, and apparently results in more efficient code than some alternative approaches, such as the table-driven approach used in Lex/Flex. It is also minimalistic in that it just spews out pure C code, with no particular library dependencies (not even stdlib, really) since you are expected to do all the I/O needed to provide symbols to it. So it seemed a good match, and a-learnin' I did go. I had not used this tool before, so I did the usual cut-and-paste of the most simple examples I could find for it, and then find the 'hole' where I stick in my regexes. I figured that out fairly quickly, so then I needed to see how to marry all this with the existing ubasic code. There was...Read more » Jun-15 8:01 PM When writing, I try to edit, but I have know that I will fail and there will be silly typos. I have gotten over this. Less so with errors in facts. And so it was the case when I was looking at the data again, and noticed that some things did not quite jibe. For one thing, the time taken for strncmp was shown to be zero, even though it was called 125 million times. Somehow I doubt that. get_next_token()'s implementation for the most part is looping over a list of keywords and calling strncmp(). So it seemed that strncmp()'s execution time was being somehow sucked up into get_next_token()'s. Another thing was that jump_linenum() was being called an awful lot. Doing a quick cross-reference to the call sites for this method, I discovered that it is used for 'goto', but also 'gosub', 'return', 'next', 'if', 'then' -- pretty much anything that changes flow-of-control other than sequentially forward. That makes some sense. But then I noticed the implementation details, and things really made sense: static void jump_linenum(int linenum) { tokenizer_init(program_ptr); while(tokenizer_num() != linenum) { do { do { tokenizer_next(); } while(tokenizer_token() != TOKENIZER_CR && tokenizer_token() != TOKENIZER_ENDOFINPUT); if(tokenizer_token() == TOKENIZER_CR) { tokenizer_next(); } if (tokenizer_token() == TOKENIZER_ENDOFINPUT) { sprintf(err_msg,"Unreachable line %d called from %d\n",linenum,last_linenum); stdio_write(err_msg); tokenizer_error_print(); longjmp(jbuf,1); // jumps back to where setjmp was called - making setjmp now return 1 } } while(tokenizer_token() != TOKENIZER_NUMBER); DEBUG_PRINTF("jump_linenum: Found line %d\n", tokenizer_num()); } } So, the first thing that caught my eye is "tokenizer_init(program_ptr);". That means any time we are changing flow-of-control, we are re-initializing the parsing of the entire program from the beginning. The init call itself is not expensive -- it just sets up some pointers -- but it makes it clear that any time one does a transfer of control, that we are setting up to scan the whole program to find the target line number. The next thing that caught my eye were the loops within. Essentially, they are tokenizing the program, and throwing away all the tokens, except for the end-of-line. This is used to sync the parser to the start of the line (with the line number being the first parsed value) to test if it is the target line number. That's when I had a realization: that probably the reason there is so much time spend in the tokenizer routine 'get_next_token()' is because all transfer-of-controls imply re-parsing the program text up to the target line. In retrospect, maybe this should have been a bit obvious looking at the numbers from the profiler, the 17,186 jump_linenum calls being related to 5,563,383 get_next_token calls, but I didn't think much of it at the time. So, I suddenly got a sinking feeling that I had given bad advice in recommending focusing on improving get_next_token(). That that function still could benefit from improvement, but the real gains might be in simply having it called far less often. The other thing that puzzled me was the apparently free calls to strncmp that were made 125 million times. Now that would be some magic. Having freshly studied jump_linenum(), I hit upon an intuition: maybe information is being lost behind the 'static' declaration. This warrants a little explaining...'static' is an odd C keyword in that is overloaded to mean either of: In this case it means 'private'. Compilers...Read more » Jun-12 3:10 PM - Jun-12 6:01 PM I was eager to get some empirical validation (or negation) of these hypotheses (and maybe even get some new ones). However, I didn't have the actual hardware. On the one hand, you can't draw conclusive inferences when testing on a non-normative platform, but on the other hand, what else can I use. So I decided to go ahead and port the program to a desktop application, and just try to be careful to avoid measuring anything that was not CPU related (like screen I/O), and even then, take the results with a grain of salt. Mostly because of personal familiarity, and partially because of expedience, I decided to port the ubasic into a Windows application. The reasons were: It seems that Microsoft has significantly dumbed-down the profiler in VS, in the past few years. On the upside, it's much easier to start up, but I do miss the granularity of control that I had before. Maybe I'm a masochist. Anyway, for this exercise, I'm using Developer Studio 2013 Community Edition. (Old, I know, but I use virtual machines for my build boxes, and I happened to have one already setup with this version in it.) But first things first: building an application. The needed changes were relatively straightforward, thanks to the clean effort of the [project's authors] -- especially considering how quickly they built this system. Mostly, I needed to do some haquery to simply stub out the hardware-specific stuff (like twiddling gpio), since my test program didn't use those, and then change the video output to go to the screen. Fortunately, since those routines were character-oriented at the point where I was slicing, it was easy for me to change those to stdio things like 'putc' and 'puts'. It still took about 3 hours to do, because you need to also understand what you're cutting out when you're doing the surgery. After that, I was able to run the sample BASIC life program. The screen output was garbage, so maybe it wasn't working, but I could see screen loads of output, followed by a pause, followed by more screen loads of output. Nothing crashed. This is a pretty good indication that things are more-or-less working. Just looking at the output change during the run showed that it was pretty slow. This was running on my 2.8 GHz desktop machine and it was slow, so I can only imagine the experience on the 48 MHz embedded processor. To make it visually look a little better, I tweaked the source code to output a different character, and implemented the 'setxy' function to actually set the cursor position, and then had Windows remember the screen size, which I set to 40x21 (I added a row because doing a putc to the last character position would stimulate a screen scroll). Now it looks a little more like 'Life'. OK, that's enough play time. We should be ready to do a profiling run. As mentioned, this is more easily launched in current Visual Studios. In the case of VS 2013, it is under the DEBUG menu as 'Performance and Diagnostics. (check the docco for your version if different; they move it from time-to-time.) Which will lead to the opening screen. And when you click 'start' you'll get into the 'performance wizard', which is just a sequence of dialog boxes with options. There's several ways to profile. The default is a low-impact sampling method. In retrospect, I probably should have used this to start with -- it usually presents a reasonably accurate view, and it is low-impact. But I was going for precision out of habit, and I chose 'Instrumentation'. This has associated costs. The 'CPU sampling' method presumably works by periodically interrupting the process and seeing where it is, and taking notes. The 'Instrumentation'...Read more » Jun-11 7:17 PM - Jun-11 9:50 PM Initially, I described some speculative causes for 'slowness': I asked what does 'slow' mean in this context, because there really was no baseline: it was a bespoke project unlike any other. It just 'felt' slow at some intuitive level. I asked if I could have a sample BASIC program that felt slow, and that I would take a looky-loo. The sample program happened to be an implementation of Conway's game of Life, and I was familiar with that. They were super popular in the 70s-80s, and I had run one at least once on my actual TRS-80 back in the day, with it's screaming hot ~1.77 MHz Z-80. And Z-80's took 4-23 clocks to do one instruction, so I would think that, yeah, a 48 MHz MIPS could probably do a little better. Now, I had no reason to believe that the video thing I mentioned was relevant here, but I did want to point out that sometimes it's not where you think it is. In that case, you could 'optimize' the BASIC until it took zero CPU time, and that still would not get you improvements to deal with an I/O bound bottleneck, or even a CPU bottleneck that is not where you are looking. Believe me, I have made this mistake before. Speculation is useful as a heuristic to formulate hypotheses, but you really need to test empirically. Not measuring risks wasting development time chasing wild aquatic fowl, and that is itself a kind of speed optimization. Jun-6 4:20 PM - Jun-11 12:44 PM [MS] had reached out asking about a project of mine, the [TRS-80 on a PIC32], and if it was considered stable. I believed it was -- it's an older project of mine, and now it's in enhancement/maintenance mode (though interesting bugs are still found from time-to-time by users!) At length, the reason for the inquiry is that they were thinking about replacing an existing BASIC interpreter that seemed slow with an emulation of a TRS-80. They did a little research and so came across my project. However, as flattered as I was at the notion of porting my emulator to another hardware platform (which I would enjoy), I had to ask: wouldn't a native implementation be faster than an implementation on an emulated CPU? And has there been any analysis done on where the slowdown might be. [The guys involved in the project] had been running at break-neck speed to get it completed for an event, and really hadn't had time to dig into the speed problem. (I know, I saw the commit history -- it was very impressive what was done in such a small time. Integrating this BASIC was just a small part of the overall project.) Since that event was over, there was a little time to come up for breath and look at possible improvements. I had taken a peek at the BASIC implementation. It was straightforward: just 2 C-language modules (4 files, header and implementation), and didn't have any funky library dependencies. The code was originally written by an Adam Dunkels [] as a personal challenge to himself to speed-code a functioning BASIC, and he released it unto the world for anyone to use if they liked. [The project team] had extended it with a bunch of new keywords, and of course adapting to their board's I/O subsystems. OK, those that know me, know that I have a fetish for disassembly. I'd check myself into Betty Ford if they had one for reversers. I don't know why it is -- it just is. It's yielded some good things professionally, but not often enough to slake my thirst. A distant third or fourth place is for code optimization, so for someone to say they have a speed problem in some straightforward C source code... That's going to be a... 'distraction', for me. I guess it's best just to take a look and get it over with....
https://hackaday.io/project/159128-ubasic-and-the-need-for-speed
CC-MAIN-2019-39
refinedweb
3,475
60.04
Step by step: getting your code to compile against Tcl/Tk 8.4 ...while being as lazy as possible...Step 1: Upgrade to Tcl/Tk 8.4.0, or better.If you have alpha or beta releases of Tcl/Tk 8.4, now is the time to replace them with the true 8.4.0 releases.Step 2: Get updated code.OK, so you have code that doesn't compile with 8.4 headers. Check back where you got it and see if an updated release is available that will compile. Better to get the fixes from the author/vendor than have to improvise some yourself.Step 3: Define USE_NON_CONSTOK, so there are no updates available. The incompatibilities between 8.3 and 8.4 headers are completely removed if the symbol USE_NON_CONST is defined when the header files are included. If you have code that compiled with 8.3 headers, defining that symbol will make the same code compile with the 8.4 headers.The simplest way to do this is to add -DUSE_NON_CONST to the CFLAGS definition during the compile, but that assumes a conventional Makefile. The surest way to do this is to find all the instances of #include <tcl.h>in the source code and insert #define USE_NON_CONSTbefore them.Step 4: There is no Step 4That's it! It should work. If not, turn to the provider of the broken package for more help. CONST migration for package/application authors For those of you who maintain code that uses the Tcl C API, there are a number of options for dealing with the source incompatibilities between the 8.3 and 8.4 headers. You can select the most appropriate solution based on the effort required, time available, and status of your code.First, as background, let's review the 3 kinds of changes that have been made regarding CONST between releases 8.3 and 8.4 of Tcl/Tk.Type I. Some routines that accepted only writable strings (char *) now are defined to accept read-only strings (const char *) as well, having added a promise that they will not write on the string passed in.For example, what was: int Tcl_Eval(Tcl_Interp *interp, char *script); /* 8.3 */is now: int Tcl_Eval(Tcl_Interp *interp, const char *script); /* 8.4 */If you had code that worked with the 8.3 headers, the script argument passed in must have been a writable string. The 8.4 interface is happy to accept a writable string as well, so there will be no compiler error due to a change of Type I. Your 8.3-compatible code will need not make any changes to be 8.4-compatible.Type II. Some routines that returned a string were defined to return a writable string, even though the returned string was really owned by the Tcl library, and documentation instructed not to write on it. Now those routines have prototypes that explicitly label the returned string to be read-only.For example, what was: char * Tcl_GetHostName(); /* 8.3 */is now: const char * Tcl_GetHostName(); /* 8.4 */If your code assigns the return value of Tcl_GetHostName to a variable of type char *, that code will cause a compiler error when compiling against the 8.4 headers. This is actually a helpful error. As noted, you were never supposed to write to the string returned by Tcl_GetHostName, so there is no reason to assign that string to a variable that would allow you to write to it. Adapting your code should be a simple matter of changing the type of the variable in which you store the return value from char * to const char *. Once your code is so adapted, it will compile against both 8.3 and 8.4 headers.Type III. The third type is the most difficult because the changes of this type force you to make a choice between supporting the 8.3 prototype, or the 8.4 prototype. Compilers cannot reconcile the difference between them without help.Type IIIa. Some routines that accepted an argv style array of strings now expect to receive an argv style array of read-only strings.For example, what was: char * Tcl_Merge(int argc, char **argv); /* 8.3 */is now: char * Tcl_Merge(int argc, const char * const *argv); /* 8.4 */Type IIIb. Some of the typedefs that determine the prototypes of routines to be written by extensions to Tcl have been changed. Some compilers include the const-ness of arguments when checking the type of function pointers, so these changes can also be irreconcilable.For example, what was: typedef char *(Tcl_VarTraceProc) (ClientData clientData, Tcl_Interp *interp, char *part1, char *part2, int flags);is now: typedef char *(Tcl_VarTraceProc) (ClientData clientData, Tcl_Interp *interp, const char *part1, const char *part2, int flags);For all Type III interfaces, you will have to make a choice whether your code will be written to the 8.3 interface or the 8.4 interface, and #define appropriate symbols to force the headers to declare compatible prototypes for your choice.With that as background, here are your alternatives for migration.Option 1. Make no changes to your code. #define USE_NON_CONSTWhen you #define USE_NON_CONST, all the consts of Type II and Type III are disabled. This leaves only the Type I changes active, and they can cause no compiler errors. This is the option recommended for users of code, who just want to get something working without becoming maintainers themselves. This might also be a suitable option for a developer with limited time who just needs to get an 8.4-compatible version out the door quickly, and can take the time later for a fuller migration. It might also be suitable for older projects that are no longer actively developed, but want to be made able to work with the 8.4 Tcl release.Option 2. Update to deal with Type II changes. #define USE_COMPAT_CONSTWhen you #define USE_COMPAT_CONST, all the consts of Type III are disabled. The Type II changes are active, so you'll need to be sure that all read-only strings returned by Tcl get stored only in const char * variables, or passed on only to other routines that accept a const char * argument. Once you've made those updates, the resulting code will compile against both 8.3 and 8.4 headers. This option is a good idea for those developers who have any time at all, and who are continuing to update their code, because any changes made under this option are likely to be bug fixes.Option 3. Move completely to 8.4 interfaces. Drop 8.3 support.With no #defines, you get all the 8.4 prototypes, including those that cannot be reconciled with their 8.3 predecessors. This will involve make several changes to your code to satisy the requirements of the Type III changes. The compiler will guide you. This option is suitable for developers that will make use of new features provided in the 8.4 releases of Tcl/Tk. Since they will require the 8.4 headers anyway, they should write exclusively to the new interface.NOTE: Each of these 3 options can be applied to your project as a whole (with a -DUSE_X_CONST added to CFLAGS), or can be applied on a file by file basis (with #define USE_X_CONST), so you have fine control over how to update your code bit by bit as suitable for you.Finally, I should note another option that some folks have found to be useful.Option 4. Use the internal symbol CONST84 to continue pre-8.4 supportSome developers want to adopt all the 8.4 interfaces, but are not prepared to drop support of pre-8.4 releases of Tcl/Tk. They have made use of the symbol CONST84 directly in their code. That symbol is the one used by the USE_NON_CONST and USE_COMPAT_CONST symbols to disable the Type III changes. It was meant to be an internal detail, but it can be effectively used if you wish.In your own code, include: #ifndef CONST84 # define CONST84 #endifThen, wherever there is a const of Type III, use the symbol CONST84 in your code instead of const. In this way, when compiling against the 8.4 headers, you will be using the const-ified interfaces, but when compiling against the 8.3 headers, you will get the original interfaces. See also Changes in Tcl/Tk 8.4 See also [2] and [3] (and subsequent messages in the thread) for a fairly detailed report of the TIP 27 impact on two extensions.Summary: In one case, adding CONST84 in a few places did 90% of the job, a few minor changes to the code fixed the rest. In another case, -DUSE_NON_CONST was necessary, since the extension receives data from parts of the Core that were not CONSTified and passes it on to other parts that were. Update: Post-8.4b1, more parts of the Core were CONSTified; after these changes, it was possible to fully CONSTify the second extension without needing -DUSE_NON_CONST (using Option 4, to retain source-level compatibility with 8.3 and 8.4 headers).
http://wiki.tcl.tk/3669
CC-MAIN-2017-30
refinedweb
1,518
65.62
zappa: Coffee Script DSL on top of Express, Node.js, and Socket.IO We gave a nod to CoffeeKup, Maurice Machado’s CoffeeScript ode to Markaby last month. Maurice is back with a new CoffeeScript ditty. Zappa is a highly opinionated DSL for writing Node.js apps on top of Express - using CoffeeScript. Be sure and check out Episode 0.2.9 on CoffeeScript and Episode 0.3.1 on Websockets and Socket.IO for a little background if you missed them. To get started, assuming you’ve got Node and Express installed, install Zappa via npm: npm install zappa You then can fire up your Zappa app from the command line: $ zappa cuppa.coffee => App "default" listening on port 5678... So what does a Zappa application look like? Just like Sinatra, routes are mapped to handlers using the four HTTP verbs: get '/:foo': -> @foo += '!' render 'index' You can declare that index view in the same file with the view function: view index: -> h1 'You said:' p @foo Layouts? You bet: layout -> html -> head -> title "You said: #{@foo}" body -> @content Currently views and layouts support Coffeekup only, but that might change. Async and Websockets You can’t really talk about Node without discussing its inherent asynchronous nature. Zappa makes async style programming straightforward as well: def sleep: (secs, cb) -> setTimeout cb, secs * 1000 get '/': -> redirect '/bar' '/:foo': -> @foo += '?' sleep 5, => @foo += '!' @title = 'Async' render 'default' view -> h1 @title p @foo Zappa also has support for Socket.IO out of the box, so Websockets programming is a snap. get '/': -> render 'default' get '/counter': -> "# of messages so far: #{app.counter}" at connection: -> app.counter ?= 0 puts "Connected: #{id}" broadcast 'connected', id: id at disconnection: -> puts "Disconnected: #{id}" msg said: -> puts "#{id} said: #{@text}" app.counter++ send 'said', id: id, text: @text broadcast 'said', id: id, text: @text client -> $(document).ready -> socket = new io.Socket() socket.on 'connect', -> $('#log').append '<p>Connected</p>' socket.on 'disconnect', -> $('#log').append '<p>Disconnected</p>' socket.on 'message', (raw_msg) -> msg = JSON.parse raw_msg if msg.connected then $('#log').append "<p>#{msg.connected.id} Connected</p>" else if msg.said then $('#log').append "<p>#{msg.said.id}: #{msg.said.text}</p>" $('form').submit -> socket.send JSON.stringify said: {text: $('#box').val()} $('#box').val('').focus() false socket.connect() $('#box').focus() view -> @title = 'Nano Chat' @scripts = ['', '/socket.io/socket.io', '/default'] h1 @title div id: 'log' form -> input id: 'box' button id: 'say', -> 'Say' As a fan of CoffeeScript, I’ll be kicking the tires on this for my next Node app.
https://changelog.com/posts/zappa-razor-sharp-dsl-for-modern-web-apps
CC-MAIN-2018-39
refinedweb
422
61.93
I get a Overflow error when i try this calculation, but i cant figure out why. 1-math.exp(-4*1000000*-0.0641515994108) Solution #1: The number you’re asking math.exp to calculate has, in decimal, over 110,000 digits. That’s slightly outside of the range of a double, so it causes an overflow. Solution #2: To fix it use: try: ans = math.exp(200000) except OverflowError: ans = float('inf') Solution #3: I think the value gets too large to fit into a double in python which is why you get the OverflowError. The largest value I can compute the exp of on my machine in Python is just sligthly larger than 709.78271. Solution #4: This may give you a clue why:*1000000*-0.0641515994108%29 Notice the 111442 exponent. Solution #5: Unfortunately, no one explained what the real solution was. I solved the problem using: from mpmath import * You can find the documentation below: Solution #6: Try np.exp() instead of math.exp() Numpy handles overflows more gracefully, np.exp(999) results in inf and 1. / (1. + np.exp(999)) therefore simply results in zero import math import numpy as np print(1-np.exp(-4*1000000*-0.0641515994108))
https://techstalking.com/programming/question/solved-python-overflowerror-math-range-error/
CC-MAIN-2022-40
refinedweb
203
68.26
Converting a SQLite julianday to a QDateTime Ok, I see the QDate::fromJulianDay( int jd ), but it takes an integer and the SQLite julianday is a double, having time, along with the date. How exactly does one go about converting the SQLite julianday into a complete QDateTime? As sqlite does not have a dedicated date/time/datetime/timstamp type, you will have to resort to text (for ISO8601 strings), real (for julian day numbers with fractions) or integer (for unix seconds since epoch). You will have to convert any of those to a datetime type. For highest compatibility I would go with ISO8601 text strings or the integers for unix seconds. Reals for julian calendar dates is quit unusual from my experience. If you really need to go with the reals, then you'll have to convert it into a integer for the day and calculate the time from the fraction: 86400 * fraction = seconds in day. Well, it is a bit late in things to convert from reals. So if I understand you correctly, I simply take the faction from the real, multiply it by 86400 and set that as the milliseconds on the QTime and I should be golden. Thank you! Basically, yes, though precision is going to be off. I would round off the result of the multiplication to the nearest 1000, so you don't give a false impression of millisecond precision. @scarleton: That's the seconds (60 * 60 * 24 = 86400), for milliseconds multiply the result with 1000. But as André already stated, that would give you most probably a false precision. Something to watch for: The julian dates start at noon (12:00 UTC) according to the "SQLite docs":. You can use this helper function to convert a julian date/time double to a QDateTime: @ #include <QtCore/qmath.h> #include <QDate> QDateTime julianDoubleToDateTime(double julian) { // The day number is the integer part of the date int julianDays = qFloor(julian); QDate d = QDate::fromJulianDay(julianDays); // The fraction is the time of day double julianMSecs = (julian - static_cast<double>(julianDays)) * 86400.0 * 1000; // Julian days start at noon (12:00 UTC) QTime t = QTime(12, 0, 0, 0).addMSecs(qRound(julianMSecs)); return QDateTime(d, t, Qt::UTC); } @ Thank you, that works like a charm! Thanks, you're welcome. I've added a doc note to [[Doc:QDateTime]] for further reference.
https://forum.qt.io/topic/7259/converting-a-sqlite-julianday-to-a-qdatetime/1
CC-MAIN-2017-47
refinedweb
391
61.46
The most recent release of the GAE states the following changes: Datastore Cross Group (XG) Transactions: For those who need transactional writes to entities in multiple entity groups (and that's everyone, right?), XG Transactions are just the thing. This feature uses two phase commit to make cross group writes atomic just like single group writes. Have you read any of the docs? It sounds like you haven't (based on you saying "I can't seem to find any additional information"). In that case, check out the links below and see if still have any questions. Conceptually, doing a cross group transaction is pretty similar to a typical GAE transaction, just slower, and only available in the HRD. Note that in general, GAE transactions, both "normal" and XG have different isolation characteristics than what you may be used to coming from a SQL database. The second link discusses this immediately after the XG section. Here is an excerpt from the first link showing how simple using XG can be. from google.appengine.ext import db xg_on = db.create_transaction_options(xg=True) def my_txn(): x = MyModel(a=3) x.put() y = MyModel(a=7) y.put() db.run_in_transaction_options(xg_on, my_txn)
https://codedump.io/share/AGwJDgp4V5Qc/1/cross-group-xg-transactions-and-further-explanation-of-use
CC-MAIN-2017-09
refinedweb
199
57.16
JavaScript Boilerplate is the collection of best practices.. MODULEhas renamed to JSBfor better JavaScript semantics use strict, dir changes, css fixes, additional grunt plug-ins also have been added etc.. JSB is main namespace that has been defined and JSB.helper is one of the components. src/css/style.css - Style sheets for the html help file. Clone the repository using the quick start guide. To get started include the JS files in your js directory. The starting point is the src/js/_main.js file which has defined the main module and the component to be used. If you were to observe the code, (function (JSB, $, undefined) { ...... (2) })(window.JSB = window.JSB || {}, jQuery); The above code defines the JSB namespace and also passes true values of jquery and undefined to the inner component. Instead of JSB you can define your project name or application name as well and that would become your global namespace under which all the other components should be declared/defined. For e.g. if it is a project name MYPROJECT instead of JSB you can even write MYPROJECT as well. Once you have defined the wrapper (global namespace), you can start of modules inside the global namespace. The second step would be to define the components, which can be page level or widget level too. JSB.subModule = (function () { function _subModule() { ... (3) } return new _subModule() })(); The above code has defined a component called helper as a sub module of JSB namespace. JSB.helper holds an object that gets returned through new _subModule(). We can define all the functions that we want for the helper module inside the function _subModule(). The third step would be to define the private values, private functions , privileged functions etc. within the _subModule function. Comments have been provided as to which one is a private function and which is a privileged one. At the end of the function the init() function is exposed which in turn returns the object itself. When the object is returned all the privileged functions are exposed along with it and are accessible outside. Next is the src/js/_config.js file, which has all the global parameters that needs to be leveraged across the application. Think of this file/module as a container file to define your global variables, URLS etc. It is globally available inside the JSB namespace and we can access the parameters by specifying JSB.config.param to get its value in any other component. Here it has been primarily defined as an object literal as everything needs to be exposed globally. For creating utility methods to be used across application, you can leverage the src/js/_helper.js file. It works on the same principle as the src/js/_main.js. For E.g. the way to access a helper function outside the module would be JSB.helper.getCookie for the getCookie function. Clone the git repo - git clone git://github.com/mdarif/JavaScript-Boilerplate.git - or download it You can also get the JavaScript Boilerplate through npm if you have already installed node. npm install javascript-boilerplate OR Grunt Install Grunt CLI, this will put the grunt command in your system path, allowing it to be run from any directory. $ npm install -g grunt-cli Now install Grunt $ npm install grunt You should also install all the dependencies $ npm install compass task. This task requires you to have Ruby, Sass, and Compass >=0.12.2 installed. If you're on OS X or Linux you probably already have Ruby installed; test with ruby -v in your terminal. When you've confirmed you have Ruby installed, run gem update --system && gem install compass to install Compass and Sass. appfolder content $ grunt server $ grunt You should be able to see the below message for a successful build and a folder name dist has been created with all the expected output, parallel to src folder, with all the tasks completed. Done, without errors. $ grunt test We use jasmine as a unit testing framework to test our boilerplate code, as of now it's been only done for _.main.js, you would get all the test done in the next release. Anyone and everyone is welcome to contribute.
https://www.npmjs.com/package/javascript-boilerplate
CC-MAIN-2017-09
refinedweb
703
65.42
Created on 2017-07-07 07:51 by louielu, last changed 2017-07-21 02:34 by terry.reedy. This issue is now closed. Add event for KeyRelease-Up and KeyRelease-Down to change sample font. Current code only changed font when using button-click on listbox. New changeset bb2bae84d6b29f991b757b46430c3c15c60059e9 by terryjreedy (Louie Lu) in branch 'master': bpo-30870: IDLE: Change sample font when select by key-up/down (#2617) If one scrolls with the mousewheel or scrollbar, the selection does not change and the example should not change, and I presume it will not with the patch. If one presses up or down, the selection does change, just as if one clicked, and the example should change. I consider it a bug that it does not. Good catch. New changeset 7ab334233394070a25344d481c8de1402fa12b29 by terryjreedy in branch '3.6': [3.6] bpo-30870: IDLE: Change sample font when select by key-up/down (GH-2617) (#2640) We already know that setting StringVar font_name triggers a change to changes. We also know that manually clicking or Up or Down triggers <<ListBoxSelect>>, which sets font_name and redraws the box. The challenge is to do something that will trigger the virtual event. Then we can write a test methods something like def test_sample(self): fontlist = configure.fontlist if fontlist.size(): name0 = fontlist.get(0).lower() # fontlist.selection_set(0) # or something print('\n', changes) # temp to testing that changes changes self.assertEqual(changes['main']['EditorWindow']['font'], name0) But selection_set does not trigger the event. After fiddling around with various bindings event_generate()s and update()s and update_idletasks(), I concluded, again, that either event_generate or its documentation is badly broken. The only thing I got to work in hours of experiments is this: import tkinter as tk root = tk.Tk() seq = '<ButtonRelease-1>' root.bind(seq, lambda event: print('generated', event)) root.update_idletasks() # or update() root.event_generate(seq) # update here fails Adding a widget and binding to the widget always failed. Here is my attempt using Serhiy's simulate_mouse_click. (This goes in test_configdialog.FontTabTest. def test_sample(self): fontlist = configure.fontlist if fontlist.size(): name0 = fontlist.get(0).lower() fontlist.see(0) x, y, dx, dy = fontlist.bbox(0) fontlist.bind('<ButtonRelease-1>', lambda event: print(event)) mouse_click(fontlist, x + dx//2, y + dy//2) fontlist.update() print('\n', changes) # temporary, see if changes has anything self.assertEqual(changes['main']['EditorWindow']['font'], name0) Serhiy, do you have any idea why I cannot get event_generate to work for a listbox, even with your function? I have tried somewhere close to 20 variations. Serhiy, I tried tkinter.test.support.simulate_mouse_click to test this patch but it seems not to work. Code at end of previous message. Any idea on how to fix? It isn't my. It was added by Guilherme in r69050. I'll take a look at code tomorrow. I don't know how to make the testing code working. My manual test procedure was faulty. Without a unit test, I should have asked for another person to verify. I believe I read somewhere (SO?) that root.withdraw sometimes affects the effectiveness of event_generate. I will try de-iconifying for just this. New changeset 5b62b35e6fcba488da2f809965a5f349a4170b02 by terryjreedy in branch 'master': bpo-30870: IDLE -- fix logic error in eae2537. (#2660) New changeset 953e527763f5af293668135acdf5f0a20c3f6f4f by terryjreedy in branch '3.6': [3.6] bpo-30870: IDLE -- fix logic error in eae2537. (GH-2660) (#2661) It just get wierd, I can't do event_generate with Terry, too. Attach poc.py that should print out a 'testing', but it didn't. It seem setUpModule will smash out the test, I've add a trust-will-work test inside the test_configdialog.py: class Test(unittest.TestCase): def setUp(self): self.root = tkinter.Tk() def test_test(self): self.root.bind('<KeyRelease-Up>', lambda x: print('testing')) self.root.update() self.root.event_generate('<KeyRelease-Up>') This will print out `testing` when commet out setUpModule's `root = Tk()` line. But if this line is running, then the trust-test won't print out `testing` configdialog misuse `self.withdraw` at init, it should be `self.wm_withdraw`, #30900 fix this problem. After that, it should be a success to use event_generate in configdialog unittest with no `self.withdraw`. The new gui tests passed on Travis (linux), which I strongly suspect does not run gui tests. The generate key test failed on Appveyor (Windows), which means is does run gui tests. It also failed on my machine: generate key release did not work. The generate click test does pass on both Appveyor and my machine, which is progress. Adding config.fontlist.focus_force() before the key event worked. Louie, I will push that along with other edits tomorrow. I will try exposing the window just for the tests. Serhiy: question about tkinter.wantobjects. ConfigDialog sets the font options of label font_sample and text text_highlight_sample with a font tuple such as font=('courier', 12, ''). In the test, I expected retrieval of the font option with sample_font = dialog.font_sample['font'] hilight_font = dialog.text_highlight_sample['font'] to return tuples, but I get a string: '{courier new} 10 normal'. I checked and root.wantobjects() is returning the default True. Should not the options be returned as tuples? PR2666 adds 4% test coverage. 40% left to go. I expect some tests will cover more lines with less code. I am working on a test for set_font_sample. New changeset 9b622fb90331f259894e6edb29b5c64b9366491a by terryjreedy (Louie Lu) in branch 'master': bpo-30870: IDLE: Add configdialog fontlist selection unittest (#2666) New changeset 42abf7f9737f78a5da311a42945d781dfcd6c6c0 by terryjreedy in branch '3.6': [3.6] bpo-30870: IDLE: Add configdialog fontlist selection unittest (GH-2666) (#2701) I am closing this as basically complete. I opened #30981 to add and perhaps complete font page tests.
https://bugs.python.org/issue30870
CC-MAIN-2020-40
refinedweb
949
69.79
#include <Config.h> List of all members. you can dynamically "link in" external configuration settings by passing them to the addEntry() of the plist::Dictionary superclass. You may want to call writeParseTree() first to flush current settings, and then readParseTree() afterward to pull any pre-existing values from the configuration file into the instances you've just registered. Of course, you could also just write your values into the configuration file first, and just rely on getEntry/setEntry to read/write the value. This may be more convenient if you use the value infrequently and don't need an instance of it sitting around. Definition at line 136 of file Config.h. [inline] constructor Definition at line 139 of file Config.h. how many bytes of the IP to flash Definition at line 153 of file Config.h. Referenced by behaviors_config(). whether or not to trigger flashing when initially started Definition at line 154 of file Config.h.
http://www.tekkotsu.org/dox/classConfig_1_1behaviors__config.html
crawl-001
refinedweb
158
56.55
This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including rxjs-report-usage with all npm packages installed. Try it out: require()any package directly from npm awaitany promise instead of using callbacks (example) This service is provided by RunKit and is not affiliated with npm, Inc or the package authors. The script within this package collects anonymous API usage statistics and reports them to the RxJS core team. This package is included as a dependency in: eslint-plugin-rxjs rxjs-etc rxjs-marbles rxjs-spy rxjs-tslint-rules So if you are using the most-recent version of any of those packages, you can run the following npm command: npm rxjs-report-usage Or, with yarn: yarn rxjs-report-usage If you're not using any of those packages, you can install rxjs-report-usage as a devDependency and then run one of the above commands, or you can use npx to run the script without installing the package: npx rxjs-report-error When run inside a project, the script locates all JavaScript and TypeScript files - except for those in the node_modules directory - and parses them with Babel. The parsed code is searched for import statements and require calls that consume rxjs and a usage count is recorded for each consumed RxJS API. The script also locates any rxjs and typescript packages within node_modules and reports their versions. The versions of other packages are not included in the report. The anonymous statistics that are collected look like this: { "apis": { "rxjs": { "concat": 1, "merge": 1, "of": 4 }, "rxjs/operators": { "concatMap": 1, "mergeMap": 1 } }, "packageVersions": { "rxjs": ["6.5.5"], "typescript": ["3.9.5"] }, "schemaVersion": 1, "timestamp": 1592659729551 } Once the script has collected the usage statistics, the payload is shown and the developer is prompted to confirm the sending of the payload to the core team. The script sends no information without the developer's consent. For more information see this blog post: Reporting API Usage.
https://npm.runkit.com/rxjs-report-usage
CC-MAIN-2020-40
refinedweb
342
57.4
sqflite 1.1.6 sqflite # SQLite plugin for Flutter. Supports both iOS and Android. - Support transactions and batches - Automatic version managment during open - Helpers for insert/query/update/delete queries - DB operation executed in a background thread on iOS and Android Getting Started # In your flutter project add the dependency: dependencies: ... sqflite: ^1.1.6 For help getting started with Flutter, view the online documentation. Usage example # Import sqflite.dart import 'package:sqflite/sqflite.dart';(); SQL helpers # Example using the helpers final String tableTodo = 'todo'; final String columnId = '_id'; final String columnTitle = 'title'; final String columnDone = 'done'; class Todo { int id; String title; bool done; Map<String, dynamic> toMap() { var map = <String, dynamic>{ columnTitle: title, columnDone: done == true ? 1 : 0 }; if (id != null) { map[columnId] = id; } return map; } Todo(); Todo.fromMap(Map<String, dynamic>; Transaction # Don't use the database but only use the Transaction object in a transaction to access the database - Dart type List<int>is supported but not recommended (slow conversion)... - Currently INTEGER are limited to -2^63 to 2^63 - 1 (although Android supports bigger ones) More # 1.1.6 # - Open database in a background thread on Android 1.1.5 # - Add databaseExistsas a top level function - handle relative path in databaseExistsand deleteDatabase - Supports hot-restart while in a transaction on iOS and Android by recovering the database from the native world and executing ROLLBACKto prevent SQLITE_BUSYerror - If in a transaction, execute ROLLBACKbefore closing to prevent SQLITE_BUSYerror 1.1.4 # - Make all db operation happen in a separate thread on iOS 1.1.3 # - Fix deadlock issue on iOS when using isolates 1.1.2 # - Sqflite now uses a thread handler with a background thread priority by default on Android 1.1.1 # - Use mixin and extract non flutter code into sqlite_api.dart - Deprecate SqfliteOptionswhich is only used internally 1.1.0 # 1.0.0 # - Upgrade 0.13.0 version as 1.0.0 - Remove deprecated API (applyBatch, apply) 0.13.0 # - Add support for continueOrErrorfor batches 0.12.0 # - iOS objective C prefix added to prevent conflict - on iOS create the directory of the database if it does not exist 0.11.2 # - add Database.isOpenwhich becomes false once the database is closed 0.11.1 # - add Sqlflite.hexto allow querying on blob fields 0.11.0 # - add getDatabasesPathto use as the base location to create a database - Warning: database are now single instance by default (based on path), to use the old behavior use singleInstance = falsewhen opening a database - dart2 stable support 0.10.0 # - Preparing for 1.0 - Remove deprecated methods (re-entrant transactions) - Add Transaction.batch - Show developer warning to prevent deadlock 0.9.0 # - Support for in-memory database ( :memory:path) - Support for single instance - new database factory for handling the new options 0.8.9 # - Upgrade to sdk 27 0.8.8 # - Allow testing for constraint exception 0.8.6 # - better sql error report - catch android native errors - no longer print an error when deleting a database fails 0.8.4 # - Add read-only support using openReadOnlyDatabase 0.8.3 # - Allow running a batch during a transaction using Transaction.applyBatch - Restore Batch.committo use outside a transaction 0.8.2 # - Although already in a transaction, allow creating nested transactions during open 0.8.1 # - New Transactionmechanism not using Zone (old one still supported for now) - Start using Batch.applyinstead of Batch.commit - Deprecate Database.inTransactionand Database.synchronizedso that Zones are not used anymore 0.7.1 # - add Batch.query, Batch.rawQueryand Batch.execute - pack query result as colums/rows instead of List 0.7.0 # - Add support for --preview-dart-2 0.6.2+1 # - Add longer description to pubspec.yaml 0.6.2 # - Fix travis warning 0.6.1 # - Add Flutter SDK constraint to pubspec.yaml 0.6.0 # - add support for onConfigureto allow for database configuration 0.5.0 # - Escape table and column name when needed in insert/update/query/delete - Export ConflictAlgorithm, escapeName, unescapeName in new sql.dart 0.4.0 # - Add support for Batch (insert/update/delete) 0.3.1 # - Remove temp concurrency experiment 0.3.0 # 2018/01/04 - Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here. 0.2.4 # - Dependency on synchronized updated to >=1.1.0 0.2.3 # - Make Android sends the reponse in the same thread then the caller to prevent unexpected behavior when an error occured 0.2.2 # - Fix unchecked warning on Android 0.2.0 # - Use NSOperationQueue for all db operation on iOS - Use ThreadHandler for all db operation on Android 0.0.3 # - Add exception handling 0.0.2 # - Add sqlite helpers based on Razvan Lung suggestions 0.0.1 # - Initial experimentation sqflite_example # Demonstrates how to use the sqflite plugin. Quick test # flutter run Specific app entry point flutter run -t lib/main.dart Getting Started # For help getting started with Flutter, view the online documentation. Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: sqflite: '; We analyzed this package on Oct 29, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.5.1 - pana: 0.12.21 - Flutter: 1.9.1+hotfix.4 Platforms Detected platforms: Flutter References Flutter, and has no conflicting libraries.
https://pub.flutter-io.cn/packages/sqflite/versions/1.1.6
CC-MAIN-2019-47
refinedweb
910
52.76
Named which suits your route. Here is an example to understand this concept. Step 1: In the very first step, you are required to create a file with the name test.php. Store this file in the path: resources/views/. <html> <body> <h1> Example of Redirecting to Named Routes </h1> </body> </html> Step 2: Make sure you set up the route for your test.php file in the routes.php file. You can find routes.php at app/Http. Here we are renaming the route to testing. We have set up another route for redirecting the request to testing route. This new route has been named as redirect. Route::get(‘/test’, [‘as’=>’testing’,function() { return view(‘test2’); }]); Route::get(‘redirect’,function() { return redirect()->route(‘testing’); }); Step 3: To test the route’s name, paste the URL: into the web server and the final output will appear like the following. Explanation: Once you execute the mentioned URL, you will be redirected to the test URL:. But this URL will automatically redirect you to the testing route. Redirection To Controller Actions By now, you have clearly understood that we can redirect to the named route. But, you must also know that redirection to controller actions is also possible. This can be done with the help of action() method. For this, you need 2 arguments which are: the name of the action and the controller itself. And in case, there is any other parameter that you want to pass in the action() method then pass it as the second argument. return redirect()->action(‘NameOfController@methodName’,[parameters]); The following example will help you to understand this concept clearly. Step 1: Create a controller with the name RedirectController. For the creation of the controller, execute the following command on the command prompt (cmd) or on the terminal. laravel> php artisan make:controller RedirectController –plain Step 2: Once you create the controller successfully then include the given code to the RedirectController.php file. You can find this file at app/Http/Controllers/. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class RedirectController extends Controller { public function index() { echo “Redirecting to controller’s action.”; } } Step 3: Now, add the following code to the routes.php file. You can get this file from the route app/Http/. Route::get(‘rr’,’RedirectController@index’); Route::get(‘/redirectcontroller’,function() { return redirect()->action(‘RedirectController@index’); }); Step 4: At last, paste the URL: to the web server and you will be displayed with the following outcome on the web page.
https://www.w3school.in/laravel-redirections/
CC-MAIN-2019-04
refinedweb
427
57.67
. An ultra-simple Web server that provides slices of a very large (mock) data source for a dojox.grid.Grid client that uses a dojox.data.QueryReadStore to page the data on demand. import cherrypy #do an "easy_install cherrypy" to get it from cherrypy.lib.static import serve_file import demjson #do an "easy_install demjson" to get it import os from random import randint #for building up mock data json = demjson.JSON(compactly=False) jsonify = json.encode NUM_ITEMS = 1000000 class Content: def __init__(self): """ Maybe you would call out to a db with some sql to get some data based on the query string that comes into /data. For now, we'll build up some static data to use. """ self.items = [] possible_item_labels = ["foo", "bar", "baz", "qux"] id=0 for i in xrange(NUM_ITEMS): self.items.append({ 'id' : id, 'label' : possible_item_labels[randint(0,3)] }) id +=1 #keep track of sort order b/c sorting is expensive... self.current_sort_order = "" @cherrypy.expose def data(self, **kw): """ Serve up the data via kw will contain whatever is in your store's query. By default the query string will come across as something like: ?name=*&start=0&count=20 to populate the table Note: you may get into trouble if you have multiple users trying to access this url and changing the sort order of items all at the same time (but relax, this is just a little demo.) """ #sorting the items by values for a given dictionary key... if kw.get('sort') and self.current_sort_order != kw.get('sort'): if kw['sort'][0] == '-': #descending order, slice off the - self.items.sort(lambda m,n:cmp(m.get(kw['sort'][1:]), \ n.get(kw['sort'][1:])),reverse=True) else: #ascending order self.items.sort(lambda m,n:cmp(m.get(kw['sort']), \ n.get(kw['sort']))) self.current_sort_order = kw['sort'] #slicing the data... start = int(kw['start']) end = start + int(kw['count']) #serving up the slice of interest as well as the total size return jsonify({ 'numRows':NUM_ITEMS, 'items':self.items[start:end], 'identifier' : 'id' }) @cherrypy.expose def index(self, **kw): """ Serve up the web page through """ return serve_file(os.path.join(os.getcwd(), 'page.html')) #the page containing the grid cherrypy.server.socket_port = 8000 cherrypy.quickstart! Excellent article Excellent article .
http://www.linuxjournal.com/magazine/dojos-industrial-strength-grid-widget?page=0,4&quicktabs_1=2
CC-MAIN-2017-17
refinedweb
374
50.84
Opened 2 years ago Closed 2 years ago Last modified 2 years ago #21862 closed Bug (duplicate) Loading app fails with Python 3.3 resulting in: TypeError: '_NamespacePath' object does not support indexing Description I have just created a new Django project using the freshly released Django 1.7a1 with Python 3.3. I've create the project using django-admin. Project Setup manage.py project/ photo/ models.py settings.py urls.py wsgi.py I have created a custom app 'photo' that contains a single model 'Photo' and nothing else. I've added the app in the settings using the old-style dotted notation without an 'AppConfig'. The INSTALLED_APPS in 'settings.py': INSTALLED_APPS = [ ... 'project.photo', ] Excpected Behaviour The app 'project.photo' is loaded and './manage.py shell' or './manage.py runserver' are running fine. Actual Behaviour When I am running './manage.py migrage' or even just './manage.py shell', I am getting the following error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/core/management/__init__.py", line 427, in execute_from_command_line utility.execute() File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/core/management/__init__.py", line 391, in execute django.setup() File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/apps/registry.py", line 84, in populate app_config = AppConfig.create(entry) File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/apps/base.py", line 111, in create return cls(entry, module) File "/home/elbaschid/.virtualenvs/disperser/lib/python3.3/site-packages/django/apps/base.py", line 43, in __init__ self.path = upath(app_module.__path__[0]) TypeError: '_NamespacePath' object does not support indexing Possible Solution A similar problem has been reported on the pytest project with a fix that has been accepted: As the commit message there states "Starting with Python 3.3, NamespacePath passed to importlib hooks seem to have lost the ability to be accessed by index.". This seems to be the same issue here. Change History (8) comment:1 Changed 2 years ago by bmispelon - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 follow-up: ↓ 6 Changed 2 years ago by bmispelon - Severity changed from Normal to Release blocker - Triage Stage changed from Unreviewed to Accepted Nevermind, I hadn't read your report thoroughly enough (I created the "photo" app with startapp instead of using the same layout as you). If I remove the __init__.py file from the app's folder (which is a perfectly valid thing to do in Python 3), it triggers the error. Since apps without an __init__.py file worked with Django 1.6, I'm going to mark this ticket as a release blocker as well. In the meantime, you should be able to work around the problem simply by adding an empty __init__.py file to project/photo. Thanks. comment:3 Changed 2 years ago by timo comment:4 Changed 2 years ago by timo Carl's reply from IRC: "I think the question I raised here still applies. We look for a lot of things relative to the app's package directory; it's not clear how that would be handled with a namespace package. It may be that the right resolution for this ticket is just that we need a clearer error (or that #21862 is a dupe of #17304, and part of the resolution of #17304 should be a clearer error). comment:5 Changed 2 years ago by carljm It looks like with the new app-loading stuff, the correct way to get the base path for an app is now app_config.path. And by default app_config.path now uses module.__path__[0] (which is causing this error) rather than __file__ (which caused the error prompting #17304, pre-app-loading). We _could_ resolve this bug by changing module.__path__[0] to list(module.__path__)[0], and then we would "support" apps that are namespace packages, although if they actually are multi-located namespace packages, we would be arbitrarily choosing one location (the first found on sys.path) and only supporting templates etc in that location and no others. Alternatively (and perhaps less confusingly), AppConfig could check for len(module.__path__) > 1 and raise a clear error that apps cannot be namespace packages. Third option, and most invasive, would be to "fully" support apps as namespace packages, by replacing AppConfig.path with AppConfig.paths, and requiring any code using it (e.g. the app-directories template loader) to potentially look in multiple paths for each app. Personally I think I'd vote for the second option (raise an error); I think this bug was filed simply as a result of someone forgetting the __init__.py, not because there was a real use case for a namespace package app. At some point in the future when everyone is using Python 3.3+, it's possible that __init__.py becomes a historical relic and everyone just leaves it out as a matter of course, even when they don't really need a namespace package. If that happens, we would need to revisit this choice. (As a side note, it appears AppStaticStorage is still using app_module.__file__ and should perhaps be updated to use app_config.path.) comment:6 in reply to: ↑ 2 Changed 2 years ago by carljm - Resolution set to duplicate - Status changed from new to closed Since apps without an __init__.py file worked with Django 1.6, I'm going to mark this ticket as a release blocker as well. In my testing, this is not true. With Django 1.6.1 I get the same error reported in #17304. Based on that, I am going to close this as a duplicate of #17304. The details have changed due to app-loading, but the core issue, and options for resolution, remain the same. comment:7 Changed 2 years ago by elbaschid Thanks for looking into this. I appreciate everyone's time. I wasn't aware of the fact that namespace packages aren't support and will be putting the __init__.py back into my apps. comment:8 Changed 2 years ago by aaugustin I confirm Carl's analysis, especially regarding app-loading. Hi, I'm running Python 3.3.3 too but I can't reproduce the error. How did you install Django?
https://code.djangoproject.com/ticket/21862
CC-MAIN-2016-26
refinedweb
1,085
59.9
hmartin @Olaf I'd recommend copying over the pygenstub.py file from the repo instead of installing with pip hmartin. hmartin : ) hmartin An alternative might be to create a webview and run TF.js there. Theoretically this will allow the ML to still run on GPU. I have not tested this though... hmartin I'm working on a project to enable exactly this! See However, I haven't implemented ui or scene yet, but would be happy to collaborate on those. hmartin I've been slightly annoyed that there's no way to save podcasts that I like in Overcast. Pythonista to the rescue 😀OvercastParser takes an overcast URL and returns the iTunes id, audio stream url, Overcast ID, and episode title. Check it out here: hmartin The i is lowercase... import pygame hmartin!
https://forum.omz-software.com/user/hmartin
CC-MAIN-2022-40
refinedweb
134
76.72
Subject: Re: [OMPI users] Can not turn off C++ build. From: Jeff Squyres (jsquyres_at_[hidden]) Date: 2012-11-29 11:19:59 No problem! Glad to help. I added you to the ticket about not being able to turn off the C++ compiler checks (), in case that ever gets fixed. It's somewhat of a low priority. On Nov 29, 2012, at 11:17 AM, Ray Sheppard wrote: > Thanks Jeff, > Of course you were right. I had thought the lost function was something internal to y'alls build. It is pretty scary that they have been building and porting for weeks (while I was running around SC and the holidays) and it takes an old fortran guy to notice they don't have a working C++ compiler. Well, truth be told, you did the noticing. Thanks again. > Ray > > On 11/28/2012 5:09 PM, Jeff Squyres wrote: >> According to config.log, your icpc is broken -- it won't compile a trivial C++ program. Try it yourself -- try compiling >> >> ----- >> #include <stdio.h> >> #include <iostream> >> using namespace std; >> int main(int argc, char* argv[]) { >> cout << "Hello, world" << endl; >> return 0; >> } >> ----- >> >> Do you need to set some environment variables before you invoke the Intel compilers? >> >> >> On Nov 28, 2012, at 5:03 PM, Ray Sheppard wrote: >> >>> supports -finline-functions... yes >>> configure: WARNING: -finline-functions has been added to CXXFLAGS >>> checking if C and C++ are link compatible... yes >>> checking for C++ optimization flags... -O3 -DNDEBUG -finline-functions >>> checking size of bool... 0 >>> checking alignment of bool... configure: WARNING: *** Problem running configure test! >>> configure: WARNING: *** See config.log for details. >>> configure: error: *** Cannot continue. >>> >>> >>> >>> >>> >>> >>> >>> >>> > > _______________________________________________ > users mailing list > users_at_[hidden] > -- Jeff Squyres jsquyres_at_[hidden] For corporate legal information go to:
http://www.open-mpi.org/community/lists/users/2012/11/20809.php
CC-MAIN-2014-15
refinedweb
287
76.72
Looking. Posted on August 24, 2010, in opinion, php, Technology. Bookmark the permalink. 31 Comments. namespaces have been supported in pdt for awhile. Preferences->PHP->php interpreter Each of your projects can be either 5.2 or 5.3. Also checkout the zend studio 8 beta a lot of issues with version 7 have been addressed in 8. Yes I know. I want to say that namespaces aren’t supported in Zend Studio 5.5 (you cannot choose PHP5.3). PDT, Netbeans and Zend Studio 7 support PHP 5.3. In fact I preffer PDT than Zend Studio 7. The improvements it has doesn’t incentive me to pay the price. Hi Gonzalo, you should definitly try Jetbrains PHPStorm. My situation was similar to yours, I developed years using ZendStudio from 5.5 to 6 and I did always miss things. Coming from IntelliJ IDEA (Java) to Eclipse (PHP), I first hate that Eclipse (ZendStudio), but there was no real alternative for me. After years of waiting now a big story begins… I used PHPStorm from the first minute of EAP. 1.02 is pretty stable and I love it. PHP, JS, CSS. HTML5 etc. All in one. There are still some things to improve, but hey the price is… compare that to ZendStudio Pro… 50 percent off these days. Give it a try. Jp downloading … I agree, no IDE is as good as Zend Studio 5.5 was, don’t know why Zend took the wrong way turning to Eclipse. For now I’m tied to Netbeans, it’s working fine, and for the xdebug problems I use the firefox or chrome plugins so i can turn on and off the debugging on the project. I’ve tried Aptana but has the same performance problems as every eclipse based IDE. Wow! Thanks for the PHPStorm tip! It looks great! I also used to run Zend Studio 5.5, but I also lost interest when they switched to PDT, and raised the price. I have since switched to NetBeans, currently running 6.8 and developing PHP 5.3. I also develop on linux, and NetBeans seems to work well. Another vote for PHPStorm. Of all the dedicated PHP IDEs I’ve tried, including the very expensive PHPEd, I find that PHPStorm satisfies all my needs. They have a 1/2 off sale until Sept 1st for a personal license and version 2.0 is supposed to be right around the corner and will add support for Zend Debugger. I’ve been testing PHPStorm a bit. It looks great. But When I open my last project, the problems appear again. As I read in the website the namespaces support is not yet complete. Full support will be Q4 2010. I use a lot functions that return classes (and now those classes are within a namespace). PHPStorm doesn’t understand the PHPDoc with functions returning classes and autocomplete doesn’t work. Maybe this bug isn’t very important, but for me is awful. I realy take care about PHPDoc to help the autocomplete, and with this vesion doesn’t work. I will wait impatient until next release. It’s really lightweight and the price is almost for free comparing to competitors. Give CodeLobster PHP Edition a try. CodeLobster is Windows-only, we’re looking for Linux here. I’ve been using PhpED for 5 or 6 years now, and I can’t imagine developing without it. I second the vote for PhpED. Pros: On Windows, hands down the most intuitive, stable and easy to configure PHP IDE (when I first started out, I had a heck of a time before I configured Zend Studio 5.5. PhpED worked right after installation and has continued to do so ever since). Faster than anything else that is out there. Pro version has a profiler. Overall, the best debugging environment for PHP. Cons: Lags behind on HTML, JavaScript and CSS support. However, there is a major (version 6) release right around the corner that is supposed to address these very deficiencies. I also use PhpStorm, which is OK if you like Java GUI on Windows. Nowadays I’m testing PHPStorm and it’s incredible. Probably the better IDE I’ve seen. It has a few issues that I don’t like them, but probably because of my personal habits (I think I will adapt myself easily to them). I was in love with Zend Studio 5x Series. And I had suggested it to many others. It was just too good. Zend switched to Eclipse. sigh… I’ve switched to Netbeans. I also tried different IDEs for a few years including most on this lost plus many more like Komodo and UltraEdit. Eclispe was ok but the workflow was too confusing – it tries to do too many things. It seems that the IDEs written in Java are slow compared to others. I finally settled on PhpED and I’ve been using it for several years now. Cannot fault it! It’s just perfect and they keep on making it better. Updates are fairly frequent. They even implemented some of my feature suggestions!🙂 There is a Linux version but I don’t know if it’s still supported. ActiveState Komodo. Gonzalo, your unit tests could drastically reduce your debugging needs. I’d stick with NB. I really think so but debugging is something really necessary. I’ve spent a lot of time debugging with “echo” I felt right but now I think I need debugging. Unit testing is cool but debugging is necessary. Nowadays, at least for me Netbeans it’s the number one (but I need to master debugging in netbeans yet) I also used Zend Studio 5.x and switched to Netbeans after Zend switched to Eclipse. Pretty happy with it. And debugging works like a charme for me with FF addon. The problem with Eclipse is when you are working with a big set of files. When “building namespace” appears even when you are trying to rename a file, you are forced to drink a cup of coffee. Coffee is cool but we cannot drink 20 couples of coffee in a morning🙂. But I admit debugging with Eclipse is perfect. I have the same problem, since zend studio 5.5 nothing quite did the job. Then I found jedit, I’m currently testing it, and it’s fast with highlighting and code completion working really well. Give it a go. I KNEW there were others like me out there! Zend 5.5 (and earlier versions) were fantastic and must take a lot of the credit for actually making me start with and stick with PHP. Switching to the Eclipse platform was a HUGE mistake, and countless developers have expressed similar opinions on Zend’s own message boards. Since then I’ve used Netbeans and, frankly, it does the job very good once you’re used to it and know how to deal with some of the minor issues. Still doesn’t have the x-factor that Zend Studio 5.5 had, though. I use netbeans 6.9 now, though in the past when I was stumbling looking for a good feel IDE I tried lots of them. I agree with your take on zend studio 5.5, it is still by far the best zend has ever produced. Netbeans on the other hand has been growing it’s php plugin, I started using it netbeans when they first launched version 6.5 and so far I am happy with the strides they are making to improve the functionality – they actual put in features that the community request, not all but most….so in a nutshell I would recommend netbeans 6.9. >>Unit testing is cool but debugging is necessary. Actually, I see it as the opposite. Debugging is _nice_ but unit testing is necessary. But that is neither here nor there. I would also recommend PHPStorm or IntelliJ. IntelliJ has all of the features of PHPStorm but also has excellent support for other languages such as Scala, Python, Ruby, and of course, Java. Check out Parasoft’s Unit Testing best practices for more info on this topic. They have a ton of free white papers on how Unit Testing increases developer productivity. Netbeans 6.9.1 with Zend Framework Support Another vote up for stunning and life-saver PHPStorm 🙂 Zend Studio 5.x was awesome!! Currently using netbeans. If I need another full blown IDE to work on another project quickly I’ll start up Eclipse. For smaller / quick edits I like Sublime Text 2 I know – old thread – came across via Google while looking for any chance up updating Zend 5.5.1 to handle php5.3 I’ve been using Zend for years, and dearly wish 5.5.1 could be upgraded to handle php5.3 I absolutely loath the current trend of “projects” and local files. I have personal dev servers, under version control, and want to work directly via sftp. Most new IDEs don’t support this. The best replacement I’ve found so far is UEStudio – but man I wish I could find the settings/templates to make it look and act more like Zend 5.5.1 When I wrote this post I didn’t knew about PhpStorm. Now it’s my default IDE. It’s not free but IMHO it’s the best one. It’s fast and simple to use, and if you study a little bit its features and shortcuts, it boots your productivity to a higher level (PhpStorm people don’t pay me for this answer. In fact I pay them for the license :))
https://gonzalo123.com/2010/08/24/looking-for-the-perfect-php-ide/
CC-MAIN-2016-40
refinedweb
1,610
76.72
I’ve been trying to work with Harebrain on Google Colab and use Google Drive for storage. I tried using the python package, but the package is using a python package called pexpect, which displays a prompt / textfield input to accept the Google Drive auth token and this textfield is not displayed in the jupyter notebook. The input field simply isn’t included in the HTML output of the notebook. This is the code I use (assuming you have the String extension for the shell method): import Python public let colab = Python.import("google.colab") colab.drive.mount("/content/gdrive", force_remount: true) let root_dir = "/content/gdrive/My Drive/" let base_dir = root_dir + "fastai-v3/course-v3/nbs/dl2/" ("cd " + base_dir).shell() I would like to contribute by fixing this, but I have trouble finding the right forum for this. On GitHub swift-jupyter has no issues and doesn’t point me anywhere else (e.g. Google groups). So my best guess what to bring this up here and hope to be pointed somewhere useful. Thanks in advance!
https://forums.fast.ai/t/python-textfield-output-not-working/51000
CC-MAIN-2019-51
refinedweb
176
70.84
We have seen the basics of Django templating in the previous parts of the series. Now, we can move on to the more backend stuff in Django which deals with the Databases, queries, admin section, and so on. In this particular part, we'll cover the fundamental part of any application in Django i.e the Model. We'll understand what the model is, how to structure one, how to create relationships and add constraints on the fields, etc. A model is a Django-way(Pythonic) to structure a database for a given application. It is technically a class that can act as a table in a database generally and inside of the class, the properties of it act as the attributes of that database. It's that simple. Just a blueprint to create a table in a database, don't worry about what and where is our database. We will explore the database and its configuration in the next part. By creating a model, you don't have to write all the basic SQL queries like CREATE TABLE NAME( attrb1_name type, attrb2_name type, . . . ); If your application is quite big or is complex in terms of the relations among the entities, writing SQL queries manually is a daunting task and also quite repetitive at times. So Django handles all the SQL crap out of the way for the programmer. So Models are just a Pythonic way to create a table for the project/application's database. Creating a model for an application is as easy as creating a class in python. But hey! It's more than that as there are other questions to address while designing the class. You need to design the database before defining the fields in the model. OK, well it's not straightforward as it seems to but still for creating simple and dummy projects to start with. You can use certain tools like lucidchart, dbdiagrams.io, and other tools you are comfortable with. It's important to visualize the database schema or the structure of the application before tinkering with the actual database inside the project. Let's not go too crazy and design a simple model to understand the process. Here's a basic model for a Blog: from django.contrib.auth.models import User class Article(models.Model): title = models.CharField(max_length=255) post = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Article') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Ignore the from django.db import models as it is already in the file created by Django. If not, please uncomment the line and that should be good to go. This is a basic model you might wanna play with but don't dump it anywhere. We define or create our models in the application inside the project. Inside the application, there is already a file called models.py just append the above code into it. The application can be any application that makes the most sense to you or better creates an app if not already created and name it as article or post or anything you like. If you are familiar with Python OOP(object-oriented programming), we have basically inherited the models.Model class from the django.db module into our model. If you want more such examples, let's see more such models : An E-Mail application core model. Attributes like sender, subject of the mail, body of the mail, recipients_list i.e. the To: section in a mail system and the attachment_file for a file attachment to a mail if any. #from django.db import models from user import EmailUser class EMail(models.Model): sender = models.EmailField(max_length = 255) subject = models.CharField(max_length = 78) body = models.CharField(max_length = 40000) recipients_list = models.ManyToManyField(EmailUser, related_name = 'mail_list') attachment_file = models.FileField(blank=True) A sample model for a note-taking app, consisting of a Note and a Book. A book might be a collection of multiple notes i.e. a single book can have multiple notes so we are using a ManyToManyField, what is that? We'll see that shortly. from django.db import models from user.models import User class Notes(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length = 1024) content = models.Textfield() created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) book = models.ManyToManyField(Book, related_name = 'book') class Book(): name = models.CharField(max_length = 1024) These are just dummies and are not recommended to use anywhere especially in a serious project. So, we have seen a model, but what are these fields and the constraints like on_delete, max_length, and others in the upcoming section on fields. Fields are technically the attributes of the class which here is the model, but they are further treated as a attribute in a table of a database. So the model becomes a list of attributes which will be then parsed into an actual database. By creating attributes inside a class we are defining the structure for a table. We have several types of fields defined already by django for the ease of validating and making a constrained setup for the database schema. Let's look at some of the types of fields in Django Models. Django has a lot of fields defined in the models class. If you want to go through all the fields, you read through the django docs field references. We can access the fields from the models module like name = models.CharField(max_length=10), this is a example of defining a attributes name which is a CharField. We can set the max_length which acts a constraint to the attribute as we do not want the name field to be greater than 10 and hence parsing the parameter max_length to 10. We have other field types like: IntegerField-> for an integer value. TextField-> for long input of text (like text area in html). DateField-> for inputting in a date format. URLField-> for input a URL field. BooleanField-> for a boolean value input. And there are other fields as well which can be used as per requirements. We also have some other fields which are not directly fields so to speak but are kind of relationship defining fields like: ForeignKey-> Define a many-to-one relationship to another model/class. ManyToManyField-> define a many-to-many relationship to another model/class. OneToOneField-> define a one to one relationship between different tables/model/class. So, that's about the field types for just a feel of how to structure or design a database table using a model with some types of attributes. We also need to talk about constraints that need to add to the fields inside the models. We can add constraints and pass arguments to the fields in the models. We can add arguments like null, blank, defualt, choices, etc. null=True/False-> Set a check for the entry in the table as not null in the database. blank=True/False-> Set a check for the input validation to empty or not. unique=True/False-> Set a constraint to make the entry unique throughout the table. defualt=anyvalue-> Set a default value for the field. choices=list-> Set a list of defined choices to select in the field (a list of two valued tuple). We also have another constraint specific to the fields like max_length for CharField, on_delete for ForeignKey which can be used as a controller for the model when the related model is deleted, verbose_name to set a different name for referencing the entry in the table/model from the admin section compared to the default name of the model, verbose_name_plural similar to the verbose_name but for referencing the entire table/model. Also auto_now_add and auto_now for DateTimeField so as to set the current date-time by default. More options and arguments that can be passed to the fields in models are given in the django docs field options These are some of the options or arguments that we can or need to pass to the fields to set up a constrained schema for our database. Meta class is a nested class inside the model class which is most of the time used for ordering the entries(objects) in the table, managing permissions for accessing the model, adding constraints to the models related to the attributes/fields inside it, etc. You can read about the functionalities of the Meta class in the documentation. As a class can have functions, so does a model as it is a Python class after all. We can create kind of a helper methods/functions inside the model. The model class provides a helpful __str__() function which is used to rename an object from the database. We also have other predefined helper functions like get_absolute_url that generates the URL and returns it for further redirection or rendering. Also, you can define the custom functions that can be used to help the attributes inside the model class. Django has an Object Relational Mapper is the core concept in Django or the component in Django that allows us to interact with the database without the programmer writing SQL/DB queries. It is like a Pythonic way to write and execute sql queries, it basically abstracts away the layer to manually write SQL queries. We'll explore the details of how the ORM works under the hood but it's really interesting and fascinating for a Beginner to make web applications without learning SQL(not recommended though personally). For now, it's just magical to see Django handling the DB operations for you. You can get the references for learning about the Queryset in ORM from the docs Let us set up a model from what we have learned so far. We'll create a model for a Blog Post again but with more robust fields and structure. #from django.db import models from django.contrib.auth.models import User class Article(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique_for_date='publish') post = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Posts') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=16, choices=option, default='draft') def __str__() return self.title class Meta: ordering = ('-publish',) We can see in the above model that we have defined the Meta class which is optional and is generally written to modify how to entries inside the table appear or order with other functionalities as well. We have also added the choices option in the status field which has two choices Draft and Publish one which is seen by the django interface and the other to the end-users. We have also added certain fields like a slug that will create the URL for the blog post, also certain options like unique has been set to restrict duplicate entries being posted to the database. The related_name in the ForeignKey refers to the name given to the relation from the Article model to the User model in this case. So, we can see that Django allows us to structure the schema of a database. Though nothing is seen as an end result, when we configure and migrate the model to our database we will see the results of the hard work spent in creating and designing the model. By this time, you will have gotten a feel of what a database might be. Most of the projects are designed around SQL databases but No-SQL databases and others are also used in cases that suite them the most. We have tools to manage this database in SQL we call it the Database Management System (DBMS). It's just a tool to manage data, but there is not just a single Database management tool out there, there are gazillions and bazillions of them. Most popular include MySQL, PostgreSQL, SQLite, Oracle, Microsoft Access, Maria DB, and tons of others. Well, these different DBMS tools are almost similar with a few hiccups here and there. So, different Database tools might have different fields they provide. For Example, in Database PostgreSQL provides the ListField which SQLite doesn't that can be the decision to be taken before creating any project. There might be some fields that some DBMS provide and other doesn't. We understood the basics of creating a model. We didn't touch on the database yet but the next part is all about configuration and migration so we'll get hands-on with the databases. We covered how to structure our database, how to write fields in the model, add constraints and logic to them and explore the terminologies in Django like ORM, Database Types, etc. Thank you for reading the article, if you have any feedback kindly let me know, and until then Happy Coding :)
https://techstructiveblog.hashnode.dev/django-basics-creating-models
CC-MAIN-2022-05
refinedweb
2,143
65.22
View Complete Post Hello all, Is there a way to ; - get an upgraded Sharepoint designer 2007 list workflow into a 2010 VS WSP or - get an upgraded Sharepoint designer 2007 list workflow into a 2010 re-usable workflow Without having to re-create ? :) Thanks, casey Hi, SharePoint 2010 creates 2 extra versions when sending a document to a record centre. The size of these versioned documents are always 6.2KB and does not have any check-in comments. Please explain the purpose of these versions? Thanks, Hilmi J. Hi frnds, I am new to this programming.. I am trying to download files from a specific folder in ftp server. after downloading those files i want to store in my computer. . I got the code on internet but wen i am trying i am getting this error Error 2 Type or namespace definition, or end-of-file expected. . please help me very urgent. here is my complete code using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Net; using System.Text; using System.Runtime.InteropServices; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string[] files = GetFileList(); foreach (string file in files) { Download(file); } public string[] GetFileList() { string[] downloadFiles; StringBuilder result = new StringBuilder(); WebResponse response = null; StreamReader reader = null; try { FtpWebRequest reqFTP; reqFTP = (FtpWebReq I'm developing using VS2010. 2 projects: sharepoint site definition and a webapplication in visual basic.net. The code file .vb is not deployed with the sharepoint site definition. Please anyone can help me. I am migrating a list which includes a lookup column of Sharepoint from SP2007 to SP2010 but having an issue that this column doesn't save data when working on SP2010. Do you know to fix it ? Many Thanks Ngoc Han Hello world? In our company we have both MOSS and SPFoundation. We have decided to migrate contents like site/web/list from MOSS to new SP environment. Could anyone tell the procedure to do this by using Content Migration Deployment Object Model? Many Thanks! Gore T. Richard... <? < Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/22256-how-to-get-sp2007-bdc-definition-file-into.aspx
CC-MAIN-2017-22
refinedweb
373
60.92
This module is unmaintained. Maybe someday... DOMForm is a Python module for web scraping and web testing. It knows how to evaluate embedded JavaScript code in response to appropriate events. DOMForm supports both the ClientForm 0.1.x HTML form interface and the HTML DOM level 2 interface (note that ATM the DOM is written to an out-of-date version of the specification, and has some hacks to get it to work with "DOM as deployed"). The ClientForm interface makes it easy to parse HTML forms, fill them in and return them to the server. The DOM interface makes it easy to get at other parts of the document, and makes JavaScript support possible. The ability to switch back and forth between the two interfaces allows simpler code than would result from using either interface alone. DOMForm is partly derived from several third-party libraries. JavaScript support currently depends on Mozilla's GPLed spidermonkey JavaScript interpreter (which is available separately from Mozilla itself), and a Python interface to spidermonkey. This package allows you to use web pages containing JavaScript code, have that code automatically executed at appropriate times, and have the results reflected both in an HTML DOM tree and in a higher-level browser-like object model (only the ClientForm part of this browser interface is implemented so far). Of course, automatic execution of much code depends on the use of either the browser-like interface or equivalent DOM methods: otherwise, the code can't know when the JavaScript should be executed. XXX lots of stuff not implemented yet: eg., javascript: URLs (easy to do, though). It's easy to switch between the ClientForm API and the DOM, thus making it hard to get stuck in a position where further progress requires disproportionate coding effort: from urllib2 import urlopen from DOMForm import ParseResponse response = urlopen("") window = ParseResponse(response) window.document # HTML DOM Level 2 HTMLDocument interface forms = window._htmlforms # list of objects supporting ClientForm.HTMLForm i/face form = forms[0] assert form.name == "some_form" domform = form.node # level 2 HTML DOM HTMLFormElement interface control = form.find_control("some_control") # ClientForm.Control i/face domcontrol = control.node # corresponding level 2 HTML DOM HTMLElement i/face doc.some_form._htmlform # back to the ClientForm.HTMLForm interface again doc.some_form.some_control._control # ClientForm.Control interface again response = urlopen(form.click()) # domform.submit() also works Note that the level 2 HTML DOM interface is currently based on an old version of the specification, with some imperfect changes to provide some support for XHTML. To interpret JavaScript, you need to pass the interpret argument to ParseResponse or ParseFile: window = ParseResponse(response, interpret=["javascript"]) The HTML DOM should allow you to get at anything you need to know. Still, since the DOM does some normalisation and is only created after the original HTML has been fed through HTMLTidy, you may sometimes need or want access to the original HTML. ClientCookie's SeekableProcessor is one way of doing that: from ClientCookie import build_opener, SeekableProcessor opener = build_opener(SeekableProcessor) response = opener.open("") window = ParseResponse(response) html = response.read() response.seek(0) # carry on using response object as if it hadn't been .read() Or you can store the html somewhere, then use ParseFile instead of ParseResponse. If you want the HTML after the Javascript has been interpreted, use from xml.dom.ext import XHtmlPrint XHtmlPrint(doc, fileobj) XHtmlPrettyPrint makes nicer output. Both functions will print any DOM node, not just an HTMLDocument. There's some more documentation in the docstrings. Thanks to Andrew Clover for advice and code on DOM 'liveness', all the PyXML contributors, and Gisle Aas, for the HTML::Form Perl code from which ClientForm was originally derived. Most of the bugs are in JavaScript support (which is very dodgy) and the DOM implementation. The ClientForm work-alike stuff is relatively stable (but see the entities and select_default bugs listed below). except *feature to be fixed. There are a few print statements scattered about, as a result of this. Note that code listed with JavaScript error messages can be the WRONG CODE! Don't take it seriously. decorate_DOM(window)after this happens, to regenerate the HTMLFormand all its Controls, and rebind them to the DOM. I probably won't fix this (I'm guessing it won't cause problems). Windowclass is still just stubs. This will be fixed, gradually. ATM, you can likely quite easily derive your own Windowclass with stubs that suit your application, and pass it to one of the Parse*functions through the window_classargument. javascript:scheme URLs, external JavaScript loading, etc. aren't implemented yet (but they're easy to add). innerHTMLisn't implemented. Thanks to my hacks (for live-ness, IE compatibility, bug fixes, changes to match newest DOM standard etc.), it's probably quite buggy, too. sgmlop. RADIOcontrols. This should be fixed soon. onclick- executed. You just have to fire your own events: from DOMForm import fireHTMLEvent, fireMouseEvent # Say we've got a DOM node, domnode, representing a button, and we want to # simulate clicking it. fireHTMLEvent(domnode, "focus") fireMouseEvent(domnode, "click") fireHTMLEvent(domnode, "blur") # Of course, this is missing events like mouseover, which would be fired # by a browser, but we probably don't even need the focus or blur either. For installation instructions, see the INSTALL file included in the distribution. Python 2.3 and PyXML 0.8.3 are required (earlier versions may work, but are untested). Currently mxTidy is required (I may switch to uTidylib at some point). The spidermonkey Python module is required if you want JavaScript interpretation. Development release. This is the first alpha release: there are many known bugs, and interfaces will change. Good question. I wanted something smaller, not dependant on any browser, and also liked the idea of an easy-to-understand implementation of the browser object model in pure Python. 2.3 (earlier versions may work, but are untested). The BSD license (included in distribution). Note that spidermonkey and its Python interface are under the GPL. _htmlformsbegin with an underscore? Because attributes that start with an underscore ("_") are not exposed to JavaScript by the spidermonkey module. The ClientCookie package makes it easy to get seek()able response objects, which is convenient for debugging. See also here for few relevant tips. Also see General FAQs. I prefer questions and comments to be sent to the mailing list rather than direct to me. John J. Lee, May 2006.
http://wwwsearch.sourceforge.net/old/DOMForm/
CC-MAIN-2017-04
refinedweb
1,064
57.57
Component Extensions - A Tour of C++/CX By Thomas Petchel | April 2013 Ready to write your first Windows Store app? Or have you already been writing Windows Store apps using HTML/JavaScript, C# or Visual Basic, and you’re curious about the C++ story? With Visual C++ component extensions (C++/CX), you can take your existing skills to new heights by combining C++ code with the rich set of controls and libraries provided by the Windows Runtime (WinRT). And if you’re using Direct3D, you can really make your apps stand out in the Windows Store. When some people hear about C++/CX they think they have to learn a whole new language, but the fact is that for the vast majority of cases you’ll be dealing with just a handful of nonstandard language elements such as the ^ modifier or the ref new keywords. Furthermore, you’ll only use these elements at the boundary of your app, that is, only when you need to interact with the Windows Runtime. Your portable ISO C++ will still act as the workhorse of your app. Perhaps best of all, C++/CX is 100 percent native code. Although its syntax resembles C++/Common Language Infrastructure (CLI), your app won’t bring in the CLR unless you want it to. Whether you have existing C++ code that was already tested or just prefer the flexibility and performance of C++, rest assured that with C++/CX you don’t have to learn a whole new language. In this article you’ll learn what makes the C++/CX language extensions for building Windows Store apps unique, and when to use C++/CX to build your Windows Store app. Why Choose C++/CX? Every app has its own unique set of requirements, just as every developer has his own unique skills and abilities. You can successfully create a Windows Store app using C++, HTML/JavaScript or the Microsoft .NET Framework, but here are some reasons why you might choose C++: - You prefer C++ and have existing skills. - You want to take advantage of code that you’ve already written and tested. - You want to use libraries such as Direct3D and C++ AMP to fully unleash the hardware’s potential. The answer doesn’t have to be one or the other—you can also mix and match languages. For example, when I wrote the Bing Maps Trip Optimizer sample (bit.ly/13hkJhA), I used HTML and JavaScript to define the UI and C++ to perform the background processing. The background process essentially solves the “traveling salesman” problem. I used the Parallel Patterns Library (PPL) (bit.ly/155DPtQ) in a WinRT C++ component to run my algorithm in parallel on all available CPUs to improve overall performance. This would have been difficult to do from just JavaScript alone! How Does C++/CX Work? At the heart of any Windows Store app is the Windows Runtime. At the heart of the Windows Runtime is the application binary interface (ABI). WinRT libraries define metadata through Windows metadata (.winmd) files. A .winmd file describes the public types that are available, and its format resembles the format that’s used in .NET Framework assemblies. In a C++ component, the .winmd file contains only metadata; the executable code resides in a separate file. This is the case for the WinRT components that are included with Windows. (For .NET Framework languages, the .winmd file contains both the code and the metadata, just like a .NET Framework assembly.) You can view this metadata from the MSIL Disassembler (ILDASM) or any CLR metadata reader. Figure 1 shows what Windows.Foundation.winmd, which contains many of the fundamental WinRT types, looks like in ILDASM. Figure 1 Inspecting Windows.Foundation.winmd with ILDASM The ABI is built using a subset of COM to enable the Windows Runtime to interact with multiple languages. In order to call WinRT APIs, the .NET Framework and JavaScript require projections that are specific to each language environment. For example, the underlying WinRT string type, HSTRING, is represented as System.String in .NET, a String object in JavaScript and the Platform::String ref class in C++/CX. Although C++ can directly interact with COM, C++/CX aims to simplify this task through: - Automatic reference counting. WinRT objects are reference-counted and typically heap-allocated (no matter which language uses them). Objects are destroyed when their reference count reaches zero. The benefit that C++/CX offers is that the reference counting is both automatic and uniform. The ^ syntax enables both of these. - Exception handling. C++/CX relies on exceptions, and not error codes, to indicate failures. Underlying COM HRESULT values are translated to WinRT exception types. - An easy-to-use syntax for consuming the WinRT APIs, while still maintaining high performance. - An easy-to-use syntax for creating new WinRT types. - An easy-to-use syntax for performing type conversion, working with events and other tasks. And remember, although C++/CX borrows the C++/CLI syntax, it produces pure native code. You can also interact with the Windows Runtime by using the Windows Runtime C++ Template Library (WRL), which I’ll introduce later. However, I hope that after using C++/CX you’ll agree it makes sense. You get the performance and control of native code, you don’t have to learn COM and your code that interacts with the Windows Runtime will be as succinct as possible—letting you focus on the core logic that makes your app unique. C++/CX is enabled through the /ZW compiler option. This switch is set automatically when you use Visual Studio to create a Windows Store project. A Tic-Tac-Toe Game I think the best way to learn a new language is to actually build something with it. To demonstrate the most common parts of C++/CX, I wrote a Windows Store app that plays tic-tac-toe (or depending on where you grew up, you might call it “noughts and crosses” or “Xs and Os”). For this app, I used the Visual Studio Blank App (XAML) template. I named the project TicTacToe. This project uses XAML to define the app’s UI. I won’t focus much on the XAML. To learn more about that side of things, see Andy Rich’s article, “Introducing C++/CX and XAML” (msdn.microsoft.com/magazine/jj651573), in the 2012 Windows 8 Special Issue. I also used the Windows Runtime Component template to create a WinRT component that defines the logic of the app. I love code reuse, so I created a separate component project so that anyone can use the core game logic in any Windows Store app using XAML and C#, Visual Basic, or C++. Figure 2 shows what the app looks like. Figure 2 The TicTacToe App When I worked on the Hilo C++ project (bit.ly/Wy5E92), I fell in love with the Model-View-ViewModel (MVVM) pattern. MVVM is an architectural pattern that helps you separate the appearance, or view, of your app, from its underlying data, or model. The view model connects the view to the model. Although I didn’t use full-on MVVM for my tic-tac-toe game, I found that using data binding to separate the UI from app logic made the app easier to write, more readable and easier to maintain in the future. To learn more about how we used MVVM in the Hilo C++ project, see bit.ly/XxigPg. To connect the app to the WinRT component, I added a reference to the TicTacToeLibrary project from the TicTacToe project’s Property Pages dialog. By simply setting the reference, the TicTacToe project has access to all of the public C++/CX types in the TicTacToeLibrary project. You don’t have to specify any #include directives or do anything else. Creating the TicTacToe UI As I said earlier, I won’t go much into the XAML, but in my vertical layout, I set up one area to display the score, one for the main play area and one to set up the next game (you can see the XAML in the file MainPage.xaml in the accompanying code download). Again, I used data binding pretty extensively here. The definition of the MainPage class (MainPage.h) is shown in Figure 3. #pragma once #include "MainPage.g.h" namespace TicTacToe { public ref class MainPage sealed { public: MainPage(); property TicTacToeLibrary::GameProcessor^ Processor { TicTacToeLibrary::GameProcessor^ get() { return m_processor; } } protected: virtual void OnNavigatedTo( Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; private: TicTacToeLibrary::GameProcessor^ m_processor; }; } So what’s in MainPage.g.h? A .g.h file contains a compiler-generated partial class definition for XAML pages. Basically, these partial definitions define the required base classes and member variables for any XAML element that has the x:Name attribute. Here’s MainPage.g.h: The partial keyword is important because it enables a type declaration to span files. In this case, MainPage.g.h contains compiler-generated parts, and MainPage.h contains the additional parts that I define. Notice the public and ref class keywords in the MainPage declaration. One difference between C++/CX and C++ is the concept of class accessibility. If you’re a .NET programmer, you’ll be familiar with this. Class accessibility means whether a type or method is visible in metadata, and therefore accessible from external components. A C++/CX type can be public or private. Public means that the MainPage class can be accessed outside of the module (for example, by the Windows Runtime or by another WinRT component). A private type can be accessed only inside the module. Private types give you more freedom to use C++ types in public methods, which isn’t possible with public types. In this case, the MainPage class is public so that it’s accessible to XAML. I’ll look at some examples of private types later. The ref class keywords tell the compiler that this is a WinRT type and not a C++ type. A ref class is allocated on the heap and its lifetime is reference-counted. Because ref types are reference-counted, their lifetimes are deterministic. When the last reference to a ref type object is released, its destructor is called and the memory for that object is released. Compare this to .NET, where lifetimes are less deterministic and garbage collection is used to free memory. When you instantiate a ref type, you typically use the ^ (pronounced “hat”) modifier. The ^ modifier is similar to a C++ pointer (*), but it tells the compiler to insert code to manage the object’s reference count automatically and delete the object when its reference count reaches zero. To create a plain old data (POD) structure, use a value class or value struct. Value types have a fixed size and consist of fields only. Unlike ref types, they have no properties. Windows::Foundation::DateTime and Windows::Foundation::Rect are two examples of WinRT value types. When you instantiate value types, you don’t use the ^ modifier: Also notice that MainPage is declared as sealed. The sealed keyword, which is similar to the C++11 final keyword, prevents further derivation of that type. MainPage is sealed because any public ref type that has a public constructor must also be declared as sealed. This is because the runtime is language-agnostic and not all languages (for example, JavaScript) understand inheritance. Now direct your attention to the MainPage members. The m_processor member variable (the GameProcessor class is defined in the WinRT component project—I’ll talk about that type later) is private simply because the MainPage class is sealed and there’s no possibility that a derived class can use it (and, in general, data members should be private when possible to enforce encapsulation). The OnNavigatedTo method is protected because the Windows::UI::Xaml::Controls::Page class, from which MainPage derives, declares this method as protected. The constructor and the Processor property must be accessed by XAML, and therefore both are public. You’re already familiar with public, protected and private access specifiers; their meanings in C++/CX are the same as in C++. To learn about internal and other C++/CX specifiers, see bit.ly/Xqb5Xe. You’ll see an example of internal later on. A ref class may have only publicly accessible types in its public and protected sections—that is, only primitive types, public ref or public value types. Conversely, a C++ type can contain ref types as member variables, in method signatures and in local function variables. Here’s an example from the Hilo C++ project: The Hilo team uses std::vector and not Platform::Collections::Vector for this private member variable because we don’t expose the collection outside of the class. Using std::vector helps us use C++ code as much as possible and makes its intention clear. Moving on to the MainPage constructor: I use the ref new keywords to instantiate the GameProcessor object. Use ref new instead of new to construct WinRT reference type objects. When you’re creating objects in functions, you can use the C++ auto keyword to reduce the need for specifying the type name or use of ^: Creating the TicTacToe Library The library code for the TicTacToe game contains a mixture of C++ and C++/CX. For this app, I pretended that I had some existing C++ code that I’d already written and tested. I incorporated this code directly, adding C++/CX code only to connect the internal implementation to XAML. In other words, I used C++/CX only to bridge the two worlds together. Let’s walk through some of the important parts of the library and highlight any C++/CX features not already discussed. The GameProcessor class serves as the data context for the UI (think view model if you’re familiar with MVVM). I used two attributes, BindableAttribute and WebHostHiddenAttribute, when declaring this class (like .NET, you can omit the “Attribute” part when you declare attributes): The BindableAttribute produces metadata that tells the Windows Runtime that the type supports data binding. This ensures that all the public properties of the type are visible to the XAML components. I derive from BindableBase to implement the functionality required to make binding work. Because BindableBase is intended for use by XAML and not JavaScript, it uses the WebHostHiddenAttribute (bit.ly/ZsAOV3) attribute. Per convention, I also marked the GameProcessor class with this attribute to essentially hide it from JavaScript. I separated GameProcessor’s properties into public and internal sections. The public properties are exposed to XAML; the internal properties are exposed only to other types and functions in the library. I felt that making this distinction helps make the intent of the code more obvious. One common property usage pattern is binding collections to XAML: This property defines the model data for the cells that appear on the grid. When the value of Cells changes, the XAML is updated automatically. The type of the property is IObservableVector, which is one of several types defined specifically for C++/CX to enable full interoperability with the Windows Runtime. The Windows Runtime defines language-independent collection interfaces, and each language implements those interfaces in its own way. In C++/CX, the Platform::Collections namespace provides types such as Vector and Map that provide concrete implementations for these collections interfaces. Therefore, I can declare the Cells property as IObservableVector but back that property by a Vector object, which is specific to C++/CX: So when do you use Platform::String and Platform::Collections collections versus the standard types and collections? For example, should you use std::vector or Platform::Collections::Vector to store your data? As a rule of thumb, I use Platform functionality when I plan to work primarily with the Windows Runtime, and standard types such as std::wstring and std::vector for my internal or computationally intensive code. You can also easily convert between Vector and std::vector when you need to. You can create a Vector from a std::vector or you can use to_vector to create a std::vector from a Vector: There’s a copy cost associated when marshaling between the two vector types, so again, consider which type is appropriate in your code. Another common task is converting between std::wstring and Platform::String. Here’s how: // Convert std::wstring to Platform::String. std::wstring s1(L"Hello"); auto s2 = ref new Platform::String(s1.c_str()); // Convert back from Platform::String to std::wstring. // String::Data returns a C-style string, so you don’t need // to create a std::wstring if you don’t need it. std::wstring s3(s2->Data()); // Here's another way to convert back. std::wstring s4(begin(s2), end(s2)); There are two interesting points to note in the GameProcessor class implementation (GameProcessor.cpp). First, I use only standard C++ to implement the checkEndOfGame function. This is one place where I wanted to illustrate how to incorporate existing C++ code that I’d already written and tested. The second point is the use of asynchronous programming. When it’s time to switch turns, I use the PPL task class to process the computer players in the background, as shown in Figure 4. void GameProcessor::SwitchPlayers() { // Switch player by toggling pointer. m_currentPlayer = (m_currentPlayer == m_player1) ? m_player2 : m_player1; // If the current player is computer-controlled, call the ThinkAsync // method in the background, and then process the computer's move. if (m_currentPlayer->Player == TicTacToeLibrary::PlayerType::Computer) { m_currentThinkOp = m_currentPlayer->ThinkAsync(ref new Vector<wchar_t>(m_gameBoard)); m_currentThinkOp->Progress = ref new AsyncOperationProgressHandler<uint32, double>([this]( IAsyncOperationWithProgress<uint32, double>^ asyncInfo, double value) { (void) asyncInfo; // Unused parameter // Update progress bar. m_backgroundProgress = value; OnPropertyChanged("BackgroundProgress"); }); // Create a task that wraps the async operation. After the task // completes, select the cell that the computer chose. create_task(m_currentThinkOp).then([this](task<uint32> previousTask) { m_currentThinkOp = nullptr; // I use a task-based continuation here to ensure this continuation // runs to guarantee the UI is updated. You should consider putting // a try/catch block around calls to task::get to handle any errors. uint32 move = previousTask.get(); // Choose the cell. m_cells->GetAt(move)->Select(nullptr); // Reset the progress bar. m_backgroundProgress = 0.0; OnPropertyChanged("BackgroundProgress"); }, task_continuation_context::use_current()); } } If you’re a .NET programmer, think of task and its then method as the C++ version of async and await in C#. Tasks are available from any C++ program, but you’ll use them throughout your C++/CX code to keep your Windows Store app fast and fluid. To learn more about async programming in Windows Store apps, read Artur Laksberg’s February 2012 article, “Asynchronous Programming in C++ Using PPL” (msdn.microsoft.com/magazine/hh781020), and the MSDN Library article at msdn.microsoft.com/library/hh750082. The Cell class models a cell on the game board. Two new things that this class demonstrates are events and weak references. The grid for the TicTacToe play area consists of Windows::UI::Xaml::Controls::Button controls. A Button control raises a Click event, but you can also respond to user input by defining an ICommand object that defines the contract for commanding. I use the ICommand interface instead of the Click event so that Cell objects can respond directly. In the XAML for the buttons that define the cells, the Command property binds to the Cell::SelectCommand property: I used the Hilo DelegateCommand class to implement the ICommand interface. DelegateCommand holds the function to call when the command is issued, and an optional function that determines whether the command can be issued. Here’s how I set up the command for each cell: You’ll commonly use predefined events when doing XAML programming, but you can also define your own events. I created an event that’s raised when a Cell object is selected. The GameProcessor class handles this event by checking whether the game is over and switching the current player if needed. To create an event, you must first create a delegate type. Think of a delegate type as a function pointer or a function object: I then create an event for each Cell object: Here’s how the GameProcessor class subscribes to the event for each cell: A delegate that’s constructed from a ^ and a pointer-to-member function (PMF) holds only a weak reference to the ^ object, so this construct won’t cause circular references. Here’s how Cell objects raise the event when they’re selected: void Cell::Select(Platform::Object^ parameter) { (void)parameter; auto gameProcessor = m_gameProcessor.Resolve<GameProcessor>(); if (m_mark == L'\0' && gameProcessor != nullptr && !gameProcessor->IsThinking && !gameProcessor->CanCreateNewGame) { m_mark = gameProcessor->CurrentPlayer->Symbol; OnPropertyChanged("Text"); CellSelected(this); } } What’s the purpose of the Resolve call in the preceding code? Well, the GameProcessor class holds a collection of Cell objects, but I want each Cell object to be able to access its parent GameProcessor. If Cell held a strong reference to its parent—in other words, a GameProcessor^—I’d create a circular reference. Circular references can cause objects to never be freed because the mutual association causes both objects to always have at least one reference. To avoid this, I create a Platform::WeakReference member variable and set it from the Cell constructor (think very carefully about lifetime management and what objects own what!): When I call WeakReference::Resolve, nullptr is returned if the object no longer exists. Because GameProcessor owns Cell objects, I expect the GameProcessor object to always be valid. In the case of my TicTacToe game, I can break the circular reference each time a new game board is created, but in general, I try to avoid the need to break circular references because it can make code less maintainable. Therefore, when I have a parent-child relationship and children need to access their parent, I use weak references. Working with Interfaces To distinguish between human and computer players, I created an IPlayer interface with concrete implementations HumanPlayer and ComputerPlayer. The GameProcessor class holds two IPlayer objects—one for each player—and an additional reference to the current player: Figure 5 shows the IPlayer interface. Because the IPlayer interface is private, why didn’t I just use C++ classes? To be honest, I did it to show how to create an interface and how to create a private type that isn’t published to metadata. If I were creating a reusable library, I might declare IPlayer as a public interface so other apps could use it. Otherwise, I might choose to stick with C++ and not use a C++/CX interface. The ComputerPlayer class implements ThinkAsync by performing the minimax algorithm in the background (see the file ComputerPlayer.cpp in the accompanying code download to explore this implementation). Minimax is a common algorithm when creating artificial intelligence components for games such as tic-tac-toe. You can learn more about minimax in the book, “Artificial Intelligence: A Modern Approach” (Prentice Hall, 2010), by Stuart Russell and Peter Norvig. I adapted Russell and Norvig’s minimax algorithm to run in parallel by using the PPL (see minimax.h in the code download). This was a great opportunity to use pure C++11 to write the processor-intensive part of my app. I’ve yet to beat the computer and have never seen the computer beat itself in a computer-versus-computer game. I admit this doesn’t make for the most exciting game, so here’s your call to action: Add additional logic to make the game winnable. A basic way to do this would be to have the computer make random selections at random times. A more sophisticated way would be to have the computer purposely choose a less-optimal move at random times. For bonus points, add a slider control to the UI that adjusts the game’s difficulty (the less difficult, the more the computer either chooses a less-optimal move or at least a random one). For the HumanPlayer class, ThinkAsync has nothing to do, so I throw Platform::NotImplementedException. This requires that I test the IPlayer::Player property first, but it saves me a task: The WRL There’s a great sledgehammer available in your toolbox for when C++/CX doesn’t do what you need or when you prefer to work directly with COM: the WRL. For example, when you create a media extension for Microsoft Media Foundation, you must create a component that implements both COM and WinRT interfaces. Because C++/CX ref classes can only implement WinRT interfaces, to create a media extension you must use the WRL because it supports the implementation of both COM and WinRT interfaces. To learn more about WRL programming, see bit.ly/YE8Dxu. Going Deeper At first I had misgivings about C++/CX extensions, but they soon became second nature, and I like them because they enable me to write Windows Store apps quickly and use modern C++ idioms. If you’re a C++ developer, I highly recommend you at least give them a shot. I reviewed just some of the common patterns you’ll encounter when writing C++/CX code. Hilo, a photo app using C++ and XAML, goes deeper and is much more complete. I had a great time working on the Hilo C++ project, and I actually refer back to it often as I write new apps. I recommend that you check it out at bit.ly/15xZ5JL. Thomas Petchel works as a senior programming writer in the Microsoft Developer Division. He has spent the past eight years with the Visual Studio team creating documentation and code samples for the developer audience. Thanks to the following technical experts for reviewing this article: Michael Blome (Microsoft) and James McNellis (Microsoft) Michael Blome has worked for more than 10 years at Microsoft, engaged in the Sisyphean task of writing and rewriting MSDN documentation for Visual C++, DirectShow, C# language reference, LINQ and parallel programming in the .NET Framework. James McNellis is a C++ aficionado and a software developer on the Visual C++ team at Microsoft, where he builds awesome C and C++ libraries. He is a prolific contributor on Stack Overflow, tweets at @JamesMcNellis. Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/dn166929.aspx
CC-MAIN-2018-43
refinedweb
4,363
54.63
I am not sure whether this matters, but I notice that you don't ever read anything from the ethernet client. I wonder what the library does when the buffer is full. It's a longshot, but you might consider reading what it has received, even if you just throw it away. I will try out using client.flush() every time I make a request, just to keep it clear. client.flush(); delay(10); client.stop(); #include <Ethernet.h>byte mac[] = { mac };const char serverName[22] = "subdomain.domain.com";EthernetClient client;void logData(char* n, char* d, int tank1, int tank2, int fhz){ //name, desc, tank1 level, tank2 level if (client.connect(serverName, 80)){ char bigstring[128]; char buffer[12]; bigstring[0] = 0; strcat(bigstring, "GET /logger?t="); strcat(bigstring, n); strcat(bigstring, "&d="); strcat(bigstring, d); strcat(bigstring, "&t1="); strcat(bigstring, itoa(tank1, buffer, 10)); strcat(bigstring, "&t2="); strcat(bigstring, itoa(tank2, buffer, 10)); strcat(bigstring, "&fl="); strcat(bigstring, itoa(fhz, buffer, 10)); strcat(bigstring, "&fr="); strcat(bigstring, itoa(freeRam(), buffer, 10)); strcat(bigstring, "&loc="); strcat(bigstring, itoa(clientLocationID, buffer, 10)); strcat(bigstring, " HTTP/1.1"); Serial.println(bigstring); client.println(bigstring); client.println("Host:subdomain.domain.com"); client.println(); client.flush(); delay(10); client.stop(); } else{ Serial.println("failed"); }}void setup(){ Serial.begin(9600); if (Ethernet.begin(mac) == 0) { Serial.print("failed"); // no point in carrying on, so do nothing forevermore: while(true); } // give the Ethernet shield a second to initialize: delay(1000); logData("Boot", "", 0, 0, 0);} logData("Pumping", "Update", getRecycledPercent(), getCityPercent(), getFlowHz()); Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=109623.0;prev_next=next
CC-MAIN-2015-11
refinedweb
291
51.04
What's New in Windows Server 2003 and ProLiant Architecture and Tools Windows 2000 made a gigantic leap in technology from Windows NT in terms of scalability, stability, industry-standard protocols, and manageability. In the process, Windows 2000 allowed companies to simplify and consolidate their computing environments, which resulted in significant savings. Before merging with HP, Compaq eliminated hundreds of domain controllers and simplified an NT domain structure that consisted of 13 master account domains and about 1,700 resource domains to a single root domain with three child domains. In my book, Windows 2000: Active Directory Design and Deployment, I dedicated three chapters to identifying new features, benefits, and business justification. Moving to Windows 2003 from Windows 2000 won't be nearly as dramatic as was moving from NT to Windows 2000, but there are some significant benefits. If you are migrating from NT to 2003, you can expect all the benefits of the migration to Windows 2000 plus the additional benefits provided by Windows Server 2003. While we outline the significant new features and benefits of Windows Server 2003 in this chapter, we also will identify benefits throughout the remaining chapters of this book and discuss how you can apply them in the various aspects of your Windows Server 2003 design and deployment. In this chapter, we won't attempt to identify every single change or improvement made since Windows 2000. Rather, we will focus on significant features that will aid system architects or Administrators in identifying benefits to their organizations that might help solve a particular problem, aid in justifying a migration to Windows Server 2003, or provide information that will aid in the design or reconfiguration of the Active Directory (AD) enterprise. In this chapter we focus on new features in Active Directory (AD), Networking, and Security. You can read about the new features in Exchange, Clusters, Virtual Private Networking (VPN), and Terminal Services (TS) in Chapters 12-15, respectively. Active Directory (AD) Some of the new features in AD fix problems with Windows 2000, whereas others add new functionality. A majority of the improvements that will make a difference in the Windows 2000 enterprise are in the area of replication and Global Catalog (GC) servers. In the sections that follow, we discuss some of the significant features and enhancements in this area. We explain some in detail, and summarize others because we detail them in subsequent chapters of this book. Universal Group Membership Caching Windows 2000 native mode, as well as Windows Server 2003, requires users to be authenticated by a Global Catalog (GC) server. This often causes a problem for remote sites that have no GC and must therefore authenticate across a WAN (Wide Area Network). Microsoft provided an option in the form of a Registry key that permitted authentication without contacting a GC. However, without GC contact, universal groups cannot be added to the user's token. Thus, if a deny ace was set for a universal group on a resource, and a member of that group was authenticated without a GC, that user would have access to the resource because the universal group would not be in the user's token. In Windows Server 2003, a new feature called Universal Group Membership Caching (sometimes called GC Caching) gives users a new option for dealing with this situation. Because at the time of this writing this feature is in its infancy, it is not well documented. Thus, we've chosen to provide a fair amount of detail here as it could have tremendous benefit for enterprises that have small remote sites or sites that do not have a local GC. Overview of Universal Group Membership Caching Universal Group Membership Caching allows a user to log on, be authenticated by a local domain controller (DC), and retrieve global and universal group memberships from a "cache" located as attributes to the user object on the local DCeven though the DC is not a GC. Group Membership Caching is not enabled by default and is intended to provide more efficient logon performance for users at sites where a GC is not justifiable, typically at smaller sites. Group Membership Caching is intended as a stop-gap until the number of users at a site justifies installation of a GC, as caching will require use of resources on the DCs to support it. The term "cache" as used here is not defined as you might normally think of a cachea temporary, volatile storage that is cleared on logoff or reboot. Rather, these values are stored as attributes of user objects in the AD and are purged only by an Administrator or by time-sensitive values. You create the cache by enabling the caching feature on the NTDS settings object in a site. When caching is enabled and the user logs on and is authenticated by a DC in that site, three attributes are added to the user object: msDS-Cached-Membership: This attribute contains all the universal and global groups the user is a member of as stored in the GC. msDS-Cached-Membership-Time-Stamp: This is the time that a user's cached membership was last updated. Certain triggers use this attribute to ensure that the group membership listed in the msDS-Cached-Membership attribute is up-to-date. msDS-Site-Affinity: This attribute contains the Globally Unique Identifier (GUID) of the sites where the user has logged on and a time stamp when the attribute was last updated. This is the only attribute of the three that is replicated via AD replication. NOTE Users who are authenticated by a DC that is also a GC will not have these attributes populated on that DC/GC. They will be populated on other DCs in the site that are not GCs. When you are authenticated by a GC, it always has the membership information and doesn't need to go anywhere else for the membership. Functional Level Requirements The Universal Group Membership Caching feature does not require any particular functional level. In fact, you can have Windows 2000 DCs in the domain and in the site where Universal Group Membership Caching is enabled. However, this can be a serious problem because Windows 2000 DCs don't have this functionality. Therefore, if a Windows 2000 DC validates the user, the group membership will be inconsistent because the Windows 2000 DC will have to always contact the GC. It is recommended that all DCs in a site where Universal Group Membership Caching is enabled are Windows Server 2003 DCs. Facilitating Universal Group Membership Caching Universal Group Membership Caching is a site attribute that must be enabled specifically in the properties of the NTDS Site Settings object for each site on which you want Universal Group Membership Caching functional. To enable this feature, follow these steps: In the Sites and Services Snap-in, click on the site icon of the site you want to enable Universal Group Membership Caching for. In the right pane of the snap-in, right-click on the NTDS Site Settings object and select Properties. In the Properties window, select the box for Enable Universal Group Membership Caching, as shown in Figure 1.1. Click OK to close the Properties dialog box. Repeat this process for each site that is to have Universal Group Membership Caching turned on. Figure 1.1 Setting the Enable Universal Group Membership Caching option in the NTDS settings object via the Sites and Services snap-in. NOTE Caching for any user happens only on the sites in which it is enabled. Thus, a user can log on and be authenticated by a DC using cached memberships at one site, then travel to another where Universal Group Membership Caching is not enabled, and be required to contact a GC to be authenticated. Enabling Universal Group Membership Caching on Initial User Logon After caching is enabled on a site, each user's group membership is stored on the authenticating DC in that site after the user's initial logonafter caching is enabled. The msDS-Site-Affinity attribute is populated with that site's GUID and is replicated to the other DCs in the site. This is accomplished in the following sequence of events. Refer to Figure 1.2 for the domain configuration in this and subsequent examples in this document. Universal Group Membership Caching is enabled at the Atlanta site. User "Joe" logs on and is authenticated by DC ATL-DC1. ATL-DC1 contacts a GC server, DAL-DC6 in the Dallas site. The three attributes, msDS-Cached-Membership, msDS-Cached-Membership-Time-Stamp, and msDS-Site-Affinity, are all populated. Figure 1.2 Domain configuration for scenarios used in this section. msDS-Cached-Membership contains the Security Identifiers (SIDs ) of all the global and universal groups that the user is a member of, obtained from the GC, DAL-DC6. msDS-Cached-Membership-Time-Stamp contains the time that the group membership attribute was updated. (In this case, it's the time the attribute was initially populated.) msDS-Site-Affinity contains the Atlanta site. This attribute contains GUIDs of all the sites that the user has logged on to. The msDS-Site-Affinity attribute value is populated to the other DCs in the site. Table 1.1 lists the attribute values populated for Joe after the initial logon (note that this is a conceptual illustration only; the group memberships are actually a binary blob). This table shows Joe's user object as viewed from all three DCs in the Atlanta site. Table 1.1 Attributes After Initial Login with Universal Group Membership Caching Enabled and Authentication by ATL-DC1 Figure 1.3 and 1.4 illustrate ADSIedit showing the cache of a user who has logged in for the first time to a site with caching enabled. Figure 1.3 shows the msDS-Cached-Membership and msDS-Cached-Membership-Time-Stamp attributes, and Figure 1.4 shows the msDS-Site-Affinity attribute. Note that while ADSIedit shows the hex representation, LDP simply shows this as <binary blob>, as shown in Figure 1.5. Caching Behavior After Initial Logon in a Site After the cache attributes are populated by the DC that authenticates Joe, and the Site Affinity attribute is replicated to the other DCs in the Atlanta site in the example, subsequent attempts by Joe to log on will be handled as described in the upcoming case scenarios. (Refer to Figure 1.2.) Prior to describing these three basic authentication scenarios, however, we need to define some terminology. We will present more detail on these parameters in the "Managing Cache Parameters" section. Site Stickiness: This value defines the maximum length of time a user's Group Membership Cache will be refreshed. If the time stamp is less than one-half of the stickiness setting, the attributes are refreshed. If it is between 50% and 100% of the stickiness setting (default = 180 days), the cache is refreshed when the user logs on or changes his or her password. If the time stamp is greater than the stickiness setting, the cache is cleared and the user must contact a GC to log on. Staleness Threshold: Specifies the lifetime of cached memberships. The Staleness Threshold is compared to the msDS-Cached-Membership-Time-Stamp. If the time stamp, compared with the current time when a user logon attempts to use the cached memberships for the security token, is older than the staleness value, the user is forced to contact a GC for group membership, which will repopulate the msDS-Cached-Membership value and reset the time stamp. Refresh Interval: This parameter specifies the time between cache refreshes. This is the period of time when a DC will issue a cache refresh to update group memberships for users in its site. Refresh Limit: This parameter defines the maximum number of users on a single DC whose cached attributes can be refreshed in each refresh cycle. The default is 500, but there is no limit. Refer to the Managing Cache Parameters section for more on this important value. Falling Behind Check: This check determines whether the refresh process is keeping up. A search is made for the oldest msDS-Cached-Membership-Time-Stamp value. If that time stamp is older than the staleness interval, error event ID 1670 is logged, stating that the refresh task has fallen behind. Figure 1.3 User's populated msDS-Cached-Membership and msDS-Cached-Membership-Time-Stamp attributes via the ADSIedit.msc tool. Figure 1.4 User's populated msDS-Site-Affinity attributes via the ADSIedit.msc tool. Figure 1.5 The LDP tool shows the Site Affinity attribute as a <binary blob>. Now that the terminology is defined, we can consider the following example scenarios. Example 1 Joe logs in and is authenticated by ATL-DC1 again. A check is made for the Staleness Threshold. If the Staleness Threshold is not exceeded (one week by default), ATL-DC1 populates Joe's token with the membership list contained in the msDS-Cached-Membership attribute without contacting the GC. If the Staleness Threshold is exceeded, and cache refresh has not purged the values on the caching attributes, the DC contacts a GC for group membership in the authentication process. Example 2 Joe logs in and is authenticated by ATL-DC2 or ATL-DC3. Joe's msDS-Cached-Membership attribute and associated time stamp are populated during normal cache refresh by the DCs. On cache refresh, the DC examines the site GUIDs stored in Joe's msDS-Site-Affinity attribute. If one of those is the GUID of the site the DC is in, the DC contacts the GC (DAL-GC6) and populates the msDS-Cached-Membership attribute. If this refresh is completed before the user is authenticated by ATL-DC2 or DC3 and the user logs in before expiration of the time stamp, the user gets his group membership from the DC without contacting the GC. Note that the msDS-Cached-Membership-Time-Stamp is set when the msDS-Cached-Membership attribute is populated initially or during a refresh, so this could be different on each DC. Figure 1.6 shows the ADSIedit view of the state of a user's cached attributes on a DC that did not authenticate the user. In this case, the DC has had the Site Affinity attribute replicated, but the cache refresh has not taken placethus the msDS-Cached-Membership and msDS-Cached-Membership-Time-Stamp are <Not Set>. Figure 1.7 shows that the msDS-Site-Affinity attribute is set (GUID of the site). Figure 1.8 shows the LDP view of this same situation. Note that LDP shows only the attributes that are populated, so only msDS-Site-Affinity is set, and the other two don't show up at all. Figure 1.6 View of DC where user was not authenticated, showing msDS-Cached-Membership and msDS-Cached-Membership-Time-Stamp attributes not populated. Cache refresh has not happened. Figure 1.7 View of DC where user was not authenticated, showing msDS-Site-Affinity attribute populated. Cache refresh has not happened. Figure 1.8 Using LDP.exe to view DC where user was not authenticated, showing msDS-Cached-Membership and msDS-Cached-Membership-Time-Stamp attributes not populated and the msDS-Site-Affinity attribute populated. Cache refresh has not happened. Example 3 Cache refresh occurs when the other DCs in the site identify that the user's msDS-Site-Affinity attribute contains their site's GUID and populates the msDS-Cached-Membership attribute. After cache refresh is completed, the attribute values for Joe would be as shown in Table 1.2. Table 1.2 User Joe's Attribute Values After Cache Refresh Logging into Remote Sites Again referring to Figure 1.2, suppose Joe is a mobile user and he travels to the Chicago site to work for two weeks. When he logs on and is authenticated by CHI-DC10, the DC determines that Chicago's site is not in Joe's msDS-Site-Affinity attribute, so it contacts a GC to get Joe's membership and populates the cache attributes, including adding a new time stamp and adding Chicago's site GUID to the msDS-Site-Affinity attribute. On the next refresh, CHI-DC11 will populate Joe's attributes as well. In this configuration, sites Dallas and Seattle are core sites with many users, good bandwidth, and GC servers at each site. Therefore, Universal Group Membership Caching is not enabled at those sites. If Joe travels to Seattle and logs in, the authenticating DC contacts a GC for Joe's group membership as it normally would. Time Passes . . . Joe completes his work in Chicago and returns to his home office in Atlanta. After a period of time, if Joe does not log in or change his password from Chicago, his attributes are purged from the Chicago DCs, including the site affinity. We will discuss these timeouts in the upcoming "Refreshing the Cache" section. If Joe goes back to Chicago after this time, his attributes will be refreshed as they were the first time he logged in. This guarantees that Joe's group membership is up-to-date. WARNING After the group membership attribute is populated, the DC will not contact a GC again for the user's membership until the next cache refresh. It will always use the cached membership in the msDS-Cached-Membership attribute. This can be a problem, especially in troubleshooting. If the Administrator changes the user's group membership (that is, he adds Joe to a new universal group) and has Joe log on, the new group might not be part of Joe's token. The administrator can force a cache refresh to update the membership, as described in the "Refreshing the Cache" section of this chapter. Refreshing the Cache Refreshing the cache is critical. If the cache isn't refreshed in a timely fashion, the user will not have the correct group membership because the security token is built from the cached attribute. The refresh process is not trivial, and the DC performs a number of actions to keep the cache up-to-date. This refresh is completed independently every eight hours, or on reboot, on each DC for all users. Stale cached attributes are eventually purged. For example, user Joe in our example traveled to Chicago from his home site in Atlanta. While he is in Chicago, his site affinity time stamp will be refreshed regularly while he is logged on. After he leaves, assuming the site stickiness setting is left at the default, Joe's cached attributes will be refreshed for another 90 days, even if he doesn't log on. When Joe returns to Atlanta, his cache for Chicago will be refreshed for another 90 days. Let's say Joe returns to Chicago and logs in 120 days after he left. Because he is beyond one-half the stickiness setting and less than the total stickiness setting, the site affinity time stamp will be refreshed when he logs on. If Joe returns after 180 days since leaving Chicago, he will have to contact a GC to get his cache populated because it will have been purged. These checks are to ensure that mobile users who go from site to site are not logging on with stale membership caches. NOTE If the msDS-Cached-Membership values are purged, the worst thing that can happen is that the user will have to contact a GC when he or she logs in again, and if one is not available, cached credentials will be used. If cached credentials fail, login will be denied. Managing the Cache The cache update mechanisms and checks introduced in the previous sections are somewhat confusing and hard to keep track of, but they are configurable. In this section, we will explain how to configure the parameters and manage the cache. Setting the Registry You control cache refresh parameters through Registry settings. It is important that you understand what you are doing before changing these values as they can have a negative impact on WAN traffic and user logon performance. Cached Membership Site Stickiness: This parameter is configurable through the Registry at: HKLM\CurrentControlSet\Services\NTDS\Parameters Value: "Cached Membership Site Stickiness (minutes)" Data Type: REG_DWORD Default: 180 Days Staleness Threshold: This value is configurable through the following Registry parameter: HKLM\CurrentControlSet\Services\NTDS\Parameters Value: "Cached Membership Staleness (minutes)" DataType: REG_DWORD Default: 1 week Cached Membership Refresh Interval: This is manually configurable through the following Registry parameter: HKLM\CurrentControlSet\Services\NTDS\Parameters Value "Cached Membership Refresh Interval (minutes) DataType: REG_DWORD Default: 8 hours Cached Membership Refresh Limit: This parameter is configurable through the Registry at: HKLM\CurrentControlSet\Services\NTDS\Parameters Value "Cached Membership Refresh Limit" DataType: REG_DWORD Default: 500 Diagnostic Logging: This parameter is similar to other NTDS Diagnostic logging parameters such as GC, Replication Events, Name Resolution, and so on, which were available in Windows 2000. The value's default is 0, meaning minimal logging. The range of values is 05, with 5 being very verbose. Microsoft recommends setting this value to 5 for troubleshooting. It will cause more verbose events to be recorded in the Application log. It is set in the Registry at: HKLM\CurrentControlSet\Services\NTDS\Parameters Value: 20 Group Caching DataType: REG_DWORD ValueData: 0-5 Default: 0 If you change these parameters from the default, you should be aware of the following: The longer the user's cache remains active, the more resources will be required by each DC in the site for refreshing the cache. Reducing timeouts for the cache forces the user to be authenticated by a GC more frequently. The most common administrative chore associated with Universal Group Membership Caching is forcing a cache refresh to clean things up and start over. You can accomplish this task in four ways: purging the cached attributes for a single user, refreshing the cache for all users on a single DC, and deleting all cached attributes for all users at all DCs in a site, forcing a refresh for the entire site. Deleting the Cache for a Single User The Administrator might want to do this if a user's group membership has changed and it is desirable for the effects to take place immediately rather than waiting for the cache to refresh. The Administrator can use ADSIedit to accomplish this, as outlined in the following steps: Open ADSIedit from Windows 2003 Support Tools. Expand the domain container, expand the Users folder, and drill down to the user object to be modified (for example, "Joe"). Right-click on the user object and select Properties. Browse the list of attributes to find the msDS-Cached-Membership attribute. In the Edit Value field, delete the existing value, or change it to zero (0). Repeat step 3 for the msDS-Cached-Membership-Time-Stamp attribute. The next time the user logs in, because these attributes are not populated, the user is forced to contact the GC to get group membership, which will in turn populate the user's cache with the new group membership and a new time stamp. Refreshing the Cache on a Single DC If some users' group memberships are out of date, it could be because their authenticating DC cache refresh failed. The Administrator can force a cache reset on a single DC by setting the updateCachedMemberships value to 1 on the rootDSE. The Administrator can do this using the LDP tool, as outlined in the following steps: Open the LDP.exe tool from the Windows Support Tools for Windows Server 2003. Connect to the server and bind as an Enterprise Admin, or a user that has the Refresh Group Cache for Logons right on the NTDS Settings Object for the DC. In the LDP tool, go to Browse Modify and enter updateCachedMemberships in the Attribute field and 1 in the Value field, and then press Enter. The result should look like the example in Figure 1.9. Select the Run button and the right-hand pane of the LDP tool should report "Modified" (also displayed in Figure 1.9). Figure 1.9 Setting the updateCachedMemberships attribute. NOTE Setting the updateCachedMemberships attribute triggers the DC to refresh the cache without rebooting the server. Another way to refresh the cache on a single DC is to reboot it. This triggers the refresh to occur about 15 minutes after reboot. Deleting the Cache for an Entire Site You can purge the Group Membership Cache for all users in a site by setting the Site Stickiness Setting to zero (0), as noted previously in the "Setting the Registry" section. Doing this on one DC in the site purges all the cached attributes on that DC, including the msDS-Site-Affinity attribute. The site affinity attribute reset is then replicated to all other DCs in the site. At the next cache refresh, the DCs determine that they don't have the site affinity attribute, and reset the msDS-Cached-Membership and the msDS-Cached-Membership-Time-Stamp attributes for all users. Conclusion At the time of this writing, the Universal Group Membership Caching feature is so new that there is really no data in terms of recommendations based on experience. However, Universal Group Membership Caching has some negative impact on users and on the domain. Because the cache is a static value that is refreshed or updated periodically, this can cause delays in the user being affected by group membership changes. Therefore, if you're thinking about implementing this feature at a site, take note of the following: The location of the nearest GC (is user performance acceptable?) The bandwidth of the inbound and outbound links to the site The number of users at the site (more users puts a heavier load on the DC) Whether an Administrator is available to maintain this (this is difficult to anticipate, but be aware that there will be some administrative overhead) Any increased hardware cost associated with upgrading to a GC If there are hundreds of users at a site, it might be prudent to locate a GC at that site, even if it is connected to the rest of the network via slow links. HP designed its network so that GCs are placed more frequently in sites with slow WAN links, thus shielding the users from those links. If there are only a few users in a small sales office, the use of Universal Group Membership Caching will give the users the performance of a local GC without the overhead and expense of having one at that site. The difference, of course, is the membership update latency. Global Catalog (GC) Improvements In addition to the Universal Group Membership Caching feature, several other significant improvements were made to GC server functionality, including improved replication performance of the partial attribute set (PAS), improvements in GC demotion performance, and improvements in the way GCs advertise themselves. Perhaps the biggest single improvement, not only in the arena of GC performance, but in all of Active Directory, is the addition of the Install from Media (IFM) feature. Partial Attribute Set (PAS) Replication GCs provide quick access to commonly used objects and attributes for any domain in the forest, reducing WAN traffic and improving search performance from the user's perspective. By definition, GCs contain all the objects of all domains in the forest, all the attributes of the objects in the domain for which the GC is a DC, and some of the attributes of the objects in the other domains in the forest. The objects and attributes for the other domains are stored in a read-only context and comprise the PAS, which is defined in the schema. Attributes in the PAS have the property isMemberOfPartialAttributeSet set to TRUE, which causes them to be replicated to the GC server. If an Administrator desires to add additional attributes to the PAS so that searches on certain attributes occur more quickly, he or she could edit the appropriate object via the Active Directory Schema Manager, and change the attribute from the Optional list in the object properties to the Mandatory list. This action sets isMemberOfPartialAttributeSet to TRUE. For instance, on the PrintQueue object, printColor is an optional attribute. An Administrator who is a member of the Schema Admins group desires to add printColor as a mandatory attribute so that attribute will be replicated to all GCs. Thus, a user visiting a site from another domain can locate a color printer faster because the local GC has the printColor attribute associated with the printers. To set this, the Administrator would open the Active Directory Schema Manager snap-in, right-click on the printQueue object on the left pane, go to Properties, and add the printColor attribute from the Optional list to the Mandatory list, as illustrated in Figure 1.10. In Windows 2000, an operation as simple as this would cause all GCs in the forest to perform a full synchronization of the read-only directory partitions, causing a bandwidth spike for each GC roughly equivalent to promoting a DC to a GC, and causing a temporary disruption of service. Windows Server 2003 changes this behavior by replicating only the changed attributes. This is a significant improvement in performance, making the attribute change almost insignificant in most cases. GC Partition Occupancy In Exchange 2000 and Windows 2000, there was an issue with Exchange failures caused during a GC promotion. Exchange 2000 and later versions rely on the GC for the Global Address List (GAL). When a GC is promoted, it does not require a reboot at the end of the process. When it is rebooted, the GC advertises itself as a GC and is used by Exchange for directory lookups. If it is rebooted before the read-only partitions are fully replicated, some MAPI clients might use the GC for the GAL, causing possible mail failure for those clients. Windows 2000 SP3 includes a workaround that allowed the Administrator to add the Global Catalog Partition Occupancy value to 6. This is located in the Registry at HKLM\system\currentcontrolset\services\ntds\parameters. This parameter does not allow the new GC to advertise itself until replication is complete for all naming contexts (NCs). (See Microsoft KB 304403 "Exchange Considerations for Promoting a Domain Controller to a Global Catalog Server" for more details.) Windows Server 2003 implements a new value in this same Registry location to set this behavior by default. The value is Global Catalog Promotion Complete, and the data for this value is set to 1 by default. This prevents the GC from advertising itself until the replication of all NCs to the GC is complete. At that point, DSAccess adds that GC to its GCList for use by Exchange clients. Figure 1.10 Changing an optional attribute to a mandatory attribute in the Active Directory Schema Manager. Install from Media (IFM) The Install from Media (IFM) feature is perhaps the single most significant improvement in the Windows Server 2003 GC features, and one of the top improvements in all of Active Directory. You enable this feature in DCPromo to permit replication from a restored backup of a DC or GC as the source, rather than replicating from a live DC or GC over the WAN. Thus, you can back up the system state of an existing DC/GC and then restore it to media that will be local to a server that will be promoted to become the new DC/GC. The media can be tape, CD, DVD, hard disk or other media that will be local to the new server (of course, the media must have the capacity to store the restored system state files). DCPromo can then be executed with the /ADV switch from a command line: DCPromo /ADV DCPromo produces an additional dialog box, shown in Figure 1.11, with the option to specify a path to the restored backup media. DCPromo will then use this media as the source to replicate the AD without touching a source DC. At the end of DCPromo, a connection is made to a live DC to source changes that occurred since the media was created. The "DCPromo" section later in this chapter details how the IFM feature works, and discusses the use of unattended answer files. Figure 1.11 The new DCPromo dialog box permits Administrators to specify a path to restored backup files to be used as a source for replicating AD, rather than replicating over the network. Although it is highly beneficial to build DCs using this feature, it's even more beneficial to build GC servers in this way because of the size of the GC compared to a DC. A good example is Hewlett-Packard's AD deployment. The system state backup of a GC in HP's environment is about 10 to 12GB, but can be defragmented to about 7.5GB. In Windows 2000, HP experienced a number of GC-related problems that required GCs to be rebuilt. Because of the size of the AD and available bandwidth on the network, rebuilding a GC took from three to five days, depending on the location. This seriously impacted the users because the GC is used for Exchange's GAL, and loss of a GC at a site required the users to find another GC for GAL operations, impacting performance and putting an additional load on other GCs. In some cases, HP actually had backup GCs in some sites to mitigate the downtime required if a GC had to be rebuilt. Initial testing of Windows 2003's IFM feature proved that a GC could be rebuilt in about 20 minutes from media. HP viewed this as a critical feature to making the AD environment more resilient and significantly reducing downtime. IFM was a key reason why HP migrated to Windows Server 2003. In fact, HP had migrated the Americas domain to Windows Server 2003 native in November 2002, shortly after the release of Release Candidate 3 of Windows Server 2003. Thus, HP was running its production environment on beta software. That speaks volumes for the importance of IFM as well as for the stability of Windows Server 2003. Today, in actual practice, HP can rebuild a GC using IFM in about 20 minutes. Removing GC Role One of the contributing factors in the lengthy process of rebuilding a GC in Windows 2000 was the time required to demote the GC. The operation is quite simple. In the Sites and Services snap-in, you right-click on the NTDS Settings object of a DC and select Properties. On the Properties page, there is an option for Global Catalog. If this box is checked, clearing it initiates a demotion process that removes the read-only partitions from that DC. In Windows 2000, the GC removal process was limited to about 500 objects every time the Knowledge Consistency Checker (KCC) ran. By default, this was every 15 minutes. Thus, an AD with 4,000 users, 6,000 computers, and 500 groups (total of 10,500 objects) would require 21 iterations of the KCC to clean up one GC and make it a DC. Using the default 15-minute interval, this would require 5 hours and 15 minutes to complete this change. Windows Server 2003 changed the way this demotion is handled. Instead of replicating a certain number of objects per each KCC cycle, the operation continues removing objects until all objects are removed. Replicating these objects is a low priority among replication tasks, so if another replication request comes in, it takes priority. Thus, if you remove the GC role during low utilization periods, the process continues, possibly uninterrupted. Otherwise, it uses available bandwidth until the job is complete. This results in a more efficient way to remove the GC. Combined with the IFM feature, removing a GC role and adding the role to another DC is much faster and more efficient. Domain Controller Rename While supporting Windows 2000 Administrators during the past several years, I ran into a number of situations in which the name of the DC had to be changed. The problem with Windows 2000, of course, is that the only way to change the computer name of a DC is to demote it, change the name, and then repromote it. This is a complex process to perform a simple task. Of course, the answer in NT was worseyou had to reinstall the DC. Windows Server 2003 provides a very viable feature called Domain Controller Rename (not to be confused with Domain Rename). This functionality requires the domain to be in Windows Server 2003 domain functional level and can be performed either via the GUI (Graphical User Interface) or by using the Netdom option. You'll learn both methods in the following sections. The Netdom method gives you more options, such as renaming the NetBIOS or the DNS (Domain Name System) name, whereas the GUI method renames both. NOTE The Netdom method of renaming a DC requires the domain that the DC is a member of to be in Windows Server 2003 functional mode (all DCs are Windows Server 2003), whereas the GUI method works in Windows 2000 Native or Windows Server 2003 functional levels but only on Windows Server 2003 machines. Using the GUI Method This method is fairly simple. Use the same process you would use to rename any Windows 2000 Professional, Windows 2000 Server, Windows Server 2003 member server, or XP workstation. Right-click on My Computer, select Properties, and select the Change button in the Computer Name tab. A pop-up message appears, as shown in Figure 1.12. Just click OK and the familiar Computer Name Changes dialog box appears that allows you to change the name, as shown in Figure 1.13. You are prompted for credentials and, if all goes well, you are notified of the need for a reboot. As you can see, this process is pretty much the same as the process for renaming any other computer. This process modifies Registry values and cleans up DNS (mostly). If you want to see what is going on under the hood, or if you want to change the NetBIOS or the DNS name (but not both) read the "Using the Netdom Method" section coming up next. Using the Netdom Method Windows Server 2003 added a couple of new options to the Netdom command-line utility: Computername and RenameComputer. The RenameComputer option isn't made to work for a DC. Although it does seem to work without error, it doesn't do all the things it needs to for a DC rename, so don't use it. Using the Netdom Computername command requires several steps, and the process gives you a good view of what is going on under the hood. The steps to rename a DC with the existing name of DC1 to ATL-DC1 are as follows: NOTE Before proceeding, you must set the domain functional mode to Windows Server 2003 (all DCs in the domain must be Windows Server 2003). From a command prompt, execute the following command: Where <CurrentComputername> is the current name for the DC (the simple NetBIOS name), and <newcomputername> is the new name it is to be changed to, in Fully Qualified Domain Name (FQDN) format. The Netdom command for the example is Note that <existingcomputername> is always the current name of the computer. Verify the success of the addition of the new name with the Netdom /enumerate command. For this example, the following command would be used. Here we see that DC1.corp.net and ATL-DC1.corp.net are listedthe old name and the new name we just defined. Now define the new computername as the primary with the Netdom /makeprimary command: At this point, the /enumerate command will not work correctly until the computer is rebooted and the new computername is recognized. Verify the results by executing the following command: You will see the old name, DC1.Corp.net, listed twice, unlike the previous /enumerate command, in which the new and old name were listed. This is expected behavior and will be corrected after rebooting the computer, but don't reboot yet. Just for observation, open Regedt32, go to HKLM\System\CCS\Services\TCPIP\Parameters, and observe the NV HostName value. NV HostName should now reflect the new name, ATL-DC1. Reboot the computer and log in as a Domain Administrator. Open a command window and use Netdom to enumerate the computernames. Note that we have used the new name of the DC, ATL-DC1 as the first computername parameter: Delete the old computername, DC1, by executing the following command: Check to make sure the new name is recognized: Netdom Computername <currentcomputername> /add:<newcomputername> Netdom Computername DC1 /add: ATL-DC1.company.com Figure 1.12 Warning message when attempting to rename a DC from within the UI (user interface). Figure 1.13 Familiar dialog box to rename a computernow available to rename a DC. WARNING The Netdom option called computername should not be confused with an actual computername. You should enter the word Computername after the Netdom command, followed by the existing computername, as in this example. C:> Netdom Computername DC1 /enumerate DC1.company.com ATL-DC1.company.com Netdom Computername DC1 /makeprimary:ATL-DC1.company.com WARNING Remember that the <existingComputername> is always the NetBIOS version of the existing computername, and the <newComputername> used for arguments such as /makeprimary, /add, /enumerate, and /remove is always the FQDN version of the namejust as in the examples here. Netdom Computername DC1 /enumerate DC1.company.com DC1.company.com Netdom computername ATL-DC1 /enumerate The results show DC1 and ATL-DC1 listed, with ATL-DC1 listed as the primary name. Netdom computername ATL-DC1 /remove:DC1.company.com From a command prompt, issue the command Hostname to return the new name. Go to My computer, select Properties, and then click the Computer Name tab. The new name should be displayed. Open the DNS management snap-in on a DNS server and walk through the SRV records. There should be no records with the old nameonly records with the new name. DNS Caveat Although both methods of DC rename do a good job of cleaning up DNS, they both fail in changing the name of delegation records with the old computername. This can be a big problem if you let DCPromo configure DNS on the forest root DC (the first one in the forest) because it automatically delegates the _msdcs zone to that first DC. If you have child domains and use this delegation, a DC from each domain will have a delegation record to this zone. If you rename any of these DCs, the delegation record will not be updated (as of the RTM release of Windows Server 2003). This is demonstrated in Figure 1.14. This is a screen shot of the DNS snap-in of a DC, previously named ALMA.Company.com, renamed to ATL-DC1.company.com. Note that the _msdcs zone is delegated, and there is one delegation record to ALMA.Company.com. Left in this state, all queries for Cname records and GC records will fail because the referral will go to a nonexistent server. You can easily change this by right-clicking on the record in the right pane, selecting Properties, selecting EDIT, and then entering the correct name and the IP address. Do this for each delegation record that points to a renamed DC. Figure 1.14 DCRename function does not clean up DNS delegation records for the renamed DC. Application Partitions One of the criticisms of AD has been that its scalability is limited by the fact that you have only three naming contexts: configuration, schema, and domain. Windows 2003 introduced application partitions. An application partition is a user-defined naming context that can be hosted by any set of DCs from any domain. Thus, there is no domain boundary in such a partition. You create the partition in the NTDSUtil tool. When you create such a partition, you also create a DNS forward lookup zone and place SRV records of the DCs that host the partition. Think of a partition as a truck and data, such as the zone information, as cargo on the truck. When you replicate the partition, the zone information goes with it. You can add other data to the partition and replicate it to the DCs in the replica set. Application partitions have the following characteristics: User-created and user-managed. Can contain DCs across domains, but within a single forest. Cannot contain security principals. Can be queried using Lightweight Directory Access Protocol (LDAP). Can be replicated using normal AD replication. Can be located using DNS SRV records. Impacts the site topology in terms of replication traffic. These partitions replicate in addition to the configuration, schema, and any domain partitions defined by default. Observes site topology and schedule. Can't include GCs as replicas. Can be created directly by applications. Hosted only by Windows Server 2003 DCs. How Application Partitions Work Figure 1.15 shows how an application partition, Payroll.company.com, was created in the Company.com forest. The forest also contains EU.company.com and NA.company.com child domains. The application partition contains a DC from each of the three domains. Thus, DC1, DC3, and DC5 host the Payroll NC as well as the schema, configuration, and respective domain NCs. This partition is represented in the figure as a triangle, which usually denotes a domain. This is appropriate because this partition is a NC just like a domain is, although with limited capabilities. As noted previously in this section, executing Repadmin /showreps on one of the DCs lists the application partition's replication information just as any other NC: Kansas City\NA-DC5 DC Options: (none) Site Options: (none) DC object GUID: 5b557f71-d9f1-4ad2-9252-185eefa117eb DC invocationID: ac23b6a7-9734-4388-b644-80ba020aab13 ==== INBOUND NEIGHBORS =============================== <snip> DC=Payroll,DC=company,DC=com Seattle\Company-DC1 via RPC DC object GUID: df3cf60f-5b62-469a-a957-1782b52a00e8 Last attempt @ 2003-11-07 19:47:56 was successful. Oslo\EU-DC3 via RPC DC object GUID: 144b8bc1-3321-4fcf-9b27-40c3f2cc0346 Last attempt @ 2003-11-07 21:32:52 was successful. Figure 1.15 User-defined application partitions can use any DC from any domain in the forest as a replica. Default Application Partitions: ForestDnsZones and DomainDnsZones Microsoft implemented two application partitions in Windows 2003 domains that are created and configured by default when a domain is created. They are called ForestDnsZones and DomainDnsZones, and you can see them in the DNS snap-in as forward lookup zones. All DCs (including GCs) in the forest are replicas for the ForestDnsZones partition, and all DCs in a domain are replicas for the DomainDnsZones partition. There is a separate DomainDnsZones partition for each domain in the forest. We describe these partitions in detail in the "DNS" section in Chapter 6, "The Physical Design and Developing the Pilot." Microsoft says it's inappropriate to replicate data where it isn't needed. In an Active Directory Integrated (ADI) zone, the zone data is held in AD and is replicated to all DCs, whether they are name servers or not. With the application partitions of ForestDnsZones and DomainDnsZones, DNS zone information is replicated only to DCs that are also DNS servers. ForestDnsZones contain only SRV records of DCs who are also DNS servers in the forest, and DomainDnsZones contain only SRV records of DCs who are also DNS servers in the domain. Each domain has one of these zones. Because it really isn't recommended to use these default partitions for other purposes, let's look at an example of how you can use a custom application partition. User-Defined Application Partition Example The CFO of a company wants to develop a new in-house application to manage the compensation plan of the company's employees. Most of the data that the application will use is semi-static (pay rate, tax ID, health benefit selections, health benefit costs, and so on) and typically changes only on an annual basis. The human resources organizations that will leverage the application are split into two distinct groups. The NACompensation group manages North American employees and is located in New York. The APCompensation group manages Asia-Pacific employees and is located in Tokyo. The CFO mandates to the developers that unlike most information in the AD, the data managed by this application should be considered sensitive and should be replicated only between New York and Tokyo (both hub sites), but nowhere else. The in-house developers decide that the data needs to be replicated between both the New York and Tokyo sites and should also be updated from both locations for the purposes of day-to-day human resources functions, data analysis, and application fault tolerance. As such, the developers determine that the type of data, the data's user affinity, the requirement for replicated data, and the need for multi-master updates fit well with the features and capabilities of AD. The developers decide to use an AD application partition, which is created on a DC in New York, followed by the addition of a Tokyo DC to the replica set. After the DCs have a replica of the application partition, they register an A record in DNS for the application partition name as well as an _ldap SRV record for the site in which the server resides. The benefits of this architecture include the following: The application server can obtain data via the LDAP from the AD. The application can use DNS to locate a local LDAP server hosting the application partition. The AD will allow data to be written to the AD partition in either the New York or Tokyo DC. Data written to either DC will replicate to the DC in the other geography, but not to any other DCs. If the DC in New York fails, the application can fail over to the DC in Tokyo (the reverse is true as well). The down side to this is that these partitions will work only on DCs, and it has long been recognized that installing applications on DCs is not a best practice. Another option is another Microsoft product called Active Directory Application Mode (ADAM). ADAM allows LDAP querying and replication to nondomain controllers but has some restrictions. We discuss ADAM in Chapter 5, "Active Directory Logical Design." Creating an Application Partition In the following example, we will create an application partition called MyAppPart in a forest that has three domains: Company.com, NA.company.com, and EU.com. From a command prompt, run ntdsutil.exe. Go to the Domain Management menu, then to the Connection menu, and connect (bind) to a DC in the domain. In this case, we'll assume we connected to DC1. Create an application partition named MyAppPart. At the domain management command prompt, type Make sure the MyAppPart folder exists under the NA.Company.com forward lookup zone and that there is an SRV record in it for DC1. To add DC2 from the Company.com domain, at the Domain Management menu, type Again note that there are SRV records for this new DC in the MyAppPart zone in DNS. You also can list all the DCs hosting the partition by going in NTDSUtil to Domain Management and entering this command: All the DCs added as replicas should be listed. create nc dc=myAppPart,dc=na,dc=company,dc=com dc1.na.company.com add nc replica dc=myAppPart,dc=company,dc=com dc2.na.company.com list nc replica dc=myAppPart,DC=company,dc=com Finally, when a DC is demoted, DCPromo recognizes whether that DC is the last replica of an application partition. You will see a screen listing the application partitions and asking for confirmation that you want to continue and delete these partitions. AD Replication Microsoft made a number of improvements to AD replication. This section provides a quick summary of these improvements, but you'll find a more detailed description, including examples of implementation, in the "Replication Topology" section of Chapter 5. Lingering Objects Lingering objects have been causing problems in Windows 2000 deployments for some time, yet at conferences, none of the attendees recognize this issue. Simply stated, lingering objects are objects that are reanimated after their tombstonelifetime expires and is purged. This is caused when a DC or GC comes back online after having been offline for more than the tombstonelifetime period, 60 days by default. Objects that were deleted, tombstoned, and purged while the DC/GC was offline are replicated back into the environment when the DC/GC comes back online. This causes security problems because the user object of a dismissed employee could be reanimated, cause replication to break, and otherwise clutter the AD. The real problem is when a GC comes back online and reanimates read-only contexts of the objects, which were difficult or impossible to delete before Windows 2000 SP3. Windows 2003 and Windows 2000 SP3 and later provide functionality to prevent these objects from replicating through the forest and permit deletion of the read-only objects via a Registry key. "Tight" behavior refers to a condition in which replication from a DC/GC trying to reanimate purged objects is shut down until it is repaired. "Loose" behavior allows the lingering objects to be reanimated. Loose behavior is the default in Windows 2000 and is the default after upgrading from Windows 2000 to Windows Server 2003. We discuss this thoroughly in Chapter 5. ISTG Performance and Practical Limit to Number of Sites Even when Windows 2000 was still in beta, Microsoft was promising improvements in the performance of the Intersite Topology Generator (ISTG). The ISTG uses the spanning tree algorithm to generate the connection objects and the AD replication topology. This is the foundation of AD replication. The efficiency of this topology determines replication latency and the time the AD takes to perform its calculations. The performance of the KCC was inefficient enough to impose a practical limit on the number of about 200 sites in a topology in Windows 2000. Windows Server 2003 has a completely rewritten spanning tree algorithm that makes dramatic improvements in the ISTG's performance, raising the site limit to about 3,000, according to Microsoft testing as of this writing. It also has improved general AD performance and reduced latency in many cases. Chapter 5 provides a complete description of this issue. Bridgehead Load Balancing Another limit in Windows 2000 was the number of sites that could be connected to a single hub site in a single domain. That is, if you have a strict hub and spoke topology and a single domain, you are limited to about 100 to 150 sites connected to a hub site. This is due to the fact that the KCC will only pick one Bridgehead Server (BHS) per domain per site, and large numbers of sites put a load on that single DC in the hub site sufficient to impact the DC's performance. The solution in Windows 2000 was to create all the connection objects manually, making connections from the site BHS to multiple DCs in the hub site. Unfortunately, this had to be managed manually as well. Windows Server 2003 provides the Active Directory Load Balancing Tool (ADLB), which is a GUI-based tool you can use to create and manage these connections. Chapter 5 provides details on this feature as well. Improved Data Compression Windows Server 2003 has improved the algorithm that decompresses inter-site replicated data. This improves replication performance and reduces latency. Windows Server 2003 also permits you to turn off inter-site compression of data, trading the increased bandwidth for local DC performance. (See Chapter 5 for additional details.) Other Chapter 5 also covers a number of improvements in Windows 2003 Server in the area of AD replication. The chapter describes and analyzes practical examples and case studies of companies that have had success and failure in deploying AD in Windows 2000 and 2003. FRS and DFS Chapter 5 also covers the new features and fixes made in Windows Server 2003, and provides a good description of new troubleshooting and diagnostic tools. For the purpose of this chapter, a brief summary is in order. FRS performs serialized version vector joins: Windows 2000 used parallel version vector joins when a DC joined the domain to source FRS content from other DCs in the domain. This caused all FRS content from all DCs to be pulled to the new DC at the same time, causing a high-bandwidth utilization on the network, and the sourcing DCs were unavailable for a period of time. Windows 2003 provides a serial vvjoin whereby one DC is sourced for the new DC, and then the others are sourced, one at a time, for changes, resulting in better performance and higher availability of the DCs. Changes to the automatic non-authoritative restore functionality: When Windows 2000 FRS encountered certain serious errors, such as Journal Wrap, it would automatically perform a nonauthoritative restore from a good DC to the one with the error, forcing a full sync of FRS content. This caused the sourcing DC to be unavailable for a period of time. Windows 2003 turns this behavior off by default, logging an event to inform the Administrator that a nonauthoritative restore should be performed at the Administrator's earliest convenience. You can turn the default back to automatic via a Registry key. NTFS Journal size: FRS uses the NTFS Journal to identify changes to files in the SYSVOL tree and then issue change orders to replicate those files. When the NTFS Journal was filled, it would overwrite the entries at the start, causing FRS to get lost, break replication, and require a nonauthoritative restore to get going again. Windows 2003 raised the Journal size from 32MB in Windows 2000 to 128MB. FRS detects and suppresses excessive replication: Windows 2003 makes FRS more tolerant in the event of an application that scans the SYSVOL tree, such as antivirus or disk defragmenter programs. These programs can cause large numbers of files to be copied to the staging directories. FRS now identifies situations where files are being replicated repeatedly in short periods of time and suppresses the replication, accompanied by an event. FRS does not stop replicating if the staging area is filled: Windows 2003 still has a 660MB limit on the staging area before replication is disabled, but it implements a cleanup operation. When 90% of capacity of the staging directory is filled, FRS deletes the oldest files until the directory is at 60% capacity, thus never reaching the limit. Allows compressed data replication: Windows 2003 FRS allows replication of compressed data, which is not possible in Windows 2000. Tools: Ultrasound and Sonar Multiple Distributed File System (DFS) roots on a single server: Windows 2000 allowed only a member server to host a single DFS root. Windows 2003 permits multiple DFS roots on a single server. DFS link targets can point to targets across different domains. The DFS MMC (Microsoft Management Console) snap-in that is included in Windows 2003 and the Windows 2003 Admin Pack includes the capability to customize a replica set's FRS replication topology. DFS referral list can be configured to prioritize DFS servers based on site cost, which is much more efficient than in Windows 2000. Time Services Kerberos authentication relies heavily on accurate time synchronization between all computers in the forest. By default, the time skew between any two computers in the forest must be five minutes or less. Windows 2003 uses the Network Time Protocol (NTP) for a much more efficient means of synchronizing computers in the network than Simple Network Time Protocol (SNTP) used in Windows 2000, with the capability to synchronize computers within milliseconds. Windows Server 2003 also provides a new version of the Win32tm.exe utility to configure time services. Chapter 5 describes in detail how time services work in conjunction with Kerberos for security, as well as time-service configuration and troubleshooting tips. Domain Rename If Windows Server 2003 were a retail business with a big electric sign out front advertising three exciting reasons to patronize the business, Domain Rename would likely be one of the three. With mergers, acquisitions, and divestitures becoming commonplace in the business community these days, the ability to rename a domain or forest is a very useful tool, especially because the alternative is to migrate users, groups, and computers from one domain/forest into another. In fact, HP is a good example of such a situation. Compaq had developed an extensive Windows 2000 infrastructure, participating as an early adopter in Microsoft's Rapid Deployment Program (RDP) and Joint Deployment Program (JDP). At the time of the merger with HP, Compaq was just completing a two-year migration of users from the old NT domains inherited from mergers with Digital and Tandem. HP, on the other hand, had a small NT environment and had not built a Windows 2000 structure at all. The decision was made to use Compaq's Windows 2000 infrastructure and to migrate the HP users into it. This made perfect sense, except for the name of the domain. The internal namespace for Compaq was CPQCORP.NET and was structured as shown in Figure 1.16. Thus, there became a business requirement to rename the domain. HP decided that the new domain should be HPQCORP.NETthe net change being one letterC to H! As of this writing, HP has not renamed this domain, but is planning on it. However, Microsoft has had a couple of customers successfully rename a domain, and Microsoft successfully renamed its corporate development domain as well. One of its customers mistakenly renamed a domain with Exchange 2003 (pre-SP1) and then had to rename it back to the original. Pretty impressive to do it twice, ending up with the same name and be successful. It also shows good resiliency. This section provides a fairly high-level description of how Domain Rename works to give you an idea of what's involved. We give pointers to Microsoft whitepapers that provide the details on how to actually rename a domain. The remainder of the section reviews Domain Rename from a design perspective, discussing capabilities and limitations of Domain Rename, application compatibility issues, details on Exchange compatibility, benefits and risks analysis, and a few examples along the way. Figure 1.16 Compaq's Windows 2000 and 2003 domain structure. How Domain Rename Works The Domain Rename procedure is well documented in two whitepapers, Understanding How Domain Rename Works, and Step-by-Step Guide to Implementing Domain Rename, which you can download from. In this section, we don't rehash the material in the whitepapers, but rather, summarize their contents and apply my experience to make recommendations. The whitepapers are the definitive guide to Domain Rename, so download, read, and use them. The step-by-step guide provides the actual procedure. I worked at Microsoft during the Windows 2003 beta documenting training materials for Domain Rename, and have monitored HP's Domain Rename efforts. In addition, I have worked with a few customers who were considering using it, so I've had a good bit of exposure to Domain Rename. Following is a high-level view of the procedure. The forest must be at Windows 2003 functional level, and all domains must be at Windows Server 2003 functional level. This means every DC in the forest must be Windows Server 2003. Identify a member server in a domain (must have reliable access to the domain naming master) from which to run the Domain Rename commands. Get the Domain Rename tools, rendom.exe and gpfixup.exe, from the Windows Server 2003 CD in the \ValueAdd\ MSFT\MGMT\Domren directory, from the Web at, or from the Web site that contains the whitepapers noted previously. These tools are also available on the Windows Server 2003 CD, but the versions included on early Windows Server 2003 CD releases broke Exchange. It's best to get them from the Web site to get any new versions available. The Step-by-Step Guide to Implementing Domain Rename whitepaper details the process used to rename the domain. Following is an overview of that process: Using the rendom.exe tool, generate an XML (Extensible Markup Language) listing of the naming contexts in the forest. Edit the XML, changing the old domain name to the new, and create a new DNS forward lookup zone for the new domain. Run rendom.exe and generate a list of the DCs in the forest. Run rendom.exe and upload the instructions for the Domain Rename, including the information in the XML just created, to the domain-naming operations master. This populates attributes msDS-UpdateScript and msDS-DNSRootAlias. The msDS-UpdateScript attribute actually contains the VB Script that performs the Domain Rename. In addition, as a side effect, the Service Principal Name attribute of the DC accounts is updated as well. You can view the script using the LDP tool as an attribute on the partitions container (CN=partitions,cn=configuration,DC=company,DC=com). Make sure all DCs can be contacted, and then execute the script on each DC. You can retry the command to execute the script as many times as needed until all DCs execute it successfully. The rename process generates a "state" file every time you execute the command to run the script on each DC. The state file reports the state of each DC (that is, whether it has been updated). Rerunning the command to execute the scripts does not execute on DCs that have been successfully updated. Run GPfixup.exe to fix Group Policy associations. Clean up Certificate Authority (CA), domain-based DFS volumes per the Microsoft whitepapers. Clean up other applications. Rename all DCs in the forest so they have the new DNS suffix. These steps have been included here to show you how complex this process really is, and that there really isn't an easy way back once you start. The key is step 5. You need to realistically determine how long it will take to contact every DC in every site in the entire forest. According to HP's AD team, end-to-end replication took a few hours, but they estimated that it could take several weeks to update all the DCs in the Domain Rename process. Now let's examine the capabilitieswhat Domain Rename can and can't doto determine whether this operation can meet your requirements. Capabilities of Domain Rename It is important to note that Domain Rename is not the same as "Prune and Graft." Prune and Graft operations usually imply a "merge" of two forests; that is, Company A buys Company B. Moving the B.com domain to become a child of A.com (B.A.com) is referred to as pruning and grafting. Domain rename is bounded by the forest. NOTE Domain Rename is not the same as Prune and Graft. Prune and Graft, or merging of domains across forests, is not possible in Windows 2003. Now let's see what you can and can't do with Domain Rename. The following list identifies significant operations that Domain Rename can perform: Rename a single domain. B.A.com [Right Arrow] X.A.com C.B.A.com [Right Arrow] C.Z.A.com Rename a domain to change its parent. C.B.A.com [Right Arrow] C.A.com C.B.A.com [Right Arrow] C.com C.B.A.com [Right Arrow] C.D.com Rename a domain to create a new domain tree within the same forest. C.B.A.com [Right Arrow] C.com Rename a forest root domain. A.com [Right Arrow] Z.com B.A.com [Right Arrow] B.Z.com Rename the DNS name, the NetBIOS name of a domain, or both. Some enterprises have had a problem when upgrading from Windows NT to Windows 2000 because their domain name included a special character such as a hyphen (Master-MUD), which was not supported by DNS. So they created a split name in Windows 2000 with the NetBIOS name retaining the name with the illegal character, and the DNS name comprising a new version without the character. Domain Rename enables you to rename the NetBIOS name without renaming the DNS name. Examples: Examples: Example: Example: Limitations of Domain Rename Domain Rename has a number of limitations, some of which could prevent you from deploying Domain Rename, forcing you to use a migration solution instead. These limitations include the following: The forest root domain cannot be restructured for placement in another location in the domain tree, such as moving it to become a child domain of another domain. B.A.com [Right Arrow] A.B.com A.com [Right Arrow] A.Z.com Applications may not support Domain Rename. See the upcoming "Application Compatibility" section of this chapter for more details. Renaming a domain impacts all child, grandchild, and so on, domains under it. You must rename all of them. All DCs must be able to be contacted during the rename process. If you can't contact them to execute the rename instructions, you have to shut them off and reinstall or manually demote them, and then promote them back into the new domain. Because the rename instruction is executed independently on each DC, if some DCs cannot be contacted, some DCs will become members of the new domain and some will still be members of the old domain. This is a problem because it essentially splits the DCs into two domains and as such it cannot replicate domain data between them. If there are changes such as group membership modifications, user password changes, user object modification, and so forth, they will not replicate to the other domain until the Domain Rename has completed successfully. This could result in a loss of service. All clients must have their domain suffix changed to the new domain. However, you can do this prior to the rename operation via Group Policy. Domains cannot be "merged" between forests (pruning and grafting). Example: Application Compatibility The problem at this point in the evolution of the Domain Rename technology is that there just isn't much data on application compatibility. Even Microsoft, at the time of this writing, doesn't have a definitive list of Microsoft applications that support Domain Rename. Note that no application is completely "incompatible," as it can certainly be uninstalled and reinstalled, but obvious costs and risks are involved in doing that. It is important to include application compatibility in any cost/benefit analysis for Domain Rename. There are certainly other ways to solve a problem than by renaming the domain and cleaning up afterwards. In the next section, we discuss the cost/benefit of Domain Rename in detail. Although our experience with Domain Rename is limited at this point, we do know the following: Domain Rename is compatible with no issues for NETLOGON, LSASS, and Key Distribution Center (KDC). Domain Rename is compatible with workarounds for DFS, Group Policy, Unintentional Disjoint Namespace, Trusts, and Certificate Services. Refer to the Domain Rename whitepapers we noted earlier in this section for details. Domain Rename is incompatible with Exchange 2000 and Exchange 2003 (pre-SP1). See details in the upcoming "Exchange Recovery Options" section if you rename a domain with Exchange 2000 or 2003 pre-SP1 deployed (these options aren't pretty, but Microsoft says they work). Exchange 2003 SP1 supports Domain Rename. However, as of this writing, SP1 has not been released, so there are no cases to cite. Systems Management Server (SMS) supports renaming the DNS name, but not the NetBIOS name at this writing. Check with Microsoft for current information. Certificate Services has workarounds to support Domain Rename. You can prepare and clean up Certificate Services to support Domain Rename. Details are in the Microsoft Domain Rename whitepapers previously noted. You must move root CAs on DCs in renamed domains to member servers. See Microsoft KB 298138: "HOW TO: Move a Certification Authority to Another Server." You can't rename a DC that is also a CA. Actually it's possible, but the process to make it work is prohibitive. NOTE The information in this list is accurate as of this writing. Because reviewing application compatibility is an ongoing process, you should contact Microsoft via its Web site or directly via its support center to determine the current status of these and other applications. When I asked Microsoft for a list of applications it had compiled, the company told me that rather than providing the list (which will have changed by the time this book is printed), it preferred to give the following guidelines: Check with the support provider for each application in question. There are simply too many products in the market to keep an exhaustive list updated, and the application developer is the one most deeply familiar with the dependencies of the product. Perform extensive testing in a lab test environment. The only way to be fully prepared is to test, test, and test. Each organization is different and has unknown variables that may or may not be impacted by a Domain Rename. You should conduct the tests in a lab environment that represents the customer's production environment as closely as possible. Exchange Recovery Options It has already been noted that Exchange 2000 and Exchange 2003 (RTM or pre-SP1) do not support Domain Rename, and renaming a domain with these versions of Exchange deployed breaks the System Attendant. Microsoft recommends the following process for recovering Exchange if Domain Rename is deployed: Option 1: Remove and then reinstall Exchange. Treat this as a disaster recovery scenario: Uninstall Exchange 2000. Rename domains back to their original names. Reinstall Exchange 2000. Reassociate mailboxes. See KB 326278: "Mailbox Recovery for Microsoft Exchange 2000." Option 2: Build a new forest and migrate the desired objects. This might not be a viable option for large organizations. Option 3: Ensure that Exchange 2000 SP1 is installed, and then upgrade to Exchange 2003 with E2K SP1 installed. Microsoft reported customers who successfully renamed the domain back to the original name as a recovery measure, but careful planning and understanding the issues will avoid this, as it is time-consuming and costly. In terms of planning, it is important to determine whether Domain Rename is appropriate for your situation. Let's review the benefits and risks to help you determine whether Domain Rename really is the best solution. WARNING Rendom.exe versions prior to 6.0.4011.0 failed to detect Exchange 2000. Such versions erroneously allowed Domain Rename operations when Exchange was detected in the forest. Broken versions shipped on Microsoft.com in 2003 and on Windows 2003 installation media. Domain Rename breaks Pre-SP1 Exchange's System Attendant and implicitly Exchange 2000 name resolution. The fix for this was to rename modified domain names back to the original name. The updated rendom.exe is available from. Exchange SP1 and later supports domain rename, but make sure you use the rendom.exe from this Web site. Benefits and Risks When considering Domain Rename as a solution for your situation, review the previous list of capabilities and limitations to determine whether Domain Rename fits your requirements. If it does, assess the impact on downtime, testing, and IT staff costs as well as how much time it will take. Remember that you must contact all DCs in the forest to complete the operation. Make sure all your applications will support Domain Rename as well. As noted previously, the best way to do this is to test your applications' compatibility in a Domain Rename operation in an accurate test environment. Next, determine how a simple migration stacks up against this criteria and see which one (migration or Domain Rename) makes sense. Microsoft's experience at this point suggests the following: Simple environments accomplish Domain Rename fairly easily. Large organizations can benefit from Domain Rename as a cost-effective alternative to a costly migration operation. However, a complex environment introduces a lot of variables that must be examined for compatibility, such as applications, and conditions that don't support Domain Rename noted in this section. Organizations that need to repair the domain namespace, such as those who have a single label name, or a "dotted name" where a dot "." is part of the NetBIOS name, or a name with a nonstandard character that DNS doesn't support. The latter two could be carryovers from NT migration, and usually were accomplished by having NetBIOS names different from the DNS names because DNS has a problem with these formats. Domain rename is a way to clean this up. Microsoft had several customers who incorrectly deployed Domain Rename, breaking something (such as Exchange) in the process. They recovered by renaming the domain back to the original name. This is impressive as it shows the resilience of Domain Rename. In HP's case, although Domain Rename is a big undertaking, it's not nearly as difficult as migrating the users, groups, and computers to a new domain. Remember, it took Compaq two years to migrate the Compaq objectsit would have taken much longer with the HP users and they would have had to start all over again. In HP's case, the decision was basically whether to take another two or three years to remigrate everyone, or spend the time and money to test and implement the Domain Rename. One customer I spoke to at a conference worked for a subsidiary of a large aerospace company that was changing its company name. The company was currently at Windows 2000 and considered upgrading to Windows Server 2003 so it could simply rename the domain. The company has a single domain, 15 domain controllers in 8 sites, and about 1,000 users. I gave him an explanation of how it works, and helped him create a Domain Rename lab that I created for the conference. After three hours trying the lab (three DCs in the test forest), he decided migration with Active Directory Migration Tool (ADMT) would be easier and more reliable. Domain rename is a one-way street. Recovery of the original domain depends on your backups, whether you have any DCs left, and how the rest of the environment can absorb the impact. Remember that there are other alternatives to solve your problem; if you use Domain Rename, make sure it is the best solution available, and then thoroughly test it. Additional Information Appendix B, "ProLaint Product Details," contains a Domain Rename flowchart that will be helpful in assessing the impact of implementing Domain Rename, as well as providing a good overview for the design of the process. In addition, a training exercise for Domain Rename is available on the book's Web site at. This exercise can easily be done using VMWare or Microsoft's Virtual PC software and will give you a good idea of how Domain Rename is accomplished. DCPromo DCPromo improvements in Windows 2003 consist primarily of the new Install from Media (IFM) feature noted previously in this chapter, and some improvements in the DCPromo answer file for unattended promotions. The next section provides a step-by-step procedure on how to use the IFM feature, followed by a section on unattended DCPromo operation. The latter provides details on creating a DCPromo unattended answer file and using it with the IFM restored backup files to create an unattended DCPromo using IFM. These two exercises require a DC and a member server in a domain. Install from Media (IFM) Previously, we described this feature from a benefits standpoint in the "Global Catalog Improvements" section of this chapter. This section provides a step-by-step description of how to perform IFM to restore a DC or a GC. The exercise backs up a DC's system state (AD), copies the backup file (.bkf) to a share on a member server, and restores the .bkf to a local directory on the member server. NOTE IFM can restore only a replica DC. It cannot create the first DC in the domain because it uses the backup of an existing DC to source from. Log on to a DC as a domain Administrator. Create a directory to hold the backup files, such as C:\backup. Using Windows 2000 Backup, back up the System State (which contains the AD). Save the backup to C:\backup. Log on to the member server that is to become a DC. Create a directory to contain the restore files, such as C:\NTDSrestore, on the member server and share it as NTDSrestore. Grant proper permissions to allow writing to that directory/share for the account you are using. On the DC, map a drive to \\<server>\NTDSrestore (the share created in step 5), where <server> is the name of the member server where the share was created. On the DC, open the Windows 2000 Backup Utility, and use the Restore Wizard to restore the .bkf file created in step 3 to the \NTDSrestore share. Make sure that you Select the System State as the file to be restored. Select Advanced Options, and then specify the location; otherwise, the file will be restored to the original location. On the member server, execute the following command from a command prompt: C:> Dcpromo /adv This launches the familiar Active Directory Installation Wizard, but produces an additional screen, shown previously in Figure 1.11 in the "Global Catalog Improvements" section of this chapter. In this dialog box, you can select the From These Restored Backup Files option and enter the path to where you restored the backup: C:\NTDSRestore, in this case. NOTE The restored files must exist on local media to the member servertape, CD, DVD, disk, and so on. This operation will not work from a network share. DCPromo proceeds as usual. The difference is that it will be sourcing from the media, not from a live DC. At the end, it will sync with a live DC to replicate changes between the state of the media and the current state of the AD. TIP If you test this with a copy of your production data in a lab environment, try running a normal DCPromo operation and time it. Use IFM to promote another DC and compare the time. Unattended DCPromo There are only a few new commands to the DCPromo unattended answer file syntax for Windows Server 2003, but the combination of an unattended answer file and the IFM feature presents some intriguing possibilities. For instance, one company had a remote office in Alabama with no IT staff. The company sent the receptionist to training so that she could perform basic tasks that required on-site attention. The company developed a simple .bat file and an unattended answer file to run from it, and sent that on a floppy disk (or even e-mail), along with the restored media and some instructions about where to put things, and she could run the .bat file and promote the DC without having to answer any questions in the process. In this section, we will demonstrate how you can create an unattended answer file for DCPromo on a member server. Then, you run DCPromo from a command line with the /adv switch to allow the AD to be installed from the restored backup rather than from a live DC, with the /answer: switch to read the answer file. This exercise assumes you have a DC and a member server in a domain. Follow steps 1 through 7 from the "Install from Media (IFM)" section. Using Notepad or your favorite editor, create a file named Unattend.txt that includes the following: From a command line (or entered in a .bat file), execute the following command: [Unattended] Unattendmode=fullunattended [DCINSTALL] UserName=<enter domain admin acct> Password=<enter pwd> UserDomain=<enter domain of the user acct> DatabasePath=c:\windows\ntds LogPath=c:\windows\ntds SYSVOLPath=c:\windows\sysvol SafeModeAdminPassword CriticalReplicationOnly SiteName=<Enter pre-defined site name here> ReplicaOrNewDomain=Replica ReplicaDomainDNSName=<name of the domain you are building a replica for> ReplicateFromMedia=yes ReplicationSourcePath=c:\NTDSrestore RebootOnSuccess=yes For example, to promote a member server to DC in the company.com domain, locating the DC in the Seattle site and putting the SYSVOL path on the D:\ drive using the account of the Administrator Norm Johnson (NormJ), the answer file would look like the following (assume we save it as DCPromoAnswer.txt): [Unattended] Unattendmode=fullunattended [DCINSTALL] UserName=NormJ Password=myPassword2003 UserDomain=Company.com DatabasePath=c:\windows\ntds LogPath=c:\windows\ntds SYSVOLPath=D:\windows\sysvol SafeModeAdminPassword=Safepwd CriticalReplicationOnly SiteName=Seattle ReplicaOrNewDomain=Replica ReplicaDomainDNSName=Company.com ReplicateFromMedia=yes ReplicationSourcePath=c:\NTDSrestore RebootOnSuccess=yes C:> Dcpromo /adv /answer:dcpromoAnswer.txt If you successfully provide all the answers to DCPromo's questions, you will not be prompted. DCPromo completes and reboots the server. Obviously, you might have typos or other problems, so it's best to test this out before using it in production. A couple of important things to note: The siteName option must point to a valid, existing AD site. You can leave commands in the file with no answer without error. You can use a number of additional commands in these DCPromo answer files. (See Microsoft KB 223757 "Unattended Promotion and Demotion of Windows 2000 Domain Controllers.") When running DCPromo in unattended mode, you will not see the dialog box that prompts you for the path to the media, shown earlier in Figure 1.11. If you enter the actual password in the answer file, when DCPromo runs, it strips the password out. If you want to run the answer file again, you must re-enter the password each time (or leave it blank and let it prompt you). WARNING The backup media is good only for the time specified by tombstonelifetime (default 60 days). Do not use media older than this, because it will cause lingering objects in the AD. (See Microsoft KB 216993 "Backup of the Active Directory has 60-day Useful Life.") Linked Value Replication (LVR) Windows NT performs replication on an object level, whereas Windows 2000 improves on this and performs replication on an attribute level. This is a significant improvement: When you changed the password on a user account, NT 4 replicated the whole object and Windows 2000 replicated the password attribute and not the rest of the object. However, this still had some limitations when replicating multi-valued attributes. Multi-valued attributes are attributes of AD objects that contain multiple values. Functionally, you can describe the Jet database as a table with rows, columns, and values in the cells. Table 1.3 depicts how a global group object would be stored in Jet. The cells labeled Group Name, Type, Members, and Scope are attributes. The entries Domain Users, Security, and Scope are attributes. Note that the group members are all lumped together in a single attribute, instead of each name being an attribute itself. In this case, Members is a multi-valued attribute. The problem comes when you remove or modify a member of the group, or add another member. Because Windows 2000 replicates the entire attribute, all valuesthus all the members of the groupare replicated, too. In the case of large groups of thousands of members, this can have a negative impact on replication performance due to the increase in network bandwidth required. In addition, there is a limitation in the capability of the database write operation to make a change in large attributes. Because of this, Microsoft does not support groups that contain more than 5,000 members. Deployments like HP's with tens of thousands of users solved this with nested groups. Table 1.3 Functional Layout of a Global Group Object in the Jet Database In Windows 2003, replication is performed on attribute values. Thus, for large groups, if the membership is modified, only the value (member) that is added, modified, or deleted is replicated. Thus, a single value can be replicated rather than the entire group. This has eliminated the infamous 5,000-member limit on groups. Group Policy Microsoft seems to be following a philosophy to expose options for just about anything through Group Policy. Windows NT had 79 System Policies, Windows 2000 had about 700 Group Policy settings, and Windows 2003 has added more than 200 new settings, many of which deal with new features such as Time Services (NTP), Wireless Network Policy, and Software Restriction policies. In addition, some significant new tools were produced that make managing and troubleshooting Group Policy much easier. First, we cover the new tools, and then we cover some of the new policies. Three new tools are significant to troubleshooting and managing Group Policy: Gpupdate.exe, DCgpofix.exe, and the Group Policy Management Console. GPupdate.exe This tool replaces the old Secedit /refreshpolicy. Remember this because secedit no longer refreshes policies. GPupdate.exe includes a number of switches: /Target <computer | user>: Specifies whether to update computer or user policy. No switch refreshes both. /Force: Reapplies all policy settings, not just the ones that changed. /logoff: Forces a logoff if client-side settings have been changed that require a logoff/logon (not background-processed). /boot: Forces a reboot if client-side settings have been changed that require a reboot (not background-processed). DCgpofix.exe Customers using Windows 2000 frequently called for support when trying to restore the Default Domain Policy or Default Domain Controllers Policy to the original default settings. Microsoft developed a tool to address this problem. DCgpofix.exe has been enhanced and is now a built-in tool that restores the Default Domain Policy, the Default Domain Controllers Policy, or both using the following switch: /Target: Domain /Target: DC /Target: Both In addition, the /? switch produces a help file. WARNING If you reset these policies to the default, you will lose all manual settings you have made, including Encrypted File System (EFS) settings. Group Policy Management Console (GPMC) The GPMC tool is a welcome sight for Administrators of environments with multiple domains and many policies. It has a number of great features, including the following: Manages all policies from all domains in one GUI-based tool. Employs Resultant Set of Policy (RSoP). The Planning option reports "what if" scenarios such as what would be the effects of modifying settings on the Default Domain policy, or adding a new policy. The Logging option allows modification of the GPO settings. Allows you to dump the settings to a text file, which is very handy for customer support folks trying to diagnose a problem over the phone. GPMC is available as a free download from Microsoft's Download Center on their Web site, although you technically need to have a Windows Server 2003 license. It runs on Windows 2000 or Windows 2003 domains. However, the machine that GPMC runs on must be a Windows Server 2003 server or a Windows XP client. We include more details and examples in Chapter 5. New Client-Side Extension Policies Windows Server 2003 policy includes three new Client Side Extensions (CSEs)Wireless Network Policy, Software Restriction Policy (SAFER), and QOS (Quality of Service) Packet Schedulerin addition to the CSEs that were in Windows 2000. The QOS Packet Scheduler was part of several updates to QOS in Windows Server 2003. This feature is used in QOS for bandwidth throttling. Software Restriction Policies are a new security feature described in the "Security" section of this chapter. Wireless Network Policy added settings in the policy to define wireless settings such as preferred networks (by Service Set IdentifierSSID) and types of networks to access. Figure 1.17 shows the Wireless Network Policy Properties page available via the Group Policy Editor. NOTE By default, no Wireless Network Policies are defined. The Wireless Network section of the Computer Configuration of Group Policy is blank. Right-click on the Wireless Network icon and select Create Wireless Network Policy. Note that you can create only one Wireless Network Policy. Figure 1.17 Wireless Networks Property Policy page as it appears in the Group Policy Editor. Changes in User Rights One of the most glaring changes that trips up a lot of Administrators new to Windows Server 2003 is the old Logon Locally right as used in Windows 2000. This right does not exist as such in Windows Server 2003. It now has four settings: Allow Logon Locally: Users and groups in this list are allowed specifically to log on locally. The default groups that were set in Windows 2000 (such as that in the Default Domain Policy) are configured here by default. Deny Logon Locally: Users and groups in this list are specifically denied privilege to log on to the machine. Allow Logon Through Terminal Services: Users and groups listed are permitted specific logon rights via Terminal Services. Deny Logon Through Terminal Services: Users and groups listed are specifically denied logon rights via Terminal Services. New DNS/Net Logon Policies Net Logon settings, exposed only in the Registry, are easily configured now in Group Policy. Fourteen settings are located in Computer Configuration\Administrative Templates\System\Net logon. Some interesting ones include the following: Site Name: You can specify a site name so that all computers to which this policy applies will be members of this site instead of letting the DC Locator process find one. This setting is potentially dangerous because it's easy to set, but it's useful only if you have all the computers defined in OUs that represent sites. You could also force Site Affinity this way. However, if you forget about it and the site configuration or the OU structure changes, or if you move computers to another OU, you might have trouble figuring out why the DC Locator is behaving the way it is and finding the wrong site. Of course, it can't find the right site because you defined the site manually. Expected Dial-Up Delay on Logon: You can specify additional time for a dial-up client to wait for a DC's response at logon. This could help make the logon process more tolerant if users are having connection issues due to timeouts. Log File Debug Output Level: This is a great improvement. In Windows 2000, you had to enable Net Logon logging (to the Netlogon.log) by modifying a Registry key. This policy setting not only turns it on, but also has several degrees of verbosity that you can set. However, the verbosity values are strange. The default verbosity value is 536936447. Nonzero values turn it on, and the higher the value, the more verbose the logging will be. Contact PDC on Logon Failure: This setting lets you turn off the functionality of a DC querying the PDC for password change if a user's password is judged by the DC to be incorrect. This was designed to take care of the problem of a password change not being replicated to a DC that authenticates the user after changing passwords. If you have a large geographic domain, and users in remote sites must go over a slow WAN link to get to the PDC, this would save some time and traffic, although it would result in logon failure until replication caught up. New Windows 2003 DC Locator DNS Records Located in Computer\Administrative Templates\System\Net logon\Domain Controller Locator Records, this is another dangerous set of policies that allow you to change the behavior of the DC Locator. Here are some interesting ones: Dynamic Registration of the SRV DNS Records: You can turn off dynamic registration of DC DNS SRV records. Each SRV record has a TTL (Time to Live) attribute that is set to 60 minutes by default in Windows 2000. This means that every hour, all DCs update all their SRV records, which can cause a duplication of DNS records. To avoid this, Administrators can turn off Dynamic Registration when all the DCs register their records in DNS. Automated Site Coverage: You can disable Auto Site Coverage so that affected DCs will not provide site coverage for sites other than their own. This is perhaps a good thing under peculiar circumstances in which you don't want a very busy DC to cover more than its site. Several other settings allow you to manually constrain the DC Locator. Make sure you have good reason for tweaking these settings, and that you thoroughly test and document them before implementing. New Client-Side DNS Settings Several new settings control the client DNS functions, located in Computer Configuration\ Administrative Templates\System\Network\DNS Client. In Windows 2000, there was only a single setting: Primary DNS Suffix. Now there are 13 settings. Some of the interesting (and frightening) ones are as follows: Primary DNS Suffix: This oldie but goodie is useful in operations such as Domain Rename that pushes DNS suffix changes to clients in advance of the rename. DNS Servers: Defines a list of DNS servers to which a client will send name resolution requests. The scary thing is that this supersedes the DNS list in the local TCP/IP, as well as Dynamic Host Configuration Protocol (DHCP) configured DNS servers, and it applies to all network interfaces of the computers that this policy applies to. Dynamic Update: Although there might be some isolated cases in which you don't want to register a network interface in DNS, this qualifies as yet another opportunity to shoot yourself in the foot. Let's quote from the Explain tab on the setting in the Group Policy Object Editor: Computer Configuration\Administrative Templates\ System\ Logon\Always wait for the network at computer startup and logon: Enabling this setting ensures that Folder Redirection, Software Installation, roaming user profile settings, or perhaps other applications that require network access complete in just one logon. Without this setting enabled, these features might require two logons because the user can be logged on before the network settings are available. If you disable this setting, the computers to which this setting is applied may not use dynamic DNS registration for any of their network connections, regardless of theconfiguration for individual network connections. Note that this disables dynamic registration on all interfaces of affected computers. Computer Configuration\Administrative Templates\ System\ Group Policy Allow Cross Forest User Policy and Roaming User Profiles: Enabling this setting allows a user's policy and roaming user profile to apply when logging in from a computer in another forest that is trusted to the user's home forest via a two-way trust. Group Policy Refresh Interval for Computers: By default, workstations refresh policy every 90 minutes with a random offset of 10 to 30 minutes. This policy allows easy reconfiguration. One customer I worked with experienced a strange issue in which every time the policy was refreshed, the computer would hang for 15 to 20 seconds and then work again. Sometimes this is expected (that was the case here). Windows 2000 made this very difficult to modify. Turn Off Background Refresh of Group Policy: The customer just noted could have enabled this setting, which turns off the refresh while the computer is in use. NOTE As of this writing, the application of Group Policy between Windows 2003 forests or between a Windows 2003 forest and an MIT Kerberos Realm does not work for a trust created for forest-wide authentication. In this model, the authenticated users group from one forest is added to the authenticated users of the other, so security is wide open between the forests. (Refer to Microsoft KB 827182 "Group Policy Settings are not applied when you log on to a server by using an account from an MIT Kerberos realm.") System Restore and Remote Assistance Windows XP and Windows 2003 Remote Assistance Enabling the Remote Assistance policy allows expert help by permitting access to the computer. Note that the user will still be prompted to allow access to the computer when the expert contacts it. You can find this policy in Computer Configuration\Administrative Templates\ System\Remote Assistance. Windows XP System Restore Computer Configuration\The System Restore policy enables or disables the user's ability to restore an XP client to a previous known good state. You can find this policy in Administrative Templates\System\System Restore. Windows Installer System Restore Computer Configuration\ Windows Installer creates a system restore checkpoint for each application during installation. You can disable this with this policy setting, found in Administrative Templates\System\System Restore. Error-Reporting Policies The error-reporting policies enable you to control the error-reporting feature Microsoft first built into Windows XP. A typical error is shown in Figure 1.18. When an error is encountered, this pop-up window appears, prompting the user to indicate whether the information should be sent to Microsoft (assuming a current connection to the Internet). Microsoft uses these reports to gather data on problems to aid in resolution. It's a way of gathering data from a large number of users who would likely not report the problem, and I've actually seen cases in which Microsoft has used the data to resolve problems. In addition, if there is a possible solution, the user will be notified. I've seen cases in which a Microsoft Office application, such as Word, caused an error report and after I sent it, Microsoft notified me that the error could be solved by upgrading to a service pack and gave me the link to it. Microsoft is not trying to steal information and it offers the option of reviewing the report before it is sent. I highly recommend you always send this report. However, Group Policy also provides a number of options for error reporting, including the following. Basic Error Reporting Basic error reporting provides two options: Display Error Notification: Determines whether the user is offered the option of sending the report to Microsoft. Report Errors Properties: A number of options in regard to sending the reports to Microsoft. If the Display Error Notification policy is enabled and these properties are disabled, the user will be notified of a problem, but will not be able to report it to Microsoft. You can find this policy at Computer\Administrative Templates\System\Error Reporting. Advanced Error Reporting Only one advanced error-reporting option is available. This policy setting contains more granular configuration of error reporting, such as enabling or disabling reporting of operating system errors, unplanned shutdown events, and application errors. You can find this policy at Computer\ Administrative Templates\System\Error Reporting\Advanced Error Reporting. Figure 1.18 Typical error produced by the error-reporting mechanism in Windows XP and Windows Server 2003. Miscellaneous Policies This is one of those dangerous policies that tend to generate support calls. The Configure Windows NTP Client setting is particularly dangerous in that it allows you to specify an NTP Server. As noted in the "Time Services" section of Chapter 6, the Windows Time Service structure is configured properly by default and works fine without manual intervention. I've seen one customer already who thought he wanted to configure this by specifying an NTP server. It completely broke Time Services, which, of course, broke authentication. We ultimately had to restore everything to defaults to get it to work again. I recommend just leaving it alone. That is, if it's not broken, don't fix it! You can find this policy in Administrative Templates\System\Windows Time Service. Remote Procedure Call: This policy, which you can find in Administrative Templates\System\Remote Procedure Call, contains options that will help with troubleshooting (first two bullets) and make RPC more or less tolerant of errors (last two bullets): RPC (Remote Procedure Call) troubleshooting state information Propagation of extended error information Ignore delegation failure Minimum Idle Connection Timeout for RPC/HTTP connections (relating to the new Exchange and Outlook feature) New Uses of WMI Filters Windows Server 2003 provides new capabilities for customizing queries using WMI (Windows Management Instrumentation), including the WMIC interface and the WMI filters in Group Policy. We cover WMI in detail in Chapter 10, "System Administration," in the "Windows Management Instrumentation" section. The WMI filter in Group Policy basically allows a WMI query (filter) to be applied from within a policy. For instance, the following WMI filter checks to see whether the physical memory of the computer is greater than 128MB: Select TotalPhysicalMemory from win32_ComputerSystem where TotalPhysicalMemory >= 134217728 Using the Group Policy Management Console (GPMC), which we describe briefly in this chapter and in more detail in Chapter 10, we can define the WMI filter and associate it with a Group Policy Object (GPO). The procedure to do this is as follows: In the GPMC, expand Forest, Domains, <domain name>. Under the domain name, you'll see a list of all GPOs followed by OU folders, a Group Policy Object folder, and finally the WMI Filters folder. Right-click on the WMI Filters folder, and select New. The New WMI Filter dialog box is displayed. Click the Add button to display the WMI Query dialog box. In the Query field, enter a valid WMI filter, such as the example shown in Figure 1.19. Click OK and return to the New WMI Filter dialog box. You can add other WMI filters at this point, but it's best to do one at a time. Click the Save button. If the WMI filter you added is correct (syntax, and so on), it will be added to the list. Close the New WMI Filter dialog box and you'll see the filter added under the WMI Filter folder in the left pane of the GPMC. Click on the filter you just created and in the left pane, shown in Figure 1.20, you'll see the WMI filter description at the top and a list of GPOs that use this WMI filter at the bottom. Click in the white area of the GPOs that use this WMI filter section and select Add. A list of GPOs is displayed. Select a GPO to have the filter apply to and click OK. To add the filter to additional GPOs, repeat this procedure. You can't add more than one GPO at a time. Figure 1.19 Dialog box for creating WMI filter in GPMC snap-in. Figure 1.20 Linking a WMI filter to an existing GPO in the GPMC snap-in. We have created a WMI filter on the Accounting Policy (in the example in the figures) so that this policy applies only to computers that have 128MB of memory or more. This is similar to the security filtering in Windows 2000, where you could apply or deny a policy only to certain users or groups. Of course, there is a price to be paid for this. Just like ACL (Access Control List) filtering in Windows 2000, you pay a logon performance price for WMI filtering. In addition, keep in mind that the Windows 2000 clients don't support the WMI queries, so they will always apply the policy, and the filter won't apply to them. Tools Microsoft made a number of enhancements to tools used for troubleshooting and monitoring in Windows 2003. The bad news is that most of them won't run on a Windows 2000 machine. The good news is that they will run on a Windows XP client or a Windows 2003 server in a Windows 2000 domain. One of the best troubleshooting tools I've found so far is a Windows XP client. In fact, I've required more than one customer to buy a copy of XP and load it on a client machine so that we could do proper troubleshooting. Here is a summary of some significantly improved tools in Windows Server 2003 (at least the ones I like). Descriptions and examples of how these tools are used are contained in various chapters in this book. Windows XP client: This is a very useful tool, as it can execute most of the new Windows 2003 version of old tools as well as new ones. I have often required a customer to purchase XP and put it on a laptop so that we could run the enhanced version of the tools in a Windows 2000 domain or forest. GPresult: One of the most valuable tools ever for diagnosing Group Policy problems on the client, the Windows Server 2003 version of this tool is invaluable, as it produces RSoP information and provides all security and user rights details. Where Windows 2000's version simply told which GPO it got the security from, Windows 2003's version displays all the settings, such as password length. This will reduce your time in diagnosing Group Policy problems considerably. W32tm: This is a new version of the time configuration utility with new options and syntax. (See Chapter 6 for more details.) GPMC (Group Policy Management Console): This new tool allows management of all GPOs from one tool, and allows Administrators to use RSoP in planning and deployment phases. (See Chapter 5 for more details.) ADLB (Active Directory Load Balancing Tool): This tool allows management of manual connections and enables you to add additional BHSs to a hub site for load balancing. (See Chapters 5 and 10 for more information.) Sonar: This is a monitoring tool for FRS. (See Chapter 6.) Ultrasound: This is an advanced monitoring tool for FRS. (See Chapter 6.) Repadmin: This new version has a /replsum option that displays end-to-end replication information to show outstanding change requests on each DC in the enterprise. It also contains a switch to remove lingering objects, and it will run on an XP client in a Windows 2003 domain. (See Chapter 5.) Dcgpofix (in Windows Support Tools): This was previously a secret tool available only from Microsoft PSS. It restores the default Domain Policy, or Default Domain Controllers policy, or both. This is useful if you have hosed either of these and want to restore them to their default condition. It will lose all changes you've made, including EFS settings. NTDSUtilChange Directory Service Repair Mode (DSRM) Password: This allows the DSRM Administrator password to be reset onlinewithout rebooting. GPupdate: This replaces the Secedit /refreshpolicy command and is available native to Windows XP and Windows Server 2003. WMIC: This is an interface in XP and Windows Server 2003 to provide commands to the WMI APIs (Application Programming Interfaces). (See Chapter 10 and elsewhere in this chapter for more information.) Active Directory Users and Computers snap-in: This policy enables you to select multiple objects (users, groups, and so on); it also allows you to save LDAP queries in a saved queries folder, and permits drag and drop. Remote Desktop: This replaces the old Terminal Services Administration Mode and Terminal Services Client. Built into XP and Windows Server 2003, Remote Desktop permits copy and cut/paste between a remote console and a local machine. (See Chapters 10 and 15, and section 1.2.3 "Remote Desktop Client and Resource Redirection" in this chapter.) Account Lockout: This is a lockoutstatus.exe and a DLL (Dynamic Link Library) that produces an additional Acct Info tab in the User object. It permits better management and monitoring of account lockout. (See Chapter 5 for more information.) dsadd, dsmod, dsrm, dsget and dsquery: These built-in command-line tools permit adding and modifying objects in the AD. Entering the command followed by /? produces a brief online help for each command. (for example, dsadd /?). Windows Server 2003 only. dsadd: Adds a computer, contact, group, OU, quota, or user to the AD. dsmod: Modifies a computer, contact, group, OU, server, user, quota, or partition in the AD. dsrm: Removes (deletes) objects from the AD. dsget: Displays properties of an object such as computer, contact, subnet, group, OU, server, site, user, quota, and partitions. Dsquery: Searches the AD for computers, contacts, subnets, groups, OUs, sites, servers, users, quotas, and partitions. Scalability Previously in this chapter, I've noted new features that provide enhanced scalability. These features are summarized here only to identify them with the fact that they do enhance scalability for the Windows architecture: Increase of the maximum NTDS.DIT database to about one billion objects: Like Windows 2000, this is a fairly flat curve in terms of performance. You can increase the number of objects without directly impacting performance. Performance will stay fairly consistent. IFM: This permits DCs and GCs to be configured or rebuilt in minutes compared to hours or days in Windows 2000. This makes the environment more resilient and easier to extend. Improved replication: A rewritten spanning tree algorithm made the ISTG much faster and reduced replication latency. LVR: This enhanced the replication performance of multi-valued attributes, eliminating the size of these attributes, such as the 5,000-member limit of global groups in Windows 2000. Inter-site compression: This can be disabled, reducing load on BHSs. In addition, the compression algorithm was improved to aid in decompression of data so that even if you opt to leave the data compression intact, there is still a performance increase. ADLB: Helps manage environments where remote sites with slow links require manual intervention to schedule replication and build connection objects. Interoperability and Functional Levels Microsoft introduced a new feature in Windows 2003, called functional levels, which provides interoperability with Windows 2000 and Windows NT DCs. Functional levels were implemented in Windows 2000, but they were simply known as "native mode" and "mixed mode," referring to whether there were downlevel (NT) DCs in the domain. Windows Server 2003 adds a degree of complexity: Not only does it add another OS that a DC can be installed with, but also introduces the concept of a "forest native mode." Forest native mode means all DCs in all domains in the forest must be at Windows Server 2003, all domains must be switched to native mode (similar to how Windows 2000 domains had to be switched to native mode), and the forest must then be switched to native mode. This is very important because the features and improvements discussed in this chapter depend on the functional level of the domain or forest. To get all the Windows Server 2003 benefits, you must be in a native Windows Server 2003 forest. Table 1.4 gives a good summary of each functional level, what DCs are allowed (by OS), and a comment about functionality. Chapter 3, "Migration Planning: Business and Technical," provides a thorough treatment of functional levels, including a detailed description of how they work and how to configure them, as well as how they affect the design and the migration. Table 1.4 Functional Levels in Windows Server 2003 Domains and Forests Schema In Windows 2000, Microsoft made no small effort to frighten everyone away from modifying the schema because it cannot be restored from an earlier date. If damaged, the schema could cause the entire infrastructure to fail. This is still true in Windows Server 2003. However, there has been an improvement on the front of object management in the schema. Classes and attributes in the schema can now be disabled (as was the case in Windows 2000), but they can also be marked as "defunct" or "redefined." What we need still is the ability to purge and delete, which hopefully is coming in a future update. Dynamic TTL In Windows 2000, objects existed until they were explicitly deleted. With Windows 2003, objects can be created with a Time To Live (TTL) stamp. They are then deleted when the time stamp expires unless they are refreshed. This should help keep the AD clean.
http://www.informit.com/articles/article.aspx?p=347702&amp;seqNum=5
CC-MAIN-2016-50
refinedweb
19,289
52.39
Here is the code: Next I am writing a program to look through the results and count the longest streak of heads or tails. I got the idea from my stats class; knowing that there is an approximate chance of 0.195% of ten straight tosses being all heads or all tails, I want to find out how many coin tosses I need to throw to consistently get at least one streak of 10 straight. Yes I know I can calculate this by hand, but it's a much more fun idea to code. Code: Select all #include <fstream> #include <random> using namespace std; int main() { ofstream outFile; outFile.open("coinflip.txt"); random_device rd; for(int l = 1; l <= 10000; l++) { for(int k= 1; k <= 5; k++) { for(int j = 1; j <= 5; j++) { for(int i=1; i <=5; i++) { outFile << rd() % 2; } outFile << " "; } outFile << endl; } outFile << endl; } outFile.close(); return 0; } Thanks
https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=49487&p=389824
CC-MAIN-2020-05
refinedweb
155
75.95
You can click on the Google or Yahoo buttons to sign-in with these identity providers, or you just type your identity uri and click on the little login button.. Après plusieurs mois au point mort ou presque, Sylvain a pu hier soir publier des versions corrigeant un certain nombre de bogues dans pylint et astng ([1] et [2]). Il n'en demeure pas moins qu'à Logilab, nous manquons de temps pour faire baisser la pile de tickets ouverts dans le tracker de pylint. Si vous jetez un œuil dans l'onglet Tickets, vous y trouverez un grand nombre de bogues en souffrance et de fonctionalités indispensables (certaines peut-être un peu moins que d'autres...) Il est déjà possible de contribuer en utilisant mercurial pour fournir des patches, ou en signalant des bogues (aaaaaaaaaarg ! encore des tickets !) et certains s'y sont mis, qu'ils en soient remerciés. Maintenant, nous nous demandions ce que nous pourrions faire pour faire avance Pylint, et nos premières idées sont : Mais pour que ça soit utile, nous avons besoin de votre aide. Voici donc quelques questions : Vous pouvez répondre en commentant sur ce blog (pensez à vous enregistrer en utilisant le lien en haut à droite sur cette page) ou en écrivant à sylvain.thenault@logilab.fr. Si nous avons suffisamment de réponses positives nous organiserons quelque chose.. Enjoy!.:. Can we fix these one also with compat ?.! Hi. we'll hold the next pylint bug day on july 8th 2011 (friday). If some of you want to come and work with us in our Paris office, you'll be welcome. You can also join us on jabber / irc: I know the announce is a bit late, but I hope some of you will be able to come or be online anyway! Regarding the program, the goal is to decrease the number of tickets in the tracker. I'll try to do some triage earlier this week so you'll get a chance to talk about your super-important ticket that has not been selected. Of course, if you intend to work on it, there is a bigger chance of it being fixed next week-end ;) Hi!: The latest release of logilab-astng (0.23), the underlying source code representation library used by PyLint, provides a new API that may change pylint users' life in the near future... It aims to allow registration of functions that will be called after a module has been parsed. While this sounds dumb, it gives a chance to fix/enhance the understanding PyLint has about your code. I see this as a major step towards greatly enhanced code analysis, improving the situation where PyLint users know that when running it against code using their favorite framework (who said CubicWeb? :p ), they should expect a bunch of false positives because of black magic in the ORM or in decorators or whatever else. There are also places in the Python standard library where dynamic code can cause false positives in PyLint. Let's take a simple example, and see how we can improve things using the new API. The following code: import hashlib def hexmd5(value): """"return md5 checksum hexadecimal digest of the given value""" return hashlib.md5(value).hexdigest() def hexsha1(value): """"return sha1 checksum hexadecimal digest of the given value""" return hashlib.sha1(value).hexdigest() gives the following output when analyzed through pylint: [syt@somewhere ~]$ pylint -E example.py No config file found, using default configuration ************* Module smarter_astng E: 5,11:hexmd5: Module 'hashlib' has no 'md5' member E: 9,11:hexsha1: Module 'hashlib' has no 'sha1' member However: [syt@somewhere ~]$ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import smarter_astng >>> smarter_astng.hexmd5('hop') '5f67b2845b51a17a7751f0d7fd460e70' >>> smarter_astng.hexsha1('hop') 'cffb6b20e0eef296772f6c1457cdde0049bdfb56' The code runs fine... Why does pylint bother me then? If we take a look at the hashlib module, we see that there are no sha1 or md5 defined in there. They are defined dynamically according to Openssl library availability in order to use the fastest available implementation, using code like: for __func_name in __always_supported: # try them all, some may not work due to the OpenSSL # version not supporting that algorithm. try: globals()[__func_name] = __get_hash(__func_name) except ValueError: import logging logging.exception('code for hash %s was not found.', __func_name) Honestly I don't blame PyLint for not understanding this kind of magic. The situation on this particular case could be improved, but that's some tedious work, and there will always be "similar but different" case that won't be understood. The good news is that thanks to the new astng callback, I can help it be smarter! See the code below: from logilab.astng import MANAGER, scoped_nodes def hashlib_transform(module): if module.name == 'hashlib': for hashfunc in ('sha1', 'md5'): module.locals[hashfunc] = [scoped_nodes.Class(hashfunc, None)] def register(linter): """called when loaded by pylint --load-plugins, register our tranformation function here """ MANAGER.register_transformer(hashlib_transform) What's in there? Now let's try it! Suppose I stored the above code in a 'astng_hashlib.py' module in my PYTHONPATH, I can now run pylint with the plugin activated: [syt@somewhere ~]$ pylint -E --load-plugins astng_hashlib example.py No config file found, using default configuration ************* Module smarter_astng E: 5,11:hexmd5: Instance of 'md5' has no 'hexdigest' member E: 9,11:hexsha1: Instance of 'sha1' has no 'hexdigest' member Huum. We have now a different error :( Pylint grasp there are some md5 and sha1 classes but it complains they don't have a hexdigest method. Indeed, we didn't give a clue about that. We could continue on and on to give it a full representation of hashlib public API using the astng nodes API. But that would be painful, trust me. Or we could do something clever using some higher level astng API: from logilab.astng import MANAGER from logilab.astng.builder import ASTNGBuilder def hashlib_transform(module): if module.name == 'hashlib': fake = ASTNGBuilder(MANAGER).string_build(''' class md5(object): def __init__(self, value): pass def hexdigest(self): return u'' class sha1(object): def __init__(self, value): pass def hexdigest(self): return u'' ''') for hashfunc in ('sha1', 'md5'): module.locals[hashfunc] = fake.locals[hashfunc] def register(linter): """called when loaded by pylint --load-plugins, register our tranformation function here """ MANAGER.register_transformer(hashlib_transform) The idea is to write a fake python implementation only documenting the prototype of the desired class, and to get an astng from it, using the string_build method of the astng builder. This method will return a Module node containing the astng for the given string. It's then easy to replace or insert additional information into the original module, as you can see in the above example. Now if I run pylint using the updated plugin: [syt@somewhere ~]$ pylint -E --load-plugins astng_hashlib example.py No config file found, using default configuration No error anymore, great! This fairly simple change could quickly provide great enhancements. We should probably improve the astng manipulation API now that it's exposed like that. But we can also easily imagine a code base of such pylint plugins maintained by each community around a python library or framework. One could then use a plugins stack matching stuff used by its software, and have a greatly enhanced experience of using pylint. For a start, it would be great if pylint could be shipped with a plugin that explains all the magic found in the standard library, wouldn't it? Left as an exercice to the reader!!? Le 27 mars 2014, Logilab a accueilli un hackathon consacré aux codes libres de simulation des phénomènes mécaniques. Etaient présents: Patrick Pizette et Sébastien Rémond des Mines de Douai sont venus parler de leur code de modélisation DemGCE de "sphères molles" (aussi appelé smooth DEM), des potentialités d'intégration de leurs algorithmes dans LMGC90 avec Frédéric Dubois du LMGC et de l'interface Simulagora développée par Logilab. DemGCE est un code DEM en 3D développé en C par le laboratoire des Mines de Douai. Il effectuera bientôt des calculs parallèles en mémoire partagée grâce à OpenMP. Après une présentation générale de LMGC90, de son écosystème et de ses applications, ils ont pu lancer leurs premiers calculs en mode dynamique des contacts en appelant via l'interface Python leurs propres configurations d'empilements granulaires. Ils ont grandement apprécié l'architecture logicielle de LMGC90, et en particulier son utilisation comme une bibliothèque de calcul via Python, la prise en compte de particules de forme polyhédrique et les aspects visualisations avec Paraview. Il a été discuté de la réutilisation de la partie post/traitement visualisation via un fichier standard ou une bibliothèque dédiée visu DEM. Frédéric Dubois semblait intéressé par l'élargissement de la communauté et du spectre des cas d'utilisation, ainsi que par certains algorithmes mis au point par les Mines de Douai sur la génération géométrique d'empilements. Il serait envisageable d'ajouter à LMGC90 les lois d'interaction de la "smooth DEM" en 3D, car elles ne sont aujourd'hui implémentées dans LMGC90 que pour les cas 2D. Cela permettrait de tester en mode "utilisateur" le code LMGC90 et de faire une comparaison avec le code des Mines de Douai (efficacité parallélisation, etc.). Florent Cayré a fait une démonstration du potentiel de Simulagora. Denis Laxalde de Logilab a travaillé d'une part avec Rémy Mozul du LMGC sur l'empaquetage Debian de LMGC90 (pour intégrer en amont les modifications nécessaires), et d'autre part avec Mathieu Courtois d'EDF R&D, pour finaliser l'empaquetage de Code_Aster et notamment discuter de la problématique du lien avec la bibliothèque Metis: la version actuellement utilisée dans Code_Aster (Metis 4), n'est pas publiée dans une licence compatible avec la section principale de Debian. Pour cette raison, Code_Aster n'est pas compilé avec le support MED dans Debian actuellement. En revanche la version 5 de Metis a une licence compatible et se trouve déjà dans Debian. Utiliser cette version permettrait d'avoir Code_Aster avec le support Metis dans Debian. Cependant, le passage de la version 4 à la version 5 de Metis ne semble pas trivial. Voir les tickets: Alain Leufroy et Nicolas Chauvat de Logilab ont travaillé à transformer LibAster en une liste de pull request sur la forge bitbucket de Code_Aster. Ils ont présenté leurs modifications à Mathieu Courtois d'EDF R&D ce qui facilitera leur intégration. En fin de journée, Alain Leufroy, Nicolas Chauvat et Mathieu Courtois ont échangé leurs idées sur la simplification/suppression du superviseur de commandes actuel de Code_Aster. Il est souhaitable que la vérification de la syntaxe (choix des mots-clés) soit dissociée de l'étape d'exécution. La vérification pourrait s'appuyer sur un outil comme pylint, la description de la syntaxe des commandes de Code_Aster pour pylint pourrait également permettre de produire un catalogue compréhensible par Eficas. L'avantage d'utiliser pylint serait de vérifier le fichier de commandes avant l'exécution même si celui-ci contient d'autres instructions Python. Mickaël Abbas d'EDF R&D s'est intéressé à la modernisation de l'allocation mémoire dans Code_Aster et a listé les difficultés techniques à surmonter ; l'objectif visé est un accès facilité aux données numériques du Fortran depuis l'interface Python. Une des difficultés est le partage des types dérivés Fortran en Python. Rémy Mozul du LMGC et Denis Laxalde de Logilab ont exploré une solution technique basée sur Cython et ISO-C-Bindings. De son côté Mickaël Abbas a contribué à l'avancement de cette tâche directement dans Code_Aster. Luca Dall'Olio d'Alneos et Mathieu Courtois ont testé la mise en place de Doxygen pour documenter Code_Aster. Le fichier de configuration pour doxygen a été modifié pour extraire les commentaires à partir de code Fortran (les commentaires doivent se trouver au dessus de la déclaration de la fonction, par exemple). La configuration doxygen a été restituée dans le depôt Bitbucket. Reste à évaluer s'il y aura besoin de plusieurs configurations (pour la partie C, Python et Fortran) ou si une seule suffira. Une configuration particulière permet d'extraire, pour chaque fonction, les points où elle est appelée et les autres fonctions utilisées. Un exemple a été produit pour montrer comment écrire des équations en syntaxe Latex, la génération de la documentation nécessite plus d'une heure (seule la partie graphique peut être parallélisée). La documentation produite devrait être publiée sur le site de Code_Aster. La suite envisagée est de coupler Doxygen avec Breathe et Sphinx pour compléter la documentation extraite du code source de textes plus détaillés. La génération de cette documentation devrait être une cible de waf, par exemple waf doc. Un aperçu rapide du rendu de la documentation d'un module serait possible par waf doc file1.F90 [file2.c [...]]. Voir Code Aster #18 configure doxygen to comment the source files Maximilien Siavelis d'Alneos et Alexandre Martin du LAMSID, rejoints en fin de journée par Frédéric Dubois du LMGC ainsi que Nicolas Chauvat et Florent Cayré de Logilab, ont travaillé à faciliter la description des catalogues d'éléments finis dans Code_Aster. La définition de ce qui caractérise un élément fini a fait l'objet de débats passionnés. Les points discutés nourriront le travail d'Alexandre Martin sur ce sujet dans Code_Aster. Alexandre Martin a déjà renvoyé aux participants un article qu'il a écrit pour résumer les débats. Mathieu Courtois d'EDF R&D a montré à Rémy Mozul du LMGC un mécanisme de remontée d'exception du Fortran vers le Python, qui permettra d'améliorer la gestion des erreurs dans LMGC90, qui a posé problème dans un projet réalisé par Denis Laxalde de Logilab pour la SNCF. Voir aster_exceptions.c Tous les participants semblaient contents de ce deuxième hackathon, qui faisait suite à la première édition de mars 2013 . La prochaine édition aura lieu à l'automne 2014 ou au printemps 2015, ne la manquez pas !): Some time ago, we moved Pylint from this forge to Bitbucket (more on this here).. So for now the winner is, but the first one allowing me to test on several Python versions and to launch tests on pull requests will be the definitive winner! Bonus points for automating the release process and checking test coverage on pull requests as well. Pylint 1.1 eventually got released on pypi! A lot of work has been achieved since the latest 1.0 release. Various people have contributed to add several new checks as well as various bug fixes and other enhancement. Here is the changes summary, check the changelog for more info. New checks: Packages will be available in Logilab's Debian and Ubuntu repository in the next few weeks. Happy christmas! image!! Un sprint PyLint est organisé dans le cadre de la conférence PyConFR, les 13 et 14 septembre à Paris. Si vous voulez améliorer PyLint, c'est l'occasion : venez avec vos bugs et repartez sans ! Les débutants sont bienvenus, une introduction au code de Pylint sera réalisée en début de sprint. Une expérience avec le module ast de la librairie standard est un plus. Croissants et café offerts par l'organisation, merci de vous inscrire pour faciliter la logistique. Voir avec Boris pour plus d'informations (merci à lui !) I'm pleased to announce the new release of Pylint and related projects (i.e. logilab-astng and logilab-common)! By installing PyLint 0.25.2, ASTNG 0.24 and logilab-common 0.58.1, you'll get a bunch of bug fixes and a few new features. Among the hot stuff: Many thanks to everyone who contributed to these releases, Torsten Marek / Boris Feld in particular (both sponsored by Google by the way, Torsten as an employee and Boris as a GSoC student). Logilab était à la conférence PyConFR qui a pris place à Paris il y a deux semaines. Nous avons commencé par un sprint pylint, coordonné par Boris Feld, où pas mal de volontaires sont passés pour traquer des bogues ou ajouter des nouvelles fonctionnalités. Merci à tous! Pour ceux qui ne connaissent pas encore, pylint est un utilitaire pratique que nous avons dans notre forge. C'est un outil très puissant d'analyse statique de scripts python qui aide à améliorer/maintenir la qualité du code. Par la suite, après les "talks" des sponsors¸ où vous auriez pu voir Olivier, vous avons pu participer à quelques tutoriels et présentations vraiment excellentes. Il y avait des présentations pratiques avec, entre autres, les tests, scikit-learn ou les outils pour gérer des services (Cornice, Circus). Il y avait aussi des retours d'information sur le processus de développement de CPython, le développement communautaire ou un supercalculateur. Nous avons même pu faire de la musique avec python et un peu d'"embarqué" avec le Raspberry Pi et Arduino ! Nous avons, avec Pierre-Yves, proposé deux tutoriels d'introduction au gestionnaire de versions décentralisé Mercurial. Le premier tutoriel abordait les bases avec des cas pratiques. Lors du second tutoriel, que l'on avait prévu initialement dans la continuité du premier, nous avons finalement abordé des utilisations plus avancées permettant de résoudre avec énormément d'efficacité des problématiques quotidiennes, comme les requêtes sur les dépôts, ou la recherche automatique de régression par bissection. Vous pouvez retrouver le support avec les exercices là. Pierre-Yves a présenté une nouvelle propriété importante de Mercurial: l'obsolescence. Elle permet de mettre en place des outils d'édition d'historique en toute sécurité ! Parmi ces outils, Pierre-Yves a écrit une extension mutable-history qui vous offre une multitude de commandes très pratiques. La présentation est disponible en PDF et en consultation en ligne sur slideshare. Nous mettrons bientôt la vidéo en ligne. Si le sujet vous intéresse et que vous avez raté cette présentation, Pierre-Yves reparlera de ce sujet à l'OSDC. Pour ceux qui en veulent plus, Tarek Ziadé à mis à disposition des photos de la conférence ici.. The three main maintainers/developpers of Pylint/astroid (Claudiu, Torsten and I) will meet together in Berlin during EuroPython 2014. While this is not an "official" EuroPython sprint but it's still worth announcing it since it's a good opportunity to meet and enhance Pylint. We should find place and time to work on Pylint between wednesday 23 and friday 25. If you're interested, don't hesitate to contact me (sylvain.thenault@logilab.fr / @sythenault). We:. Here are the list of things we managed to achieve during those last two days at EuroPython. After several attempts, Michal managed to have pylint running analysis on several files in parallel. This is still in a pull request () because of some limitations, so we decided it won't be part of the 1.3 release. Claudiu killed maybe 10 bugs or so and did some heavy issues cleanup in the trackers. He also demonstrated some experimental support of python 3 style annotation to drive a better inference. Pretty exciting! Torsten also killed several bugs, restored python 2.5 compat (though that will need a logilab-common release as well), introduced a new functional test framework that will replace the old one once all the existing tests will be backported. On wednesday, he did show us a near future feature they already have at Google: some kind of confidence level associated to messages so that you can filter out based on that. Sylvain fixed a couple of bugs (including which was annoying all the numpy community), started some refactoring of the PyLinter class so it does a little bit fewer things (still way too many though) and attempted to improve the pylint note on both pylint and astroid, which went down recently "thanks" to the new checks like 'bad-continuation'. Also, we merged the pylint-brain project into astroid to simplify things, so you should now submit your brain plugins directly to the astroid project. Hopefuly you'll be redirected there on attempt to use the old (removed) pylint-brain project on bitbucket. And, the good news is that now both Torsten and Claudiu have new powers: they should be able to do some releases of pylint and astroid. To celebrate that and the end of the sprint, we published Pylint 1.3 together with Astroid 1.2. More on this here.
http://www.logilab.org/view?rql=Any%20X%20WHERE%20T%20tags%20X%2C%20T%20eid%208759%2C%20X%20is%20BlogEntry
CC-MAIN-2014-52
refinedweb
3,384
61.56
pytest plugin to test OpenERP modules Project description py.test plugin for testing OpenERP modules Usage install/update via: pip install -U pytest-oerp and to run tests type: py.test --oerp-server-path=<path to openerp server directory> \ --oerp-db=<db name, default is test> this will load OpenERP using the config on ~/.openerp_serverrc and create a pool and transaction for the choosen database for the testcases where you receive an oerp attribute. Writting tests Testcases only need to receive oerp to create a transaction on oerp an example follows: def test_simple(oerp): product_obj = oerp.pool.get('product.product') product_ids = product_obj.search(oerp.cr, 1, []) this will be run inside OpenERP like code in modules and you can use the full openerp api. You can only load stuff from OpenERP library inside functions, because the library is added to sys.path dynamically. OpenERP API As pytest-oerp is running inside OpenERP everything you need to do that can be done inside a module can be done in a pytest-oerp test. The usual cr, uid attributes are oerp.cr and 1 (that means the first user, usually admin). oerp also has a pool attribute that is useful. Todo There are a lot of polish and features that should be done but a tentative list would be: - support passing a configuration to OpenERP - more tests (always a good thing) - don’t depend on mock (great lib but probably unnecessary for this) - redirect print log - addini in pytest so you can configure with pytest.ini - lettuce support, but this will probably go in another package Notes The official repository of this plugin is at For more info on py.test see All work on the plugin has been sponsored by PROGE () Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pytest-oerp/
CC-MAIN-2018-22
refinedweb
317
61.36
Get the highlights in your inbox every week. Add methods retroactively in Python with singledispatch Add methods retroactively in Python with singledispatch Learn more about solving common Python problems in our series covering seven PyPI libraries. Image from Unsplash.com, Creative Commons Zero examine singledispatch, a library that allows you to add methods to Python libraries retroactively. singledispatch Imagine you have a "shapes" library with a Circle class, a Square class, etc. A Circle has a radius, a Square has a side, and a Rectangle has height and width. Our library already exists; we do not want to change it. However, we do want to add an area calculation to our library. If we didn't share this library with anyone else, we could just add an area method so we could call shape.area() and not worry about what the shape is. While it is possible to reach into a class and add a method, this is a bad idea: nobody expects their class to grow new methods, and things might break in weird ways. Instead, the singledispatch function in functools can come to our rescue. @singledispatch def get_area(shape): raise NotImplementedError("cannot calculate area for unknown shape", shape) The "base" implementation for the get_area function fails. This makes sure that if we get a new shape, we will fail cleanly instead of returning a nonsense result. @get_area.register(Square) def _get_area_square(shape): return shape.side ** 2 @get_area.register(Circle) def _get_area_circle(shape): return math.pi * (shape.radius ** 2) One nice thing about doing things this way is that if someone writes a new shape that is intended to play well with our code, they can implement get_area themselves. from area_calculator import get_area @attr.s(auto_attribs=True, frozen=True) class Ellipse: horizontal_axis: float vertical_axis: float @get_area.register(Ellipse) def _get_area_ellipse(shape): return math.pi * shape.horizontal_axis * shape.vertical_axis Calling get_area is straightforward. print(get_area(shape)) This means we can change a function that has a long if isintance()/elif isinstance() chain to work this way, without changing the interface. The next time you are tempted to check if isinstance, try using singledispatch! In the next article in this series, we'll look at tox, a tool for automating tests on Python code. 3 Comments Why wouldn't you just have a Shape class with all the methods common to all shapes and then simply just raise your NotImplementedError exception in get_area in the Shape class then have all of your shapes inherit from Shape and then override get_area as needed in the child classes? Isn't that what inheritance is for? In your example get_area has no side effects so grow new methods isn't a concern. I fail to see how singledispatch accomplishes anything except make your code more complicated, harder to read and many would say non-pythonic. I also tend to agree with you on this. I think the more Pythonic way would be yo use a dict to map the type to the squaring function/lambda. This is probably a wraper around this, but it is not explicit and is yet another library dependency to maintain. great
https://opensource.com/article/19/5/python-singledispatch
CC-MAIN-2020-34
refinedweb
522
64.41
UPDATE: An update to this simple client is posted here. Introduction This post serves a tutorial on JMS client development and WebLogic JMS resource definitions. Main Article Quite often I find that I want to be able to send some JMS messages programmatically, so I decided to write a simple, reusable Java class to help with this need. In this example, I am using WebLogic Server 11g as my JMS server. Preparation First, I will set up a JMS Queue on my WebLogic Server. This is done through the WebLogic Server console, which is normally accessible at, using an adminstrative user like weblogic. After you log in, navigate to Services -> Messaging -> JMS Modules in the menu on the left hand side of the console. You will see one or more modules listed. Your list will almost certainly be different to mine. If you are not sure which one to use, take a look at the settings. The most important thing to note is the port that is used to connect to the server that your JMS module is deployed on. You will need that later. You can find that by clicking on the name of the JMS Module, then going to the Targets tab. Then go to Environment -> Servers in the main menu and read the port number of the server you saw selected as the Target for the JMS Module. In my case, it is 9001. Click on the name of the JMS Module to display the resources. You will most likely see a mixture of Queues and Topics and one or more Connection Factories. Note that you will need to have a QueueConnectionFactory for this example to work. You should have one there already, take a note of its JNDI name. In my example it is jms/QueueConnectionFactory. Now we will create the Queue. Click on the New button to start. Select Queue as the type of resource we want to create. Click on Next. Enter the Name and JNDI Name for the new queue. I have followed the convention of using the same name for each, but with “jms/” prepended to the JNDI Name. Click on Next. Select your Subdeployment from the drop down list and the JMS Server in the Targets section. Note that you need to choose the same one as before. Then click on Finish to create the Queue. You should now see your new Queue listed in the resources page, as shown below. JMSSender Class Here is the Java Class that provides the simple JMS client. There are two libraries (jar files) that are needed to compile and run this class. These are located in your WebLogic Server directory: - <WebLogic_Directory>\server\lib\wlclient.jar - <WebLogic_Directory>\server\lib\wljmsclient.jar Update: In newer versions of WebLogic Server, there is a new lightweight library called wlthint3client.jar (in the same location) that you can use instead of these libraries. In JDeveloper, right click on the project and select Project Properties… from the popup menu. Navigate to the Libraries and Classpath page. Click on the Add Jar/Directory… button and navigate to the libraries mentioned above to add them to your project. Then create a new Java Class and add the code below. Take note of the two comments near the beginning of the file with “NOTE:” in them. You will need to change five lines of code here to make this code work. # Copyright 2012. package bamrunner; import java.util.Hashtable; import javax.naming.*; import javax.jms.*; public class JMSSender { private static InitialContext ctx = null; private static QueueConnectionFactory qcf = null; private static QueueConnection qc = null; private static QueueSession qsess = null; private static Queue q = null; private static QueueSender qsndr = null; private static TextMessage message = null; // NOTE: The next two lines set the name of the Queue Connection Factory // and the Queue that we want to use. private static final String QCF_NAME = "jms/QueueConnectionFactory"; private static final String QUEUE_NAME = "jms/OPOQueue"; public JMSSender() { super(); } public static void sendMessage(String messageText) { // create InitialContext://localhost:9001"); properties.put(Context.SECURITY_PRINCIPAL, "weblogic"); properties.put(Context.SECURITY_CREDENTIALS, "welcome1"); try { ctx = new InitialContext(properties); } catch (NamingException ne) { ne.printStackTrace(System.err); System.exit(0); } System.out.println("Got InitialContext " + ctx.toString()); // create QueueConnectionFactory try { qcf = (QueueConnectionFactory)ctx.lookup(QCF_NAME); } catch (NamingException ne) { ne.printStackTrace(System.err); System.exit(0); } System.out.println("Got QueueConnectionFactory " + qcf.toString()); // create QueueConnection try { qc = qcf.createQueueConnection(); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Got QueueConnection " + qc.toString()); // create QueueSession try { qsess = qc.createQueueSession(false, 0); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Got QueueSession " + qsess.toString()); // lookup Queue try { q = (Queue) ctx.lookup(QUEUE_NAME); } catch (NamingException ne) { ne.printStackTrace(System.err); System.exit(0); } System.out.println("Got Queue " + q.toString()); // create QueueSender try { qsndr = qsess.createSender(q); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Got QueueSender " + qsndr.toString()); // create TextMessage try { message = qsess.createTextMessage(); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Got TextMessage " + message.toString()); // set message text in TextMessage try { message.setText(messageText); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Set text in TextMessage " + message.toString()); // send message try { qsndr.send(message); } catch (JMSException jmse) { jmse.printStackTrace(System.err); System.exit(0); } System.out.println("Sent message "); // clean up try { message = null; qsndr.close(); qsndr = null; q = null; qsess.close(); qsess = null; qc.close(); qc = null; qcf = null; ctx = null; } catch (JMSException jmse) { jmse.printStackTrace(System.err); } System.out.println("Cleaned up and done."); } public static void main(String args[]) { sendMessage("test"); } } How to use it The code shown above has a main() method included, which will send a simple message containing the word “test.” You can just right click on the Class and run it to execute the main() method. After you do this, you will be able to see your message in the queue (assuming everything worked). To do this, click on the name of your queue in the resources page (where we left the console earlier), then select the Monitoring tab. You will see the details of messages in the queue. Select the queue and click on the Show Messages button. You will see a list of the messages. You can click on the message ID to drill down to more details, including the data. Here you see the JMS header information and the data in the message body (payload): All site content is the property of Oracle Corp. Redistribution not allowed without written permission
http://www.ateam-oracle.com/a-simple-jms-client-for-weblogic-11g/
CC-MAIN-2016-50
refinedweb
1,095
60.21
. When you send an SMS to the Arduino with the message “STATE”, it replies with the latest temperature and humidity readings. Before proceeding with this tutorial we recommend the following resources: - Guide to SIM900 GSM GPRS Shield with Arduino - Guide for DHT11/DHT22 Humidity and Temperature Sensor With Arduino - Enroll in our free Arduino Mini Course - Recommended course: 25 Arduino Step-by-step Projects First, watch the video demonstration SIM900 GSM Shield There are several modules you can use to send and receive SMS with the Arduino. We did this project using the SIM900 GSM shield and that’s the shield we recommend you to get. The SIM900 GSM shield is shown in figure below: For an introduction to the GSM shield, and how to set it up, read the Guide to SIM900 GSM GPRS Shield with Arduino. Parts Required Here’s a list of all the components needed for this project: - Arduino UNO – read Best Arduino Starter Kits - SIM900 GSM Shield - 5V 2A Power Adaptor - FTDI programmer (optional) - SIM Card - DHT11 or DHT22 Temperature and Humidity Sensor - 10 kOhm resistor - Breadboard - Jumper Wires You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price! Preliminary steps Before getting started with your SIM900 GSM module, you need to consider some aspects about the SIM card and the shield power supply. need to go through: Settings > Advanced Settings > Security > SIM lock and turn off the lock sim card with pin. Getting the right power supply The shield has a DC jack for power as shown in figure below. Download our Free eBooks and Resources Next to the power jack there is a toggle switch to select the power source. Next to the toggle switch on the board, there is an arrow indicating the toggle position to use an external power supply – move the toggle switch to use the external power supply as shown above. To power up the shield, it is advisable to use a 5V power supply that can provide 2A as the one shown below. You can find the right power adapter for this shield here. Make sure you select the model with 5V and 2A. Setting up the SIM900 GSM Shield The following steps show you how to set up the SIM900 GSM shield. 1) Insert the SIM card into the SIM card holder. You need a SIM card with the standard size. The shield is not compatible with micro or nano SIM cards. If you need, you may get a sim card size adapter. Also, it is advisable to use a SIM card with a prepaid plan or unlimited SMS. 2) Confirm the antenna is well connected. 3) On the serial port select, make sure the jumper cap is connected as shown in figure below to use software serial. 4) Power the shield using an external 5V power supply. Double-check that you have the external power source selected as we’ve mentioned earlier.. 7) You can test if the shield is working properly by sending AT commands from the Arduino IDE using an FTDI programmer – as we’ll show below. Testing the Shield with FTDI programmer You don’t need to do this step to get the shield working properly. This is an extra step to ensure that you can communicate with your GSM shield and send AT commands from the Arduino IDE serial monitor. For that, you need an FTDI programmer as the one shown in figure below.. Now that you know the shield is working properly, you are ready to start building the project. Schematics The figure below shows the circuit schematics for this project. You have to connect the SIM900 GSM shield and the DHT11 temperature and humidity sensor to the Arduino as shown in the figure below. Installing the DHT library To read from the DHT sensor, you must have the DHT library installed. If you don’t have the DHT library installed, follow the instructions below: - Installing the Adafruit_Sensor library To use the DHT temperature and humidity sensor, The following code reads the temperature and humidity from the DHT sensor and sends them via SMS when you send an SMS to the Arduino with the message “STATE”. You need to modify the code provided with the phone number your Arduino should reply the readings to. The code is well commented for you to understand the purpose of each line of code. Don’t upload the code now. Scroll down and read the explanation below the code. /* * Rui Santos * Complete Project Details */ // Include DHT library and Adafruit Sensor Library #include "DHT.h" #include <Adafruit_Sensor.h> //Include Software Serial library to communicate with GSM #include <SoftwareSerial.h> // Pin DHT is connected to #define DHTPIN 2 // Uncomment whatever type of sensor you're using #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Initialize DHT sensor for normal 16mhz Arduino DHT dht(DHTPIN, DHTTYPE); // Create global varibales to store temperature and humidity float t; // temperature in celcius float f; // temperature in fahrenheit float h; // humidity // Configure software serial port SoftwareSerial SIM900(7, 8); // Create variable to store incoming SMS characters char incomingChar; void setup() { dht.begin(); Serial.begin(19200); SIM900.begin(19200); // Give time to your GSM shield log on to network delay(20000); Serial.print("SIM900 ready..."); //(){ if (SMSRequest()){ if(readData()){ delay(10); // REPLACE THE X's WITH THE RECIPIENT'S MOBILE NUMBER // USE INTERNATIONAL FORMAT CODE FOR MOBILE NUMBERS SIM900.println("AT + CMGS = \"+XXXXXXXXXX\""); delay(100); // REPLACE WITH YOUR OWN SMS MESSAGE CONTENT String dataMessage = ("Temperature: " + String(t) + "*C " + " Humidity: " + String(h) + "%"); // Uncomment to change message with farenheit temperature // String dataMessage = ("Temperature: " + String(f) + "*F " + " Humidity: " + String(h) + "%"); // Send the SMS text message SIM900.print(dataMessage); delay(100); // End AT command with a ^Z, ASCII code 26 SIM900.println((char)26); delay(100); SIM900.println(); // Give module time to send SMS delay(5000); } } delay(10); } boolean readData() { //Read humidity h = dht.readHumidity(); // Read temperature as Celsius t = dht.readTemperature(); // Read temperature as Fahrenheit f = dht.readTemperature(true); // Compute temperature values in Celcius t = dht.computeHeatIndex(t,h,false); // Uncomment to compute temperature values in Fahrenheit //f = dht.computeHeatIndex(f,h,false); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); return false; } Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.print(" *C "); //Uncomment to print temperature in Farenheit //Serial.print(f); //Serial.print(" *F\t"); return true; } boolean SMSRequest() { if(SIM900.available() >0) { incomingChar=SIM900.read(); if(incomingChar=='S') { delay(10); Serial.print(incomingChar); incomingChar=SIM900.read(); if(incomingChar =='T') { delay(10); Serial.print(incomingChar); incomingChar=SIM900.read(); if(incomingChar=='A') { delay(10); Serial.print(incomingChar); incomingChar=SIM900.read(); if(incomingChar=='T') { delay(10); Serial.print(incomingChar); incomingChar=SIM900.read(); if(incomingChar=='E') { delay(10); Serial.print(incomingChar); Serial.print("...Request Received \n"); return true; } } } } } } return false; } Importing libraries First, you include the libraries needed for this project: the DHT libary to read from the DHT sensor and the SoftwareSerial library to communicate with the SIM900 GSM module. #include "DHT.h" #include <Adafruit_Sensor.h> #include <SoftwareSerial.h> DHT sensor. #define DHTPIN 2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); You also create float variables to store the temperature and humidity values. float t; // temperature in celcius float f; // temperature in fahrenheit float h; // humidity GSM shield; setup() In the setup(), you begin the DHT and the SIM900 shield. The SIM900 shield is set to text mode and you also set the module to send the SMS data to the serial monitor when it receives it. This is done with the following two lines, respectively: SIM900.print("AT+CMGF=1\r"); SIM900.print("AT+CNMI=2,2,0,0,0\r"); Functions STATE – the SMSRequest() function. This functions returns true if the Arduino receives a message with the text STATE and false if not. You read the SMS incoming characters using: incomingChar = SIM900.read(); loop() In the loop(), you check if there was an SMS request with the SMSRequest() function – you check if the Arduino received a STATE. Then, you store the message you want to send in the dataMessage variable. Finally you send the SMS text message using: SIM900.print(dataMessage); Demonstration When you send the STATE message to the Arduino, it replies with the sensor data. Watch the video at the beginning of the post for a more in depth project demo. Wrapping Up This is a great project to get you started with the SIM900 GSM shield. You’ve learned how to read and send SMS text messages with the Arduino. You can apply the concepts learned in pretty much any project. Here’s some ideas of projects: - Surveillance system that sends an SMS when it detects movement - Control a relay via SMS - Request specific sensor data from a collection of sensors by adding more conditions to the code If you like Arduino, you’ll certainly like these 25 Arduino Step-by-step Projects. 49 thoughts on “Request Sensor Data via SMS using Arduino and SIM900 GSM Shield” Hi all, the SIM900 GSM is still a 2G interface … and most providers will soon get up the 2G standard to move at least o 4G standard … as announced for the end of 2018 Here in Australia the 2G networks have been shut down. Most carriers now use 4G as a minimum. The SIM900 is a very old device. There are 3G and 4G modules out there but they are a little on the expensive side compared to the SIM900. Hi Peter. You are right. Some locations no longer support 2G network. We need to shift to a 3G or 4G module soon, so that everyone in any location is able to make our projects. Thanks for your note. Regards, Sara 🙂 Yes. You are right. We need to look for a module that supports 3G or 4G. Thanks for letting us know. Here, in Portugal, 2G network is still working, but there are many countries that no longer support that. Hi Sara, I have upgraded to the SIM5216E (on an Arduino MEGA) here in Australia. With some minor software changes your projects work fine. How about adding voltage and current sensors to your SMS projects. May be reading NMEA messages as well – just a thought. Hi Harry. Thank you for your suggestions. We should definitely upgrade our tutorials to use the SIM5216E – it should be supported in all locations. We have a tutorial about reading NMEA messages with the NEO-6M GPS module, that you may find useful: Regards, Sara 🙂 hello can i use a 9v battery for arduino and a 12v battery for Sim 900 module? Yes. Can i use battery or any other power supply source instead of using adaptor for Sim 900 Gsm Module? Yes. Can i use battery 7,4 volt, 2200 mA for sim900 module ? Hi Arif. If you’re using a similar shield, the recommended power is: 5V up to 2A, or 9V 1A, or 12V 1A. You should check with your supplier, or test it yourself. Regards, Sara 🙂 can i use 9v battery for the gsm module? Yes. 9V 1A is recommended. Or 5V 2A, or 12V 1A. Regards, Sara. Iam trying to make this project full wireless but the problem is that in market the battery 9v 1 amp battery is not available the battery that is available is 9v 600mah can u give any suggestions ? Hi Arsalan. You have to experiment and see if that battery meets your project requirements. Regards, Sara 🙂 Hello I have completed this project and it works very fine but i want to add pressure sensor BMP180 to it too can u guide me to which pins i can add BMP180 ? Hi Ali. Take a look at the following getting started guide for the BMP180: It should help you with your project. Regards, Sara 🙂 Hi How can i make this work with Fingerprint Authentication? Since i have a project which is a Vault with fingerprint scanner and a temp humid sensor. I dont know how to work with two sensor on loop together Hi. We don’t have that specific project you’re looking for. We have guides on how to use fingerprint sensor and temperature and humidity sensor. Take a look at the links below: I hope this helps Regards, Sara 🙂 Hello, can you use an integer variable to store an incoming SMS number? Hi Gilbert. I don’t think so. An int stores a 16-bit value. This yields a range of -32,768 to 32,767. So, it is not appropriate to store an SMS number. Instead, I recommend using a char variable. Regards, Sara 🙂 For example I would like to send a number(let’s say 40) via sms. Is there a way I can store this number in an integer variable? I would like to use that number in an if condition.. For example: if value<30 (where value is the integer variable) Hi again. When the arduino receives data from an SMS, it stores it in a char variable. Take a look at this link and see if you are able to convert the char to an int number: forum.arduino.cc/index.php?topic=103511.0 Regards, Sara 🙂 Hi there Sara, you said the number will be stored in char variable… Can it be used in an if function; for example if value<30 (where value is the char variable)? Hi Gilbert. You can’t compare a char with a number. You should convert the char to a number first. You can use the atoi() function to convert. Regards, Sara Is there any library for sim900 in this project as we have used for the DHT sensor? Hi. You don’t need to install any library for the SIM900. It communicates via serial. In the code we use the softwareserial library that is installed by default. Regards, Sara 🙂 Gsm sim 900 is stackable to arduino so is it possible to attach the sim 900 shield above the arduino board and skip the adaptor source You can stack the SIM900 module and Arduino. I have done that myself. The SIM900 module needs a lot of power when transmitting. You only need 1 power supply. Mine is connected to the Arduino. How do i make this work with Sim800 and without FTDI programmer? Hi Keith. I haven’t experimented with SIM800 yet. So, I’m don’t know how to do that. Try searching for “SIM800 wiring Arduino”. Regards, Sara bonjour j’ai essayer de le faire mais je n’arrive pas à recevoir les données via sms.et j’ai essayer d’envoyer un simple sms mais sa marcher toujours pas Hi. Without further details, it is very difficult to help. Regards, Sara 1)Can we use this code for sim800c & lm35 temperature sensor 2) can we change the keyword STATE to TEMPERATURE Hi. We don’t have any tutorials about the SIM800. Yes, you can change the keyword to TEMPERATURE. Regards, Sara Hi…i need code and library file for same project with LM35 temperature sensor Hi. We don’t have this project with the LM35 temperature sensor. However, using that temperature sensor is very easy. After declaring the tempPin as an input, you can read the temperature in Kelvin with the following line of code: tempK = (((analogRead(tempPin)/ 1023.0) * 5.0) * 100.0); You can take a look at the code of the following project and see if it helps: Regards, Sara I’m not able to separate LCD code from LM35 code…Pls do help for above project with LM35 Bonjour a tous ,je veux poser ma question a sara ,juste savoir comment on peux envoyer le donnes lue par deux capteur differents et comment programmer le moniteur serie avec le baud Hi I’m using the GSM 900 SHIELD installed directly on the Arduino …… g how can it work with this code please help You just need to follow the steps on the tutorial. hi, im using sim900 and ultrasonik sensor and ds3231 built in temp sensor, when i tried to make it send a sensor value using the smsrequest code, it doesnt work, the sim recieved my message but it wont send an sms to my phone? help please thanks nevermind, i just deleted the if before readData, thanks a lot for the code Como poderia fazer para ele enviar mensagem sempre que a temperatura fosse maior que 27. enviar automatico sempre que a temperatura passar 27 e enviar para mais de 1 numero Hi Guilherme. W’re working on that project at the moment. So, it will be released soon: next week or the other week. Regards, Sara hello good afternoon, did you manage to send message whenever it exceeds a certain temperature? and for more than 1 number thank you very much for the help, awesome project congratulations Boa tarde sara, conseguiu aquele projeto de enviar mensagem automaticamente apos 27 graus? Olá Guilherme. Temos esse projeto com a TTGO SIM800L board: Cumprimentos, Sara
https://randomnerdtutorials.com/request-sensor-data-sms-arduino-sim900-gsm-shield/
CC-MAIN-2019-47
refinedweb
2,865
63.7
The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original array. What am i doing wrong? a = range(10) def listreduction(array): if len(array) == 1: array[0] = 0 return split = len(array)/2 array[split] = 0 return listreduction(array[split:]) listreduction(a) print a [0, 1, 2, 3, 4, 0, 6, 7, 8, 9] This is probably what you want. a = range(1, 10) def list_reduction(l, prev_split_pos=None): split_pos = (len(l) + prev_split_pos) / 2 if prev_split_pos else len(l) / 2 if split_pos == prev_split_pos: return l[split_pos] = 0 return list_reduction(l, split_pos) list_reduction(a) print a So, to your code. Everytime you do a list slice, you actually generate a new list, which is not at all connected to the old one. This is why you don't see any mutations to it except the first one.
https://codedump.io/share/JJ4kIMrWTZUm/1/how-to-use-a-function-to-change-a-list-when-passed-by-reference
CC-MAIN-2017-30
refinedweb
191
69.01
Moderately OT and definitely not about Perl. You've been warned. It has been over a decade since I hacked C. As a result, I don't remember any of it. Oh, I can read through C code and get a general idea and still kind of recall pointers, but that's about it. Still can't recall how to use malloc for example. So, I decided to look at a local university for C classes. They didn't appear to have any, but their online catalog is, um, less than clear about what they do have. I went ahead and called down to the university and a receptionist thought that they offered C, but wasn't sure. She would have someone call me back. Someone did call me back and identified himself as the head of their computer science department (at least, that's what I recall from the conversation, but I could be mistaken). I was informed that not only did PSU not offer C, they would not be offering it in the future because "C is obsolete". I was informed that the world of computing is moving to Object Oriented languages and PSU will only be teaching those skills that prepare students for the future. Since I have some friends who are college professors, I hesitate to say "Ivory Tower", but the thought does cross my mind. Claiming that "C is obsolete" ¹ and that the future belongs to OO languages strikes me as more than a little absurd. Cheers, Ovid 1. Obligatory Perl reference: I guess that means Perl is written in an obsolete language, eh? Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. However, to teach them *only* object-oriented programming is not being fair to the students. Procedural programming still has it's place (who's going to write a OOP device driver??!), and the other programming philsophies such as functional can be useful. I do agree that most Comp Sci students will be using one of C++, Java, or Vis Basic as their main programming environment, and I cannot fault the university toward teaching those languages (as thie is what the industry appears to demand), but they should at least touch on other aspects of programming, particularly for those students with higher asperations in their programming careers. Would this necessary mean teaching C specifically? Probably not. Continuing to think about the problem, say that I wanted to teach some alternate language or approach (say, LISP). Most likely, I'd only have a semester to do this, and while that would be enough time to teach such a language, it would not be enough to go into all the details and tricks with it. So a second semester might be needed. But then you have to consider what population of the students would take this course; only a small fraction of comp.sci. students, in my experience, would have the initiative to take such a course. Thus, it would be very likely that a course may be offered one year, but the low turnout kills it since it otherwise takes up valuable classroom space. Alternatively a course that dealt with alternative languages as a whole, and covering all the different types of programming models, would probably get more students, but there is NWIH you could teach all the tricks and details of these languages in a single semester, and I'd rather avoid teaching such a mess of a course instead of having it as separate units. That said, I believe that most people that are true programmers at heart are ones that can self-teach themselves nearly any language; I know I have. Yes, it's nice to have "C++/Java training" on your resume so that you can get hired, but to also be able to demonstrate that you can learn other non-standard languages on your own would be a more valuable skill, at least to me. If the company decided to try a new approach and required that a new language or similar feature set be learned from scratch, I'd rather have someone that has demonstrated the ability to quickly learn a skill on their own rather than someone that can only cookie-cut out new programs and would require training in the new. Are you trying to brush up your C out of curiosity, or a out of a practical need? Anyway, C is alive and well, as is it's bigger brother C++. Nowdays, programming in C instead of C++ is similar to programming in Perl without Perl's OO constructs. Anything you can do with one you can do with the other. However, if you insist on not using OO in Perl, you have to forgo many a lovingly crafted module. Similarly, if you stick to C and shy away from C++, you have to forgo a range of powerful language constructs, and ready-to-use libraries such as STL. Rudif P.S. The venerable K&R hello.c still compiles under a current C++ compiler (although it draws a double warning) #include <stdio.h> main() { printf("hello, world\n"); } [download] 'main' : function should return a value; 'void' return type assumed [download] My.. Where I work, when we interview programmers for jobs, this is what we look for - the domain knowledge and experience : software for sci/eng measuring instruments - the programming experience : C++, real time, component software - the person : do you have courage and curiosity, can you identify and solve problems, can you find nuggets of knowledge wherever they hide - your head, books, vendor doc (yes!), web; do you know the hardships and joys of teamwork? Knowledge and experience are minimal conditions, personal qualities are decisive. If you meet a prospective employer who is not probing for these qualities, you should probably look around for another one. Rudif). That's why I'll be really interested to see if the new perl takes off. It's got lots of advanced features that academics might appreciate. But it's quite complicated and I'm not sure that everyday coders will take to it. Does America have 'technical colleges' like we do here? That would be a much better bet for finding a C course, and cheaper to. ____________________ Jeremy I didn't believe in evil until I dated it. While I can understand that they want to try to turn out students capable of handling the challenges and technologies of tomorrow, in doing so it sounds like they are forgetting that to see further (a la Sir Issac Newton), you must stand on the shoulders of giants. In the RO (read-only) world of academia, perhaps a language may be "obsolete" because there are other languages designed to do the same thing, or because little can be learned from it that cannot be learned using another, but in the RW (real world) that I work (and have to get paid) in, a language is only obsolete when it is no longer useful (or no compiler or interpreter can be found for it). (Also, had that been the prevailing attitude everywhere, I can only imagine how much more legacy COBOL code would have failed because no one could find that it was going to have problems when 01-01-00 came around, for instance.) As to impossiblerobot's question in Re: Re: (OT) Where is programming headed? about the different types of languages, the best references I could find at hand were the language listing at , and a page on programming languages at . Update: Just so no one thinks I am speaking completely out of turn, for reference I do have a B.S. degree in computer science, although it has been a few years since I completed it, and I do think academic training and research in computer science does have purpose. I can't imagine a university CS department that doesn't require their students to take at least one semester or quarter of Assembler. For me it was one of my most challenging programming courses and I believe it gave me much needed insight into what was really going on under the hood. Believe it or not, PL/1 was the language used for my first three required programming courses and going straight into assembler from there was a mind altering experience. If it had been a technical school, I might agree since they usually have a narrower focus (and sometimes offer more obscure languages like RPG--nothing wrong with that mind you). --Jim There was (maybe still is) an author by the name of James Martin who wrote numerous books on various comp sci subjects, and whose message always seemed (at least to me) to be ”Programmers will be obsolete…“ Obviously not the case. My guess is your university and James Martin should get together. Programmers . Says C will be around for a very long time in certain circles, as will COBOL, Java, Perl etc. They will not be the coolest/most populat forever, but will survive in niches where they offer the best solution. It is more important what you write rather than what it is written in (within reason). ps: Watch your exchange rates! Today your $.02 USD is only worth $0.0312 CD.
http://www.perlmonks.org/index.pl?node_id=131789
CC-MAIN-2017-30
refinedweb
1,551
66.57
API wrapper for 4chan. Project description Contents - 4chan API reader. Installing python3 -m pip install aio4chan Usage import asyncio import aiohttp import aio4chan loop = asyncio.get_event_loop() session = aiohttp.ClientSession(loop = loop) client = aio4chan.Client(session = session, loop = loop) async def execute(): """ Traverse 4chan. """ boards = await client.get_boards() # short names board_ids = (board.board for board in boards) for board_id in board_ids: pages = await client.get_threads(board_id) # list of pages, each containing threads thread_ids = (thread.no for page in pages for thread in page.threads) for thread_id in thread_ids: # need both board_id and thread_id thread = await client.get_thread(board_id, thread_id) for post in thread: try: # might not exist comment = post.com except AttributeError: continue # print where we got it, and the comment print(board_id, '>', thread_id, '>', post.no, '\n', post.com) try: loop.run_until_complete(execute()) except KeyboardInterrupt: pass finally: loop.run_until_complete(session.close()) loop.close() Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/aio4chan/
CC-MAIN-2019-43
refinedweb
169
55.3
My website had been stable and running without error but I'd been running on 2.3.3, 2.0.52 and 3.1.3; since everything was behind the times I decided to finally reinstall; I made the mistake of doing it on the drive that everything was being served off of instead of using my backup drive. :-( I installed python 2.4 and it seems to work when I call it from the shell. I did not do a frameworkInstall, which seems to be recommended by some people. I am too much of a unix novice to understand what the implications of frameworkInstall are. I installed apache and mod_python as follows: cd ~/Desktop/httpd-2.0.53 ./configure --enable-so --with-mpm=worker make sudo make install cd ~/Desktop/mod_python-3.1.4 ./configure --with apxs=/usr/local/apache2/bin/apxs --with-python=/usr/local/bin/python2.4 make sudo make install I restored my old httpd.conf file and my website files. My index.html file is straight html which links to .py files. As soon as I try to access any of the .py stuff I now get an internal server error message and the server log shows this: [Tue Feb 15 16:25:25 2005] [notice] mod_python: Creating 32 session mutexes based on 6 max processes and 25 max threads. [Tue Feb 15 16:25:25 2005] [notice] Apache configured -- resuming normal operations [Tue Feb 15 16:25:36 2005] [error] make_obcallback: could not import mod_python.apache.\n Traceback (most recent call last): File "/usr/local/lib/python2.4/site-packages/mod_python/apache.py", line 22, in ? import time ImportError: Failure linking new module: : dyld: /usr/local/apache2/bin/httpd Undefined symbols: /usr/local/lib/python2.4/lib-dynload/time.so undefined reference to _PyArg_Parse expected to be defined in the executable /usr/local/lib/python2.4/lib-dynload/time.so undefined reference to _PyArg_ParseTuple expected to be defined in the executable /usr/local/lib/python2.4/lib-dynload/time.so undefined reference to _PyDict_GetItemString expected to be defined in the executable /usr/local/lib/python2.4/lib-dynload/time.so un <--what happened here?? [Tue Feb 15 16:25:36 2005] [error] make_obcallback: could not import mod_python.apache. for what its worth I can access various parts of the time module when I run Python2.4 from the shell. Going back through the the mailing list I saw that Graham Dumpleton (back on Dec 23) suggested the output from this might be useful; what I get is different from what he saw but I'm not sure what to make of my result: jraines-Computer:~/Desktop/Website jrraines$ otool otool -L /usr/local/apache2/modules/mod_python.so otool: can't open file: otool (No such file or directory) /usr/local/apache2/modules/mod_python.so: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 71.1.1) jraines-Computer:~/Desktop/Website jrraines$ ls /usr/local/apache2/modules httpd.exp mod_python.so My problem seemed like it might be similar to a thread titled Weird ob_callback problems at the end of Jan. I tried the suggestions Grisha made:Try defining DYLD_FORCE_FLAT_NAMESPACE=1 environment variable before launching httpd. That didn't help either.
http://modpython.org/pipermail/mod_python/2005-February/017444.html
CC-MAIN-2020-16
refinedweb
539
50.63