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
Config::Fast - extremely fast configuration file parser # default config format is a space-separated file company "Supercool, Inc." support nobody@nowhere.com # and then in Perl use Config::Fast; %cf = fastconfig; print "Thanks for visiting $cf{company}!\n"; print "Please contact $cf{support} for support.\n"; This module is designed to provide an extremely lightweight way to parse moderately complex configuration files. As such, it exports a single function - fastconfig() - and does not provide any OO access methods. Still, it is fairly full-featured. Here's how it works: %cf = fastconfig($file, $delim); Basically, the fastconfig() function returns a hash of keys and values based on the directives in your configuration file. By default, directives and values are separated by whitespace in the config file, but this can be easily changed with the delimiter argument (see below). When the configuration file is read, its modification time is first checked and the results cached. On each call to fastconfig(), if the config file has been changed, then the file is reread. Otherwise, the cached results are returned automatically. This makes this module great for mod_perl modules and scripts, one of the primary reasons I wrote it. Simply include this at the top of your script or inside of your constructor function: my %cf = fastconfig('/path/to/config/file.conf'); If the file argument is omitted, then fastconfig() looks for a file named $0.conf in the ../etc directory relative to the executable. For example, if you ran: /usr/local/bin/myapp Then fastconfig() will automatically look for: /usr/local/etc/myapp.conf This is great if you're really lazy and always in a hurry, like I am. If this doesn't work for you, simply supply a filename manually. Note that filename generation does not work in mod_perl, so you'll need to supply a filename manually. By default, your configuration file is split up on the first white space it finds. Subsequent whitespace is preserved intact - quotes are not needed (but you can include them if you wish). For example, this: company Hardwood Flooring Supplies, Inc. Would result in: $cf{company} = 'Hardwood Flooring Supplies, Inc.'; Of course, you can use the delimiter argument to change the delimiter to anything you want. To read Bourne shell style files, you would use: %cf = fastconfig($file, '='); This would let you read a file of the format: system=Windows kernel=sortof In all formats, any space around the value is stripped. This is one situation where you must include quotes: greeting=" Some leading and trailing space " Each configuration directive is read sequentially and placed in the hash. If the same directive is present multiple times, the last one will override any earlier ones. In addition, you can reuse previously-defined variables by preceding them with a $ sign. Hopefully this seems logical to you. owner Bill Johnson company $owner and Company, Ltd. website products $website/newproducts.html Of course, you can include literal characters by escaping them: price \$5.00 streetname "Guido \"The Enforcer\" Scorcese" verbatim 'Single "quotes" are $$ money @ night' fileregex '(\.exe|\.bat)$' Basically, this modules attempts to mimic, as closely as possible, Perl's own single and double quoting conventions. Variable names are case-insensitive by default (see KEEPCASE). In this example, the last setting of ORACLE_HOME will win: oracle_home /oracle Oracle_Home /oracle/orahome1 ORACLE_HOME /oracle/OraHome2 In addition, variables are converted to lowercase before being returned from fastconfig(), meaning you would access the above as: print $cf{oracle_home}; # /oracle/OraHome2 Speaking of which, an extra nicety is that this module will setup environment variables for any ALLCAPS variables you define. So, the above ORACLE_HOME variable will automatically be stuck into %ENV. But you would still access it in your program as oracle_home. This may seem confusing at first, but once you use it, I think you'll find it makes sense. Finally, if called in a scalar context, then variables will be imported directly into the main:: namespace, just like if you had defined them yourself: use Config::Fast; fastconfig('web.conf'); print "The web address is: $website\n"; # website from conf Generally, this is regarded as dangerous and bad form, so I would strongly advise using this form only in throwaway scripts, or not at all. There are several global variables that can be set which affect how fastconfig() works. These can be set in the following way: use Config::Fast; $Config::Fast::Variable = 'value'; %cf = fastconfig; The recognized variables are: The config file delimiter to use. This can also be specified as the second argument to fastconfig(). This defaults to \s+. If set to 1, then MixedCaseVariables are maintained intact. By default, all variables are converted to lowercase. If set to 1 (the default), then any ALLCAPS variables are set as environment variables. They are still returned in lowercase from fastconfig(). If set to 1, then settings that look like shell arrays are converted into a Perl array. For example, this config block: MATRIX[0]="a b c" MATRIX[1]="d e f" MATRIX[2]="g h i" Would be returned as: $conf{matrix} = [ 'a b c', 'd e f', 'g h i' ]; Instead of the default: $conf{matrix[0]} = 'a b c'; $conf{matrix[1]} = 'd e f'; $conf{matrix[2]} = 'g h i'; This allows you to pre-define var=val pairs that are set before the parsing of the config file. I introduced this feature to solve a specific problem: Executable relocation. In my config files, I put definitions such as: # Parsed by Config::Fast and sourced by shell scripts BIN="$ROOT/bin" SBIN="$ROOT/sbin" LIB="$ROOT/lib" ETC="$ROOT/etc" With the goal that this file would be equally usable by both Perl and shell scripts. When parsed by Config::Fast, I pre-define ROOT to pwd before calling fastconfig(): use Cwd; my $pwd = cwd; @Config::Fast::Define = ([ROOT => $pwd]); my %conf = fastconfig("$pwd/conf/core.conf"); Each element of This is a hash of regex patterns specifying values that should be converted before being returned. By default, values that look like true|on|yes will be converted to 1, and values that match false|off|no will be converted to 0. You could set your own conversions with: $Config::Fast::CONVERT{'fluffy|chewy'} = 'taffy'; This would convert any settings of "fluffy" or "chewy" to "taffy". Variables starting with a leading underscore are considered reserved and should not be used in your config file, unless you enjoy painfully mysterious behavior. For a much more full-featured config module, check out Config::ApacheFormat. It can handle Apache style blocks, array values, etc, etc. This one is supposed to be fast and easy. $Id: Fast.pm,v 1.7 2006/03/06 22:18:41 nwiger Exp $ This module is free software; you may copy this under the terms of the GNU General Public License, or the Artistic License, copies of which should have accompanied your Perl kit.
http://search.cpan.org/dist/Config-Fast/lib/Config/Fast.pm
CC-MAIN-2014-23
refinedweb
1,152
54.52
How to Survive Moving Have you moved to a new state or country? Do you like the place? If you don't, try exploring some of the positive aspects of moving such as new places, new friends, and hopefully, a whole new adventure. This article aimed at children will tell you how to survive moving away for the first time. [edit] Steps - When you find out you are leaving, get a notebook where all of your friends can leave contact information and well wishes for your new home. - Call your old friends. - E-mail, write, send packages, and ask them to send you packages to your new home. - Try and make arrangements with your parents to see if you could go and visit your old friends or have your friends visit you. - Make sure you try to make friends with a lot of people. If you don't like any of your new friends, find someone who you can at least turn to. Try not to stick to just one person. Try and find someone who you can trust with secrets and who is very respectful. Whenever you are down you can look to them to pour out all of your sadness. - Sometimes it doesn't hurt to cry. Doing this in your room or with your parents can be useful. Sometimes you just need to let it all out. - Don't think negatively about the place. Just think of it as an adventure. - Find an activity, like a club or group to get involved in. [edit] Tips - Remember that sometimes you will always feel sad no matter how long you have lived in a place. Have friends from your original home send you postcards, pictures and packages. You can send them small gifts in return (for example, a favourite pack of gum). - Make a card or friendship bracelet. - Call them on their birthdays. - Write to them and tell them what you are doing. - Keep in touch on social networking websites - You are the one who is exploring a whole new world, not your friends, so tell them what it's like! [edit] Warnings - Don't live in the past - stay in touch with your old friends, but try to make new ones, too. If possible, introduce them to one another.
http://www.wikihow.com/Survive-Moving
crawl-002
refinedweb
381
91.71
You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org Help:MySQL queries MySQL queries against the Wiki Replicas databases allow you to search and collect metadata about pages and actions on the Wikimedia movement's public wikis. Also consider the Quarry web interface as an alternative for one-off queries. Database layout The database layout is available at the MediaWiki wiki: mw:Manual:Database layout. A dump of the currently running database layouts can be found here. There are also two commands you can use to view the layout. SHOW TABLES will show the available tables in a database. DESCRIBE table_name will show the available columns in a specific table. Slices The various databases are stored in 'slices'. The slices are named with a leading 's' and a digit—for example s1, s2, etc.—followed by the internal domain name '{analytics,web}.db.svc.eqiad.wmflabs' (e.g. s1.analytics.db.svc.eqiad.wmflabs and s1.web.db.svc.eqiad.wmflabs). A table of this information is available here: List meta_p.wiki. Data storage There are a few tricks to how data is stored in the various tables. - Page titles use underscores and never include the namespace prefix. (eg: page_title='The_Lord_of_the_Rings') - User names use spaces, not underscores. (eg: actor_name='Jimbo Wales') - Namespaces are integers. A key to the integers is available here. Views Toolforge has exact replicas of Wikimedia's databases, however, certain information is restricted using MySQL views. For example, the user table view does not show things like user_password or user_email to Toolforge users. You can only access data from the public (redacted) databases marked as _p (eg: enwiki_p). Alternative views There are some alternative views in which the data from the underlying tables are redacted in a different way, so that the corresponding indices can be used. If you utilize the listed columns in your queries (especially in WHERE clause or ORDER BY statement) it is recommended to use these alternative views. This will speed up things quite a lot. - Technical bit The script that creates and maintains the indexes used by the alternative views is called maintain_replica_indexes.py. This script uses the definitions found in index-conf.yaml to generate those indexes. That last file is where you can learn, for instance, that an additional index called log_actor_deleted is being created on the logging table using log_actor, log_deleted columns. The alternative tables boost the queries not just using indexes; they also do so by subsetting the original table. For instance, actor_revision table only includes those actors that match a row in the revision table's rev_actor column. The script that populates the alternative views can be found in maintain-views.py; this script uses maintain-views.yaml to populate those views. The last file is where you can find the definition of actor_revision table, for instance. Wiki text Unfortunately there is no way to access the wikitext directly via MySQL replica databases. You have to use the mw:API instead. Accessing the databases There are a variety of ways to access the databases. preset shell script From the command line, a shell script exists that automatically selects the correct slice for you. The sql shell script is a wrapper around the mysql command. Either method works, though the sql shell script selects the appropriate slice for you. $ sql enwiki_p This command will connect to the appropriate cluster (in this case, s1.analytics.db.svc.eqiad.wmflabs) and give you a MySQL prompt where you can run queries. $ sql enwiki_p < test-query.sql > test-query.txt This command takes a .sql file that contains your query, selects the appropriate slice, runs the query, and outputs to a text file. The advantage here is that it doesn't add lines around the data (making a table), it instead outputs the data in a tab-delimited format. $ sql enwiki_p < test-query.sql | gzip >test-query.txt.gz This command does the same thing as the command above, but after outputting to a text file, it gzips the data. This can be very helpful if you're dealing with large amounts of data. mysql command If you wish to use the mysql command directly, a sample query would look like this: $ mysql --defaults-file=~/replica.my.cnf -h s1.analytics.db.svc.eqiad.wmflabs enwiki_p -e "SHOW databases;" The --defaults-file option points to the file replica.my.cnf where your MySQL credentials are stored (username, password). The -h option tells MySQL which host to access (in this case s1.analytics.db.svc.eqiad.wmflabs) and enwiki_p is the database you want to access. The -e option tells MySQL to execute the following command enclosed in quotes. You can also have MySQL output the results to a file. $ mysql --defaults-file=~/replica.my.cnf -h s1.analytics.db.svc.eqiad.wmflabs enwiki_p < test-query.sql > test-query.txt mysql command with default Another way to use the mysql command directly but without the need to specify the --defaults-file option each time, is to copy your replica.my.cnf to .my.cnf once. $ ln -s replica.my.cnf .my.cnf From that point your login data is automatically loaded by the mysql command. All subsequent commands then look similar as shown above. $ mysql -h s1.analytics.db.svc.eqiad.wmflabs -e "show databases;" Writing queries Because the replica databases are read-only, nearly all of the queries you will want to run will be SELECT queries. SELECT * FROM `user`; This query selects all columns from the user table. More information about MySQL queries are available below (in the example queries) and in the MySQL SELECT. Queries end in a semi-colon (;). If you want to cancel the query, end it in \c. If you want to output in a non-table format, use \G. Optimizing queries Task T50875 Resolved To optimize queries, you can ask the MySQL server how the query is executed (a so-called EXPLAIN query). Because of the permissions restrictions on the Wiki Replica servers, a simple EXPLAIN query will not work. There is however a workaround using MariaDB's SHOW EXPLAIN FOR: - Open 2 SQL sessions - In session 1: SELECT CONNECTION_ID() AS conid; - Note the number returned. - Run the query to be explained. - In session 2: - Use the number you found above for <conid>. SHOW EXPLAIN FOR <conid>; If the rightmost column contains 'using filesort', your query is likely to take a long time to execute. Review whether the correct index is used, and consider switching to one of the alternative views. A helpful tool for this is the online SQL Optimizer, which will display the execution plan for a given query. Quarry can also show the plan for a currently executing query. meta_p database The "meta_p" database contains metadata about the various wikis and databases. It consists of one table: wiki and it is available on every slice (s1–s8.analytics.db.svc.eqiad.wmflabs). Example queries - Help:MySQL queries/Example queries contains a large collection of examples which were once in this page directly. - en:Wikipedia:Database reports (and its equivalents in other languages) contain many useful examples. - Published queries on Quarry are another good source of examples (try using Google site search for specific topics) - The tsreports tool is another source of valuable suggestions. See also - (This page was originally imported from)
https://wikitech-static.wikimedia.org/w/index.php?title=Help:MySQL_queries&oldid=575281
CC-MAIN-2022-33
refinedweb
1,230
58.48
I have a simple array: arr = ["apples", "bananas", "coconuts", "watermelons"] I also have a function f that will perform an operation on a single string input and return a value. This operation is very expensive, so I would like to memoize the results in the hash. I know I can make the desired hash with something like this: h = {} arr.each { |a| h[a] = f(a) } What I’d like to do is not have to initialize h, so that I can just write something like this: h = arr.(???) { |a| a => f(a) } Can that be done? Say you have a function with a funtastic name: “f” def f(fruit) fruit + "!" end arr = ["apples", "bananas", "coconuts", "watermelons"] h = Hash[ *arr.collect { |v| [ v, f(v) ] }.flatten ] will give you: {"watermelons"=>"watermelons!", "bananas"=>"bananas!", "apples"=>"apples!", "coconuts"=>"coconuts!"} Updated: As mentioned in the comments, Ruby 1.8.7 introduces a nicer syntax for this: h = Hash[arr.collect { |v| [v, f(v)] }] Did some quick, dirty benchmarks on some of the given answers. (These findings may not be exactly identical with yours based on Ruby version, weird caching, etc. but the general results will be similar.) arr is a collection of ActiveRecord objects. Benchmark.measure { 100000.times { Hash[arr.map{ |a| [a.id, a] }] } } Benchmark @real=0.860651, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.8500000000000005, @total=0.8500000000000005 Benchmark.measure { 100000.times { h = Hash[arr.collect { |v| [v.id, v] }] } } Benchmark @real=0.74612, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=0.740000000000002, @total=0.750000000000002 Benchmark.measure { 100000.times { hash = {} arr.each { |a| hash[a.id] = a } } } Benchmark @real=0.627355, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=0.6199999999999974, @total=0.6299999999999975 Benchmark.measure { 100000.times { arr.each_with_object({}) { |v, h| h[v.id] = v } } } Benchmark @real=1.650568, @cstime=0.0, @cutime=0.0, @stime=0.12999999999999998, @utime=1.51, @total=1.64 In conclusion Just because Ruby is expressive and dynamic, doesn’t mean you should always go for the prettiest solution. The basic each loop was the fastest in creating a hash. h = arr.each_with_object({}) { |v,h| h[v] = f(v) } This is what I would probably write: h = Hash[arr.zip(arr.map(&method(:f)))] Simple, clear, obvious, declarative. What more could you want? I’m doing it like described in this great article array = ["apples", "bananas", "coconuts", "watermelons"] hash = array.inject({}) { |h,fruit| h.merge(fruit => f(fruit)) } More info about inject method: Another one, slightly clearer IMHO – Hash[*array.reduce([]) { |memo, fruit| memo << fruit << f(fruit) }] Using length as f() – 2.1.5 :026 > array = ["apples", "bananas", "coconuts", "watermelons"] => ["apples", "bananas", "coconuts", "watermelons"] 2.1.5 :027 > Hash[*array.reduce([]) { |memo, fruit| memo << fruit << fruit.length }] => {"apples"=>6, "bananas"=>7, "coconuts"=>8, "watermelons"=>11} 2.1.5 :028 >
https://exceptionshub.com/in-ruby-how-do-i-make-a-hash-from-an-array.html
CC-MAIN-2021-21
refinedweb
475
61.93
Now: CreateRemoteThread As stated in the introduction, I will be expanding upon the CreateRemoteThread DLL injection method. If you need a review of this technique, have a look at this CodeProject article: Three Ways to Inject Your Code into Another Process. There are many other tutorials on CodeProject that deal with this method, so feel free to reference them as well. The next set of important information can be found in the Microsoft document: Best Practices for Creating DLLs.:. DllMain In almost every article or tutorial on DLL injection, the DllMain is not an empty stub.: DllMain CreateThread LoadLibrary You should never perform the following tasks from within DllMain: * Call LoadLibrary or LoadLibraryEx (either directly or indirectly). * ... * Call CreateProcess. Creating a process can load another DLL. * ... You should never perform the following tasks from within DllMain: * Call LoadLibrary or LoadLibraryEx (either directly or indirectly). * ... * Call CreateProcess. Creating a process can load another DLL. * ... LoadLibrary LoadLibraryEx CreateProcess Once again let me stress that I am not trying to advocate that the Best Practices article is the only way to do things. Let us just assume we had to follow that set of guidelines for this tutorial. If we eliminated the calls to LoadLibrary and CreateThread in the DllMain function, our DLL would be pretty useless with the CreateRemoteThread DLL injection method. This is because there is no way to execute any other functions in the DLL from the loader with this technique.. While this works, it is not compatible with the Best Practices guidelines and requires a call to CreateThread or LoadLibrary to initialize the DLL. kernel32 Considering that we are already writing data into the process, why not write a DLL loader into the space we allocated? Rather than start the remote thread on the address of LoadLibrary, let, any initialize code will be safely called in the export function we load and run, and we can clean up after ourselves in the end. This approach is a bit tricky and will take some extra code and work, but we are not programmers because we like things easy. Let us get started! Before I get to the actual code, I need to explain some of the techniques and concepts I employ. workspace[workspaceIndex++] = 0xCC; This notation is simply writing the expected hex characters to the virtual workspace. The variable workspace is the local memory allocated as the buffer. The variable workspaceIndex is the index to write to. The postfix use of the ++ operator will allow for the current byte to be written out into the buffer and then the index increment afterwards. This allows cleaner code, since the alternative would look like: workspace workspaceIndex ++ workspace[workspaceIndex] = 0xCC; workspaceIndex++; MessageBoxA MessageBox lpStartAddress With all of the background information finally done, it is time to get to the code. The injection function is quite large to the comments and the design of making things as straightforward as possible. Error code is duplicated in two parts, but writing it out twice is a lot more effective than trying to make another function to reduce the line count. The code is written to generate the basic amount of assembly to accomplish our task. It is not necessary to try to optimize or reduce the size of it since it will only be called once per DLL that needs injection. To begin, I will present the function documentation: Function: Inject Parameters: hProcess - The handle to the process to inject the DLL into. const char* dllname - The name of the DLL to inject into the process. char* funcname - The name of the function to call once the DLL has been injected. Description: This function will inject a DLL into a process and execute an exported function the DLL to "initialize" it. The function should be in the format shown below, no parameters and no return type. Do not forget to prefix extern "C" if you are in C++. __declspec(dllexport) void FunctionName(void) The function that is called in the injected DLL -MUST- return, the loader waits for the thread to terminate before removing the allocated space and returning control to the Loader. This method of DLL injection also adds error handling, so the end user knows if something went wrong. There are only two header files needed for this code to compile on VS6, VS7, VS8, and Dev-CPP. They are: #include <span class="code-keyword"><windows.h></span> #include <span class="code-keyword"><stdio.h> </span> What follows now are the main marked sections of the code with additional comments. There is too much code to actually paste it into the article. This section defines the variables used in this function. Since the code was made to compile in C or C++, they are at the top. The variables themselves should be self-explanatory by their names, the main ones of interest are the DWORD xxxAddr = 0; set. These variables are the placeholders for the data we write into the process at the top. Refer to the "Data and string writing" section for more details. DWORD xxxAddr = 0; This section starts off by obtaining the handle to the kernel32.dll on the user's computer and then loads a set of functions our code will call. After that, it will build the text strings that will be written into the process. Finally, it will allocate the local workspace memory and allocate memory in the target. This section will write out all of the data and strings we need injected into the process. Included is the place holder for the user32.dll, MessageBoxA function address, and the names of the DLLs, functions, and error messages used. Before each is written out, the address is stored in the placeholder as mentioned above at the end of the "Function variables" section. At the end of this section, a few INT 3s are written out and then the final address to begin execution is saved. Note that I have added a commented out section that can be used for debugging: INT 3 // For debugging - infinite loop, attach onto process and step over //workspace[workspaceIndex++] = 0xEB; //workspace[workspaceIndex++] = 0xFE; When program execution hits this, the program enters an infinite loop. At this point, you can attach your debugger, step over this part and trace though the following code to watch it step by step. Note that you might want to change the priority of the process beforehand to idle or below average so it does not chew up your CPU. This section will load the user32.dll and then the MessageBoxA function. I choose not to add any error checking since it should not fail. If it does fail, not quite sure why it would, the program will crash only if there is an error and the MessageBoxA function is invoked. The handle to the DLL and the function are both saved in the data area for later use. MessageBoxA This section is the meat of the function. The high level implementation of this code could be viewed as follows: // Load the injected DLL into this process HMODULE h = LoadLibrary("mydll.dll"); if(!h) { MessageBox(0, "Could not load the dll", "Error", MB_ICONERROR); ExitProcess(0); } // Get the address of the export function FARPROC p = GetProcAddress(h, "Initialize"); if(!p) { MessageBox(0, "Could not load the function", "Error", MB_ICONERROR); ExitProcess(0); } // So we do not need a function pointer interface __asm call p // Exit the thread so the loader continues ExitThread(0); It seems like a little C/C++ code, but it translates into a good deal of Assembly code due to the error handling. Do not be discouraged or intimidated by it though! Follow the assembly comments in the source and you should be fine. This section gives the user two choices on how the DLL should be exited from. The first choice is to simply exit the thread and let the DLL reside in memory. That way, the DLL itself can unload when it needs to later on, or the process will unload it on a clean exit. The second choice is to free the library and exit the thread at the same time. By doing this, the DLL will execute and then be removed from the process. To control which one is used, simply change the preprocessor define so the code that you want to execute is compiled. By default, the first choice is compiled. // Call ExitThread to leave the DLL loaded #if 1 ... #endif // Call FreeLibraryAndExitThread to unload DLL #if 0 ... #endif The last section deals with finally writing out the build code and then cleaning up after ourselves. Before we write to our allocated memory in the process, we first call VirtualProtect to make sure we have the right permissions. After the memory is written and the previous page access is restored, we have to call FlushInstructionCache to ensure the changes are made right away. At this point the code is written into the process so we can free the local workspace with a call to HeapFree. The only thing left to do is to execute our thread and then deallocate the memory that it once used. Now, the DLL has been injected into the process and we have cleaned up behind ourselves! VirtualProtect FlushInstructionCache HeapFree The fruits of our labor can be seen in the article's screenshot at the top (taken from OllyDbg). If all is done right, we now have a way to use the CreateRemoteThread DLL injection method that uses a DLL designed in accordance to the Best Practices article by Microsoft. At the end of the day, if you look at what we have done and ask yourself the question "was it worth it?", you may not have a definite answer. If the only goal is to make a DLL injector that "works", the general way of going about this is fine. However, if you were interested in a bit more robust solution, then this approach might be just it for you. Either way, thank you for reading this and I hope you have enjoyed it. Here is a simple WinMain that acts as a loader for a process to inject a DLL into. In this example, I load the Pinball game and inject a DLL into it. Note that everything is hardcoded just for this example. Ideally, you would place the DLL to be injected in the same folder as the process as well as the loader. That makes life a bit more easier. WinMain // Program entry point int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Structures for creating the process STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; BOOL result = FALSE; // Hardcoded just for a demo, you will need to use a game/program of // your own to test. It is not a good idea to use stuff in system32 // due to the DEP enabled on those apps. char* exeString = "\"C:\\Program Files\\Windows NT\\Pinball\\PINBALL.EXE\" -quick"; char* workingDir = "C:\\Program Files\\Windows NT\\Pinball"; // Holds where the DLL should be char dllPath[MAX_PATH + 1] = {0}; // Set the static path of where the Inject DLL is, hardcoded for a demo _snprintf(dllPath, MAX_PATH, "InjectDLL.dll"); // Need to set this for the structure si.cb = sizeof(STARTUPINFO); // Try to load our process result = CreateProcess(NULL, exeString, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, workingDir, &si, &pi); if(!result) { MessageBox(0, "Process could not be loaded!", "Error", MB_ICONERROR); return -1; } // Inject the DLL, the export function is named 'Initialize' Inject(pi.hProcess, dllPath, "Initialize"); // Resume process execution ResumeThread(pi.hThread); // Standard return return 0; } I also include a sample DLL to inject into a process to test it. I did not make a project for it however, it is up to you to make your own DLL to inject. Here is the source for it though in case you want to make one yourself. #include <span class="code-keyword"><windows.h></span> // Define the DLL's main function BOOL APIENTRY DllMain(HMODULE hModule, DWORD ulReason, LPVOID lpReserved) { // Get rid of compiler warnings since we do not use this parameter UNREFERENCED_PARAMETER(lpReserved); // If we are attaching to a process if(ulReason == DLL_PROCESS_ATTACH) { // Do not need the thread based attach/detach messages in this DLL DisableThreadLibraryCalls(hModule); } // Signal for Loading/Unloading return (TRUE); } extern "C" __declspec(dllexport) void Initialize() { MessageBox(0, "Locked and Loaded.", "DLL Injection Successful!", 0); } You do not have to name your function Initialize, but if you change it, make sure you update your loader to use the correct function name in the call to Inject. Also make sure to verify that the compiler does not optimize out your exported function with a program such as Dependency Walker. Also make sure you do not forget to use the extern "C" on a C++ export function so the function name is not mangled. Initialize Inject extern "C" width="546" border="0" alt="Image 2" data-src="/KB/threads/completeinject/completeinject2.png" class="lazyload" data-sizes="auto" data-> This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here HMODULE h = LoadLibrary(dllName); if (!h) { wchar_t msgBuf[MAX_PATH +1]; swprintf_s(msgBuf, L"Could not load the dll : %s", dllName); wprintf(L"Could not load the dll : %s\n", dllName); wprintf(L"LoadLibrary failed (%d).\n", GetLastError()); MessageBox(0, msgBuf, L"Error", MB_ICONERROR); ExitProcess(0); } FARPROC p = GetProcAddress(h, "Initialize"); if (!p) { MessageBox(0, L"Could not load the function: Initialize", L"Error", MB_ICONERROR); ExitProcess(0); } // So we do not need a function pointer interface __asm call p ExitThread(0); //exits here, does not indicate a crash VirtualProtectEx(hProc, codeCaveAddr, workspaceIndx, PAGE_EXECUTE_READWRITE, &oldProtect); WriteProcessMemory(hProc, codeCaveAddr, workspace, workspaceIndx, &bytesRet); VirtualProtectEx(hProc, codeCaveAddr, workspaceIndx, oldProtect, &oldProtect); FlushInstructionCache(hProc, codeCaveAddr, workspaceIndx); HeapFree(GetProcessHeap(), 0, workspace); hThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)((void*)codecaveExecAddr), 0, 0, NULL); WaitForSingleObject(hThread, INFINITE); VirtualFreeEx(hProc, codeCaveAddr, 0, MEM_RELEASE); WaitForInputIdle(pi.hProcess, INFINITE); inject(pi.hProcess, hooksPath, L"Initialize"); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); char* exeString = "\"C:\\Program Files\\Windows NT\\Pinball\\PINBALL.EXE\" -quick"; char* workingDir = "C:\\Program Files\\Windows NT\\Pinball"; char* exeString = "\"C:\\Windows\\notepad.exe\""; char* workingDir = "C:\\Windows"; hwnd = ::FindWindowA(TEXT("IEFrame"), TEXT("Google - Windows Internet Explorer")); DWORD dwProcessID; DWORD dwThreadID = GetWindowThreadProcessId(hwnd, &dwProcessID ); hProcess = ::OpenProcess( PROCESS_ALL_ACCESS,false, dwProcessID); DWORD pID = ::GetProcessId(hProcess); hThread = ::OpenThread(READ_CONTROL, false, dwThreadID); DWORD tid_read = ::GetThreadId(hProcess); DWORD pid_read = ::GetProcessId(hThread); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { char* winName = "Google - Mozilla Firefox"; char* winClass = "MozillaWindowClass"; // Holds where the DLL should be char dllPath[MAX_PATH + 1] = {0}; // Set the static path of where the Inject DLL is, hardcoded just for a demo _snprintf(dllPath, MAX_PATH, "C:\\Users\\anoppa\\Desktop\\aMoreCompleteDLLInjectionSolution\\InjectMaxSize.dll"); while(::FindWindowA(winClass, winName) == NULL) { Sleep(200); SwitchToThread(); } HWND hwnd = ::FindWindowA(winClass, winName); DWORD dwProcessID; GetWindowThreadProcessId(hwnd, &dwProcessID ); HANDLE hProcess = ::OpenProcess( PROCESS_ALL_ACCESS,false, dwProcessID); // Inject the DLL, the export function is named 'Initialize' Inject(hProcess, dllPath, "Initialize"); //Note: we inject AFTER the window has been created in order to allow the injected DLL to perform subclassing //The injected DLL uses subclassing to allow resizing the window outside bounds of the windows desktop SetWindowPos(hwnd, NULL, -50, -50, 1970, 1330, 20); //IgnoreZOrder =0x04, DoNotActivate = 0x10 // Standard return return 0; } General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/20084/A-More-Complete-DLL-Injection-Solution-Using-Creat?msg=4569042
CC-MAIN-2019-43
refinedweb
2,596
52.19
Marcos Duarte Laboratory of Biomechanics and Motor Control () Federal University of ABC, Brazil Change detection refers to procedures to identify abrupt changes in a phenomenon (Basseville and Nikiforov 1993, Gustafsson 2000). By abrupt change it is meant any difference in relation to previous known data faster than expected of some characteristic of the data such as amplitude, mean, variance, frequency, etc. The Cumulative sum (CUSUM) algorithm is a classical technique for monitoring change detection. One form of implementing the CUSUM algorithm involves the calculation of the cumulative sum of positive and negative changes ($g_t^+$ and $g_t^-$) in the data ($x$) and comparison to a $threshold$. When this threshold is exceeded a change is detected ($t_{talarm}$) and the cumulative sum restarts from zero. To avoid the detection of a change in absence of an actual change or a slow drift, this algorithm also depends on a parameter $drift$ for drift correction. This form of the CUSUM algorithm is given by:$$ \begin{array}{l l} \left\{ \begin{array}{l l} s[t] = x[t] - x[t-1] \\ g^+[t] = max\left(g^+[t-1] + s[t]-drift,\; 0\right) \\ g^-[t] = max\left(g^-[t-1] - s[t]-drift,\; 0\right) \end{array} \right. \\ \\ \; if \;\;\; g^+[t] > threshold \;\;\; or \;\;\; g^-[t] > threshold: \\ \\ \left\{ \begin{array}{l l} t_{talarm}=t \\ g^+[t] = 0 \\ g^-[t] = 0 \end{array} \right. \end{array} $$ There are different implementations of the CUSUM algorithm; for example, the term for the sum of the last elements ($s[t]$ above) can have a longer history (with filtering), it can be normalized by removing the data mean and then divided by the data variance), or this sum term can be squared for detecting both variance and parameter changes, etc. For the CUSUM algorithm to work properly, it depends on tuning the parameters $h$ and $v$ to what is meant by a change in the data. According to Gustafsson (2000), this tuning can be performed following these steps: The function detect_cusum.py from Python module detecta implements the CUSUM algorithm and a procedure to calculate the ending of the detected change. The function signature is: ta, tai, taf, amp = detect_cusum(x, threshold=1, drift=0, ending=False, show=True, ax=None) Let's see how to use detect_cusum.py; first let's import the necessary Python libraries and configure the environment: import numpy as np %matplotlib inline import matplotlib.pyplot as plt from detecta import detect_cusum Running the function examples: >>> x = np.random.randn(300)/5 >>> x[100:200] += np.arange(0, 4, 4/100) >>> ta, tai, taf, amp = detect_cusum(x, 2, .02, True, True) >>> x = np.random.randn(300) >>> x[100:200] += 6 >>> detect_cusum(x, 4, 1.5, True, True) >>> x = 2*np.sin(2*np.pi*np.arange(0, 3, .01)) >>> ta, tai, taf, amp = detect_cusum(x, 1, .05, True, True) x = np.random.randn(10000) x[400:600] += 6 print('Detection of onset (data size = %d):' %x.size) %timeit detect_cusum(x, 4, 1.5, True, False) Detection of onset (data size = 10000): 41 ms ± 639 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
https://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DetectCUSUM.ipynb
CC-MAIN-2021-25
refinedweb
520
54.42
I finally found some time this Saturday to try the new (to me) ArcGIS Pro Python package manager with Pro 1.4.1 to install Spyder and Jupyter. Long time needed upgrade to my toolbox! The Python Package Manager—ArcPy Get Started | ArcGIS Desktop Python and ArcGIS Pro 1.3 : Conda After adding Spyder using the Python package manager, I open the Pro Python command prompt (proenv.bat shortcut) and type "spyder". Spyder launches, but I get a bunch of errors in the internal console, and IPython windows are missing their prompt. I was hoping Conda would take care of needed dependencies, but apparently not: >>> WARNING:traitlets:kernel died: 6.010343790054321 Traceback (most recent call last): File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\traitlets\traitlets.py", line 528, in get value = obj._trait_values[self.name] KeyError: 'banner' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch handler(msg) (...) File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\widgets\ipythonconsole\shell.py", line 91, in long_banner from IPython.core.usage import quick_guide ImportError: cannot import name 'quick_guide' Spyder launches and I can see its help, but no IPython windows are working. Oh yeah, also Spyder doesn't seem to launch from its Windows start bar shortcut either. I did the same process with Jupyter, and "jupyter notebook" also opens a web page but no consoles available. Maybe I just need a tutorial that I haven't seen yet. BTW thank you so much David Wynne and the team, this package manager built into Pro (About ArcGIS Pro > Python) is pretty slick. As soon as I can figure out how to get it to work! I'm sure I just need some simple guidance. worked for me I just created a desktop shortcut... run as administrator .... C:\ArcPro\bin\Python\envs\arcgispro-py3\Scripts\spyder.exe just replace C:\ArcPro ... with your installation path that 'bin\... resides in The Pro install included spyder and its dependencies, so check your install
https://community.esri.com/thread/193784-trying-to-run-spyder-from-pro-conda-prompt
CC-MAIN-2019-13
refinedweb
367
51.44
NAME | DESCRIPTION | ERRORS | USAGE | SEE ALSO | NOTES Each naming system in an XFN federation has a naming convention. XFN defines a standard model of expressing compound name syntax that covers a large number of specific name syntaxes and is expressed in terms of syntax properties of the naming convention. The model uses the attributes in the following table to describe properties of the syntax. Unless otherwise qualified, these syntax attributes have attribute identifiers that use the FN_ID_STRING format. A context that supports the XFN standard syntax model has an attribute set containing the fn_syntax_type (with identifier format FN_ID_STRING)); Its value is the ASCII string "standard" if the context supports the XFN standard syntax model. Its value is an implementation-specific value if another syntax model is supported. Its value is an ASCII string, one of "left_to_right", "right_to_left", or "flat". This determines whether the order of components in a compound name string goes from left to right, right to left, or whether the namespace is flat (in other words, not hierarchical; em all names are atomic). Its value is the separator string for this name syntax. This attribute is required unless the fn_std_syntax_direction is "flat". If present, its value is the escape string for this name syntax. If this attribute is present, it indicates that names that differ only in case are considered identical. If this attribute is absent, it indicates that case is significant. If a value is present, it is ignored. If present, its value is the begin-quote string for this syntax. There can be multiple values for this attribute. If present, its value is the end-quote string for this syntax. There can be multiple values for this attribute. If present, its value is the attribute value assertion separator string for this syntax. If present, its value is the attribute type-value separator string for this syntax. If present, its value identifies the code sets of the string representation for this syntax. Its value consists of a structure containing an array of code sets supported by the context; the first member of the array is the preferred code set of the context. The values for the code sets are defined in the X/Open code set registry. If this attribute is not present, or if the value is empty, the default code set is ISO 646 (same encoding as ASCII). If present, identifies locale information, such as character set information, of the string representation for this syntax. The interpretation of its value is implementation-dependent. The XFN standard syntax attributes are interpreted according to the following rules: In a string without quotes or escapes, any instance of the separator string delimits two atomic names. A separator, quotation or escape string is escaped if preceded immediately (on the left) by the escape string. A non-escaped begin-quote which precedes a component must be matched by a non-escaped end-quote at the end of the component. Quotes embedded in non-quoted names are treated as simple characters and do not need to be matched. An unmatched quotation fails with the status code FN_E_ILLEGAL_NAME. If there are multiple values for begin-quote and end-quote, a specific begin-quote value must be matched with its corresponding end-quote value. When the separator appears between a (non-escaped) begin quote and the end quote, it is ignored. When the separator is escaped, it is ignored. An escaped begin-quote or end-quote string is not treated as a quotation mark. An escaped escape string is not treated as an escape string. A non-escaped escape string appearing within quotes is interpreted as an escape string. This can be used to embed an end-quote within a quoted string.. The name supplied to the operation was not a well-formed component according to the name syntax of the context. Code set mismatches that occur during the construction of the compound name's string form are resolved in an implementation-dependent way. When an implementation discovers that a compound name has components with incompatible code sets, it returns this error code. The syntax attributes supplied are invalid or insufficient to fully specify the syntax. The syntax specified is not supported. Most applications treat names as opaque data. Hence, the majority of clients of the XFN interface will not need to parse compound names from specific naming systems. Some applications, however, such as browsers, need such capabilities. These applications would use fn_ctx_get_syntax_attrs() to obtain the syntax-related attributes of a context and, if the context uses the XFN standard syntax model, it would examine these attributes to determine the name syntax of the context. FN_attribute_t(3XFN), FN_attrset_t(3XFN), FN_compound_name_t(3XFN), FN_identifier_t(3XFN), FN_string_t(3XFN) fn_ctx_get_syntax_attrs (3XFN), xfn
http://docs.oracle.com/cd/E19455-01/806-0628/6j9vie85v/index.html
CC-MAIN-2014-23
refinedweb
785
55.44
us to check many words against a single target word and maximum distance - not a bad improvement to start with! Of course, if that were the only benefit of Levenshtein automata, this would be a short article. There's much more to come, but first let's see what a Levenshtein automaton looks like, and how we can build one. Construction and evaluation The diagram on the right shows the NFA for a Levenshtein automaton for the word 'food', with maximum edit distance 2. As you can see, it's very regular, and the construction is fairly straightforward. The start state is in the lower left. States are named using a ne style notation, where n is the number of characters consumed so far, and e is the number of errors. Horizontal transitions represent unmodified characters, vertical transitions represent insertions, and the two types of diagonal transitions represent substitutions (the ones marked with a *) and deletions, respectively. Let's see how we can construct an NFA such as this given an input word and a maximum edit distance. I won't include the source for the NFA class here, since it's fairly standard; for gory details, see the Gist. Here's the relevant function in Python: def levenshtein_automata(term, k): nfa = NFA((0, 0)) for i, c in enumerate(term): for e in range(k + 1): # Correct character nfa.add_transition((i, e), c, (i + 1, e)) if e < k: # Deletion nfa.add_transition((i, e), NFA.ANY, (i, e + 1)) # Insertion nfa.add_transition((i, e), NFA.EPSILON, (i + 1, e + 1)) # Substitution nfa.add_transition((i, e), NFA.ANY, (i + 1, e + 1)) for e in range(k + 1): if e < k: nfa.add_transition((len(term), e), NFA.ANY, (len(term), e + 1)) nfa.add_final_state((len(term), e)) return nfa This should be easy to follow; we're basically constructing the transitions you see in the diagram in the most straightforward manner possible, as well as denoting the correct set of final states. State labels are tuples, rather than strings, with the tuples using the same notation we described above. Because this is an NFA, there can be multiple active states. Between them, these represent the possible interpretations of the string processed so far. For example, consider the active states after consuming the characters 'f' and 'x': This indicates there are several possible variations that are consistent with the first two characters 'f' and 'x': A single substitution, as in 'fxod', a single insertion, as in 'fxood', two insertions, as in 'fxfood', or a substitution and a deletion, as in 'fxd'. Also included are several redundant hypotheses, such as a deletion and an insertion, also resulting in 'fxod'. As more characters are processed, some of these possibilities will be eliminated, while other new ones will be introduced. If, after consuming all the characters in the word, an accepting (bolded) state is in the set of current states, there's a way to convert the input word into the target word with two or fewer changes, and we know we can accept the word as valid. Actually evaluating an NFA directly tends to be fairly computationally expensive, due to the presence of multiple active states, and epsilon transitions (that is, transitions that require no input symbol), so the standard practice is to first convert the NFA to a DFA using powerset construction. Using this algorithm, a DFA is constructed in which each state corresponds to a set of active states in the original NFA. We won't go into detail about powerset construction here, since it's tangential to the main topic. Here's an example of a DFA corresponding to the NFA for the input word 'food' with one allowable error: Note that we depicted a DFA for one error, as the DFA corresponding to our NFA above is a bit too complex to fit comfortably in a blog post! The DFA above will accept exactly the words that have an edit distance to the word 'food' of 1 or less. Try it out: pick any word, and trace its path through the DFA. If you end up in a bolded state, the word is valid. I won't include the source for powerset construction here; it's also in the gist for those who care. Briefly returning to the issue of runtime efficiency, you may be wondering how efficient Levenshtein DFA construction is. We can construct the NFA in O(kn) time, where k is the edit distance and n is the length of the target word. Conversion to a DFA has a worst case of O(2n) time - which leads to a pretty extreme worst-case of O(2kn) runtime! Not all is doom and gloom, though, for two reasons: First of all, Levenshtein automata won't come anywhere near the 2n worst-case for DFA construction*. Second, some very clever computer scientists have come up with algorithms to construct the DFA directly in O(n) time, [SCHULZ2002FAST] and even a method to skip the DFA construction entirely and use a table-based evaluation method! Indexing Now that we've established that it's possible to construct Levenshtein automata, and demonstrated how they work, let's take a look at how we can use them to search an index for fuzzy matches efficiently. The first insight, and the approach many papers [SCHULZ2002FAST] [MIHOV2004FAST] take is to observe that a dictionary - that is, the set of records you want to search - can itself be represented as a DFA. In fact, they're frequently stored as a Trie or a DAWG, both of which can be viewed as special cases of DFAs. Given that both the dictionary and the criteria (the Levenshtein automata) are represented as DFAs, it's then possible to efficiently intersect the two DFAs to find exactly the words in the dictionary that match our criteria, using a very simple procedure that looks something like this: def intersect(dfa1, dfa2): stack = [("", dfa1.start_state, dfa2.start_state)] while stack: s, state1, state2 = stack.pop() for edge in set(dfa1.edges(state1)).intersect(dfa2.edges(state2)): state1 = dfa1.next(state1, edge) state2 = dfa2.next(state2, edge) if state1 and state2: s = s + edge stack.append((s, state1, state2)) if dfa1.is_final(state1) and dfa2.is_final(state2): yield s That is, we traverse both DFAs in lockstep, only following edges that both DFAs have in common, and keeping track of the path we've followed so far. Any time both DFAs are in a final state, that word is in the output set, so we output it. This is all very well if your index is stored as a DFA (or a trie or DAWG), but many indexes aren't: if they're in-memory, they're probably in a sorted list, and if they're on disk, they're probably in a BTree or similar structure. Is there a way we can modify this scheme to work with these sort of indexes, and still provide a speedup on brute-force approaches? It turns out that there is. The critical insight here is that with our criteria expressed as a DFA, we can, given an input string that doesn't match, find the next string (lexicographically speaking) that does. Intuitively, this is fairly easy to do: we evaluate the input string against the DFA until we cannot proceed further - for example, because there's no valid transition for the next character. Then, we repeatedly follow the edge that has the lexicographically smallest label until we reach a final state. Two special cases apply here: First, on the first transition, we need to follow the lexicographically smallest label greater than character that had no valid transition in the preliminary step. Second, if we reach a state with no valid outwards edge, we should backtrack to the previous state, and try again. This is pretty much the 'wall following' maze solving algorithm, as applied to a DFA. For an example of this, take a look at the DFA for food(1), above, and consider the input word 'foogle'. We consume the first four characters fine, leaving us in state 3141. The only out edge from here is 'd', while the next character is 'l', so we backtrack one step to the previous state, 21303141. From here, our next character is 'g', and there's an out-edge for 'f', so we take that edge, leaving us in an accepting state (the same state as previously, in fact, but with a different path to it) with the output string 'fooh' - the lexicographically next string in the DFA after 'foogle'. Here's the Python code for it, as a method on the DFA class. As previously, I haven't included boilerplate for the DFA, which is all here. def next_valid_string(self, input): state = self.start_state stack = [] # Evaluate the DFA as far as possible for i, x in enumerate(input): stack.append((input[:i], state, x)) state = self.next_state(state, x) if not state: break else: stack.append((input[:i+1], state, None)) if self.is_final(state): # Input word is already valid return input # Perform a 'wall following' search for the lexicographically smallest # accepting state. while stack: path, state, x = stack.pop() x = self.find_next_edge(state, x) if x: path += x state = self.next_state(state, x) if self.is_final(state): return path stack.append((path, state, None)) return None In the first part of the function, we evaluate the DFA in the normal fashion, keeping a stack of visited states, along with the path so far and the edge we intend to attempt to follow out of them. Then, assuming we didn't find an exact match, we perform the backtracking search we described above, attempting to find the smallest set of transitions we can follow to come to an accepting state. For some caveats about the generality of this function, read on... Also needed is the utility function find_next_edge, which finds the lexicographically smallest outwards edge from a state that's greater than some given input: def find_next_edge(self, s, x): if x is None: x = u'\0' else: x = unichr(ord(x) + 1) state_transitions = self.transitions.get(s, {}) if x in state_transitions or s in self.defaults: return x labels = sorted(state_transitions.keys()) pos = bisect.bisect_left(labels, x) if pos < len(labels): return labels[pos] return None With some preprocessing, this could be made substantially more efficient - for example, by pregenerating a mapping from each character to the first outgoing edge greater than it, rather than using binary search to find it in many cases. I once again leave such optimizations as an exercise for the reader. Now that we have this procedure, we can finally describe how to search the index with it. The algorithm is surprisingly simple: - Obtain the first element from your index - or alternately, a string you know to be less than any valid string in your index - and call it the 'current' string. - Feed the current string into the 'DFA successor' algorithm we outlined above, obtaining the 'next' string. - If the next string is equal to the current string, you have found a match - output it, fetch the next element from the index as the current string, and repeat from step 2. - If the next string is not equal to the current string, search your index for the first string greater than or equal to the next string. Make this the new current string, and repeat from step 2. And once again, here's the implementation of this procedure in Python: def find_all_matches(word, k, lookup_func): """Uses lookup_func to find all words within levenshtein distance k of word. Args: word: The word to look up k: Maximum edit distance lookup_func: A single argument function that returns the first word in the database that is greater than or equal to the input argument. Yields: Every matching word within levenshtein distance k from the database. """ lev = levenshtein_automata(word, k).to_dfa() match = lev.next_valid_string(u'\0') while match: next = lookup_func(match) if not next: return if match == next: yield match next = next + u'\0' match = lev.next_valid_string(next) One way of looking at this algorithm is to think of both the Levenshtein DFA and the index as sorted lists, and the procedure above to be similar to App Engine's "zigzag merge join" strategy. We repeatedly look up a string on one side, and use that to jump to the appropriate place on the other side. If there's no matching entry, we use the result of the lookup to jump ahead on the first side, and so forth. The result is that we skip over large numbers of non-matching index entries, as well as large numbers of non-matching Levenshtein strings, saving us the effort of exhaustively enumerating either of them. Hopefully it's apparrent from the description that this procedure has the potential to avoid the need to evaluate either all of the index entries, or all of the candidate Levenshtein strings. As a side note, it's not true that for all DFAs it's possible to find a lexicographically minimal successor to any string. For example, consider the successor to the string 'a' in the DFA that recognizes the pattern 'a+b'. The answer is that there isn't one: it would have to consist of an infinite number of 'a' characters followed by a single 'b' character! It's possible to make a fairly simple modification to the procedure outlined above such that it returns a string that's guaranteed to be a prefix of the next string recognized by the DFA, which is sufficient for our purposes. Since Levenshtein DFAs are always finite, though, and thus always have a finite length successor (except for the last string, naturally), we leave such an extension as an exercise for the reader. There are potentially interesting applications one could put this approach to, such as indexed regular expression search, which would require this modification. Testing First, let's see this in action. We'll define a simple Matcher class, which provides an implementation of the lookup_func required by our find_all_matches function: class Matcher(object): def __init__(self, l): self.l = l self.probes = 0 def __call__(self, w): self.probes += 1 pos = bisect.bisect_left(self.l, w) if pos < len(self.l): return self.l[pos] else: return None Note that the only reason we implemented a callable class here is because we want to extract some metrics - specifically, the number of probes made - from the procedure; normally a regular or nested function would be perfectly sufficient. Now, we need a sample dataset. Let's load the web2 dictionary for that: >>> words = [x.strip().lower().decode('utf-8') for x in open('/usr/share/dict/web2')] >>> words.sort() >>> len(words) 234936 We could also use a couple of subsets for testing how things change with scale: >>> words10 = [x for x in words if random.random() <= 0.1] >>> words100 = [x for x in words if random.random() <= 0.01] And here it is in action: >>> m = Matcher(words) >>> list(automata.find_all_matches('nice', 1, m)) [u'anice', u'bice', u'dice', u'fice', u'ice', u'mice', u'nace', u'nice', u'niche', u'nick', u'nide', u'niece', u'nife', u'nile', u'nine', u'niue', u'pice', u'rice', u'sice', u'tice', u'unice', u'vice', u'wice'] >>> len(_) 23 >>> m.probes 142 Working perfectly! Finding the 23 fuzzy matches for 'nice' in the dictionary of nearly 235,000 words required 142 probes. Note that if we assume an alphabet of 26 characters, there are 4+26*4+26*5=238 strings within levenshtein distance 1 of 'nice', so we've made a reasonable saving over exhaustively testing all of them. With larger alphabets, longer strings, or larger edit distances, this saving should be more pronounced. It may be instructive to see how the number of probes varies as a function of word length and dictionary size, by testing it with a variety of inputs: In this table, 'max strings' is the total number of strings within edit distance one of the input string, and the values for small, med, and full dict represent the number of probes required to search the three dictionaries (consisting of 1%, 10% and 100% of the web2 dictionary). All the following rows, at least until 10 characters, required a similar number of probes as row 5. The sample input string used consisted of prefixes of the word 'abracadabra'. Several observations are immediately apparrent: - For very short strings and large dictionaries, the number of probes is not much lower - if at all - than the maximum number of valid strings, so there's little saving. - As the string gets longer, the number of probes required increases significantly slower than the number of potential results, so that at 10 characters, we need only probe 161 of 821 (about 20%) possible results. At commonly encountered word lengths (97% of words in the web2 dictionary are at least 5 characters long), the savings over naively checking every string variation are already significant. - Although the size of the sample dictionaries differs by an order of magnitude, the number of probes required increases only a little each time. This provides encouraging evidence that this will scale well for very large indexes. It's also instructive to see how this varies for different edit distance thresholds. Here's the same table, for a max edit distance of 2: This is also promising: with an edit distance of 2, although we're having to do a lot more probes, it's a much smaller percentage of the number of candidate strings. With a word length of 5 and an edit distance of 2, having to do 3377 probes is definitely far preferable to doing 69,258 (one for every matching string) or 234,936 (one for every word in the dictionary)! As a quick comparison, a straightforward BK-tree implementation with the same dictionary requires examining 5858 nodes for a string length of 5 and an edit distance of 1 (with the same sample string used above), while the same query with an edit distance of 2 required 58,928 nodes to be examined! Admittedly, many of these nodes are likely to be on the same disk page, if structured properly, but there's still a startling difference in the number of lookups. One final note: The second paper we referenced in this article, [MIHOV2004FAST] describes a very nifty construction: a universal Levenshtein automata. This is a DFA that determines, in linear time, if any pair of words are within a given fixed Levenshtein distance of each other. Adapting the above scheme to this system is, also, left as an exercise for the reader. The complete source code for this article can be found here. * Robust proofs of this hypothesis are welcome. [SCHULZ2002FAST] Fast string correction with Levenshtein automata [MIHOV2004FAST] Fast approximate search in large dictionariesPrevious Post Next Post
http://blog.notdot.net/2010/07/Damn-Cool-Algorithms-Levenshtein-Automata?repost!
CC-MAIN-2016-18
refinedweb
3,159
60.04
I have a question about the “Ordering Your Library” lesson under “Blocks and Sorting” in the Learn Ruby course. I’ve created the program, and I don’t get any return errors, but I don’t quite understand the “rev=false” and “if rev==true” bit. Here’s my code: def alphabetize(arr, rev=false) arr.sort! if rev == true arr.reverse! else return arr end end numbers = [3, 8, 2, 9, 4, 1] puts alphabetize(numbers) I understand that rev is, by default, false, and that the array “arr” will only be reversed if rev equals true. What I don’t understand is under what circumstances would rev equal true? What that would look like?
https://discuss.codecademy.com/t/ordering-your-library/368133
CC-MAIN-2018-43
refinedweb
116
73.27
Modern computers are incredibly fast, and getting faster all the time. However, computers also have some significant constraints: they only natively understand a limited set of commands, and must be told exactly what to do. A computer program (also commonly called an application) is a set of instructions that the computer can perform in order to perform some task. The process of creating a program is called programming. Programmers typically create programs by producing source code (commonly shortened to code), which is a list of commands typed into one or more text files. The collection of physical computer parts that make up a computer and execute programs is called the hardware. When a computer program is loaded into memory and the hardware sequentially executes each instruction, this is called running or executing the program. Machine Language A computer’s CPU is incapable of speaking C++. The limited set of instructions that a CPU can understand directly is called machine code (or machine language or an instruction set). Here is a sample machine language instruction: 10110000 01100001 10110000 01100001 Back when computers were first invented, programmers had to write programs directly in machine language, which was a very difficult and time consuming thing to do. How these instructions are organized is beyond the scope of this introduction, but it is interesting to note two things. First, each instruction is composed of a sequence of 1’s and 0’s. Each individual 0 or 1 is called a binary digit, or bit for short. The number of bits that make up a single command vary -- for example, some CPUs process instructions that are always 32 bits long, whereas some other CPUs (such as the x86 family, which you are likely using) have instructions that can be a variable length. Second, each set of binary digits is interpreted by the CPU into a command to do a very specific job, such as compare these two numbers, or put this number in that memory location. However, because different CPUs have different instruction sets, instructions that were written for one CPU type could not be used on a CPU that didn’t share the same instruction set. This meant programs generally weren’t portable (usable without major rework) to different types of system, and had to be written all over again. Assembly Language Because machine language is so hard for humans to read and understand, assembly language was invented. In an assembly language, each instruction is identified by a short abbreviation (rather than a set of bits), and names and other numbers can be used. Here is the same instruction as above in assembly language: mov al, 061h mov al, 061h This makes assembly much easier to read and write than machine language. However, the CPU can not understand assembly language directly. Instead, the assembly program must be translated into machine language before it can be executed by the computer. This is done by using a program called an assembler. Programs written in assembly languages tend to be very fast, and assembly is still used today when speed is critical. However, assembly still has some downsides. First, assembly languages still require a lot of instructions to do even simple tasks. While the individual instructions themselves are somewhat human readable, understanding what an entire program is doing can be challenging (it’s a bit like trying to understand a sentence by looking at each letter individually). Second, assembly language still isn’t very portable -- a program written in assembly for one CPU will likely not work on hardware that uses a different instruction set, and would have to be rewritten or extensively modified. High-level Languages To address the readability and portability concerns, new programming languages such as C, C++, Pascal (and later, languages such as Java, Javascript, and Perl) were developed. These languages are called high level languages, as they are designed to allow the programmer to write programs without having to be as concerned about what kind of computer the program will be run on. Here is the same instruction as above in C/C++: a = 97; a = 97; Much like assembly programs, programs written in high level languages must be translated into a format the computer can understand before they can be run. There are two primary ways this is done: compiling and interpreting. A compiler is a program that reads source code and produces a stand-alone executable program that can then be run. Once your code has been turned into an executable, you do not need the compiler to run the program. In the beginning, compilers were primitive and produced slow, unoptimized code. However, over the years, compilers have become very good at producing fast, optimized code, and in some cases can do a better job than humans can in assembly language! Here is a simplified representation of the compiling process: Since C++ programs are generally compiled, we’ll explore compilers in more detail shortly. An interpreter is a program that directly executes the instructions in the source code without requiring them to be compiled into an executable first. Interpreters tend to be more flexible than compilers, but are less efficient when running programs because the interpreting process needs to be done every time the program is run. This means the interpreter is needed every time the program is run. Here is a simplified representation of the interpretation process: Optional reading A good comparison of the advantages of compilers vs interpreters can be found here. Most languages can be compiled or interpreted, however, traditionally languages like C, C++, and Pascal are compiled, whereas “scripting” languages like Perl and Javascript tend to be interpreted. Some languages, like Java, use a mix of the two. High level languages have many desirable properties. First, high level languages are much easier to read and write because the commands are closer to natural language that we use every day. Second, high level languages require fewer instructions to perform the same task as lower level languages, making programs more concise and easier to understand. In C++ you can do something like a = b * 2 + 5; in one line. In assembly language, this would take 5 or 6 different instructions. a = b * 2 + 5; Third, programs can be compiled (or interpreted) for many different systems, and you don’t have to change the program to run on different CPUs (you just recompile for that CPU). As an example: There are two general exceptions to portability. The first is that many operating systems, such as Microsoft Windows, contain platform-specific capabilities that you can use in your code. These can make it much easier to write a program for a specific operating system, but at the expense of portability. In these tutorials, we will avoid any platform specific code. Some compilers also support compiler-specific extensions -- if you use these, your programs won’t be able to be compiled by other compilers that don’t support the same extensions without modification. We’ll talk more about these later, once you’ve installed a compiler. Rules, Best practices, and warnings As we proceed through these tutorials, we’ll highlight many important points under the following three categories: Rule Rules are instructions that you must do, as required by the language. Failure to abide by a rule will generally result in your program not working. Best practice Best practices are things that you should do, because that way of doing things is generally considered a standard or highly recommended. That is, either everybody does it that way (and if you do otherwise, you’ll be doing something people don’t expect), or it is superior to the alternatives. Warning Warnings are things that you should not do, because they will generally lead to unexpected results. Pest Control Services in Karachi testing this out //trying to figure out what is going on too #include <iostream> Using integerspace //or is it always "nameSpace" int main ( ) {... return 0;} //any suggestions? What is meant by this?: "Once your code has been turned into an executable, you do not need the compiler to run the program.". Once source code is translated into an executible, the executible would then need to be run, yes? otherwise what's the point of compiling? The point of compiling is to turn the code you've written into an executable. The executable can then run without having to use the compiler. In other words, you write code, use the compiler on your code, the compiler gives you an executable, and then you run the executable (a.k.a. program or application) to get the results. r u an idiot, jack? Looking forward to starting this tutorial! Me too, I really want to learn coding but sometimes I don't understand what's going on. This in-depth tutorial will make more sense... I hope. Good Luck! Same here! I've been messing around with every language under the sun for the past year.I'm really wanting to make this year the year I learn C++. So far I'm pleased with how consumable and direct this course is. Nice code, man would like anothger one of those spaghetti codes, good one keep it up Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/introduction-to-programming-languages/
CC-MAIN-2021-17
refinedweb
1,552
51.68
Scala is an exciting programming language that has been gaining popularity across the industry. Some say it may even replace Java. If you’re looking to learn Scala or you’re just curious about what it has to offer, you’re in the right place. Here’s what we will go over today: Take Educative’s hands-on Scala lessons for free, with no experience required. The Scala programming language was created in 2001 by Martin Odersky to combine (Java Virtual Machine). Scala is commonly used for strong static systems, data science, and machine learning. Scala is used in finance-related applications, content management systems, online learning platforms, distributed applications, and more. Companies like Google (for Android, Twitter, LinkedIn, Sony, Quora, and Foursquare use Scala regularly in their programs. Other companies such as Apple, The Guardian, Meetup, Verizon, SoundCloud, Airbnb, and Duolingo use Scala in certain teams or have released statements that they will be switching to Scala. It’s in high demand: Scala is increasingly popular in certain markets. Big companies are hiring more and more Scala programmers as the language becomes more popular. Learning the language will make you more in demand for the changing market. Scala syntax is precise: Compared to Java, Scala syntax is quite precise, making it more readable yet more concise. Scala pays well: Scala recently ranked 4th for the programming language with the highest salary. Scala developers in the US are some of the highest paid globally. The best of both worlds: Scala combines the benefits of OOP with Functional Programming, making it a stronger, more efficient language. Scala also combines the good qualities of statically typed and dynamic languages. Scala is growing: Both the online community and Scala frameworks are growing, so there is lots of innovative information out there. Even some Java developers are joining in and switching to Scala. According to StackOverflow, Scala ranked 17th for most wanted language. Scala has cool features: Scala brings with it many cool features to make your life easier including immutability, type interface, pattern matching, string interpolation, traits, an extensive collection of classes, and lazy computation. There are some similarities since Scala is a new generation JVM language. They are both object oriented and both produce the same bytecode. They also have similar libraries and compilers (called javac and scalac). The main difference is Scala’s ability to handle Functional Programming and multi-core architecture. Scala’s syntax is also more succinct, but learning Scala is generally a bit harder than Java since it combines both paradigms. Scala also supports Operator overloading and has a built-in lazy feature to defer computation while Java does not. Apache Spark is a general-purpose distributed processing engine with four different APIs that support languages Scala, Python, R, and Java. Spark also provides libraries for SQL, machine learning, and stream processing. Spark is written in Scala, so you will often see Scala and Spark together. Since you’re just starting out, this isn’t important yet, but know that you may see Spark-related content as you learn about Scala. Learn Scala in half the time, all for no cost. Educative’s hands-on text-based courses let you reskill in a fraction of the time. Your path to learning Scala largely depends on your familiarity with other programming languages, like Java, C++, or Haskell. It is possible to learn Scala from scratch, but it will be easier with a few minimal prerequisites, such as a basic understanding of Object Oriented Programming and programming terminology. First, get access to Scala To do this, you’ll need the Java 8 JDK. The Java Development Kit (JDK) is technology package that can be used for compiling Scala code into Java bytecode. The JDK including the JVM (Java Virtual Machine), where code is executed. Once you have the JDK, there are two popular options for a Scala environment. Either approach is fine. Get Scala through sbt: sbt is an open source, interactive tool for building Scala programs. It is the Scala build. tool. This is where you can test and compile your code, as well as integrate frameworks. Get Scala through an IDE: An Integrated Development Environment (IDE) packages all the tools to help us write and execute Scala code. A popular IDE for Scala is IntelliJ IDEA. By downloading a Scala plugin for IntelliJ, you can use it as a Scala development environment. There are other text editors you can use, such as Eclipse, NetBeans, Vim-scala, and VS Code. Scala and IntelliJ IDEA: Second, look into libraries and frameworks Libraries and frameworks are like collections of prewritten code to make your life easier as a Scala programmer. You can integrate these into your code to save time and effort. They also provide really neat features for making interactive and dynamic programs. There is a long list of Scala libraries and frameworks, but don’t let this overwhelm you. The frameworks and libraries you use largely depend on your unique needs, so you’ll likely figure this out as you go. Here are a few of the most popular to get you started: The syntax of a programming language is the set of rules for how you write code and make different components interact. It defines the different parts of your code, giving them meaning, functionality, and relationships to other parts of your program. Think of syntax like the grammar of a language. Let’s take a look at an example of some Scala code and then break down the syntax piece-by-piece. First, a very simple Scala program: the Hello World statement object Main extends App { println("Hello world!") } This program uses a method, which is a statement that performs a particular action. The string. In Scala, a string is an immutable object, meaning it cannot be modified. Now, look at a more complicated Scala program, which prints the complementary secondary color of an inputted primary color. var testVariable = "red" testVariable match { case "blue" => print("orange") case "yellow" => print("purple") case "red" => print("green") case _ => print("not a primary color") } Here, you can see the same red matches the case “red”, it prints green. Tip: Always save your Scala fils as .scala Now that you are familiar with how Scala looks, let’s break it down further and go over some of the basic definitions and syntax rules. Identifiers are used to identify class names, method named, variable names, and object names. There are six kinds of identifiers in Scala: GRG (class); a (variable name); main (method name); Main (object name); ob (object name); and args (variable name). Here are the rules you must follow for making identifiers. Keywords are reserved words used for naming actions. You cannot use these are variable or object names. Take a look at the list below: An object in Scala is an entity with a state and behavior that can be manipulated. These are similar to objects in other programing languages. Similarly, classes in Scala are like the blueprints or templates for our various objects. These define properties and behavior. Classes are defined with the keyword class. The code below defines a class of people and then defines an object — a person — to go within that category. class Person{ var name: String = "temp" var gender: String = "temp" var age: Int = 0 def walking = println(s"$name is walking") def talking = println(s"$name is talking") } // Creating an object of the Person class val firstPerson = new Person In Scala, you declare variables using keywords var (mutable variable) or val (immutable variable). Each kind of variable takes a string value. For example var Var1: String = “Scala”. Once you create your variables, you can perform operations on them using operators. Operators act upon your variables. There are several different categories of operators: Arithmetic, Relational, Logical, Bitwise, and Assignment. These are similar to operators in other programming languages. For example, you can add two variables using the + arithmetic operator. def sum(x: Double, y: Double): Double ={ x+y } Let’s break that down defis the keyword used for defining a function, and sumis the name of the function. sumis followed by ( ). This is where define the function parameters separated by commas. Parameters specify the type of input to be given to the function. (x: Double, y: Double)tells us that our function takes two parameters, xand y, that are of type Double. Functions are a group of statements that perform actions. You can reuse functions in your code and apply it to various variables or objects. For example, we could make a function that multiplies an integer by 2 (see code below). You create functions using the def keyword. Since functions perform actions, you need to define if it returns a value or not. A function definition can appear anywhere in a Scala file. Functions can have names with characters such as, +, ++, ~, &,-, --, , /, :, etc. Functions are similar to methods, and sometimes they are used interchangeably. A Scala method, however, is a part of a named class, whereas a function is an object itself that can defined to a variable. def mul2(m: Int): Int = m * 2 Output: mul2: (m: Int)Int In functional programming, functions are treated as first-class values, meaning that they can be passed as a parameter to another function. These are higher-order functions called nested functions. There are six kinds of data structures in Scala: Arrays, List, Sets, Tuple, Maps, Option. Arrays and List are the most common. Arrays: an array is a collection of similar elements. In Scala, arrays are immutable. List: lists are a versatile data structure compiled of items that have the same type. They are immutable in Scala. You must declare a list using List and defining the different items. A control structure analyses variables and makes decisions based on predetermined parameters. There are a few different types of control flow structures in Scala, which are similar to other programming languages. Scala brings a function approach to an imperative paradigm, so you have more control abstraction. if...Else: This classic programming decision-making tool makes a decision based on whether an expression returns true or false. For example, a program can test if a number is less than 5, and if it is, it will return “Less than 5” while: a while loop in Scala states that a body of code will continue to be executed as long as a condition is met. for: the for loop iterates over values in a collection, checking if there are elements we wish to iterate over. If those elements exist, it goes to the next value. If now, it exits the code. try: try is used to test particular parts of code for exceptions. If an exception is thrown, it is caught using caught so you do not get an error. match: this is used for pattern matching, where we take an object and match it to a list to finds it predefined match. We used this in our example when red was matched to green. Now that you have a basic sense of Scala syntax and vocabulary, it’s time to dive into actually practicing! Let’s go over some resources that will help you put this new Scala knowledge into practice. As the Scala community grows, so do the amazing resources available to you online. When questions come up or you get stuck, the answer is likely already waiting for you. Take a look at the free resources at your fingertips. Reddit: online community for questions and inspiration GitHub: leading open-source online community for questions/resources StackOverflow: open-source online forum for questions, resources, and data Glitter: Scala programmer chat room Scala’s Blog: articles about Scala produced by the creators of the language Scala Times: weekly newsletter for Scala programmers SoftwareMill Tech Scala Blog: articles to keep you up to date with Java and Scala If you want to learn Scala online, there’s no better time to start. You can visit our free course, Learn Scala from Scratch, to get started on your Scala journey. The highly interactive course offers a roadmap for all you need to know to master Scala quickly. It covers: Learning something new is already challenging enough. That’s why we’ve made our course completely free. Taking that first step comes at no extra cost to you. You’ll get lifetime access without any sneaky subscription fees. Happy learning! Join a community of 500,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.
https://www.educative.io/blog/scala-101-a-beginners-guide
CC-MAIN-2022-05
refinedweb
2,094
64.2
Survey period: 1 Apr 2019 to 8 Apr 2019 Assuming you're given no other information, in which direction would you point a budding new developer? View optional text answers (133 answers) Slacker007 wrote:also, the definition of engineer does not include "software". codewitch honey crisis wrote:An example is putting constants before vars in comparisons like if(0==i) ;// do stuff there instead of if(i==0) delete this; #include <stdio.h> int main() { printf("Hello world!\n"); } But hey, either them C or C++. Do not involve pointer to structure, that uses a reference type based on a macro. Just don't do that! Afzaal Ahmad Zeeshan wrote:The answer entirely depends on whether the purpose of learning is for the academic reasons; or for understanding how computer works, or whether you are looking for a job. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Surveys/2197/Which-programming-language-would-you-recommend-to?msg=5614988
CC-MAIN-2021-31
refinedweb
169
62.98
of the React: - No templates: Components are the building blocks. By keeping the markup and the corresponding UI logic together, you have the full power of JavaScript to express the UI. More on this here. - JSX syntax allows you to inline the declarative description of the UI in your JavaScript code. React translates JSX to plain JavaScript on the fly (suitable during development), or offline using the React CLI. - Virtual DOM. In React, rendering a component means creating a lightweight description of the component UI. React diffs this new description with the old one (if any), and generates a minimal set of changes to apply to the DOM. The Sample App Nothing like building an app to get familiar with a new language or framework. In this article, I share a React version of the Employee Directory app that I’ve used to explore other frameworks. “Thinking in React” encourages us to start with a mockup of the UI, and break it down into a component hierarchy. Based on this diagram, the component hierarchy for the Employee Directory app looks like this: - App - HomePage - Header - SearchBar - EmployeeList - EmployeeListItem - EmployeePage - Header - EmployeeDetails “App” is the application container that will transition pages in and out of the UI. Only one page is displayed at any given time. Source Code In this article, we will build the application going through several iterations, from a simple static prototype to the final product. The source code for the application, including the different iterations and a Cordova version, is available in this repository. Iteration 1: Static Version In this first version, we create and render the HomePage component with some hardcoded (static) sample data. Code Highlights: - Creating components is easy: You use React.createClass(), implement the render() function, and return the UI description. - The JSX returned by render() is not an actual DOM node: it’s a description of the UI that will be diffed with the current description to perform the minimum set of changes to the DOM. - JSX is optional: you can use the React APIs to create the UI description programmatically. - Composing components is easy: You can use a component created using React.createClass() as a tag in JSX. For example, HomePage is made of three other components: Header, SearchBar, and EmployeeList. Iteration 2: Data Flow In this second version, we define an array of employees in the HomePage component, and we make the data flow down the component hierarchy to EmployeeList and EmployeeListItem. In this version, the list of employees is hardcoded: we’ll work with dynamic data in iteration 4. Code Highlights: - In JSX, you can add attributes to your custom component tags to pass properties to the component instance. <EmployeeList employees={employees}/> - Properties passed by the parent are available in this.props in the child. For example EmployeeList can access the list of employees provided by HomePage in this.props.employees. - In a list component (like EmployeeList), it’s a common pattern to programmatically create an array of child components (like EmployeeListItem) and include that array in the JSX description of the component. render: function () { var items = this.props.employees.map(function (employee) { return ( <EmployeeListItem key={employee.id} employee={employee} /> ); }); return ( <ul> {items} </ul> ); } - The key attribute (like in EmployeeListItem above) is used to uniquely identify an instance of a component (useful in the diff process). Iteration 3: Inverse Data Flow In the previous version, the data flew down the component hierarchy from HomePage to EmployeeListItem. In this version, we make data (the search key to be specific) flow upstream, from the SearchBar to the HomePage where it is used to find the corresponding employees. Code Highlights: In this version, the inverse data flow is implemented by providing the child (SearchBar) with a handler to call back the parent (HomePage) when the search key value changes. <SearchBar searchHandler={this.searchHandler}/> Iteration 4: Async Data and State In this version, we implement employee search using an async service. In this sample app, we use a mock in-memory service (defined in data.js) that uses promises so you can easily replace the implementation with Ajax calls. We keep track of the search key and the list of employees in the HomePage state. Code Highlights: - The state (this.state) is private to the component and is changed using this.setState(). - The UI is automatically updated when the user types a new value in SearchBar. This is because when the state of a React component is changed, the component automatically re-renders itself (by executing its render() function). - getInitialState() executes once during the component lifecycle and and is used to set up the initial state of the component. Iteration 5: Routing In this version, we add an employee details page. Because the application now has more than one view, we add a simple view routing mechanism. Code Highlights: There are many options to implement routing. Some routing libraries are specific to React (check out react-router), but you can also use other existing routing libraries. Because the routing requirements of this sample app are very simple, I used a simple script (router.js) that I have been using in other sample apps. - componentDidMount() is called when a component is rendered. Iteration 6: Styling Time to make the app look good. In this version, we use the Ratchet CSS library to provide the app with a mobile skin. Code Highlights: - Notice the use of className instead of class Iteration 7: Maintaining State If you run iteration 6, you’ll notice that when you navigate back to HomePage from EmployeePage, HomePage has lost its state (search key and employee list). In this version, we fix this problem and make sure the state is preserved. Code Highlights: To keep track of the state, we introduce a new parent container (App) that maintains the state (searchKey and employee list) of the Home page and reloads it when the user navigates back to the Home Page. Running in Cordova The react-cordova folder in the repository provides a preconfigured Cordova project for the React version of the Employee Directory application. Pingback: 簡單玩 React | Duncan 's blog() Pingback: Animated Page Transitions with React.js | Christophe Coenraets() Pingback: Employee Directory Sample App with React and Node.js | Christophe Coenraets() Pingback: Building Salesforce Apps with React.js | Christophe Coenraets() Pingback: Belgian Beer Explorer with React, Bootstrap, Node.js and Postgres | Christophe Coenraets() Pingback: About React | 懒得折腾() Pingback: 久々にCordova (旧PhoneGap) 触ってみた | はなたんのブログ() Pingback: 学习笔记 Cordova+AmazeUI+React 做个通讯录 – 准备 | Macworks Collection() Pingback: ReactJS: Links And Resources (3) | Angel "Java" Lopez on Blog() Pingback: Mobile Web Weekly No.35 | ENUE() Pingback: 20 Resources and tutorials about ReactJS framework - JS-Republic's Blog() Pingback: Free Online Tutorials To Learn ReactJS - Stunning Mesh()
http://coenraets.org/blog/2014/12/sample-mobile-application-with-react-and-cordova/
CC-MAIN-2017-17
refinedweb
1,118
54.02
JavaMail Section Index | Page 4 How do I find out if an IMAP server supports a particular capability? If you have a folder open, you can do this: import com.sun.mail.imap.IMAPFolder; import com.sun.mail.imap.protocol.IMAPProtocol; IMAPProtocol p = ((IMAPFolder)folder).getProtocol(); ...more Where can I find a regular expression to validate an email address? One is available at. How do I get the size of a message that I am going to send? The getSize() method works fine with received message but returns -1 if I use it with a message that I am going to send! Get the InputStream for the message with getInputStream() and count the bytes. How do I configure JavaMail to work through my proxy server? Proxy servers redirect HTTP connections, not JavaMail connections. In order to connect from behind a firewall for POP3, IMAP, and SMTP access, you need to connect to a SOCKS server. Your sys admin...more What's new in JavaMail 1.3.1? JavaMail 1.3.1 includes over 20 bug fixes, as well as support for DIGEST-MD5 authentication in the SMTP provider (courtesy of Dean Gibson). What is the format of the Content-ID header? The Content-ID header, set with setContentID, needs to be formatted like <cid>. You need to make sure the < and > signs are present. Some mail readers work without them, many don't.more Is it possible to send a message that identifies if the mailreader is configurate to read HTML or text mail? The MIME content-type "multipart/alternative" is intended so you can send different versions of the same "message" all bundled together, e.g. an HTML version, a plain text version, maybe an audio ...more Can someone please specify the technique of message sorting within folder according to some criteria say Header Information? Since the Message class doesn't implement the Comparable interface, you'll need to create a custom Comparator. Then, you can call Arrays.sort(arrayOfMessages, comparator). How do I display POP3 message body properly in a browser? When i use message.writeTO() it displays without line breaks. How do I display POP3 message body properly in a browser? When i use message.writeTO() it displays without line breaks. Can I create a MimeMessage using one Session say session1 and send the mail using another Session session2? Sure. import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class MailExample { public static void main (String args[]) throws Exception { String host = ar...more Why do binary file attachment sizes increase by about 15-20% when sending a message? When included as an attachment, binary files are encoded to be 7-bit safe. This means that what used to be 8-bits per byte is now 7, hence the increase. much does James cost? James can be freely used and is released under the Apache Software License.. How can I contribute to the James project? Contribution information is available from. How can I configure sendmail to route messages through James for filtering/scanning? See the help document at.
https://www.jguru.com/faq/server-side-development/javamail?page=4
CC-MAIN-2020-50
refinedweb
513
68.77
OGR provides a fast way to create dot density maps. A dot density map represents statistical information about an area as mathematically distributed points. Areas with higher values have a higher concentration of points. This is one of my favorite types of maps because it is a great example of GIS - visualizing geographic data in a way that is instantly comprehensible. I'm using OGR in this example because it can read and write shapefiles. But unlike the Python Shapefile Library it can also perform basic geometry operations needed for this sample. Most GIS programs would display the population information on some type of memory layer instead of actually outputting a shapefile for the density layer as demonstrated here. But we're going to keep things simple for this example and just create a shapefile. Assuming you have Python installed, here are some basic gdal/ogr installation instructions. 1. Go to and download the gdal binary for your platform 2. Extract the directory to your hard drive 3. Add the "bin" directory within the gdal folder to your system shell path 4. Set the path to the "data" directory in the gdal folder to an environment variable called "GDAL_DATA" 5. Install the appropriate python module for your Python version and platform from here: If you want to follow along with the example below you can download the source shapefile: The end result of this demo is pictured above with both the input census block and output dot density shapefiles. The following code will read in the source shapefile, calculate the number of points needed to represent the population density evenly, and then create the point shapefile: from osgeo import ogr import random # Open shapefile, get OGR "layer", grab 1st feature source = ogr.Open("GIS_CensusTract_poly.shp") county = source.GetLayer("GIS_CensusTract_poly") feature = county.GetNextFeature() # Set up the output shapefile and layer driver = ogr.GetDriverByName('ESRI Shapefile') output = driver.CreateDataSource("PopDensity.shp") dots = output.CreateLayer("PopDensity", geom_type=ogr.wkbPoint) while feature is not None: field_index = feature.GetFieldIndex("POPULAT11") population = int(feature.GetField(field_index)) # 1 dot = 100 people density = population / 100 # Track dots created count = 0 while count < density: geometry = feature.GetGeometryRef() minx, maxx, miny, maxy = geometry.GetEnvelope() x = random.uniform(minx,maxx) y = random.uniform(miny,maxy) f = ogr.Feature(feature_def=dots.GetLayerDefn()) wkt = "POINT(%f %f)" % (x,y) point = ogr.CreateGeometryFromWkt(wkt) # Don't use the random point unless it's inside the polygon. # It should be close as it's in the bounding box if feature.GetGeometryRef().Contains(point): f.SetGeometryDirectly(point) dots.CreateFeature(f) count += 1 # Destroy C object. f.Destroy() feature = county.GetNextFeature() source.Destroy() output.Destroy() There is no error handling in this sample so if you run it multiple times you need delete the output dot density shapefile. Note that this type of rendering only works when you have one polygon representing each data value. For example you couldn't do this operation with a world country boundary shapefile because islands like Hawaii associated with a country would force an inaccurate representation. For that type of map you need to use a choropleth map. Also note that when you use OGR for shapefile editing you must specify a "layer" after opening a file. This extra step is necessary because OGR handles dozens of formats, some of which are layered vector formats such as DWG using the same API. Also because OGR is a wrapped C library you have to adjust to explicitly destroying objects and extreme camel casing on method calls usually not found in Python. OGR and the raster equivalent GDAL are two very powerful libraries which dominate the open source geospatial world. They are also included in several well-known commercial packages thanks to the commercial-friendly MIT license. Hi Joel, Hopefully you will gimme some tips and/or insights. I have hundreds of shapefiles, all of them contain only polygons. I need to extract the attributes at fixed distances, say every 1000 meters. It is a bit like rasterize: add a layer of points on top of the polygons layer and get the attributes at each point. Unless I am missing something, neither your nice library or the OGR one let you read the attributes at specific locations, I mean is there a way to know the attributes of this or that shapefile at this lat and lon? Thanks for your help/comments Damian Damian, You are on the right track. Check out my "Point in Polygon" post from Jan. 19th. You want to do a spatial intersection between your polygons and the fixed-width point locations. If you know the x,y location of your points this will be easy. If you need to calculate the location of each fixed-distant point the difficulty/accuracy will vary based on the projection of your data. Here is some pseudo-code. The comment box may screw up the spacing so beware. # Your collection of 1,000 meter # points pts = [[-89,33], [90, 32], [91,29]] # Your polygon shapefile r = shapefile.Reader("your_polygons") # Attributes captured attr = [] for p in pts: p[0] = x p[y] = y for s in r.sf.shapeRecords(): if point_in_poly(x, y, s.shape.points): attr.append(s.record) Let me know if that helps. P.S. - You can do the same thing with OGR using the "contains" method as described in this dot density map post. If you need to calculate the distance between two points in decimal degrees try the Haversine formula And as I predicted the indentation on my post above is screwed up so try to work around that.
http://geospatialpython.com/2010/12/dot-density-maps-with-python-and-ogr.html
CC-MAIN-2018-51
refinedweb
931
56.86
I Imported an XML file into a table.Then I tried to query the field that are not null. I have a field which seems to be blank or null but still returned in the query. I'm not sure if this is newline but upon searching the net it is what they called "Carriage return" the part of the imported XML looks like this: <Myfield> </Myfield> Where Myfield <> null Where Myfield <> "" SELECT * FROM Table1 where asc(Myfield) = '13' Perhaps what you're seeing is actually CRLF, a carriage return (ASCII 13) plus linefeed (ASCII 10), which is actually 2 characters. It should be easy to check ... SELECT * FROM Table1 WHERE Myfield = Chr(13) & Chr(10) Just in case the imported XML brought in any spaces or other non-printing characters, you could check for CRLF anywhere in the field. SELECT * FROM Table1 WHERE Myfield ALike '%' & Chr(13) & Chr(10) '%' ALike differs from Like in that it signals the db engine to expect ANSI wild cards, % and _, instead of Access' * and ?
https://codedump.io/share/SkCm8WrXoChc/1/how-to-query-a-field-with-ascii-13-or-quotcarriage-returnquot
CC-MAIN-2017-47
refinedweb
172
73.21
Celinio Fernandes wrote:Pretty interesting. I already tested these EJB 3 plugins for Struts 2. Thanks for this new one that I will check out soon. By the way, how come there are some Chinese characters in this example and in the sites you pointed at ? amine cherif wrote:Hi, Thank you lee for this article. However, as i am new struts developer, i have some general and specific questions: - is there another way to use EJB3 in struts 2 (without using plugin) ? - here is it necessary to define interceptors in order to use EJB3 ? - @EJB public void setDemoMethodInjectRemote( DemoMethodInjectRemote demoMethodInjectRemote) { this.demoMethodInjectRemote = demoMethodInjectRemote; } is it correct to make @EJB annotation before a method ? - @Interceptors(DemoInterceptor1.class) public class DemoAction extends ActionSupport { is this means that all DemoAction methods will be invoked by DemoInterceptor1 interceptor ? Thank you in advance for the responses
http://www.coderanch.com/t/496362/Struts/Intergration-Struts-EJB-struts-ejb
CC-MAIN-2015-40
refinedweb
142
50.33
A stage navigation allows to switch from one stage to another one. More... #include <PanoramicStage.h> A stage navigation allows to switch from one stage to another one. The destination stage. Can be null, in this case the experience ends. An optional color. This color is compared with the current focusing color of the stage's NavigationLookupTexture. When colors match, this stage navigation became active and the DestinationStage is used to move on the next stage. An optional UserWidget subclass to create and display an instance of. Where the widget should be placed, editable/available only if WidgetClass is not null. The widget scaling factor, editable/available only if WidgetClass is not null. An additional yaw rotation (in degrees) to apply to the mesh sphere. This can be useful to align two stages together. If YawRotationSetFlag is true, YawRotation overwrites UPanoramicStage::YawRotation. Flag to enable the YawRotation property (TOptional type can't be used in editor)
https://www.unamedia.com/ue4-stereo-panoramic-player/api/struct_f_panoramic_stage_navigation.html
CC-MAIN-2021-17
refinedweb
156
52.15
Comment Alternative to Oracle Database (Score 2) 184 184 Comment Re:Master key (Score 5, Interesting) 102 102 Comment Pleaded Guilty, Broken Link (Score 1) 312 312 The link to the article is broken (of course). If the first charge wasn't a crime then Amin had the option not to plead guilty to it. On the other hand, if he's satisfied with the plea deal his attorney presumably negotiated (presumably heavily based on the other charge), then maybe a guilty plea was his best option. Absent evidence to the contrary, one has to assume his attorney properly assessed whether that first charge could have been beaten in court and weighed that factor in advising his client. Comment Only One Immediate Question, Really (Score 1) 743 743 Comment And What Technology Would That Be? (Score 1, Funny) 109 109 Comment Among the Many Big Questions (Score 1) 72 72 2. Security? Liability? 3. Will the "financial tech incubators, accelerators, and startups" be held to the same requirements and same standards? If not, why not? 4. How will API evolution and versioning work? Who's responsible? 5. How will compliance with the standard(s) (and service levels) be enforced? 1. Apple's iOS compares quite well, but if you want to maximize stability be cautious about updates until there are some reports (some of the 7.x and 8.x releases were clunkers, though the current 8.3 seems quite good now), and turn off features you don't need, especially the privacy-invading ones. 2. Blackberry. They're still around, and they're rather solid -- provided the device is. (Some of their devices have been clunkers, others solid. Again, take a look at consensus reports.) 3. Nokia/Microsoft S40 devices. You can still find some S40 devices (unlocked and inexpensive), though they are not as feature rich and stretch the definition of "smartphone" downward. I've got an S40 device that, at least once updated to the latest S40 release, is rock solid -- and lasts a long, long time per battery charge. The S40 devices are not long for the world, though, so don't get too attached. 4. If you experiment with Android, I'd stick to the purest form of it: Google's Nexus devices. If Google cannot make Android work well on its own branded devices then nobody can. Comment IBM's Tape Capacities Are Largest Available (Score 1) 229 229 Comment And the Swiss Franc (Score 3, Insightful) 389 389 Comment Yes: Free Money from the IRS! (Score 1) 734 734 Let's suppose you have two children and your U.S. Adjusted Gross Income (AGI) is about $75,000 or less. (If you earn more the math *might* change.) When you file your U.S. tax return (filing status Single, or Head of Household if you qualify), as a resident of Belgium (a comparatively high income tax jurisdiction) you should NOT take the Foreign Earned Income Exclusion or Foreign Housing Exclusion (IRS Form 2555). Instead you should only take the Foreign Tax Credit (IRS Form 1116). You should also take the Additional Child Tax Credit (IRS Schedule 8812). Follow that particular path, preferably using your favorite tax preparation software (even the free ones like TaxAct or TaxSlayer), and you should see a REFUND at the bottom of your tax return. Yes, the IRS will send you $1000 per U.S. citizen child per year in free money. Really. (In tax years 2009 and 2010 there was another $400 in free money available as a special refundable tax credit, but maybe you missed that.) Take the money and save it for your kids, or spend it on your kids, or some of both. That's about $17,000 per child in free money over their childhoods. When they turn 18, THEY can decide whether they wish to terminate their U.S. citizenships or not. I'd advise them not (under present conditions at least), but under current law it's free to do so before age 18 1/2. Even if it's not free, they've started with $17,000 in free money plus interest. No brainer, here: get your kids' U.S. citizenships documented. U.S. citizenship literally pays. Comment YouTube Handily Beats CNN (Score 1) 105 105 Comment Better Drinks (Score 1) 448 448 Comment Re:Creating Precedence (Score 1) 325 325 Heathrow is restricted airspace. NOTHING should be in that area, it's the world's busiest airport. Though I absolutely agree nothing else should be in the controlled airspace around Heathrow (or any other controlled airspace) without the full knowledge, permission, and constant monitoring of air traffic controllers, Heathrow is not the world's busiest. Heathrow serves the largest number of international airline passengers annually. Atlanta's Hartsfield-Jackson International Airport is the world's busiest both in terms of passengers served and aircraft movements.
http://slashdot.org/~BBCWatcher/tags/slashdot
CC-MAIN-2015-32
refinedweb
815
72.05
VisualGST 0.7.0 By Gwenael Casaccio - Posted on January 8th, 2010 Tagged: GNU Smalltalk GTK IDE Hi, here is a new release of the new IDE of GNU Smalltalk. With a lot of news : * a new interface with tabs * better sender/implementor tools * code clean up * improved debugger * bundled with GST * many bug fixes :D * ... And as VisualGST is now bundled with GST, you can get it with : git clone git://git.sv.gnu.org/smalltalk.git autoreconf -vi ./configure make make install and launch it with : gst-browser I would like to thanks Paolo Bonzini and Nicolas Petton for their comments, support and help. Gwenael Cara Cepat Baca Berita Berkualitas! pencarian topik berita terpopuler fleble.com index berita terkini fleble.com english version popular english version index english Hello, This interface look great :). I have installed it, but when I launch, here is the output: $ gst-browser Object: PackageLoader class error: Invalid argument Cairo: package not found SystemExceptions.PackageNotAvailable(Exception)>>signal (ExcHandling.st:254) SystemExceptions.PackageNotAvailable(Exception)>>signal: (ExcHandling.st:264) SystemExceptions.PackageNotAvailable class(SystemExceptions.NotFound class)>>signalOn:what: (SysExcept.st:729) SystemExceptions.PackageNotAvailable class>>signal: (PkgLoader.st:57) optimized [] in PackageLoader class>>fileInPackages: (PkgLoader.st:1866) [] in Kernel.PackageDirectories(Kernel.PackageGroup)>>extractDependenciesFor:ifMissing: (PkgLoader.st:165) Kernel.PackageDirectories>>at:ifAbsent: (PkgLoader.st:236) [] in Kernel.PackageDirectories(Kernel.PackageGroup)>>extractDependenciesFor:ifMissing: (PkgLoader.st:165) Set(HashedCollection)>>do: (HashedColl.st:201) Kernel.PackageDirectories(Kernel.PackageGroup)>>extractDependenciesFor:ifMissing: (PkgLoader.st:173) PackageLoader class>>fileInPackages: (PkgLoader.st:1865) PackageLoader class>>fileInPackage: (PkgLoader.st:1855) Package(Kernel.PackageInfo)>>fileIn (PkgLoader.st:491) optimized [] in UndefinedObject>>executeStatements (/usr/local/share/smalltalk/scripts/Load.st:126) OrderedCollection(SequenceableCollection)>>do: (SeqCollect.st:812) [] in UndefinedObject>>executeStatements (/usr/local/share/smalltalk/scripts/Load.st:124) [] in BlockClosure>>ifCurtailed: (BlkClosure.st:287) BlockClosure>>ensure: (BlkClosure.st:269) BlockClosure>>ifCurtailed: (BlkClosure.st:273) UndefinedObject>>executeStatements (/usr/local/share/smalltalk/scripts/Load.st:114) Any idea? Redards Migth be of some help. I am on Kubuntu 10.04.1 LTS 32 bits. Is there un plan to give a package to debian/ubuntu distributions? (and thus, install the package with the apt tools). Regards Hello, I'm new in the Smalltalk World. Is there any tutorial regarding Visual GST? Thank you very much, Marc Hi when I try your commands above, to compile everything from source, I get the following error (I truncated the file paths with ...): genpr-scan.o: In function `main': .../smalltalk/libgst/genpr-scan.c:1: multiple definition of `main' genpr-parse.o:.../smalltalk/libgst/genpr-parse.c:1: first defined here collect2: ld returned 1 exit status ...while the content of genpr-parse.c is just the line: main() { return 0; } See requirements here. Installing flex and bison made it work. After installing several gtk development library packages like webkit, cairo and sqlite it compiled a quite complete gst-browser. Well done! The About box is showing a version of 0.6.0 - I had to fix GtkWebBrowser->createToolbar to make the Help system work. There was a semicolon missing in the cascade. Creating a namespace and populating it with classes doesn't work with this version using the menu. A menu option 'File/File in...' would be very nice and also an option 'File/Load Package...' ;) Hi, I'm new with smalltalk and I'm looking forward for an IDE with GTK. So VisualGST sounds nice and exactly for what I'm looking for. But when running make install all is going well except when just finishing the process. Folowing an abstract of what I've got : genbc.h:63:24: error: genbc-impl.h: Aucun fichier ou dossier de ce type make[2]: *** [genbc-decl.o] Erreur 1 make[2]: quittant le répertoire « /home/tim/smalltalk/libgst » make[1]: *** [match.stamp] Erreur 2 make[1]: quittant le répertoire « /home/tim/smalltalk/libgst » make: *** [install-recursive] Erreur 1 And indeed, I checked and can't found the file genbc-imp.h in the directory libgst. And when typing gst-browser : gst-browser: command not found. I went on the FAQ but cannot found anything about this file. Thanks a lot for responding to this comment and to give me the issue. Best regards. Cordialement. Tim. Responding to myself : I picked up the file here... and it worked ! Just wondering it is the good version. Anyway, I can run the gest-browser and test it. I will let you know about the good job it sounds to be ! Cordialement. Tim Hi, first of all thanks for your trying. This was a problem with Makefile.am (fixed with the new git version). Send your comment on the mailing list ;) Cheers, Gwenael Hi, Thanks for your answer. I don't know if I understood right by "fixed with the new version" but I removed all smalltalk and redownloaded and did all the process. And still got the message "genbc.h:63:24: error: genbc-impl.h: Aucun fichier ou dossier de ce type". I used this adress for downloading "git clone git://git.sv.gnu.org/smalltalk.git". Is that correct ? Thanks again for the support. Tim. Cordialement. should work now. Paolo Hi Paolo, Yes, it's ok to install now. But when I open gst-browser and go to the Help menu : 1) If i click on Help, the debugger opens and can't have any help 2) The version of gst-browser is 0.6.0 thought I expected 0.7.0 Any way, thanks again for the support. Best regards. Tim. That's great, Gwen! I really like this release, you made so many improvements :) Will this version be in gst 3.2? Cheers, Nico
http://smalltalk.gnu.org/blog/mrgwen/visualgst-0-7-0
CC-MAIN-2017-13
refinedweb
941
53.78
Steve Dickson, le Wed 15 Dec 2010 15:48:38 -0500, a écrit : > > Building it with ``make -k'': > > > > ../../master/src/auth_unix.c:187: error: ‘MAXHOSTNAMELEN’ undeclared (first use in this function) > I don't understand what this is complaining about. Obviously > MAXHOSTNAMELEN is define (see rpc/types.h) otherwise the non-hurd build > would fail. MAXHOSTNAMELEN is defined on some OSes, but not on others, as POSIX says it's an optional macro (it's not defined when there is no limitation). See > Also, I've realized adding: > #ifndef MAXHOSTNAMELEN > #define MAXHOSTNAMELEN 64 > #endif > to auth_unix.c eliminates this "error". That's a crude way, but yes it should work. > But again those ifdefs are not needed on "normal" builds so what > gives? They are not needed on OSes which have a hostname lenght limitation, but they are needed on OSes which don't. > > ../../master/src/bindresvport.c:189: error: ‘IPV6_PORTRANGE’ undeclared (first use in this function) > > ../../master/src/bindresvport.c:190: error: ‘IPV6_PORTRANGE_LOW’ undeclared (first use in this function) > This is true but these defines are in non-Linux code so I guess > the hurd builds defines both Linux and non-Linux parts of the code? It just means that these are not Linux-only. But that doesn't mean it's standard macros. And indeed, while some other IPV6_* macros are in posix, IPV6_PORTRANGE* are not, and thus aren't standard. > > ../...) > Again these are defined through sys/socket.h (actually in bits/socket.h). On which systems? In glibc it's only defined for Linux, not for other ports. > So again I'm a bit confused as to what is needed... Make that part of the code ifdefed-out (ending up in reduced functionality, yes). Samuel
https://lists.debian.org/debian-hurd/2010/12/msg00016.html
CC-MAIN-2018-17
refinedweb
288
67.76
I'm not guru in python. I don't get why I can't assign an array of values to a key for this dictionnary with this def. This is how I use the sdk definition. return_keys_list = [] return_keys_list.append('id') return_keys_list.append('transaction.amount') redirect.returnKeys(return_keys_list) ''' Property Return Keys ''' def returnKeys(self, return_keys): self.__dict__['returnKeys'] = return_keys ''' Serializing object @param: Dictionary Object @return: Serialized data ''' def serialize(self, obj): return (json.dumps(self.to_dictionary(obj))) ''' Convert object to a dictionary @param: POJO Object @return: Dictionary Object ''') I've reproduced this: import json class S: def serialize(self, obj): return (json.dumps(self.to_dictionary(obj)))) class A: def __init__(self): self.a = "1234" self.b = (1, 2, 3, 4) self.c = [1, 2, 3, 4] self.d = { 1: 2, 3: 4} print S().serialize(A()) Output: {"a": "1234", "b": [1, 2, 3, 4], "d": {"1": 2, "3": 4}} The problem is that when the code recurses into to_dictionary() with the items in the list, the code always expects that it is recursing with a object that contains a __dict__. But neither a string (nor an int) contain a __dict__. (Which I see you've stated similarly in the question.) I would file an issue on the github referring to this question. Other than patching their code, your only option is to create a class that has the items you want. It appears they do not support a string or int except as a value in a __dict__. You could use a dict as a list: class ReturnList: def __init__(self): self.list = { 1: "Item1", 2: "Item2" } redirect.returnKeys(ReturnList()) Addendum: Wait! Why did the tuple case work?? I think you could do: redirect.returnKeys((1,2,3,4)) Oh, I see why it works. It's a bug. They specifically handle list but not tuple, and it doesn't recurse for tuple types. Since the tuple contains directly json-able types, it just converts it to a json list. If your tuple contained a class or other more complex (non- json) objects, it would fail.
https://codedump.io/share/CzSOemrjF8Iv/1/assign-array-to-key-dictionary-in-python
CC-MAIN-2016-44
refinedweb
345
68.67
Help with screen sizes I am try to get all the "different" screen sizes for each iOS device but I either don't own the device or the simulator (using old Xcode template) won't run 64 bit devices so I cannot test for them. Can anyone help me fill in the blank sizes? I have a few. I used import ui print str(ui.get_screen_size()) iPhone4s_screen_size = (320, 480) iPhone5s_screen_size = (320, 568) iPhone6_screen_size = () iPhone6P_screen_size = (414, 736) iPhone6s_screen_size = () iPhone6Ps_screen_size = () iPad2_screen_size = (768, 1024) iPad_Air_screen_size = () iPad_Air_2_screen_size = () iPad_Pro_screen_size = () iPad Air 2: (1024.00, 768.00) iPad Air: (1024.00, 768.00) Adde screen resolution to Output is Pythonista version 2.0.1 (201000) on iOS 9.2.1 on an iPad5,4 with a screen size of 1024 x 768. Note you also need to know the size of the status bar, and tab bar depending on whether you want to run full screen, or panel, etc. There was a thread a little while,which documented a way to figure that out....) iPhone6, Pythonista2.0, iOS9.2, 375.00, 667.00 - Webmaster4o - iPad mini 2+3: (1024,768) - iPad mini 1st generation: dead right now, wait a few seconds for it to charge. - iPhone 5 which may or may not be the same as 5S: (320,568) - iPhone 4 (not s): dead, can't find a 30-pin charger right now. Great, thanks everyone. I'm sure this list may useful to some people. I am assuming these are in portrait. So far we got: = (1024, 768) iPad_Air_2_screen_size = (1024, 768) iPad_Pro_screen_size = (1024, 1366) Am I missing any other iOS devices? @JonB Oh the screen size changes based on the status bar? Dang. That may be a issue I am having. I always thought ui.get_screen_size() returned pixels. I noticed this is not true as the pixel count is much higher. The documentation says this function returns "points". So what are points and how are they determined? - AtomBombed @donnieh I am only guessing from what it sound like, but I would assume that if it is returning points, that it would return a tuple with four different (x,y) pixel coordinates of each of the four corners of the screen. Maybe I'm wrong, that's just my guess. @donnieh You might want to double-check the rotations. The iPad mini resolutions seem to be in portrait, but the iPad Air and Pro resolutions in landscape. Also, are these physical pixels or virtual "points"? For example, the iPhone 3GS and 4 have the same number of "points", but the iPhone 4 has four times the pixels, because one "point" is made up of four pixels (because retina). Has anyone ever hacked with MacTracker's url scheme like: import webbrowser webbrowser.open('mactracker://ABA79B4E-3781-4053-8D73-AC46D16CE643'). This (Mac or iOS) app will give you all of the speeds and feeds for every product that Apple has ever made. The only problem is that the url scheme is 10 years old and a bit long in the tooth. To open the stats page on a particular model, you need that model's UUID which I can find in the app but not elsewhere. Opening the url merely opens the MacTracker app to the right page but does not return any model back to the caller (Pythonista). It would be pretty awesome if the app would accept iPad5,4in the inbound url instead of a model uuid and would return a json dict of speeds and feeds for that particular model.. @AtomBombed ui.get_screen_size() returns a 2-tuple, (w, h) of the current device's screen size. Nothing related to pixel location etc. @dgelessus Good catch. I fixed them to all be in Portrait. Yeah these are points which are clusters of pixels. I do not know how the points are derived though. Apple determines this? Screen "point count" (not resolution) retuned from ui.get_screen_size() - (width, height) all in PORTRAIT = (768, 1024) iPad_Air_2_screen_size = (768, 1024) iPad_Pro_screen_size = (1024, 1366) - Webmaster4o So, it actually looks like iPad mini 1 is the same size as 2 and 3. This is confusing to me, though, because iPad mini 2 and three have retina screens while the first generation does not @Webmaster4o yes this is a good point, one that @dgelessus referred to above. The terms "Retina", "resolution" and marketing numbers like 2732 x 2048 (264 ppi) (for the iPad Pro) seem to have nothing to do with ui.get_screen_size(). These are all referring to the amount of pixels. While if we could somehow programmatically get the the amount of pixels in x and the amount of pixels in the y it would be useful, I do not know how to do this. Using ui.get_screen_size() returns "points". These points are clusters of pixels. Using the points is fine for determine screen size as far as I seen though. This article is helpful. get screen size always returns the same size regardless of orientation,etc. But the maz size of the view depends on whether you are fullscreen, sheet, or panel, and whether you are hiding the title bar. In the scene module you find scene.get_screen_scale() "Return the scale factor of the current device’s screen. For retina screens this will usually be 2.0 or 3.0, and 1.0 for non-retina screens." A small example. With a retina display you should see three lines. import ui, scene scale = scene.get_screen_scale() with ui.ImageContext(100, 100) as ctx: ui.set_color('white') ui.fill_rect(0, 0, 100, 100) ui.set_color('black') ui.fill_rect(0, 3, 100, 2) ui.set_color('black') ui.fill_rect(0, 7, 100, 1) if scale > 1: ui.set_color('black') ui.fill_rect(0, 10, 100, 1 / scale) img = ctx.get_image() img.show() scrSize=(1136,640) # iPhone 5 (dots)
https://forum.omz-software.com/topic/2632/help-with-screen-sizes/6
CC-MAIN-2022-40
refinedweb
961
84.17
Please support our Python advertiser: Programming Forums Thread Solved • • Posts: 39 Reputation: Solved Threads: 0 I have a small image with a black background and red lines in it and I need to count the red pixels. I know I need PIL, but I'm not sure which method to use. Then once I have the counts I need to equate them to a character, so if the red lines in the image form a circle and have x amount of red pixels, its = '0', and if the image forms a straight line and is found to have x amount of pixels it's = 'l'. Any suggestions? import Image #mypic.jpg is the circle im=image.open("mypic.jpg") im.getcolors(R) # if statement here Any suggestions? Could you test how many pixels are red? Because a circle will require many more pixels to draw then a line. I know when getting colours i used something like: I know when getting colours i used something like: python Syntax (Toggle Plain Text) - import Image - im = image.open("myPic.jpg") - for pixel in im.getdata(): - #check if it is red Make it idiot proof and someone will make a better idiot. Check out my Site | and join us on IRC | Python Specific IRC Check out my Site | and join us on IRC | Python Specific IRC Played around with it a little ... python Syntax (Toggle Plain Text) - # use PIL to count pixels in letters I and O - # image file needs to be a bitmap file to maintain - # red (255,0,0) and black (0,0,0) pixel colors correctly - - from PIL import Image - - # img_I.bmp --> 50x50 black bg + red I (times new roman, bold, 24) - img_I = Image.open("img_I.bmp").getdata() - - # img_O.bmp --> 50x50 black bg + red O (times new roman, bold, 24) - img_O = Image.open("img_O.bmp").getdata() - - # count red pixels of the I - # list(img_I) is a list of (r,g,b) color tuples for each pixel - # where (255,0,0) would be the red pixel - red_I = 0 - for red in list(img_I): - if red == (255,0,0): - red_I += 1 - - print red_I # 76 - - # count red pixels of the O - red_O = 0 - for red in list(img_O): - if red == (255,0,0): - red_O += 1 - - print red_O # 126 May 'the Google' be with you! Other Threads in the Python Forum - Previous Thread: python and xitami - Next Thread: Python-Tuple Help! • • • • Views: 657 | Replies: 2 | Currently Viewing: 1 (0 members and 1 guests) • • • •
http://www.daniweb.com/forums/thread160591.html
crawl-002
refinedweb
409
75.95
#include <glob.h>>: The following values may also be included in flags, however, they are non-standard extensions to IEEE Std 1003.2 ("POSIX.2"). If, during the search, a directory is encountered that cannot be opened or read and errfunc is non- NULL, glob() calls (*errfunc), Ns, (, Fa, path, ,, errno), however, the GLOB_ERR flag will(). If glob() terminates due to an error, it sets errno and returns one of the following non-zero constants, which are defined in the include file <glob.h>: The arguments pglob->gl_pathc and pglob->gl_pathv are still set as specified above. glob_t g; g.gl_offs = 2; glob("*.c", GLOB_DOOFFS, NULL, &g); glob("*.h", GLOB_DOOFFS | GLOB_APPEND, NULL, &g); g.gl_pathv[0] = "ls"; g.gl_pathv[1] = "-l"; execvp("ls", g.gl_pathv);() argument may fail and set errno for any of the errors specified for the library routines stat(2), closedir(3), opendir(3), readdir(3), malloc(3), and free(3). Please direct any comments about this manual page service to Ben Bullock. Privacy policy.
https://nxmnpg.lemoda.net/3/glob
CC-MAIN-2020-34
refinedweb
168
67.65
I am trying to do something similar to using a lambda query inside a WCF operation parameter. I know there is no way to achieve this as lambda expressions are run-time and they can not be used in this way, but I think there are some solutions for this. My first idea is to use some search criteria class so that I can populate this class and then use it on server-side to build a lambda expression. My thoughts on a simple implementation for this class is something like : public class PersonSearchCriteria { public string FirstName {get; set;} public string LastName {get; set;} public int IdCardNumber {get; set;} Expression<Func<TSource, bool>> predicate } This is some pseudo code. I want to be able to create an instance of this class and based on this properties values' filter my database in my databasecontext (which in this case is EntityFramework 4.0 with selft tracking entities). I found some articles: I found this by searching on wcf serialize expression
https://expressiontree-tutorial.net/knowledge-base/9087057/wcf-expression-t--parameter
CC-MAIN-2021-31
refinedweb
168
56.29
Note This documentation is intended for .NET Framework developers who want to use the managed UI Automation classes defined in the System.Windows.Automation namespace. For the latest information about UI Automation, see Windows Automation API: UI Automation. Because of the way Microsoft UI Automation uses Windows messages, conflicts can occur when a client application attempts to interact with its own UI on the UI thread. These conflicts can lead to very slow performance or even cause the application to stop responding. If your client application is intended to interact with all elements on the desktop, including its own UI, you should make all UI Automation calls on a separate thread. This includes locating elements (for example, by using TreeWalker or the FindAll method) and using control patterns. It is safe to make UI Automation calls within a UI Automation event handler, because the event handler is always called on a non-UI thread. However, when subscribing to events that may originate from your client application's UI, you must make the call to AddAutomationEventHandler, or a related method, on a non-UI thread. Remove event handlers on the same thread.
https://docs.microsoft.com/en-us/dotnet/framework/ui-automation/ui-automation-threading-issues
CC-MAIN-2017-34
refinedweb
191
52.6
Announcements Content count47 Joined Last visited Community Reputation932 Good About Sacaldur - RankMember Unity Unity Software Architecture - how to make reusable UI classes that inherit from MonoBehavior Sacaldur replied to lougv22's topic in General and Gameplay ProgrammingThe problem about this is: you might be able to use this for Image-Components of the new UI System ([tt]UnityEngine.UI.Image[/tt]), but you'd need to create a sprite on the fly, which is more expensive. Unity Trying to spawn boxes just outside the cameras viewing rect Sacaldur replied to BiiXteR's topic in General and Gameplay ProgrammingYeah, that worked, thanks :) No, that value is not the top edge of the camera, but it is its center. If it results in the desired behavior, the problem lies at another place. The camera in use might not be the main camera, resulting in [tt]Camera.main[/tt] returning the wrong camera. The spawned object might not be "centered" properly, meaning its position is not in its center. Without further knowledge about the GameObjects in the scene and the other code, I can't say with certainty what the reason for this actually is. Btw: you're better of not using [tt]Camera.main[/tt], since it probably makes a search for the proper camera by the Tag "MainCamera" every time you want to retrieve the camera. Depending on how often you use it, this could affect the performance of the game. Also, by not searching for the object you want to use, but by getting it assigned from outside, your code is getting rid of dependencies. (See "inversion of control".) Unity Trying to spawn boxes just outside the cameras viewing rect Sacaldur replied to BiiXteR's topic in General and Gameplay ProgrammingThe value stored in orthographic size is just the "vertical size". Since the camera is most certainly not showing a perfectly rectengular view of the game, the "horizontal size" is a different value. You can calculate that by [tt]horizontal size = vertical size / height * width[/tt]. Since the aspect ratio is already calculated with a [tt]aspect ratio = width / height[/tt], you can shorten the calculation to just [tt]horizontal size = vertical size * aspect ratio[/tt] Unity Trying to spawn boxes just outside the cameras viewing rect Sacaldur replied to BiiXteR's topic in General and Gameplay ProgrammingHe mentioned he is using an orthographic camera, so the depth shouldn't be a problem. Take a look at the (orthographic) size of the camera. This value is half of what the camera whill capture on the vertical axis. If you add/subtract it to/from the y-position of the camera, you'll get the upper/lower edge. To get the left/right edge, you'll have to multiply it with the cameras espect ratio, and add/subtract the result to/from the x value. The property "aspect" should be the one you can use for that, otherwise you can calculate it by deviding the viewport width by the viewport height. After you got the the corner, you'll need to add/subtract half the objects size you want to spawn in order for it to be just outside the cameras view. (All this assumes your camera is not rotated. If it's rotated in 90° steps, you'll just need to swap some angles or invert some values. If it is another angle, you'll need to do some more math, but the basic calculation should be the same.) Btw: The C# tag is visible in the topic overview, the Unity tag is not. You might want to change the order of the tags, since Unity is the most important information in this case. Unity Unity Software Architecture - how to make reusable UI classes that inherit from MonoBehavior Sacaldur replied to lougv22's topic in General and Gameplay ProgrammingWhile you're creating the UI, you know what you're using. In general, this should be Image (those are using Sprites). In some special cases, e. g. when the content is generated on runtime (e. g. once a second or more frequently), then the RawImage should be used, and only then. (If the Image is generated very seldomly, you could generate a Spriteout of it, but since its a somewhat costly operations, you can't do it to frequently, since this would have a huge impact on the performance.) Right now, you might still have some GUITextures, but since you're starting to use the new UI system, you should get rid of anything done in the old UI system as fast as possible. Once that is done, you don't need those tightly-GUITexture-coupled anymore. In the end, if there is no reason to do otherwise, you should _only_ have 1 Image component in use. And even if you'll need to use RawImage additionally for some special cases, you will know if it is a generated Texture (-> RawImage) or a predefined Sprite (-> Image). So you know the proper type and you won't need abstraction. Btw.: you have 8 tightly coupled scripts. What are those scripts doing? Unity Unity Software Architecture - how to make reusable UI classes that inherit from MonoBehavior Sacaldur replied to lougv22's topic in General and Gameplay ProgrammingAs others pointed out already, it would be better for you to just direclty use the methods and properties already available. Hiding an Image should be done by deactivating the game object. (This way, it also doesn't matter if it is an image, a text, or a composition of multiple UI elements.) Same goes for setting the image: just assign it directly, unless you want to apply some special logic that really needs to be encapsulated in another component. Besides that: You should store references to components you're using multiple times. Searching for them every time using "GetComponent" takes more time. If it is done once a frame, it's really worth the refactoring. Also, you should calculate your [tt]_imageIndex[/tt] with something like [tt]this._imageIndex = (this._imageIndex + 1) % this.sweepingFrames.Length;[/tt] Procedural Generation: Implementation Considerations Sacaldur reviewed franciscora's article in Graphics and GPU Programming - But sadly, this was the problem, since the accepted solution is:. - As I tried to state earlier: "someCondition" is probably neither a member, nor a parameter, nor a local variable, nor a property. It's very likely just a placeholder for the real condition, as well as "something" is probably a placeholder for an evaluation/calculation. Unity OOP: calling overridden method C# Sacaldur replied to BaukjeSpirit's topic in General and Gameplay Programming@kytoo: If all components are assigned to the same GameObject, you should instead use the RequireComponent-Attribute. public class SpartanKing : PlayerShape { } public class PlayerData : MonoBehaviour { } [RequireComponent(typeof(SpartanKing))] [RequireComponent(typeof(PlayerData))] public class Player : MonoBehaviour { void Start() { } }Unity will automatically assign the required components, as long as it's possible to assign them. Otherwise - an abstract class is required, such as "Collider" - you'll get an error message while trying to assign the component to a GameObject. - @Graelig: It really depends on the "somecondition", and we just don't know, what it actually is. If it's a simple null-check for "something" and "something" is just a private or protected member, just returning it would be the most simple thing. But if you're not just returning a member or if the condition is more than a simple null check, you can't omit the condition. And by the way: it's a (C#) property, not a method. The name GetSomething is misleading (it should be called GetSomething instead), but you still can't call/invoke it. ;) @JohnnyCode: What do you mean by "not reevaluating the condition"? As soon as the value of the property is requested, the "get"-code is executed, thus the "somecondition" is evaluated. (And we can assume it's not just a variable, but a shortening of the real code.) what is best way to check a code is more effiecient and runs faster than others Sacaldur replied to moeen k's topic in General and Gameplay ProgrammingBy "i work with it as unity script" you mean you're using C# as scripting language in Unity, right? "UnityScript" is what the guys behind Unity call "JavaScript", without actually being JavaScript.. - I prefer to handle the regular/good case in any kind of code first, and exceptions afterwards. So I'd do". Unity Setting up a basic engine: Rendering + Physics Sacaldur replied to vinnyvicious's topic in General and Gameplay Programming1. How many of the big engine developing companies (the guys behind Unity, Unreal Engine, Source Engine, Havoc, PhysX, and so on) went bankrupt, or suddenly changed their terms and conditions to the worse? For all I know, using their engines got even cheaper over time with much less restrictions.? Unity OOP: calling overridden method C# Sacaldur replied to BaukjeSpirit's topic in General and Gameplay ProgrammingYou should, whenever possible, assign the required GameObject instead of searching for it in the scene. This way, some one else could see the dependency in the inspector, since you have to assign the GameObject. (And it should be faster this way.) If it's not possible (the GameObjects are in difference Scenes), you should make the GameObjet's name editable through the inspector. Besides that: why are you using Keycodes? You can use the Axes of the input system as buttons as well, and you should do so. Furthermore you check for inputs in the "Player" and in the "SpartanKing" Component, with the Player forwarding the informations to the PlayerShape (and thus to the SpartanKing). Only one of them should handle the input. (So you would only need to replace the "Player-Input"-Component by a "AI-Input"-Component.)
https://www.gamedev.net/profile/209454-sacaldur/
CC-MAIN-2017-34
refinedweb
1,627
51.99
[SOLVED] QDir::exists(const QString & name) and dirs Dirs. Is this function will work with them or only with files. If no, how can I review exists of dir. If you want to know if a file exists use, @ #include <QFile> bool return; QFile filename("location/of/file"); return = filename.exists(); if(return == true){ // success } else{ // failed } @ I would assume QDir would be the same way...aka replace QFile with QDir. [quote author="tucnak" date="1325541840"]Dirs. Is this function will work with them or only with files. If no, how can I review exists of dir.[/quote] Instead of asking and waiting for someone to answer, you could just try it yourself. Should be manageable to create this code independently: @ qDebug() << "existing dir: " << QDir("/path/to/existing/dir-or-file").exists(); qDebug() << "missing dir: " << QDir("/path/to/non-existing/dir-or-file").exists(); @ For further research: QFileInfo, including exists(), isDir(), isFile(). You could have stumbled over this class by reading [[Doc:QDir]] API docs. It's mentioned in the "See also" section and even at the description of QDir::exists(). Is it really that hard to click on the link? Thanks, Volker. It was informative.
https://forum.qt.io/topic/12726/solved-qdir-exists-const-qstring-name-and-dirs
CC-MAIN-2017-39
refinedweb
196
69.99
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <mscuser.h> void MSC_MemoryRead ( void); The function MSC_MemoryRead sends data from the onboard RAM to the host. The number of bytes it sends is either the maximum packet size or the number of bytes requested by the host, whichever is lower. Modify this function to suit the application requirements. The function MSC_MemoryRead is part of the USB Function Driver layer of the RL-USB Software Stack. None. MSC_MemoryVerify, MSC_MemoryWrite #include <mscuser.h> void MSC_MemoryRead (void) { U32 n; … // Call your function to read from the flash card. Flash_MemoryRead(Offset, n, &Memory); // Send the data through the endpoint. USB_WriteEP(MSC_EP_IN, .
http://www.keil.com/support/man/docs/rlarm/rlarm_msc_memoryread.htm
CC-MAIN-2019-43
refinedweb
111
58.38
tends to be ordered by "time since last person edited it" or by event date in the case of upcoming public courses. As such, entries towards the top will cycle slowly towards the bottom of the section over time. If you're offering an upcoming class or have updated your entry, it's fine to bump it back to the top, but be considerate of others and use some common sense. Retreat For Experienced Programmers: a 4 day, low-pressure, fast-paced lab course, designed for well-seasoned programmers, where students learn and practice core concepts and Pythonic thinking: Mon - Thu, Mar 12 - 15, 2018, followed by 12 optional days of online discussion. Or really take your timePython for Programmers Online, where students learn and practice core concepts and Pythonic thinking: Apr 14 - Jun 13. Here's a sample lecture. PythonTrainer.Com is a 100% woman-owned business, registered in SAM. Enthought's experts train scientists, engineers, analysts, data scientists and geoscientists who would like to use Python more effectively. Enthought teaches public-open and private-onsite courses in cities around the US and EU. Current. Webucator regularly provides live online Python training. Upcoming Classes: Introduction to Python Training - Dec 4-7, 2017 10:00 AM - 5:00 PM ET, Jan 2-5, 2018 10:00 AM - 5:00 PM, Jan 29 - Feb 1, 2018 10:00 AM - 5:00 PM Advanced Python Training (uses Jupyter Notebook) - Jan 22-24, 2018 10:00 AM - 5:00 PM ET, Feb 19-21, 2018 10:00 AM - 5:00 PM ET Python Data Analysis with NumPy and pandas (uses Jupyter Notebook) - Dec 28-29, 2017 10:00 AM - 5:00 PM ET, Jan 25-26, 2018 10:00 AM - 5:00 PM ET, Feb 22-23, 2018 10:00 AM - 5:00 PM ET.. AcademyX provides instructor led Intro to Python and Advanced training in San Francisco, San Jose, and Sacramento. Upcoming Classes: Intro to Python - Nov 21-23, Dec 12-14, Jan 9-11, Feb 6-8, Mar 8-10 Advanced Python - Nov 17-18, Dec 15-16, Jan 19-20, Feb 14-15, Mar 15-16. Python Training I: Essentials is our 4-day intro course, and leads the student from the basics of writing and running Python scripts to more advanced features such as file operations, regular expressions, working with binary data, and using the extensive functionality of Python modules. Python Training II: Applied Python is a 4-day advanced course that puts extra emphasis placed on features unique to Python, such as tuples, array slices, and output formatting. Python for Scientists is a 5-day course that provides a ramp-up to using Python for scientific and mathematical computing. Excellent for scientists and engineers who need to manipulate large amounts of data, perform complex calculations, and visualize data in arrays and matrices. Upcoming Scheduled Classes Python Training I: Essentials September 15 - 18, 2014 Python for Scientists September 8 - 12, 2014 Python Training II: Applied Python September 22 - 25, 2014 Python Training I: Essentials October 13 - 16, 2014 Python for Scientists October 6 - 10, 2014 Private, onsite Python training for groups is available. PyCamp™ is the original, week-long, ultra-low cost Python Boot Camp developed by the Triangle Python Users Group for user groups. Let TriPython bring PyCamp to your Python user group. The current PyCamp line-up is: Wisconsin PyCamp 2014 offered June 13-17, 2014 at University of Wisconsin-Oshkosh in conjunction with Plone Symposium Midwest, PyOhio PyCamp 2014 offered July 21-25, 2014 at The Ohio State University in conjunction with the PyOhio 2014 regional Python conference... ITCourseware provides quality Python Training Courseware for instructor-led Python Training. This four day course leads the student from the basics of writing and running Python scripts to more advanced features such as file operations, regular expressions, working with binary data, and using the extensive functionality of Python modules. Continuum Analytics offers virtual, open, and custom on-site training courses for Python users of all levels and backgrounds. Driving core concept learning and in-depth understanding, Continuum’s courses are led by Python experts and give students the ability to get their hands dirty, learn best practices, and ask questions about specific problems. Practical Python Programming is a 3-day introductory course into Python with a focus on applying Python to problems in scripting, data analysis, and systems programming. Geared toward quants and data analysts, the 4-day Python for Finance course provides a strong foundation for being able to work and prototype quicker. Python for Science is a 4-day course for scientists and engineers, which gives students a strong foundation of best practices and the tools available for technical computing. Upcoming open and virtual classes can be found on the Continuum Training page. Custom on-site courses are available worldwide, all year round by contacting sales@continuum.io . DevelopIntelligence is the leader in delivering highly-customized learning solutions to software teams. We offer more than 150 developer training courses. Including instructor-led Python training, Apache training, and other open source training courses. CyberWeb Consulting features courses delivered by principal consultant WesleyChun, another well-known Python trainer. Wesley is author of Prentice Hall's bestselling, Core Python books, the video lecture course, Python Fundamentals (LiveLessons DVD), and co-author of Python Web Development with Django. In addition to being a software architect and Developer Advocate at Google, he runs CyberWeb, a consultancy specializing in Python training. Wesley has over 25 years of programming, teaching, and writing experience, including more than a decade of Python. While at Yahoo!, Wesley helped create Yahoo!Mail using Python. He has delivered courses to Google, Cisco, VMware, Avaya, Hitachi, UC Santa Barbara, UC Santa Cruz, and Foothill College as well as tutorials and sessions at O'Reilly's OSCON and PyCon. Wesley holds degrees in Computer Science, Mathematics, and Music from the University of California. He is available to travel globally. REGISTRATION OPEN for 2012 Aug 1-3 "Intro+Intermediate Python" course in San Francisco. Go to WEBSITE for more info & registration. Marakana offers Python Training as well as Pro Django Training in San Francisco as well as client sites all over the US and international. The next San Francisco Python offering is taking place the week of April 2 followed by Pro Django the week of April 17 For those that cannot make it to April classes or would like to see what the class is all about, check out Marakana Python Screencast Series! The series was taken from Marakana's 4 day Python Fundamentals course instructed by Simeon Franklin. We'll be releasing a new section every Friday so be sure to check back weekly! Accelebrate offers Python. Python Training with Mark Lassoff of LearnToProgram.tv. Mark offers training in several programming languages including Python. Known for a promoting a dynamic classroom environment, Mark has been lauded for his ability to break down complex technical information into digestable chunks. Mark provides classes onsite at your company location and provides a lab based environment that encourages retention. Mark can be reached at 203-292-0689. February 1 - February 5, 2010 at the Hacker Dojo in Mountain View, California Mark Lutz is probably the most experienced Python trainer in the world. He provides private on-site classes at your company or organization. Since 1997 he has taught roughly 250 Python classes to some 4,000 students in the US and abroad. Today, his classes cover both Python 2.X and 3.X, and present current best Python practice. Dave Kuhlman teaches introductory Python courses. Python Bootcamp is a five-day, all-inclusive training course taught by Dave Beazley at the Big Nerd Ranch - Atlanta, GA. Calvin Spealman offers private tutoring for general programming and problem specific assistance. Stratolab teaches Python for the purpose of writing video games. Clients are mostly middle and high school students. Stratolab is located in San Francisco. CameronLaird occasionally teaches classes on advanced Python topics--Python for process control, Python with LDAP, and so on.. CLEVERtrain is a four-day Python training course taught by Jonathan LaCour, who is based out of Atlanta, GA. Noah Gift is based out of San Francisco and provides Python training in the Bay Area. GreyCampus is a Dallas based training provider of Python. Canada Python Training Courses by Bernd Klein: Open enrolment training courses in Toronto. Computer Science Circles is a series of fully-online lessons designed for beginners to Python programming. This can include groups of students working with a teacher, or individual students/adults. There are programming exercises which are automatically graded, and the content runs from 'Hello World' to recursion and efficiency. An introductory workshop at Acadia University to encourage students, professors, and researchers alike to use the power of Python for their software endeavors. Savoir-faire Linux provides Python training courses in english and french in Montreal, Quebec City, Ottawa and on-site. Customized Python training are also available on any Python-related subject. Contact training@savoirfairelinux.com for more information. SIAST GIS Certificate Program has a Introduction to Python course for Geographic Information Systems. Bodenseo offers Python Courses in cooperation with Laila Zichmanis in the Toronto area.. QA, has two standard Python courses, one for Python 2 and one for Python 3 that run public schedules in their own premises in the UK. QA also provide customized on-site training which can include advanced topics. Russel Winder, joint author of Python for Rookies and other books, undertakes training and consultancy on Python programming in UK, Europe and world-wide. SCons (a Python-based build toolkit for C, C++, Fortran, D, Java, etc.) training and consultancy is also available. PythonCourses.com are teaching Python courses at various levels and for various audiences. For complete beginners to advanced users, from general python concepts to custom training designed to you specific needs or projects - we teach it. All our courses consist of lectures explaining the necessary theory without getting lost in IT jargon, followed by many hands-on exercises. We keep course groups small and put strong emphasis on personal interaction. Antonio Cuni offers training and courses about Python and PyPy in Italy and Europe. NobleProg Python Training provides public (UK,Poland and Worldwide), on-site and on-line instructor-led Python courses. Mark Lutz also teaches classes in Europe, Canada, Mexico, and other locations. Michael Foord is available for Python and IronPython training in the UK, Europe and the USA.. Python Academy specializes in Python training and offers a wide variety of public as well customized in-house courses. Training topics include a solid Introduction to Python and Advanced Python to dive deeper into the language. Furthermore, courses are available for Cython, SQLAlchemy, Twisted as well as Testing with pytest and tox. Scientists and engineers can learn about what offers Python in the course Python for Scientists and Engineers. Python can be very fast as the course High Performance Computation with Python proves. Introduction to Django provides all the basics to get started developing professional web applications. Even more insight into this powerful Python web framework offers Advanced Django. There are other courses about special topics such as extensions, optimizing, Windows programming, threads and processes, network programming, and design patterns in Python. The courses are held in German as well as in English at Python Academy's teaching center in Leipzig, Germany and other locations in Europe as well as in-house across Europe. Mark Summerfield, author of Programming in Python 3. Hundeshagen offers Python training (bootcamps) in Germany on request.. Ceintec offers Python programming training classes in Spain for beginners and advanced developers. Marcin Kaszynski teaches Python and Django in English or Polish. Kristian Rother teaches Python, Biopython , and software development practises in English, German, and Polish. Svilen Dobrev offers teaching and hands-on mentoring on python or software in general, accenting on efficiency and flexibility and team-work, in Bulgaria or anywhere. Languages: Bulgarian, English, Russian. Python training at JBI Training UK instructor-led classroom training (public and custom on-site courses) from Intro to Advanced level. Call +44 (0) 208 446 7555 and ask for Tom for more details and info on current offers. Anaska / Alter Way Group offers Python and Plone training courses and coaching in France and Europe. Python training by IT-Schulungen.com IT-Schulungen.com is a portal for IT-Trainings and offers training and consulting for Python from project experienced trainers as well as other open source technologies in Germany, Austria and Swiss. For further information please call 01805 120 222 (from within Germany) or visit our website. Python training for individuals or companies - For more than 10 years, we offer more than 1.000 different trainings - for more information, please visit our website. Bodenseo, - a training centre situated in the heart of Europe on the shores of Lake Constance, where Switzerland, Austria and Germany meet - offers public scheduled courses at Lake Constance and on-site seminars all over Europe (e.g. Switzerland, Austria, Germany, France, Luxemburg and the UK) in English, German and French. The Python courses of Bodenseo aim both at beginners and advanced learners of Python.. Australia. Peter Lovett of Plus Plus offers Introductory, Intermediate and Advanced level Python courses (as well as other languages). He is an accomplished trainer, running computer programming courses since 1985, in C, C++, Perl, Python, Java and XML around Australia, New Zealand and England, and is available for travel. As well as being highly accomplished technically, Peter is also highly effective at communicating, and gets glowing reviews for his courses.. Rahul Verma conducts Python training for Software testers, in India, focused on Implementation of general purpose test automation frameworks and day-to-day test automation requirements. You can find more details about his courses at Testing Perspective website and on Python specifically at Python Scripting for Software Testers. Rahul has presented at various conferences including Google Test Automation Conference, PyCon India, CONQUEST Germany and all Indian testing conferences. He is the author of How Would Pareto Learn Python and Design Patterns in Python which are available as free online books on his website. He is also a regular columnist with Testing Experience magazine on the subject of test automation. Vasudev Ram (Dancing Bison Enterprises), a. Anand Chitipothu offers Python training courses in Bangalore, India. He is the co-author of web.py, an open-source web framework in python. He is a software consultant and trainer with more than 10 years of programming experience, including 6+ years in Python. He conducts public python trainings in Bangalore on semi-regular basis. Biztech Academy offers Python training courses in Rajkot,Gujarat, India. they are also providing open source courses on Linux, Apache,Mysql,PHP,Perl,Python,Ajax. Noufal Ibrahim is a freelance Python developer/trainer based in Bangalore, India. He is the main organiser of the all India Python conference "PyCon India" and has been using Python since 2002. Apart from offering corporate trainings, he conducts public classes (on Python and other technologies). For schedules and other information, please refer to.. Ram Rachum! Malaysia R. Ramesh Kumar provides Python classes through his company Tech Dynamics. Primarily a developer, he has a passion for teaching and sharing his knowledge and experience. Ramesh also teaches other programming languages, and Linux/Unix courses. Pytech Resources conducts introductory and advanced Python courses in Malaysia and internationally. Its principal trainer, P.C. Boey, has more than 12 years programming experience with Python and his courses on Python programming have been very well-received. He is also available to do web development, training and consultancy work with Django. Low Kian Seong conducts beginner, intermediate and advanced Python courses in Malaysia under his own company Squid Consulting and Integration affectionately known as SqCI. He has been using Python since 2000 starting from Zope ending up in Django and have been deploying projects in MNCs all around the country. –. Singapore. New Zealand Peter Lovett of Plus Plus offers Introductory, Intermediate and Advanced level Python courses (as well as other languages). He is an accomplished trainer, running computer programming courses since 1985, in C, C++, Perl, Python, Java and XML. Although based in Sydney, Australia, he regularly travels to New Zealand, and is available for training. As well as being highly accomplished technically, Peter is also highly effective at communicating, and gets glowing reviews for his courses. Turkey Hakan Ozen is available for teaching Python. Internet - Python Online Training. Python for Programmers Online, where students learn and practice core concepts and Pythonic thinking: Apr 14 - Jun 13.. See Computer Science Circles above, which are online-only. The Open Technology Group, Inc offers all its courses for virtual LIVE instructor-led delivery via the Internet. Students may attend courses from anywhere, worldwide, provided they have a broadband Internet connection available. Python Bootcamps, Advanced Python, Introduction to Django, and GeoDjango training courses are scheduled to run Mar 7-11, Apr 18-22, May 23-27, and June 20-24). All courses are available for both in-person as well as Virtual LIVE instructor-led delivery, which may be attended from ANYWHERE. Contact us at info@otg-nc.com for global, customized, on-site delivery.. | hosted elsewhere, as shown in our 5-Minutes with Python series. You can learn more about the details with a talk series entitled Casting Your Knowledge, With Style But perhaps you're really busy on current projects and short on time. Consider doing an audio interview about an upcoming seminar you're offering and releasing it. Use it. || Public training courses presented by these trainers are listed on the PythonEvents page. Before creation of this page, CameronLaird maintained a private one on the same subject.
https://wiki.python.org/moin/PythonTraining?highlight=GeoDjango
CC-MAIN-2018-13
refinedweb
2,944
54.73
Home > Products > knitted garments Suppliers Home > Products > knitted garments Suppliers > Compare Suppliers Company List Product List < Back to list items Page:1/4 China (mainland) Our company locates in Nanxun town. It is a beautiful and modern place. It is near by Shanghai of the modernist and biggest city in China. The p... We-Nanchang Changzheng Knitted Garment Company located in Nanchang Jiangxi China is a professonal manufacturer of knitted garment. our main prod... Dongguan Yichuang Knitted Garment Co., Ltd is the manufacturer who located in the famous sweater town - Dalang town, Dongguan City. We are spec... Taiwan Our workshop covers an area of 20,000 square meters and we have nearly 300 staff members. We pay great attention to product quality to maximize ... Dern Lin Textile Co., Ltd. was founded in 1995. We supplied warp-knitted fabrics to shoes and caps manufacturers professionally in the beginning... Shuei Jin Elastic is a professional and seasoned elastic manufacturer operating in Taiwan. We have manufactured knitted/woven elastic applied to... Thailand We are a premier maker of hair accessories and socks, offering a wide variety of stylish designs. Established in 1980, we have been creating qua... India Mfrs & exporters of knitted, woven hosiery Garments, fabrics, handloommade ups, wiping cloth etc. Production capacity: 500,000pcs per month for ... We are Manufactures and exporters of Knitted readymade garments for the men's, lady?s and children's. We got the all facilities like production ... South Korea Woongchun Textech Co., Ltd. who was established in 1987 is specialized in manufacturing & exporter knitting fabric. "VELBOA"is our patent bra... Ningbo Tongsheng apparel co., ltd. /Auslin Garments (Ningbo) Co., Ltd. we are a big garment and garment accessories manufacturer and exporter ... Pakistan B4 Success acting as your Buying/Sourcing Agents will get you - our valued clients the best quality products at the most competitive prices. ... we are exporter and producer in zhejiang, and specilized in textile business with many years experience, mainly export to Europe, USA, Japan and... Ningbo Shenzhou Knitwear Group Ltd. was established in March 1990. Our company is located in Ningbo, China, a garment city with approximately 2.... Philippines We are an agent of fabrics from fabric millers in Taiwan and China. Particularly knitted and woven garment fabrics for the export market manufac... It is frank from china stage leather apparel. We have supplied best quality of sheep, goat, cow and mainly pig skin leather garments inclusive j... Established in early 2000, we are a highly diversified import and export company that has 2 overseas branches. With our staff having more than 1... We specialize in woven elastic tape, knitted jacquard elastic tape for garment accessories and shoe, woven PP tape for luggage, 70% of our produ... Singapore Sun League International Pte. Ltd. (sunleague-intl.com) is one of the major manufacturers of Industrial Laundry Equipments, Sandblasting machine... Richway Clothing Manufacturing Ltd., is a good quality Chinese apparel manufacturer of knitted and woven and true knit garments including kidswa... We are a buying sourcing agency of Indian knitted garment. We have more than 130 manufacturers and 43 exporters in our hand. We are arranging th... Jiangxi Jiawei Industrial and Commercial Ltd. was founded in 2000, which is specialized in manufacturing and exporting varied knitted underwear ... Turkey Arti Iki Textile Co., Ltd. is one of the foremost clothing manufacturers in Turkey specialized in knitted garments such as sweat shirts, T-shirt...... Aodexia International Corp., established in 2003, is a manufacturer of quality woven and knitted women's garments. We are able to supply such wo... Ningbo Shengluo Textile Industrial Co., Ltd. located in the southeastern coast of China where transportation is very developed and convenient. O... Show: 20 30 40 Showing 1 - 30 items Supplier Name Year Established Business Certification Huzhou Xianya Hand-knitted Garments Co., Ltd. Nanchang Changzheng Knitted Garment Company Dongguan Yichuang Knitted Garment Co., Ltd Horng Dah Knitted Garment Co., Ltd. Shanghai Huifeng Knitted Garment Co., Ltd. Nanchang Changzheng Knitted Garment Co., Ltd. QUANZHOU DAXING KNITTED GARMENT CO.,LTD Dern Lin Textile Co., Ltd. SHUEI JIN ELASTIC CO., LTD. Utmost Enterprise Co., Ltd. Dhanam Exports Plannet Apparels Woongchun Textech Co., Ltd. Ningbo Tongsheng Apparel Co., Ltd. B4 Success Huzhou Baiye Industry Co., Ltd. Ningbo Shenzhou Knitwear Co., Ltd. Bengtex Trading International China Stage Leather Apparel Co., Ltd. Ningbo Free Trade Zone Q's Innerwear Co., Ltd. Changzhou Fengya Weaving Co., Ltd. Sun League International Pte. Ltd. Richway Clothing Manufacturing Ltd. Tri Boss Knit Fashions Inc. Jiangxi Jiawei Industrial and Commercial Ltd. Arti Iki Textile Co., Ltd. Nignbo U&K Garment Co., Ltd. Ningbo Maoxin Knitting Garments Co., Ltd. Aodexia International Corp. Ningbo Shengluo Textile Industrial Co., Ltd. 1 2 3 4
https://www.ttnet.net/hot-search/suppliers-knitted-garments.html
CC-MAIN-2021-04
refinedweb
779
53.58
Fredrik Lundh: |Paul Prescod <paul@prescod.net> wrote: |> > one could say the same (or even more so) for the GUI, |> > but that hasn't exactly helped... |> |> GUI is a special case because there are no standards there. | |oh, there are standards. Motif is one, for example. |didn't help. people are still building new stuff on the |fundamental components (xlib, win32 gdi, etc), just |like people will keep on building new XML stuff on |top of simple XML tokenizers (xmllib, expat, sgmlop). Fredrik, generally I agree with what you have to say. But this is way out there. So what's your point? Don't need standard APIs like DOM or SAX since you can theoretically do all your parsing with the Python specific xmllib? Motif helped and continues to. Consider industry (we're not just talking Linux world money-is-no-object development here). No, it wasn't a magic bullet -- neither are DOM or SAX for that matter. But standard APIs help encourage cross-platform and cross-language support and promote developer skills portability. |> xmllib is not, as far as I know, a legal XML processor and it certainly |> does not support "modern" advances like tree processing, validation, |> defaulted attributes, XML namespaces or SAX. So it isn't legal and it |> isn't modern. | |"isn't legal"? | |now that's an interesting case of XML snobbery... Admitted, "isn't standards compliant" might have been a more specific choice of words. But I think we knew what he meant. -- Randall Hopper aa8vb@yahoo.com
https://mail.python.org/pipermail/xml-sig/1999-December/001708.html
CC-MAIN-2014-10
refinedweb
255
67.96
Each Answer to this Q is separated by one/two green lines. I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates – same string may appear once or more in the input and must appear the same number of times in the output. I see several “brute force” ways of doing that (using loops, god forbid), one of which I’m currently using. However, knowing Python there’s probably a cool one-liner do get the job done, right? >>> import random >>> x = [1, 2, 3, 4, 3, 4] >>> random.shuffle(x) >>> x [4, 4, 3, 1, 2, 3] >>> random.shuffle(x) >>> x [3, 4, 2, 1, 3, 4] Looks like this is the simplest way, if not the most truly random (this question more fully explains the limitations): Given a string item, here is a one-liner: ''.join([str(w) for w in random.sample(item, len(item))]) You’ll have to read the strings into an array and then use a shuffling algorithm. I recommend Fisher-Yates shuffle In python 3.8 you can use the walrus to help cram it into a couple of lines First you have to create a list from the string and store it into a variable. Then you can use random to shuffle it. Then just join the list back into a string. random.shuffle(x := list("abcdefghijklmnopqrstuvwxyz")) x = "".join(x) import random b = [] a = int(input(print("How many items you want to shuffle? "))) for i in range(0, a): n = input('Please enter a item: ') b.append(n) random.shuffle(b) print(b)
https://techstalking.com/programming/python/best-way-to-randomize-a-list-of-strings-in-python/
CC-MAIN-2022-40
refinedweb
279
73.58
User:PIOLPCIntern-1/docs From OLPC User:PIOLPCIntern-1::Blog::Marching::Description::Docs This is where I'm keeping any little things I type up while I'm playing around. They're more or less for my own reference, but since they're pretty simple I guess other clueless people could use them :) Oh, and I've been typing them in gedit so the formatting is kinda wonky on the wiki. I'll fix it eventually. Creating Activities with Python code asic Activity Creation for JHBuild w/ python. note: This is merely a compilation of the various descriptions of activity creation of the olpc wiki (wiki.laptop.org) combined with my experience trying to create a working activity. Sometimes the descriptions are completely copied, some paraphrased, and some are all me. 1. Create a directory called 'activityname-activity' in the sugar-jhbuild/source folder, where 'activityname' is the name of your activity (ie, read, browse). The '-activity' is a naming convention. 2. Within that directory, create another called 'activity' 3. In the activity directory, create a new file called 'activity.info'. This file should have the following in it (lines beginning with # are my comments): [Activity] - This top line should not change; it should always read [Activity]. name = NameOfActivity - This is the name of the activity as it will appear in Sugar. service_name = com.Activity.Example - "_Example_Activity_com". class = myactivity.ActivityClass - This is the location of the main class of the program, where 'myactivity' is the python file with the class in it, and - 'ActivityClass is the name of the class. icon = icon - The name of the icon image file. activity_version = 1 - The version of the activity. show_launcher = yes - Whether or not to show the icon in the sugar launcher. 4. Put the image (in .svg format) to be used as the activity's icon in the activity folder. 5. Go back to the activityname-activity directory. 6. In this directory, place the your python code files. Create the following blank files: 'setup.py', 'NEWS', and 'MANIFEST' 7. Open MANIFEST in a text editor, and type in a list of files to include in the package. (myactivity.py, for example.) 8. Edit the setup.py file to read: - !/usr/bin/env python from sugar.activity import bundlebuilder if __name__ == "__main__": bundlebuilder.start("MyActivityName") where 'MyActivityName' is the name of the activity. I don't really know where this name shows up; I created an activity with this name different from all the other ones I used and didn't see it anywhere. Maybe it's what it calls the .xo when you create an activity bundle? - You can just call bundlebuilder.start(), it will pick up the activity name from your activity/activity.info file (the above usage had no effect and will generate a obtuse warning message). --Garycmartin 9. In the terminal, run ./sugar-jhbuild shell 10. cd to the activityname-activity folder and run 'python ./setup.py dev' 11. The activity should now show up in Sugar. To create an activity bundle instead of installing it to sugar, run 'python ./setup.py dist' XO emulation Remote Display w/ qemu and vnc qemu runs disk images and is what we're using here to emulate an XO, kqemu is a module that speeds up qemu emulation, and vnc "provides remote control software which lets you see and interact with desktop applications across the network." 1. Install qemu, kqemu, and vncserver. The first step is to install kqemu: $ sudo aptitude install kqemu-common kqemu-source module-assistant $ sudo m-a prepare $ sudo m-a build kqemu $ sudo m-a install kqemu That all should have kqemu set up. You also may have to run: $ sudo modprobe kqemu Then install qemu: $ sudo aptitude install qemu Get and install vnc. I used ''. 2. Get an XO image. Get the XO image that can be found on this page: Extract that image, the final file should be a .img file. 3. Emulate the image on the network and...stuff. From here, instructions are from Emulate the image using qemu, with vnc options to qemu -kernel-kqemu -vnc 0 -k en-us [XO image name].img I actually used '-vnc 1' because 0 was taken up by something else, I think. Click and drag the img into the terminal to get it's path, or type it in manually. At this point, the server should be set up. On the computer you want to run the image on, install vncviewer software and use it to open the vncserver. $ vncviewer [ip]:1 where [ip] is the ip address of the computer that the vncserver is running on. Alternately, on a windows pc, download realvnc and connect to [ip]:1 with it.
http://wiki.laptop.org/go/User:PIOLPCIntern-1/docs
CC-MAIN-2014-52
refinedweb
785
58.28
A callback may do something, but it does not return anything, at least not something you may use. I suppose that you need 'global', ie an export of a name from within a function (the local namespace) to the surrounding global one: the namespace of the module in which the function is defined. I think the line 'global result' in your callback will help. As long as you stay within one class-instance, you can solve it in another way: let your callback produce a 'self.result', which is available in the whole class-instance. Things become interesting when you have two classes, A and B, and A needs the data that will be collected by a gui in B. I call it interesting because I am still struggling with it. A and B should agree on the layout of the data structure that goes from B to A, but how B collects these data, from which entries or canvases, is entirely his own business. In the same way: B knows nothing of the way A handles these data. First the solution, and then some explanations. class B: def __init__(self,callback=None): # build a gui ... bouton = Button( ....., command=callback) bouton.grid( ...) def retour(self): # collect the gui-data in retour_list[], # and probably close this b-gui. return retour_list class A: def __init__(self): b = B( ..., callback=self.sign) def sign(self,event=None): self.data_list = b.retour() process_data() def process_data(self) # do something usefull with self.data_list # exit (button) the application Within the usual Tkinter loop you start this with: a = A() A passes in an argument the name of a callback to B. This callback ('sign') is a method of A. The chain of activities is started by the button-push in B that activates the callback in A. The callback sends a message ('retour') to B to collect and return the data, and A processes them. How B collects the data is hidden in 'retour', and what A does with them is hidden in 'process_data'. Now I have two questions: am I making things much too complicated, or does some standard pattern solve this problem in a better way ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ========================================================================
https://mail.python.org/pipermail/python-list/2002-June/144058.html
CC-MAIN-2019-51
refinedweb
373
63.7
How We Upgraded A Very Large App from Rails 3 to Rails 4 For small projects, upgrading Rails versions is simple and can be done in a matter of hours or days. On the other hand, upgrading large projects can be quite a headache and take weeks or months. There are plenty of blog posts and upgrade guides out there explaining the mechanics of upgrading from one Rails version to another, but few of them provide the planning, organization, and implementation practices needed to upgrade a large project. Invoca upgraded our multi-million line Rails project from version 2 to 3 several years ago. At that time we created a branch from our mainline, upgraded to version 3, and started fixing bugs while the rest of the team continued to develop. The bug fixing took months, meanwhile the mainline diverged and created a continual stream of merge conflicts to resolve. For our recent upgrade from 3 to 4, we wanted a strategy that kept the upgraded code regularly merged back into the mainline and kept running our test suite for both Rails versions. Throughout this post we’ll share some of the techniques we used to streamline our Rails version upgrade. Keeping it all together Our main focus when upgrading from Rails 3 to Rails 4 was ensuring that we kept functionality equivalent between versions and minimized the differences. To do this we were able to simultaneously run both versions together in the same repo. Here are a few of the practices we used to combine Rails versions and keep our conflicts at bay. Working with different Rails versions simultaneously Bundler Gemfile Option - In order to deal with Rails 4 gem dependency issues, we created two separate gemfiles, “Gemfile” and “Gemfile_rails4”. We left “Gemfile” as-is and we upgraded the Rails version and the many dependencies in the “Gemfile_rails4”. - We then passed an option to Bundler telling it which environment to use. This allowed us to have both versions of Rails within the same repo. - To specify which gemfile to use, we would prepend the BUNDLE_GEMFILE option to `bundle exec` BUNDLE_GEMFILE=Gemfile_rails4 bundle exec <COMMAND> - The same option is used to install the upgraded gems from “Gemfile_rails4” BUNDLE_GEMFILE=Gemfile_rails4 bundle install - If the BUNDLE_GEMFILE option is not set, it will default to “Gemfile”, allowing the rest of the developers to continue working with Rails 3 without needing to change their workflow. - To make working with the Bundler option easier, we implemented a Bash script to automatically prepend the option for us. (Those that were consistently working on resolving bugs also implemented a simpler “r4” Bash alias on their local machine) - Instead of needing to use: BUNDLE_GEMFILE=Gemfile_rails4 bundle exec rails server - We instead used: script/r4 rails server script/r4 #!/bin/bash # To make your life easier, add this alias to your .bashrc or .bash_profile # alias r4="BUNDLE_GEMFILE=Gemfile_rails4 bundle exec" COMMAND="BUNDLE_GEMFILE=`pwd`/Gemfile_rails4 bundle exec $*" echo $COMMAND eval $COMMAND Static Helper Method - When implementing code changes for Rails 4, we first went through and implemented all the changes that were backwards compatible. Then, to simplify differences in code specifically for Rails 4, we implemented our own helper method. This method takes two lambdas and executes the first in Rails 4 and the second in Rails 3. class StaticHelpers def self.rails_4_or_3(rails_4_lambda, rails_3_lambda = -> {}) if Rails::VERSION::MAJOR == 4 rails_4_lambda.call elsif Rails::VERSION::MAJOR == 3 rails_3_lambda.call else raise “Rails Version #{Rails::VERSION::MAJOR} not supported.” end end end - This became our defacto method to check the Rails version and is utilized to execute different sets of code, define modules for specific Rails versions, return specific values, etc. StaticHelpers.rails_4_or_3( -> { # Snippet to execute for Rails 4 only }, -> { # Snippet for Rails 3 only } ) StaticHelpers.rails_4_or_3(-> { include Rails4OnlyModule }) Automated Testing - For every branch, we configured our automated unit testing suite to produce two test builds, one for each Rails version. This allowed us to quickly troubleshoot both versions in parallel to know whether a fix made for Rails 4 created any adverse effects to Rails 3. - The results of the first test run where disheartening, over 15,000 test failures! But, we took a methodical approach and started knocking them down. Many, of course, were common failures. In the beginning it was not uncommon for a single change to a test helper to fix hundreds if not thousands of tests. However, toward the end, the fixes started coming slower and resolved less failures. Make sure you dedicated adequate resources and time: we had a team of four working on the project for five months. Deploy It: One Piece at a Time - When our total test count reached a reasonable size, we began smoke testing by running our automated QA test suite against servers running in Rails 4 mode. - Along the way we were able to identify and resolve important feature errors that weren’t caught by our automated unit test suite. - Once we resolved our errors and failures, we began to switch server groups one at a time. We began with low priority servers such as background job processing servers, and gradually increased priority until we finally switched over our front end, customer-facing servers. - By switching dedicated groups singularly, we could focus our attention on the expected behavior of that group and could react quickly if unexpected errors occurred. It also gave us the option to quickly revert the system for that group back to its original working version to give us time to debug. Good luck! Hopefully these tips are as beneficial for you as they were for us throughout our upgrade. There are many other important facets to a Rails upgrade that must be determined by how the app works and will need their own specific implementations, and so for that reason every Rails upgrade is its own special snowflake. You'll most likely end up chasing a plethora of test cases and wonder to yourself how it was possible for your app to become a perpetual Rube Goldberg machine. Despite the trouble that comes with it, the rewarding feeling of upgrading your system will give you plenty of motivation to work through whatever problems that arise. Good luck! By Omeed Rabani
https://medium.com/invoca-engineering-blog/how-we-upgraded-a-very-large-app-from-rails-3-to-rails-4-59ed32fca020?source=collection_home---4------1---------------------
CC-MAIN-2019-09
refinedweb
1,035
58.21
Exporting maps¶ Exporting to PNG¶ You can save maps to PNG by clicking the Download button in the toolbar. This will download a static copy of the map. This feature suffers from some know issues: Exporting to HTML¶ You can export maps to HTML using the infrastructure provided by ipywidgets. For instance, let’s export a simple map to HTML: from ipywidgets.embed import embed_minimal_html import gmaps gmaps.configure(api_key="AI...") fig = gmaps.figure() embed_minimal_html('export.html', views=[fig]) This generates a file, export.html, with two (or more) <script> tags that contain the widget state. The scripts with tag <script type="application/vnd.jupyter.widget-view+json"> indicate where the widgets will be placed in the DOM. You can move these around and nest them in other DOM elements to change where the exported maps appear in the DOM. Open export.html with a webserver, e.g. by running, if you use Python 3: python -m http.server 8080 Or, if you use Python 2: python -m SimpleHTTPServer 8080 Navigate to and you should see the export! The module ipywidgets.embed contains other functions for exporting that will give you greater control over what is exported. See the documentation and the source code for more details.
http://jupyter-gmaps.readthedocs.io/en/latest/export.html
CC-MAIN-2017-51
refinedweb
207
68.06
perlmeditation CardinalNumber According to the [ FAQ], in order to adopt a seemingly abandoned module, I am required to (among other things) post a message somewhere public. ...and well, everything's public on PerlMonks these days so here goes: <br /><br /> I would like to adopt the [dist://FLTK|FLTK] (Fast Light Toolkit) module. <br /><br /> Seeing as the only upload to the namespace is nearly nine years old and doesn't even build against either of []'s current APIs, I'm sure a request on modules@perl.org would be met with little resistance but I would rather contact the current maintainer if possible. <br /><br /> Since March 2009, I have made three attempts to contact the original author, Matt Kennedy (CPAN ID: mkennedy). Mail sent to both the public @jumpline.com address and his @cpan.org redirect (which, judging from the error msg, goes to the @jumpline.com address) have bounced. So, if anyone knows this particular Matt Kennedy, I'd really appreciate some updated contact info. If not, I'll take it to the modules mailing list this Friday, August 7th, 2009.
http://www.perlmonks.org/?displaytype=xml;node_id=785628
CC-MAIN-2014-10
refinedweb
184
64.1
It seems lazy evaluation of expressions can cause a programmer to lose control. I am having trouble understanding why this would be acceptable or desired by a programmer. How can this paradigm be used to build predictable software that works as intended when we have no guarantee when and where an expression will be evaluated? Related: "Is Haskell worth learning?" Answer: Disorder is order (14 Votes) You write: "How can this paradigm be used to build predictable software that works as intended, when we have no guarantee when and where an expression will be evaluated?" When an expression is side-effect free the order in which the expressions are evaluated does not affect their value, so the behavior of the program is not affected by the order. So the behavior is perfectly predictable. Now, side effects are a different matter. If side effects could occur in any order, the behavior of the program would indeed be unpredictable. But this is not actually the case. Lazy languages like Haskell make it a point to be referentially transparent, i.e. making sure that the order in which expressions are evaluated will never affect their result. In Haskell this is achieved by forcing all operations with user-visible side effects to occur inside the IO monad. This makes sure that all side-effects occur exactly in the order you'd expect. Answer: Haskell and databases (14 Votes) If you are familiar with databases, a very frequent way to process data is: - Ask a question like select * from foobar - While there is more data, do: get next row of results and process it You do not control how the result is generated and in which way it is generated (indexes? Full table scans?), or when (should all the data be generated at once or incrementally when being asked for?). All you know is: if there is more data, you will get it when you ask for it. Lazy evaluation is pretty close to the same thing. Say you have an infinite list defined as ie. the Fibonacci sequence—if you need five numbers, you get five numbers calculated; if you need 1000 you get 1000. The trick is that the runtime knows what to provide where and when. It is very, very handy. (Java programmers can emulate this behavior with Iterators—other languages may have something similar) Related: "Why isn't lazy evaluation used everywhere?" Answer: Modularity (23 Votes) A lot of the answers are going into things like infinite lists and performance gains from unevaluated parts of the computation, but this is missing the larger motivation for laziness: modularity. The classic argument is laid out in the much-cited paper "Why Functional Programming Matters" (PDF link) by John Hughes. The key example in that paper (Section 5) is playing Tic-Tac-Toe using the alpha-beta search algorithm. The key point is (p. 9): [Lazy evaluation] makes it practical to modularize a program as a generator that constructs a large number of possible answers, and a selector that chooses the appropriate one. The Tic-Tac-Toe program can be written as a function that generates the whole game tree starting at a given position, and a separate function that consumes it. This does not intrinsically generate the whole game tree, only those sub-parts that the consumer actually needs. We can change the order and combination in which alternatives are produced by changing the consumer; no need to change the generator at all. In an eager language, you can't write it this way because you would probably spend too much time and memory generating the tree. So you end up either combining the generation and consumption into the same function, or implementing your own version of laziness Think you know what makes lazy evaluation useful? Disagree with the opinions expressed above? Bring your expertise to the question at Stack Exchange, a network of 80+ sites where you can trade expert knowledge on topics like web apps, cycling, patents, and (almost) everything in between. 27 Reader Comments It presupposes some knowledge of Haskell (it was part of a discussion within the Haskell community), so don't go there if you're still at "what is this Haskell and should I be looking at it?". edit: Based on my understanding of "lazy" from outside of Haskell. This function produces an infinite list of successive applications of a function. (A similar but differently implemented function is in the standard library.) A similar built-in function is fix function: Lazy recursion allows you to separate logic defining data and logic consuming it: simply define data to extend infinitely and consume as much of it as you want. So long as you consume finitely much of it, you're okay. (Technically, how you consume the data structure matters as well, but I won't get into that here.) A deeper and very cool application of this pattern is an "exhaustive" search over the Cantor space, or the space of infinite binary sequences (with a certain topology), which takes an arbitrary predicate on its domain and determines whether the predicate is ever true. While this task seems impossible, it is possible because the space is compact and thus each predicate must depend on a bounded number of digits of its input. The implementation is strikingly simple. Last edited by Solomonoff's Secret on Sat Nov 24, 2012 4:16 pm It presupposes some knowledge of Haskell (it was part of a discussion within the Haskell community), so don't go there if you're still at "what is this Haskell and should I be looking at it?". the most important point Lennart makes is that laziness is good for function reuse. (this is also mentioned in one of the SO answers.) a basic example : to find the minimum of a list of numbers, you can just compose the "sort" function and the "head" (first element of the list) function. in a strict language, this is a terrible way (algorithmically) to get the minimum element, as it does all the work of sorting the list (which is unnecessary.) but in a lazy language, it only does enough of work to find the minimum, e.g. O(n). in haskell you write this as min = head . sort lennart gives another, maybe better example, which i'll repeat : suppose i have a list of values, and i want to find out if at least one satisfies some boolean property (which is expensive to compute.) in java you'd write this as a for loop with an early termination (to prevent yourself from doing unnecessary work.) but in haskell, you just compute the predicate on every element (lazily!) using the "map" function map pred lst and then select one that you want using "or" any pred lst = or (map pred lst) read lennarts post for more details. by the way, this is a general strategy in lazy programming : write down an expression which computes everything you might ever want, and then write a selector which only pulls out the values you need. laziness ensures that the composition of the two does no extraneous work. a mind-blowing example of this is richard bird's sudoku solver ... sudoku.pdf the first time i read this, i think brain fluid dripped out of my ear. the functional modularity that laziness gives you is so powerful that in haskell you almost never need to resort to explicit recursion (like in scheme or ML.) most recursive "patterns" are encoded in basic higher order functions (map, foldl, mapAccumL, etc.) imagine being able to write all your java code without any loops, or ML without any recursion! Its the glass bead game of programming languages. Its something so pure and yet so remote from actual programming, that its hard to know where to begin critiquing it. The fundamental problem is that the functional model of computation bears little relation to the actual means of computation using CPU and memory. What this means is that programmers of the functional model of computation need PhD's in functional programming in order to explain why their programs aren't performing as expected. This bears repeating: its takes a PhD level brain to explain the performance of a lazy functional program. One misplaced comma or ill-defined type can turn your program from O(N) to O(N^2), and normal human beings will have a snowflake's chance in hell of explaining why. The most common data structure of our time - the most powerful and the most used - the hash-table - doesn't fit in the functional programming paradigm. It just cant be represented in functional programming - not without a massive loss of efficiency to the point of being unusable. What this tells us is that there is a mismatch between the functional programming paradigm, and the actual computational substrate we all use. I like functional programming at a high level - its great to use pure functions when coding, and I hope languages like Java and C# and C and C++ come to support pure functions more and more, but using an absolutely pure functional programming language is like trying to run with your shoelaces tied together - in this case, purity is like virginity - great until you try to use it. Hashtables most definitely exist in Haskell, at least. I have used the hash table provided by this package in many projects. ... trict.html At least in a strongly-typed functional language like Haskell, unintended grouping/ordering of function arguments (though not done with a comma) is almost always caught at compile time. And although lazy evaluation can cause unexpected space complexity (sometimes O(N) to O(N^2) as you say), the time complexity of algorithms has in my experience always been easier to eyeball in Haskell than in strict, imperative languages. I agree that there's a lot of work to be done in making the costs of lazy functional programming decisions very visible upfront. But diagnosing the unexpected memory usage of a lazy functional program is a skill no more difficult to learn than debugging a program with multi-threaded communication. Even a computer scientist with a PhD would need practice to diagnose and solve these problems quickly; but with enough practice, anyone can learn to debug these problems skillfully. That said, deferral can be great. My favourite example is a turn-based strategy game; in many such games all processing is done when the player hits "next turn", however human players aren't usually all that demanding on the game during their turns, leaving comparatively long periods of inactivity between their actions. So a great way to shorten the time a new turn takes to execute is to defer most of the work and evaluate it in the background later, or immediately if the data is required for something. This way you can use up all the wasted time between turns and shave a significant amount of wasted processing from new turn execution; though of course it adds a lot of complexity so you need to have a good idea of what you're doing when you begin, as bolting it on later isn't easy. The real question is whether a language with lazy expressions could achieve the same (or even a greater) benefit without introducing performance spikes when an expression has a lot of (or several complex) dependents? Personally I'm not convinced, though this is a good example of when the ability to choose what is or is not deferred can be beneficial; as you can potentially just leave everything for deferral, then tweak statements after profiling, but this requires a good profiler that is able to show which deferred statements are executing and when. First, hash tables are not the "most common data structure", arrays are, by an order of magnitude, especially since you build hash tables from arrays. But what you should be measuring is the most common abstract data type, not the implementation of that type. And that type would be maps (or associative arrays or whatever) and those can be expressed just fine using red-black trees, as is done in functional languages. And if you're avoiding a functional language because of uncertain efficiency... do you have any idea how inefficient hash tables are? Load a million records using hash tables (assume you've interned the keys), and you're commonly wasting huge amounts of space because all the tables are initialized to hold 16 items. Trees, of course, use only one node if they're empty. Second, the hashing functions tend to be complete crap, so your hash table is either 3/4 full at most, or you may as well have put everything in a list and do a linear search on it. Of course, that's also true with any language that allows concurrent threads of execution. And even with a PhD-level brain, explaining the performance of any non-trivial program is completely impossible, so everyone just uses a profiler. They wrote you a book: Real World Haskell. Funny, I just wrote a simple but nontrivial program in Haskell to solve a geometric puzzle. I could have written it in Java but it would have been at least 4 times as long. If you're tied to enterprise infrastructure, go with Java/.Net. If you can throw off the shackles of over-engineering, Haskell is a refreshing and productive alternative. edit: Based on my understanding of "lazy" from outside of Haskell. Some constructs look like lazy evaluation but aren't. A Future object, in Java, isn't lazy but asynchronous. You schedule it with an executor and processing starts right away. a && b, assuming common C notation is "lazy" in that it will only evaluate b when a is false, but that is really a control flow construct. Any &&, || or ? : expression, after all, can be refactored as an if / else. An iterator is a genuinely lazy construct. Proxy objects can be lazy constructs, e.g. if I have a class in Python: def __getattr__(self, attr): database_fetch(self) return getattr(self, attr) What database_fetch can do is rewrite the object (including type, interestingly enough) to be an actual Record. A lazy language, however, is one where there's no (logical) distinction between evaluated and unevaluated expressions. So you can write (and this is in the standard library) a function hGetContents that gets an entire file as a string. "The rest of the string that we haven't read yet" is not some special data structure, it's just the tail of the list, as with any list. Good call. More specifically, in Haskell a program written in the following form is a streaming program: 1. read entire contents of file into a string 2. split string into list of lines 3. transform lines into new list via one-pass algorithm 4. concatenate transformed list into a string 5. write entire string to a file This has always struck me as true with functional languages. Threaded applications sometimes, as well. After all, it's usually a typo that causes the problem, not a logic error.. Not only that, but compilers do it the same way. They call it a symbol table, but it's the same data structure.. I didn't say they were slow, I accused them of "uncertain efficiency", which was the criticism of functional languages that I was addressing. Purpose-built implementations of hash tables can be highly tuned: they may be rarely updated, or you know the key distribution, or you can do perfect hashing. In cases where they're used ubiquitously in the language you'll often see there are constraints, e.g. Perl 5 hashes only allow string keys. But when you're dealing with hash tables as a generic implementation of associative arrays, the downsides include things like periodically recopying the entire table, wasted memory for small tables, etc. The worst problem is that when hash tables are small they really do perform beautifully. Determining what the performance will be when they are large or heavily used requires statistical analysis of key distribution, and you have to amortize the cost of recopying and collision resolution! Be honest, have you ever done that, outside of class? Look at systems where indexing needs to be used in a concurrent environment with large amounts of data, like DBMSs. Most indexes are B-trees, partly because they can be sorted, but also because they play nice with concurrency: updating won't require holding locks while potentially megabytes of index is recalculated. (The exception is some temporary indexes used for hash-joins, but in those cases the number of buckets can be estimated beforehand.) IMHO lazyness has interesting properties, but it should only be an option.. F# (which is of ML->OCaml lineage) is strict but has lazy sequences or the seq{...} monad for laziness. I believe the 'compositionality' of Haskell comes mostly from partial application and pattern matching (features which are also available in strict languages) rather than lazy evaluation. All said, I believe that Haskell produces the cleanest code of any languge that I have seen. If anyone knows a couple good references about how some of these compilers work, please post them here. Do you have any higher-res. versions, or could you lead me to who produced it? Thanks! You must login or create an account to comment.
http://arstechnica.com/information-technology/2012/11/how-is-lazy-evaluation-in-haskell-useful/?comments=1&post=23526183
CC-MAIN-2013-48
refinedweb
2,908
60.04
Craig, I suggest that you look at netcdf-java at: especially download and run the ToolsUI program. The documentation doesn't exist but to get started put the file name in the dataset slot and hit return, it will bring up a description of the file etc. Right click on the variable name and then left click to get the declaration or ncdump the data. Click the ncdump tag and it will dump the data. If you look at the top it has air_temperature(0:0:1, 0:0:1, 0:100:1, 0:270:1). These are the dimensions of the data, this information is needed in the example program. 0:0:1 means start at 0, end at 0, using stride of 1. Do some trial and error with the program, you will see it can do most task without getting into the details of the underlining data packages. The following sample program displays the lat, lon, and air_temperature information. You will have to set a classpath to reference the toolsui jar file so you can compile and run the program. I would also look at the JavaDocs for how to use the methods. RObb... package ucar.nc2; import ucar.ma2.Array; import ucar.ma2.IndexIterator; public class TestGetData { public static void main(String[] args) { try { NetcdfFile ncf = NetcdfFile.open( "/local/robb/data/grib/GR12009092706_air_temp" ); Variable at = ncf.findVariable("air_temperature"); Array adata = at.read( "0,0,0:100,0:270"); Variable lat = ncf.findVariable("lat"); Array latdata = lat.read( "0:100"); Variable lon = ncf.findVariable("lon"); Array londata = lon.read( "0:270"); IndexIterator aiter = adata.getIndexIterator(); IndexIterator latiter = latdata.getIndexIterator(); while(latiter.hasNext()) { double latval = latiter.getDoubleNext(); IndexIterator loniter = londata.getIndexIterator(); while(loniter.hasNext()) { float aval = aiter.getFloatNext(); double lonval = loniter.getDoubleNext(); System.out.println( latval +" "+ lonval +" "+ aval); } } System.out.println( "Success"); } catch (Exception exc) { exc.printStackTrace(); } } } Ticket Details =================== Ticket ID: JNJ-582161 Department: Support netCDF Decoders Priority: Normal Status: Open
http://www.unidata.ucar.edu/support/help/MailArchives/decoders/msg01055.html
CC-MAIN-2014-52
refinedweb
323
53.68
Can you explain how the following two "bit puzzles" achieve what the title of the problems say they do. 1. Absolute Value int abs(int x){ int sign = x >> 31; int neg_x = ~x+1; //two's compliment return (neg_x & sign) | (x & ~sign); } 2. Lazy Addition // assumes a + b + c + d <= 127 // and that a,b,c,d are all positive // returns a + b + c + d using only 2 additions int add4(int a, int b, int c, int d){ x = a << 8 | b; y = c << 8 | d; int q = x + y; return (q & 0xff) + (q >> 8); } All the explanation in the world would be extremely helpful and appreciated!! Thank you!
http://forums.devshed.com/programming-42/bit-puzzle-help-931639.html
CC-MAIN-2015-48
refinedweb
110
62.04
Hi All, I have been searching around for the right 'phrase' to get a tutorial on animating a jpg. I have cs6 suite. So tools are not the problem. I also have Toon Boom Animate 2. I am trying to get some tutorials to take a Jpg and chop it up to create parts. So I can then animate them, or 'bone / tween them in Flash. I am not sure where to start as far as disecting a jpg into parts that I can then export and turn them into a symbol...I subscribed to Class On Demand, but I could not find a solution there. Or I was not typing the exact, perfect phrase to find it. Please those of you who know how to do this. Give me some search phrases to find a decent tutorial video(s) to watch to be able to grab a jpg, chop it into peices. I would think this is done in PS? But which tool and what is the term used to describe that utility? After I have the pic chopped into peices I think I could then just import them into my Flash Library and convert them into symbols and start animating. I saw the Panda for Lip Sync (in the 'canned' animation area) That is what I am really trying to do... However I could not perfect the proper phrase to find a video on how to do that. Creatiang a Lip Sync out of a JPg....Some of the tutorials I wathced on Youtube were way to advanced to show the little important steps to do that. I got the ones that showed after creating or knowing first hand how to draw symbols then build my comp. If you know of a video or tutorial to turn me on to, that would be appreciated. Thanks for any direction, NC P.S. I do not need the link to "getting started with flash" and making a ball roll with a start and stop button. import your jpg to flash>place it on the stage>while it's still selected, click modify>bitmap>trace bitmap (experiment with settings). after converting to a vector (tracing bitmap), use the lasso tool to select one body part you want to animate independently of the other parts (eg, the left forearm)>right click>click convert to symbol>select movieclip (if you're going to use actionscrpt) or graphic (if you're going to animate using timeline tweening). continue selecting other body parts and converting to symbols until the entire jpg is sliced and converted. I am glad I asked Kglad...I was about to go about it the LONG way around. Thanks. I will go mess around with that Peace NC Kgald, Real quick I import your jpg to flash>place it on the stage>while it's still selected, click modify>bitmap>trace bitmap after converting to a vector (tracing bitmap) When selecting the Lasso tool, to use it on the vectored file it moves the file around my work area. It does not Lasso it? What am I missing? Thanks one more thing I got the lasso to work by creating a second layer. But how do I keep chopping? I created a third layer and proceeded yet it reverts back to my original cut including the original cut and not the new cut? "Makes a box around the area where my last cut was,also included the new cut. A 'Box' keeps appearing around the area? Is there a video on this somewhere? Or a proper name for what I am doing to find a video tutoiral? after converting to a vector you should be able to lasso any part you want. that will select the lassod part. right click >convert to symbol>movieclip. then cut that piece and paste in place in a new layer whose visibility you can toggle on and off to see what's already been selected.
http://forums.adobe.com/thread/1151685
CC-MAIN-2014-10
refinedweb
660
81.12
Editors note: Last month we published another article on "5 Things I Didn't Know about Create React App" - check that one out too for more tips and tricks with React! Learn new tips and tricks for Create React App to make you more productive with tooling and help you build your apps faster. Create React App is a tool developed for setting up React applications. It saves its users from time consuming-configuration and setup. Using Create React App, users can set up and run single-page React applications in minutes. There’s a lot this ingenious tool can do for its users. Some features are quite popular, like the fact that it requires no setup, and that users can create a fully fledged application by running a single command. But this tool can do much more than even some of its most faithful users know about. In this article, we’ll go through a list of ten things you probably don’t know about Create React App. Some of them may come as a surprise to you. If you find that you know most of the things listed here, then you should keep an eye out for the few that are new to you — they might really come in handy. Create React App has out-of-the-box support for service workers. That means your application can be a Progressive Web Application that works offline and uses a cache-first strategy. In the latest installment of Create React App (version 2), service workers are opt-in only. To make use of service workers in your production build, you have to register the service worker in your index.js file. In your src/index.js file, look for the following line: // 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(); Change the serviceWorker.unregister() to serviceWorker.register(). Opting in to use a service worker makes your application an offline-first Progressive Web Application with cached assets and ability to add to the home screen for mobile users. To ensure cross-browser support, Create React App adds vendor prefixes to an application’s CSS. This reduces the stress of manually adding vendor prefixes while styling components. An example of this will be the flex display property. The snippet below will be transformed from this: .App { display: flex; flex-direction: row; align-items: center; } To this after minification: .App { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } You can control, restrict, and target support browsers by changing the browserlist property in your package.json file using the Browserslist specification. Read more on autoprefixing in Create React App here. With Create React App v2, support for CSS preprocessor has been added. Finally we have nesting and mixins supported out of the box in Create React App. In previous versions of Create React App, to achieve something similar to nesting, we made use of component composition. To get started using SCSS in your project, install node-sass, then rename all css files to scss. You can read more about getting started with SCSS in Create React App here. In the process of building our application, we can end up with bloated build files. Code splitting as a technique can help reduce the size of build files. Create React App supports the Dynamic import proposal out of the box. Using dynamic imports, bundle sizes can be reduced substantially. Dynamic imports are asynchronous so they can be used with Async/Await. Using this technique, components are imported on demand and will be built separately from your main bundle file, thus reducing the bundle size. The snippet below shows how to utilize the import() feature: import React from 'react' export class TestComponent extends React.Component{ constructor(){ super(); this.onClick = this.onClick.bind(this); } async onClick(){ const component = await import('../neededComponent.js'); } render(){ return <button onClick={this.onClick}>Lazy load me</button> } } Read more on code splitting using dynamic imports here. Usually during development we set up the server and React app on the same host and port, and then we’ll serve the frontend app on the " /" and maybe serve the API from the " /api" route. Well, with Create React app you don’t necessarily need that setup, as you can tell the Create React App server to proxy such requests to your API server. So all you need to do to get this feature working is to add a proxy field in your package.json file. “proxy”: ‘’ This way any requests that can’t be processed by the development server will proxy to the value of the proxy field in the package.json file. So request to /api/todos will proxy to. This is very convenient as you don’t have to deal with CORS issues in development. Read more on proxying API requests here. During development, one might need the development server to serve pages over HTTPS. Maybe that OAuth application requires your app to be served over HTTPS before it authenticates or for some other reason. Whatever your reasons may be, Create React App has got you covered, as always. It’s a very easy setup. All that’s required is setting the HTTPS environment variable to “true” before starting the server. Thus, instead of running: npm start On Windows cmd you run: set HTTPS=true&&npm start On Powershell run: ($env:HTTPS = $true) -and (npm start) And finally on Linux and macOS run: HTTPS=true npm start Check out the full gist on HTTPS setup during development here. During development, you’ll have some sensitive information that shouldn’t be included in your scripts. Client keys, client secrets and the rest are best stored in environment variables, and Create React App comes to our rescue again by replacing environment variables referenced in your code base with their actual values. All you need to do is create a .env file in the root of your project folder and define any variables your wish to use in your files in the following format: //.env REACT_APP_CLIENT_SECRET=client-secret REACT_APP_CLIENT_KEY=client-key The idea here is to prefix any environment variable you wish to define with REACT_APP and Create React App will replace it with its actual value when building your files. Check out how you can create different environment variables for production and development here. Create React App supports some of the latest and most used JavaScript standards. The ES6 syntax is fully supported by Create React App along with some other experimental proposals. Experimental proposals like async / await, Object spread/rest properties are a few others that are also supported out of the box. To use other experimental features like Symbols, Promise and others requires a polyfill. The polyfill is also provided by Create React App. They never stop helping, do they? Read more on the currently supported standards here. This is more of a fun fact than a point that’ll actually contribute to your development. Create React App makes use of webpack, Babel and the rest under the hood, but builds on top of them to provide a unified experience. That’s why we install one tool and we get a server, linting, transpilation and the rest alongside it. If it comes to it and you think that there are some features you require in your project that are not supported by Create React App, you can always eject. Maybe you need static type-checking using TypeScript or the build setup doesn’t work well enough. You can always eject. Now, ejecting simply means copying all of Create React Apps configurations to your project and handing over full control over to you. If you go this way, it’ll be hard but not impossible to go back. Whenever you’re ready to go down this road, simply run npm eject and the deed will be done. But remember, with great power comes great responsibility. Read more on benefits and dangers of ejecting here. These are just ten of the many things Create React App does to aid development experience. Going through their official README, you can find a lot more interesting features offered by Create React App. I hope that some of the things listed here actually help in making your development experience easier and more forthcoming. For more info on building apps with React: Check out our All Things React page that has a great collection of info and pointers to React information – with hot topics and up-to-date info ranging from getting started to creating a compelling UI. Christian is a Lagos, Nigeria based software developer and developer advocate. He keeps pushing boundaries with/for the Next Billion Users and Next Million Developers through Microsoft.
https://www.telerik.com/blogs/10-more-things-you-didnt-know-create-react-app
CC-MAIN-2022-33
refinedweb
1,494
63.8
vue2-timeago .A vue component used to format date with time ago statement just now ** minutes ago ** hours ago ** days ago yyyy-mm-dd hh:mm Get from npm / yarn: npm i vue2-timeago yarn add vue2-timeago or just include vue2-timeago.js to your view like <script src='[email protected]/dist/vue2-timeago.js'></script> Use this inside your app: import TimeAgo from 'vue2-timeago' export default { name: 'app', components: { TimeAgo, } } ####### You don't need include for version >= "1.2.2" import 'vue2-timeago/dist/vue2-timeago.css' or just include vue2-timeago.css <time-ago :refresh="60" :datetime="new Date(2018, 7, 4, 0, 24, 0)" locale="zh_TW" tooltip></time-ago> Default locale is en, and the library supports en and zh_TW. <time-ago</time-ago> <time-ago :</time-ago> use v-bind export default { ... data(){ return{ locale:"zh_TW", } }, ... <time-ago</time-ago> <time-ago :</time-ago> use v-bind <time-ago :</time-ago> timestamp Note. Don't bind with new Date() when you use refresh property. Because every time refresh will get a new date value. <time-ago :</time-ago> --> OK <time-ago refresh :</time-ago> --> not OK If you want use new Date() , just remove datetime property. <time-ago refresh></time-ago> <time-ago refresh></time-ago> Boolean , default refresh time 60/s <time-ago :</time-ago> bind value with a number <time-ago tooltip></time-ago> Show tooltip <time-ago</time-ago> Set placement <time-ago :</time-ago> show : 2d <time-ago :datetime="datetime" long></time-ago> show : 2 days ago You can do something when time refresh every time <time-ago :</time-ago> <time-ago @click.<time-ago/> locale translations: The component needs more locale translations. You can Open an issue to write the locale translations, or submit a pull request. See example here. locale support list : Thanks for help: Author: runkids.
https://morioh.com/p/ec7cb17646ac
CC-MAIN-2021-10
refinedweb
309
57.67
). And today I'd like to show you yet another use case: visualizing on a world map where your users are, hence the click-bait-y title. Foreword But before we start, I have to confess something to you: I don't like web development - at all. I find the html/css/js triplet to be a pain to work with that's only made worse by the various different browser implementations. As a C developer, JavaScript is alien and weird to me; CSS is convoluted and html is, after all, xml, and as such, should probably die in a fire. However, I have to admit that I see the appeal: you can easily prototype, handle both logic and presentation, rely on billions of online examples and modules/plugins/libraries and of course iterate crazy fast. So yeah, I don't like the technology, but it really lowers the entry barrier for developers, and that's a good thing. And so, this project has be coded in JavaScript, and it was actually pretty painless, even for a hater like me. I guess I'm becoming more mature as I grow old (up?), or maybe I just had big misconceptions about webdev, who knows? The plan The idea is to create a web page showing us a map of the world, painting countries according to the number of requests that came from them (the more requests, the darker the shade). Something like this: For this, we are going to use: - Varnish: You are on Varnish Software's blog, after all. Joking aside, Varnish being the entry point of your platform, it will see all requests, and so will have all the information needed. - Varnish Custom Statistics: VCS will collect all sorts of data about certain requests and categorize them using tags and it can do so for clusters of Varnish, not just individual instances. - vmod-geoip: Using libgeoip (possibly with a free database) this VMOD can translate IP addresses to country names or ISO "ALPHA-2" codes. - jqvmap: This is a pretty cool JavaScript map framework, and since I'm a total n00b in JavaScript, this puppy is going to do the heavy lifting for me (mandatory, related image) And that's about it, let's set things up! The VCS side Hold your breath, don't blink, this is going to be super quick. VCS actually consists of two software components: the server and the probe. The VCS probe is run on each Varnish server, reads the shmlog and pushes data to the VCS server, which most of the time is on a separate machine. The server is started with: vstatd Yes, the binary is still called "vstatd", the old name of the product, but that's not important. We'll use the default ports, time window sizes and numbers. And we have to start the probe(s), telling it where the VCS server is (let's say 192.168.0.200): vstatdprobe 192.168.0.200 And that's it, you can stop holding your breath now. What requests are collected and how is completely driven by VCL, explaining the lack of configuration here. The Varnish side It won't actually be much more complicated, first you need to: - install libgeoip, and maybe a database, such as this one (the Arch Linux package bundles it, so I had no extra work to do). - download, compile and install vmod-geoip, it's now straightforward in Varnish 4.X if the dev packages are installed. Then, we just have to add a few lines to our VCL: import std; import geoip; sub vcl_recv { std.log("vcs-key: FROM-" + geoip.country_code(client.ip)); } Done! For each request, we are going to log the country code of the country, prefixed with "vcs-key: FROM-", where "vcs-key:" is a marker announcing to VCS that the string should be used to tag the request, and "FROM-" is just a string for us to help with filtering. To check that it works, let's run: varnishlog -i VCL_Log -g raw "-g raw" removes all grouping, and "-i VCL_Log" filters only VCL_Log lines, in other words, messages coming from std.log(). The result should look a bit like: 1977337 VCL_Log c vcs-key: FROM-US 2002175 VCL_Log c vcs-key: FROM-CN 1977340 VCL_Log c vcs-key: FROM-CN 2002178 VCL_Log c vcs-key: FROM-US 1977343 VCL_Log c vcs-key: FROM-KR 2002181 VCL_Log c vcs-key: FROM-US 1977346 VCL_Log c vcs-key: FROM-CA 2002184 VCL_Log c vcs-key: FROM-US 1977349 VCL_Log c vcs-key: FROM-CA 2002187 VCL_Log c vcs-key: FROM-CN 1977352 VCL_Log c vcs-key: FROM-US 2002190 VCL_Log c vcs-key: FROM-Unknown 1977355 VCL_Log c vcs-key: FROM-Unknown 2002193 VCL_Log c vcs-key: FROM-IR 1977358 VCL_Log c vcs-key: FROM-FR Which is not too surprising; that's what we asked for. There are a few unknown IPs, but after all, we are using a free, lower quality database, so that's normal. The VCS API Data is starting to pour into our VCS server; let's see what's available. With the endpoint /all/, we can retrieve all the vcs-keys seen and currently in memory: curl $VCSIP:$VCSPORT/all/ { "keys": [ "FROM-Unknown", "FROM-A2", "FROM-AD", "FROM-AE" ] } To get info about one key (i.e., all the requests flagged using this tag), /key/STRING is used: curl $VCSIP:$VCSPORT/key/FROM-RU { "FROM-RU": [ { "timestamp": "2016-08-02T18:06:30", "n_req": 42, "n_req_uniq": "NaN", "n_miss": 42, "avg_restarts": 0.000000, "n_bodybytes": 11928, "reqbytes": 3874, "respbytes": 22050, "berespbytes": 0, "bereqbytes": 0, "ttfb_miss": 0.000166, "ttfb_hit": "NaN", "resp_1xx": 0, "resp_2xx": 0, "resp_3xx": 0, "resp_4xx": 0, "resp_5xx": 42 }, { "timestamp": "2016-08-02T18:06:00", "n_req": 43, "n_req_uniq": "NaN", "n_miss": 43, "avg_restarts": 0.000000, "n_bodybytes": 12212, "reqbytes": 3968, "respbytes": 22575, "berespbytes": 0, "bereqbytes": 0, "ttfb_miss": 0.000180, "ttfb_hit": "NaN", "resp_1xx": 0, "resp_2xx": 0, "resp_3xx": 0, "resp_4xx": 0, "resp_5xx": 43 }, { "timestamp": "2016-08-02T18:05:30", "n_req": 44, "n_req_uniq": "NaN", "n_miss": 44, "avg_restarts": 0.000000, "n_bodybytes": 12496, "reqbytes": 4042, "respbytes": 23100, "berespbytes": 0, "bereqbytes": 0, ... As you can see, data is aggregated in windows of 30 seconds (look at the timestamps) by default, giving you almost real-time feedback on how your data is consumed. Here we can tell that we get around 40 requests from Russia every 30 seconds, generating 22k of traffic to the clients. And we can also tell that I should fix my backend since all the requests received 5XX responses (truth is, I got lazy and didn't start the backend). Let's finish on a more complex request, which is actually the one we are going to use: curl $VCSIP:$VCSPORT/match/FROM-/top/300?b=10 This asks VCS: - to return only the keys matching "FROM-". - to return only the 300 most requested keys. We are good anyway since there are fewer countries than that, but it will force VCS to count and show the number of requests in the results, instead of just displaying the keys. - to use the last five time windows to compute the most requested keys, instead of only using the last one. The result should look like this: { "FROM-US": 14120, "FROM-Unknown": 5778, "FROM-CN": 2962, "FROM-JP": 1817, "FROM-GB": 1100, "FROM-DE": 1060, "FROM-KR": 1023, "FROM-BR": 756, "FROM-FR": 741, "FROM-CA": 698, "FROM-IT": 474, "FROM-NL": 444, "FROM-AU": 437, "FROM-RU": 421, "FROM-IN": 361, "FROM-TW": 299, ... And this is what we are going to use in our JavaScript, which we are now ready to write. Enter Mordor Before we start, let me state that again: this is not my turf, and I did what most new coders do: I stole code, specifically from the jqvmap README, but in my defense, the example given was doing pretty much what I needed. Some requirementsAs said at the beginning, we are going to use jqvmap, meaning we need to include 4 elements to our HTML page: - jqvmap's css, so our map is all nice and fancy - jquery, because nothing is pure js anymore and jqvmap heavily uses this framework - jqvmap's code, that's to be expected - a world map. jqvmap can plot any map, and has quite a collection, but right now, we are interested in a world map. HTML code is: <script type="text/javascript" src=""> <script type="text/javascript" src=""> <script type="text/javascript" src="" charset="utf-8"> Note that for the last two, I just used rawgit so I could avoid hosting the code while still executing it. And I'll also create an empty div for jqvmap to populate: <div id="vmap" style="width: 100%; height: 90%;"></div> Show us the code! Ok, everything is in place. Now we just have to create the map, and update it every 20 seconds, here's the map creation that will happen once the page is loaded: var g_reqs = {}; function mapUpdate() { $.getJSON("?", parseAndShow); }; function labelShow(event, label, code) { label.text(g_req[code] + " requests originated from " + JQVMap.maps['world_en'].paths[code].name) } function regionClick(event, label, code) { event.preventDefault(); } jQuery(document).ready(function() { jQuery('#vmap').vectorMap({ map: 'world_en', hoverColor: '#005aff', scaleColors: ['#d8f8ff', '#005ace'], onRegionClick: regionClick, onLabelShow: labelShow, normalizeFunction: 'polynomial' }); mapUpdate(); }); Some explanation about the vectorMap() arguments: - map: what map should be used, we only loaded one here, so there's not much suspense. - hoverColor: the default color for highlighted zone is green, but the Varnish color is blue, so I needed to adapt it. - scaleColors and normalizeFunction: we are going to give per-country values to jqvmap, and these two parameters direct how they will be translated into colors, scaleColors being the lower/upper bounds, and normalizeFunction how colors are going to be spread in the interval. - onRegionClick: give a callback to run when a country is clicked, and that callback (regionClick) actually prevents the default behavior. - onLabelShow: there's a label under the map, and we can use a callback to put whatever text we want in it. But vectormap() only creates a blank map, so we need to color it. Thankfully, jqvmap will do most of the job for us, and we only have to give it a dictionary looking like: { "us": 34, "ru": 54, "fr": 23, ...} i.e., using the lowercase country code as keys and the number of requests as values, coloring will happen automagically using scaleColors and normalizeFunction. This happens in two steps: - grab the data; this is done in mapUpdate - adapt the data from VCS to fit jqvmap, that means converting keys from "FROM-XX" to "xx", and making sure all countries are represented: function parseAndShow(data) { var countries = [ ', 'gw', 'gy', 'ht', 'hm', 'va', 'hn', 'hk', 'hu', 'is', 'in', 'id', 'ir', 'iq', 'ie', 'im', 'il', 'it', 'jm', 'jp', 'je', 'jo', 'kz', 'ke', 'ki', 'k', 'om', 'pk', 'pw', 'ps', 'pa', 'pg', 'py', 'pe', 'ph', 'pn', 'pl', 'pt', 'pr', 'qa', 're', 'ro', 'ru', 'rw', 'bl', 'sh', 'kn', 'lc', 'mf', 'pm', 'vc', 'ws', 'sm', 'st', 'sa', 'sn', 'rs', 'sc', 'sl', ', 've', 'vn', 'vg', 'vi', 'wf', 'eh', 'ye', 'zm', 'zw', 'kp' ]; var reqs = {}; $.each(countries, function(idx, key) { var ckey = "FROM-" + key.toUpperCase(); if (data[ckey]) { reqs[key] = data[ckey]; } else { reqs[key] = 0; } }); g_req = reqs; jQuery('#vmap').vectorMap('set', 'values', reqs); setTimeout(mapUpdate, 20000); } At the end, I set a timer to rerun mapupdate 20 seconds later, and I updated g_reqs so that labelShow can use it when I hover over a country. And we are done! The maps in the page are static to avoid running VCS ad vitam aeternam just for a blog post, but if you wish to see the full "actual" code, it's here. From here to there Of course, you can make the maps even sexier by adding tooltips, fancier colors and cool effects, but as you can guess, I leave this as an exercise to you, the reader. BUT, there's one last thing I wanted to show you before we part ways, a quick change for a deep addition. Let's say we add one line to our VCL: import std; import geoip; sub vcl_recv { std.log("vcs-key: FROM-" + geoip.country_code(client.ip)); std.log("vcs-key: TO-" + geoip.country_code(server.ip)); } We are now recording not only the client's country but the destination's. True, you need more than one point of presence for this to be interesting, but the point is that with very few changes to your JavaScript, you can get the original map mapping the client's activity to this one, mapping the server's activity: Where you can see in a quick glance that your Japanese servers are getting more than their share of requests. Conclusion VCS is a generic tool, offering great versatility and super easy integration, notably with JavaScript that bundles HTTP+JSON directly into the language as we have seen here. But this is only a very specific example, made to kickstart your creativity and make you think about how it can be useful for YOU and your Varnish usage. Data analysis is already a crucial part of running a website, and is not limited to just bandwidth and requests per second. Combined with Varnish, VCS can be the tool to give you the necessary insight on who your public is and how your content is consumed to create a better, more efficient service. Ready to learn more about VCS? Join us for our live webinar, How to identify issues in Varnish and track web-traffic stats in real-time: Getting the most out of Varnish Custom Statistics on September 8th. Photo (c) 2005 Michael Coté used underCreative Commons license.
https://info.varnish-software.com/blog/vcs-powered-tactical-world-map
CC-MAIN-2019-39
refinedweb
2,275
64.85
Syncing RIPE, ARIN, and APNIC objects with a custom Ansible module Vincent Bernat Internet is split into five regional Internet registry: AFRINIC, ARIN, APNIC, LACNIC, and RIPE. Each RIR maintains an Internet Routing Registry. An IRR allows one to publish information about the routing of Internet number resources.1 Operators use this to determine the owner of an IP address and to construct and maintain routing filters. To ensure your routes are widely accepted, it is important to keep the prefixes you announce up-to-date in an IRR. There are two common tools to query this database: whois and bgpq4. The first one allows you to do a query with the WHOIS protocol: $ whois -BrG 2a0a:e805:400::/40 […] inet6num: 2a0a:e805:400::/40 netname: FR-BLADE-CUSTOMERS-DE country: DE geoloc: 50.1109 8.6821 admin-c: BN2763-RIPE tech-c: BN2763-RIPE status: ASSIGNED mnt-by: fr-blade-1-mnt remarks: synced with cmdb created: 2020-05-19T08:04:58Z last-modified: 2020-05-19T08:04:58Z source: RIPE route6: 2a0a:e805:400::/40 descr: Blade IPv6 - AMS1 origin: AS64476 mnt-by: fr-blade-1-mnt remarks: synced with cmdb created: 2019-10-01T08:19:34Z last-modified: 2020-05-19T08:05:00Z source: RIPE The second one allows you to build route filters using the information contained in the IRR database: $ bgpq4 -6 -S RIPE -b AS64476 NN = [ 2a0a:e805::/40, 2a0a:e805:100::/40, 2a0a:e805:300::/40, 2a0a:e805:400::/40, 2a0a:e805:500::/40 ]; There is no module available on Ansible Galaxy to manage these objects. Each IRR has different ways of being updated. Some RIRs propose an API but some don’t. If we restrict ourselves to RIPE, ARIN, and APNIC, the only common method to update objects is email updates, authenticated with a password or a GPG signature.2 Let’s write a custom Ansible module for this purpose! Notice I recommend that you read “Writing a custom Ansible module” as an introduction, as well as “Syncing MySQL tables” for a more instructive example. Code# The module takes a list of RPSL objects to synchronize and returns the body of an email update if a change is needed: - name: prepare RIPE objects irr_sync: irr: RIPE mntner: fr-blade-1-mnt source: whois-ripe.txt register: irr Prerequisites# The source file should be a set of objects to sync using the RPSL language. This would be the same content you would send manually by email. All objects should be managed by the same maintainer, which is also provided as a parameter. Signing and sending the result is not the responsibility of this module. You need two additional tasks for this purpose: - name: sign RIPE objects shell: cmd: gpg --batch --user noc@example.com --clearsign stdin: "{{ irr.objects }}" register: signed check_mode: false changed_when: false - name: update RIPE objects by email mail: subject: "NEW: update for RIPE" from: noc@example.com to: "auto-dbm@ripe.net" cc: noc@example.com host: smtp.example.com port: 25 charset: us-ascii body: "{{ signed.stdout }}" You also need to authorize the PGP keys used to sign the updates by creating a key-cert object and adding it as a valid authentication method for the corresponding mntner object: key-cert: PGPKEY-A791AAAB certif: -----BEGIN PGP PUBLIC KEY BLOCK----- certif: certif: mQGNBF8TLY8BDADEwP3a6/vRhEERBIaPUAFnr23zKCNt5YhWRZyt50mKq1RmQBBY […] certif: -----END PGP PUBLIC KEY BLOCK----- mnt-by: fr-blade-1-mnt source: RIPE mntner: fr-blade-1-mnt […] auth: PGPKEY-A791AAAB mnt-by: fr-blade-1-mnt source: RIPE Module definition# Starting from the skeleton described in the previous article, we define the module: module_args = dict( irr=dict(type='str', required=True), mntner=dict(type='str', required=True), source=dict(type='path', required=True), ) result = dict( changed=False, ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) Getting existing objects# To grab existing objects, we use the whois command to retrieve all the objects from the provided maintainer. # Per-IRR variations: # - whois server whois = { 'ARIN': 'rr.arin.net', 'RIPE': 'whois.ripe.net', 'APNIC': 'whois.apnic.net' } # - whois options options = { 'ARIN': ['-r'], 'RIPE': ['-BrG'], 'APNIC': ['-BrG'] } # - objects excluded from synchronization excluded = ["domain"] if irr == "ARIN": # ARIN does not return these objects excluded.extend([ "key-cert", "mntner", ]) # Grab existing objects args = ["-h", whois[irr], "-s", irr, *options[irr], "-i", "mnt-by", module.params['mntner']] proc = subprocess.run("whois", *args, capture_output=True) if proc.returncode != 0: raise AnsibleError( f"unable to query whois: {args}") output = proc.stdout.decode('ascii') got = extract(output, excluded) The first part of the code setup some IRR-specific constants: the server to query, the options to provide to the whois command and the objects to exclude from synchronization. The second part invokes the whois command, requesting all objects whose mnt-by field is the provided maintainer. Here is an example of output: $ whois -h whois.ripe.net -s RIPE -BrG -i mnt-by fr-blade-1-mnt […] inet6num: 2a0a:e805:300::/40 netname: FR-BLADE-CUSTOMERS-FR country: FR geoloc: 48.8566 2.3522 admin-c: BN2763-RIPE tech-c: BN2763-RIPE status: ASSIGNED mnt-by: fr-blade-1-mnt remarks: synced with cmdb created: 2020-05-19T08:04:59Z last-modified: 2020-05-19T08:04:59Z source: RIPE […] route6: 2a0a:e805:300::/40 descr: Blade IPv6 - PA1 origin: AS64476 mnt-by: fr-blade-1-mnt remarks: synced with cmdb created: 2019-10-01T08:19:34Z last-modified: 2020-05-19T08:05:00Z source: RIPE […] The result is passed to the extract() function. It parses and normalizes the results into a dictionary mapping object names to objects. We store the result in the got variable. def extract(raw, excluded): """Extract objects.""" # First step, remove comments and unwanted lines objects = "\n".join([obj for obj in raw.split("\n") if not obj.startswith(( "#", "%", ))]) # Second step, split objects objects = [RPSLObject(obj.strip()) for obj in re.split(r"\n\n+", objects) if obj.strip() and not obj.startswith( tuple(f"{x}:" for x in excluded))] # Last step, put objects in a dict objects = {repr(obj): obj for obj in objects} return objects RPSLObject() is a class enabling normalization and comparison of objects. Look at the module code for more details. >>>>> pprint({k: str(v) for k,v in extract(output, excluded=[])}) {'<Object:inet6num:2a0a:e805:300::/40>': 'inet6num: 2a0a:e805:300::/40\n' 'netname: FR-BLADE-CUSTOMERS-FR\n' 'country: FR\n' 'geoloc: 48.8566 2.3522\n' 'admin-c: BN2763-RIPE\n' 'tech-c: BN2763-RIPE\n' 'status: ASSIGNED\n' 'mnt-by: fr-blade-1-mnt\n' 'remarks: synced with cmdb\n' 'source: RIPE', '<Object:route6:2a0a:e805:300::/40>': 'route6: 2a0a:e805:300::/40\n' 'descr: Blade IPv6 - PA1\n' 'origin: AS64476\n' 'mnt-by: fr-blade-1-mnt\n' 'remarks: synced with cmdb\n' 'source: RIPE'} Comparing with wanted objects# Let’s build the wanted dictionary using the same structure, thanks to the extract() function we can use verbatim: with open(module.params['source']) as f: source = f.read() wanted = extract(source, excluded) The next step is to compare got and wanted to build the diff object: if got != wanted: result['changed'] = True if module._diff: result['diff'] = [ dict(before_header=k, after_header=k, before=str(got.get(k, "")), after=str(wanted.get(k, ""))) for k in set((*wanted.keys(), *got.keys())) if k not in wanted or k not in got or wanted[k] != got[k]] Returning updates# The module does not have a side effect. If there is a difference, we return the updates to send by email. We choose to include all wanted objects in the updates (contained in the source variable) and let the IRR ignore unmodified objects. We also append the objects to be deleted by adding a delete: attribute to each of them. # We send all source objects and deleted objects. deleted_mark = f"{'delete:':16}deleted by CMDB" deleted = "\n\n".join([f"{got[k].raw}\n{deleted_mark}" for k in got if k not in wanted]) result['objects'] = f"{source}\n\n{deleted}" module.exit_json(**result) The complete code is available on GitHub. The module supports both --diff and --check flags. It does not return anything if no change is detected. It can work with APNIC, RIPE, and ARIN. It is not perfect: it may not detect some changes,3 it is not able to modify objects not owned by the provided maintainer4 and some attributes cannot be modified, requiring to manually delete and recreate the updated object.5 However, this module should automate 95% of your needs. Other IRRs exist without being attached to an RIR. The most notable one is RADb. ↩︎ ARIN is phasing out this method in favor of IRR-online. RIPE has an API available, but email updates are still supported and not planned to be deprecated. APNIC plans to expose an API. ↩︎ For ARIN, we cannot query key-certand mntnerobjects and therefore we cannot detect changes in them. It is also not possible to detect changes to the auth mechanisms of a mntnerobject. ↩︎ APNIC does not assign top-level objects to the maintainer associated with the owner. ↩︎ Changing the status of an inetnumobject requires deleting and recreating the object. ↩︎
https://vincent.bernat.ch/en/blog/2020-syncing-ripe-arin-apnic-ansible
CC-MAIN-2020-45
refinedweb
1,515
56.25
How To Import From Another Folder In Python? Python has a bit of a unique import system, if you’re trying to import files from a directory outside of your package, you might run into some trouble. By default Python does not allow importing files from arbitrary directories, but there is a workaround: you can add the directory to your PYTHONPATH env var or insert it into the sys.path variable. In this short tutorial, I’ll show you how to do this, explain why it’s not a good idea, and show some better ways to fix this problem. 1. Add The Folder To Your PYTHONPATH Environment Variable When you try to import something in Python, the interpreter will first look for a builtin module. If no builtin module is found, Python falls back to searching in the current working directory. If the module is not found there, the Python engine will try all the directories listed in the sys.path system variable. When starting the script, this variable is initialized from the PYTHONPATH environment variable. To add an extra import source folder, before running your script, run one of the following snippets (depending on your OS): On Linux Or MacOS export PYTHONPATH=/path/to/file/:$PYTHONPATH Windows set PYTHONPATH=C:\path\to\file\;%PYTHONPATH% As you can see PYTHONPATH contains a list of directories, separated by /path/to/file/ (or \path\to\file) at the beginning of the string, so this will be the first place where Python will look for files to import. :. We inserted 2. Add The Folder To sys.path If you cannot or do not want to modify your env vars, there is an alternative: you can also directly modify the sys.path variable at runtime. You can insert your directory at the beginning of the list of the available import paths by adding these two lines of code to your Python script (before the import statement): import sys sys.path.insert(1, '/path/to/file/') This will have exactly the same effect as modifying your PYTHONPATH. Troubleshooting: Make Sure You Have an __init__.py File In The Containing Folder If you still have issues importing the files you want, make sure that the containing directory has an __init__.py file. This is used to mark the folder as a valid Python package. If your folder does not have one, you won’t be able to import files from there, as the Python interpreter only allows importing from packages, and not from standalone files. Disclaimer: Probably There’s A Better Way To Solve Your Problem You might notice, that Python does not make importing files from arbitrary folders easy, and there is a good reason for that. Tinkering with sys.path or PYTHONPATH is probably not a good idea. In some cases it can be used as a quick hack to test something, but definitely should not be used in production. It makes your system quite brittle, and can also cause serious security issues. There are better ways to go about it: 1. Simply Include The File You Want To Import In Your Project. Just copy/move the file into a subdirectory in your working folder. Maybe create a submodule for it. 2. Install It In A Proper Location If it is part of a third party package, chances are you can just install it with pip. Pip - the default Python package manager - will copy it to its proper place: some system-specific directory (like /usr/lib/python/), which is already contained in your PYTHONPATH, so the Python interpreter can automatically find it without the need to tweak your env vars. 3. Create Your Own Package If it’s not 3rd-party code, but only loosely related to your current project, or it’s something like a library of classes/functions that you reuse in multiple projects, then the best way would probably be to bundle it up and create your own package. That way you can treat it exactly like a 3rd party pip package.
https://pythonin1minute.com/how-to-import-from-another-folder-in-python/
CC-MAIN-2022-21
refinedweb
672
68.91
Re: [Haskell-cafe] First time haskell - parse error! Re: [Haskell-cafe] First time haskell - parse error! On Mar 10, 2010, at 12:21 PM, Ketil Malde wrote: Introducing names means that I need to keep the temporary definitions in my head, and I think takeWhile (1) is as clear as it can get. And while a name can be misleading (belowLimit is a boolean, no?) or flat out wrong, the definition has Re: [Haskell-cafe] Functional Dependencies conflicts [Haskell-cafe] Re: [Haskell] ANN: scan-0.1.0.3, a Haskell style scanner Re: [Haskell-cafe] Re: [Haskell] ANN: scan-0.1.0.3, a Haskell style scanner I Re: [Haskell-cafe] FGL instance constraint Furthermore, as I said earlier, it doesn't make sense to constrain the label type just to make an instance of a type class. (Now, if we had other functions in there which _might_ depend on the label types, this _would_ make sense; as it stands however, it doesn't.) You'll notice that my Re: [Haskell-cafe] FGL instance constraint On May 1, 2010, at 8:08 AM, Ivan Lazar Miljenovic wrote: * I can't redefine the Graph methods to introduce the (Cls a) constraint [reasonable] Not sure if you can. I think Kevin means that he cannot change the signature of the methods in the Graph class because those are defined in the Re: [Haskell-cafe] profiling uniplate I guess I either need to install profiling libraries for uniplate, or disable profiling of those functions coming from uniplate. Exactly. For the former cabal install --reinstall --enable-library-profiling uniplate should do the trick. Sebastian -- Underestimating the novelty of the Re: [Haskell-cafe] MonadPlus or Alternative or ...? On May 2, 2010, at 1:11 AM, Sean Leather wrote: I want to generalize a set of functions from lists to some functor type. [...] Should I choose MonadPlus and use these? [...] Or should I choose Alternative and use these? [...] There are some types that can be an instance of Alternative but Re: [Haskell-cafe] MonadPlus or Alternative or ...? On May 2, 2010, at 11:10 AM, Sean Leather wrote: Or should I make my own class? Then, there obviously won't be any instances for existing types other than your own (which might be a good or bad thing). You may want to do this, if you don't want to require either (=) or (*), which may Re: [Haskell-cafe] MonadPlus or Alternative or ...? would you have any suggestions on a name for such a class or names for the methods? I'm afraid I don't. I'd like class Pointed t where point :: a - t a class Monoid m where id :: m (.) :: m - m - m constraint Monoidy t = (Pointed t, Monoid (t a)) (although Re: [Haskell-cafe] Haskell and the Software design process On May 3, 2010, at 6:35 AM, Alexander Dunlap wrote: Of course, there are situations where it is really awkward to not use partial functions, basically because you *know* that an invariant is satisfied That falls under Don's: Use types to encode the design into a machine checkable form Or [Haskell-cafe] Different choice operations in a continuation monad) Re: [Haskell-cafe] Different choice operations in a continuation monad Hello Holger, Re: [Haskell-cafe] Different choice operations in a continuation monad Re: [Haskell-cafe] Re: Different choice operations in a continuation monad Heinrich Apfelmus wrote: Sebastian Fischer wrote: I still don't understand why it is impossible to provide `orElse` with the original type. I will think more about the reason you gave. The reason is that you have chosen the wrong type for your continuation monad; it should be newtype [Haskell-cafe] Re: Different choice operations in a continuation monad Ed Re: [Haskell-cafe] Re: Different choice operations in a continuation monad On Jun 18, 2010, at 8:55 PM, Heinrich Apfelmus wrote: I wonder whether for every monad `m` and `a :: Codensity m a` getCodensity a f = getCodensity a return = f Is this true? Why (not)? It's not true. What a pity! An example that is not generic in the base monad m , i.e. that Re: [Haskell-cafe] Re: Different choice operations in a continuation monad [Haskell-cafe] Re: The mother of all functors/monads/categories [Haskell-cafe] Re: ANNOUNCE: HaRe, the Haskell Refactorer 0.6? I will probably [Haskell-cafe] Re: ANNOUNCE: HaRe, the Haskell Refactorer 0.6 Chris Brown wrote: Are there any problems with putting HaRe on Hackage? I've looked at this before and I must say it's certainly not trivial to do this. [...] We also need to have vim and emacs scripts available to the user after the install. The ghc-mod package [1] provides emacs Re: [Haskell-cafe] bounded ranges On Jul 23, 2010, at 12:21 AM, Chad Scherrer wrote: bdRangeSize :: (Ix i, Bounded i) = i - Int bdRangeSize _ = rangeSize (minBound, maxBound :: i) Unlike intended, the `i` in the type annotation to `maxBound` is not the same as the `i` in the signature of `bdRangeSize`. You need to enable Re: [Haskell-cafe] bounded ranges An alternative to the `asTypeOf` idiom, which is also Haskell 98, is to use a newtype instead of a dummy argument: newtype RangeSize i = RangeSize { getRangeSize :: Int } boundedRangeSize :: Ix i = (i,i) - RangeSize i boundedRangeSize = RangeSize . rangeSize bdRangeSize :: Re: [Haskell-cafe] Please report any bug of gtk2hs-0.11.0! [Haskell-cafe] ANN: weighted-regexp-0.1.0.0 Hello, this year's ICFP features A Play on Regular Expressions where two Haskell programmers and an automata theory guru develop an efficient purely functional algorithm for matching regular expressions. A Haskell library based on their ideas is now available from Hackage. For more Re: [Haskell-cafe] Please report any bug of gtk2hs-0.11.0! On Jul 26, 2010, at 6:59 PM, Andy Stewart wrote: cabal install gtk fails with the message Configuring gtk-0.11.0... setup: ./Graphics/UI/Gtk/General/IconTheme.chs: invalid argument cabal: Error: some packages failed to install: gtk-0.11.0 failed during the building phase. The [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 Hi, Re: [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 [Haskell-cafe] ANN: weighted-regexp-0.1.1.0 I have released weighted-regexp-0.1.1.0 with two additional combinators: -- | Does not match anything. 'noMatch' is an identity for 'alt'. -- noMatch :: RegExp c -- | -- Matches a sequence of the given regular expressions in any -- order. For example, the regular [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0. There is currently only `instance Eq [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 Have you thought about supporting anchors like (^) and ($) ? We went the opposite route, made full matching the default, and implemented partial matching by pre- and appending .* As there are both a fullMatch and a partialMatch function, I don't see an immediate need for anchors, although [Haskell-cafe] ANN: weighted-regexp-0.2.0.0 I Re: [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 Oh, [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 REG_NEWLINE Compile for newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning in either REs or strings. With this flag, `[^' bracket expressions and `.' never match newline, a `^' anchor matches the null string after any newline in the [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 Maybe even write a blog about how it works? A whole blog is probably unnecessary ;) But a blog *post* would be nice! -- Underestimating the novelty of the future is a time-honored tradition. (D.G.) ___ Haskell-Cafe mailing list [Haskell-cafe] Re: ANN: weighted-regexp-0.1.0.0 Hello Chris, thanks for the examples. They show that by adding anchors, the meaning of regular expressions is no longer compositional. For example (^|a) accepts the empty word only if no characters have been read yet. So (^|a) =~ does hold but a(^|a) =~ a does not hold Re: [Haskell-cafe] What's this pattern called? Hi Re: [Haskell-cafe] haskell-src-exts Question Hello, [Haskell-cafe] namespaces for values, types, and classes Dear Café, types and values are in separate namespaces. So, we can write data Name = Name where the first `Name` is a type and the second is a value. However, classes are in the same namespace as types. We cannot write class Name a where ... instance Name Name where ... Re: [Haskell-cafe] namespaces for values, types, and classes Does anyone know why types and values are in separate namespaces but classes and types are not? I think it's because you cannot currently distinguish them in module import/exports. Ah, good point. For constructors there is special syntax which allows to distinguish them in im/exports. Even [Haskell-cafe] Typed Configuration Files Dear Re: [Haskell-cafe] Typed Configuration Files [Haskell-cafe] short licensing question Hello Café, when writing a Haskell library that uses two other Haskell libraries -- one licensed under BSD3 and one under LGPL -- what are allowed possibilities for licensing the written package? PublicDomain? BSD3? LGPL? Sebastian -- Underestimating the novelty of the future is a Re: [Haskell-cafe] short licensing question On Jan 11, 2010, at 2:08 PM, Don Stewart wrote: Libraries don't link in other things as such -- the .cabal file is the only thing that ties them together -- so you can use whatever license you like. On Jan 11, 2010, at 7:02 PM, Tom Tobin wrote: I think in your case you can license the Re: [Haskell-cafe] short licensing question Re: [Haskell-cafe] short licensing question On Jan 12, 2010, at 8:46 PM, Sebastian Fischer wrote: Am I allowed to distribute the sources under BSD3 and the binary under LGPL? Would that make sense? Maybe not, because anyone who distributes a binary of my program or derivative work must license it under LGPL anyway. Well it may Re: [Haskell-cafe] How to fulfill the code-reuse destiny of OOP? Re: [Haskell-cafe] wildcards for type variables? On Jan 13, 2010, at 2:16 PM, Antoine Latter wrote: He's looking for the self-documentation aspect of this argument is completely irrelevant. Neither rolling a random unused type variable nor foralling it (my first idea) really accomplishes that. Isn't that what we have here? a function Re: [Haskell-cafe] wildcards for type variables? Re: [Haskell-cafe] Hierachical abstraction? Re: [Haskell-cafe] Strange random choice algorithm Re: [Haskell-cafe] Strange random choice algorithm Re: [Haskell-cafe] Stack ADT?) = Re: [Haskell-cafe] Stack ADT? On Feb 4, 2010, at 6:27 PM, michael rice wrote: I haven't done much with modules so I'm guessing what you've provided is the guts of StackImpl, to hide the implementation? Right. In order to make the Stack type abstract, you can hide the Stack data (that is, newtype) constructor and only [Haskell-cafe] lazy'foldl Hello, Re: [Haskell-cafe] What are free Monads? On Mar 2, 2010, at 5:59 AM, Dan Doel wrote: Nice, thank you for writing this. Feel free to make suggestions/changes. I enjoyed reading it although Section 3 is challenging for people (like me) Re: [Haskell-cafe] A GHC error message puzzle Give a definition for process and an input file that reproduce this result. Quite probably not the intended solution: process :: String - String process _ = error output: hClose: illegal operation (handle is finalized) Have fun! Sebastian -- Underestimating the novelty of the [Haskell-cafe] Re: A GHC error message puzzle Wei Hu wrote: nonTermination _ = blackhole where blackhole = blackhole My original example was actually: process :: String - String process = let x = x in x process = process works just as well. What about the other part of the solution: What is the cause of the error? Of course, [Haskell-cafe] Is bumping the version number evil, if it's not mandated by the PVP? Hello, Re: [Haskell-cafe] Is bumping the version number evil, if it's not mandated by the PVP? [CC'ing café again] On Aug 14, 2010, at 12:25 PM, Max Rabkin wrote: On Sat, Aug 14, 2010 at 11:13 AM, Sebastian Fischer s...@informatik.uni-kiel.de wrote: Hello, I wonder whether (and how) I should increase the version number of a library when the API does not change but the implementation Re: [Haskell-cafe] Is bumping the version number evil, if it's not mandated by the PVP? Re: [Haskell-cafe] Is bumping the version number evil, if it's not mandated by the PVP? My worry with bumping only the patch level is that people who explicitly want to depend on the efficient version of my library need to depend on a.b.c.D and cannot follow the good practice of depending on a.b.*. Well, then you have = a.b.c.d a.(b+1). Ok, it seems this is less of an issue [Haskell-cafe] ANN: primes-0.2.0.0 Hello, I have uploaded new versions of the primes package to Hackage: Version 0.2.0.0 significantly improves the memory requirements (and as a result also the run time) compared to 0.1.1. The run time is now almost linear and when streaming an Re: [Haskell-cafe] Question about memory usage [continuing/ Re: [Haskell-cafe] Question about memory usage Re: [Haskell-cafe] Question about memory usage On Aug 17, 2010, at 12:33 AM, Jason Dagit wrote: So next I would use heap profiling to find out where and what type of data the calculation is using. I did. I would do heap profiling and look at the types. All retained data is of type ARR_WORDS. Retainer profiling shows that the Re: [Haskell-cafe] Question about memory usage Re: [Haskell-cafe] Question about memory usage BTW, what sort of memory usage are we talking about here? I was referring to the memory usage of this program import System.Environment import Data.Numbers.Fibonacci main :: IO () main = do n - (read . head) `fmap` getArgs (fib n :: Integer) `seq` return () Re: [Haskell-cafe] Question about memory usage Hi Re: [Haskell-cafe] Simple Sudoku solver using Control.Monad.Logic a brief introduction to nondeterminism monads in general and how to implement some specific instances: On Functional-Logic Programming and its Application to Testing by Sebastian Fischer Section 5.1, Nondeterminism monads Re: [Haskell-cafe] type classes and logic Hi Re: [Haskell-cafe] type classes and logic Daniel Fischer wrote: class BEING human = HUMAN human where Sub-classing is logical implication BEING(human) = HUMAN(human) All types t that make BEING(t) = true also make HUMAN(t)=true No, it's the other way round. Every HUMAN is also a BEING, hence HUMAN(t) = BEING(t) Could I say that Re: [Haskell-cafe] ICFP Hotel Room Hi Re: [Haskell-cafe] Statically tracking validity - suggestions? does anybody know of anything on Hackage for testing whether two values are approximately equal? -- Underestimating the novelty of the future is a time-honored tradition. (D.G.) ___ Re: [Haskell-cafe] Re: Crypto-API is stabilizing Re: [Haskell-cafe] Re: Crypto-API is stabilizing On Sep 3, 2010, at 12:07 AM, Sebastian Fischer wrote: Why not use generateKeypair :: MonadRandom m = BitLength - m (Maybe (p,p)) Or if the choice to generate keys or not should solely depend on the BitLength (and not on the random generator): generateKeypair :: MonadRandom m Re: [Haskell-cafe] Re: Crypto-API is stabilizing [CC'ing maintainer of MonadRandom] On Sep 3, 2010, at 1:59 AM, Thomas DuBuisson wrote: data Key = Key { encrypt :: B.ByteString - B.ByteString, decrypt :: B.ByteString - B.ByteString, keyLength :: BitLength, serialize :: Re: [Haskell-cafe] Re: Crypto-API is stabilizing Re: [Haskell-cafe] Restricted type classes Re: [Haskell-cafe] overloaded list literals? Re: [Haskell-cafe] Graphics.Drawing On Sep 6, 2010, at 1:57 PM, han wrote: So the question is: Do you agree that Graphics.Rendering.OpenGL actually should have been Graphics.OpenGL (or just OpenGL) for wieldiness? If you don't, what is your reason? I would like to know. Often, when this topic comes up, someone claims that Re: [Haskell-cafe] overloaded list literals? Re: [Haskell-cafe] Pointed (was: Re: Restricted type classes) On Sep 7, 2010, at 5:23 AM, wren ng thornton wrote: In particular, one of the primary complaints against the Monad class is precisely the fact that it *fails* to mention the Functor class as a (transitive) dependency. Why should we believe that making unit independent from fmap will fare Re: [Haskell-cafe] Scrap your rolls/unrolls Hi Max, neat idea! Haskell supports laziness even on the type level ;) I tried to play with your code but did not get very far. I quickly ran into two problems. On Oct 22, 2010, at 7:37 PM, Max Bolingbroke wrote: The annoying part of this exercise is the the presence of a Force in the Re: [Haskell-cafe] vector-space and standard API for vectors Re: [Haskell-cafe] Red links in the new haskell theme Maybe we can keep at least the docs without red links. Pick the Classic style in the style menu. It will remember your choice. Sebastian ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org Re: [Haskell-cafe] Re: Monads and Functions sequence and sequence_ Re: [Haskell-cafe] Red links in the new haskell theme Re: [Haskell-cafe] Is Curry alive? Hi Gregory, On Nov 2, 2010, at 9:27 AM, Gregory Crosswhite wrote: I was thinking about using Curry, but it looks to me like the language is dead and hasn't seen much activity for a few years. The community is smaller than the Haskell community but the PAKCS system is still actively Re: [Haskell-cafe] Is Curry alive? Re: [Haskell-cafe] What do you call Applicative Functor Morphism? Hello, I'm curious and go a bit off topic triggered by your statement: On Nov 6, 2010, at 12:49 PM, rocon...@theorem.ca wrote: An applicative functor morphism is a polymorphic function, eta : forall a. A1 a - A2 a between two applicative functors A1 and A2 that preserve pure and * I Re: [Haskell-cafe] Review request for my baby steps towards a platform independent interactive graphics using VNC Re: [Haskell-cafe] ANNOUNCE: arrow-list. List arrows for Haskell. On Nov 6, 2010, at 10:00 PM, Sebastiaan Visser wrote: List arrows are a powerful tool when processing XML, building query languages and lots of other domains that build on functions that might return more than one value as their output. Interesting. Do you plan to write some examples that Re: [Haskell-cafe] ANNOUNCE: arrow-list. List arrows for Haskell. I) Re: [Haskell-cafe] ANNOUNCE: arrow-list. List arrows for Haskell. to Re: [Haskell-cafe] Type Directed Name Resolution Re: [Haskell-cafe] Type Directed Name Resolution Re: [Haskell-cafe] Equality constraint synonyms On Thu, 2010-11-25 at 10:41 +0900, Hugo Pacheco wrote: Would this be a desired feature for other people? I'd like to have Haskell Type Constraints Unleashed which includes equality constraint synonyms. Sebastian Re: [Haskell-cafe] Wondering if this could be done. On Mon, 2010-11-22 at 14:48 +0800, Magicloud Magiclouds wrote: (+) :: A - A - A (+) a b = A (elem1 a + elem1 b) (elem2 a + elem2 b) -- I got errors here, for the (+) is ambiguous. That's because (+) is implicitly imported from the Prelude. If you import Prelude hiding ((+)) the error
https://www.mail-archive.com/search?l=haskell-cafe@haskell.org&q=from:%22Sebastian+Fischer%22
CC-MAIN-2022-33
refinedweb
3,229
61.77
ReSharper 7.0 was only released a couple of weeks ago, and it’s a testament to the plug-in community that so many plug-ins are already up-to-date with the new version. We’re going to take a more in-depth look at some of these plug-ins soon, but for now, here’s a quick overview of some of the more popular plug-ins that already support ReSharper 7.0. - AgUnit — run and debug Silverlight unit tests, with support for MSTest, NUnit and xUnit.net. - MSpec — the MSpec context/specification testing framework has been updated to support ReSharper 7.0. - xunitcontrib — unit test support for xUnit.net. - StyleCop — StyleCop analyses your source code and enforces a given coding style. The ReSharper plug-in they provide does this as you type, underlining violations of your chosen policy, and providing many context actions that automatically fix the violation, for example, moving a “using” block into the namespace declaration, rather than above it. - JSLint for ReSharper — runs the JSLint tool against your JavaScript files, providing familiar ReSharper squiggly underlines for errors and warnings. - Agent Smith — provides spell checking for your code and formatting actions for XML documentation. - Agent Mulder — support for Dependency Injection frameworks such as Autofac, Castle Windsor, Unity. Since ReSharper doesn’t know about these containers, classes can frequently be marked as unused, or not instantiated. Agent Mulder tells ReSharper when these classes are being used, and provides navigation to the registration point from each class. - GammaXaml — provides lots of very useful additions to ReSharper’s XAML support, including context actions to add grid layout definitions or remove XAML attributes, marking unused attached properties as “dead code”, validating element names in binding and more. The latest version also provides support for the convention over configuration approach used by the Caliburn.Micro MVVM framework. - ReSharperExtensions — a very useful Live Template macro that will replace spaces for underscores when typing, such as creating a method name. - Catel.ReSharper — provides a couple of context actions to support the Catel MVVM framework. - Agent Johnson — provides a number of useful context actions and refactorings. And there are more on the way — for example, the Gallio plug-in, providing support for the MbUnit testing framework is currently being updated. It’s well worth pointing out that all of these plug-ins are open source, so please feel free to contribute! Anything from feature suggestions to bug reports, to code or even a simple vote of thanks. And if you want to start developing a plug-in yourself, you can download the SDK and check out the development guide (and not forgetting ReSharper 6 users, the 6.x SDK is still available, as is the 6.x plug-in development guide). We’ll also come up a blog post soon covering new important updates that have been implemented in ReSharper 7 SDK, so stay tuned. This may be great, but it always seems that the plugins that my org uses never make the jump early. We are going to be stuck on 6.x until the mbunit plugin is updated. “And there are more on the way — for example, the Gallio plug-in, providing support for the MbUnit testing framework is currently being updated.” For R# 5.0 -> 6.0, the Gallio plugin took MONTHS to be released. Jetbrains does not develop this plugin, so is there some source that you could point us to stating this? I tried to Google it, and there is nothing. There is even no issue that I can find in their bug tracker. Why does the plugin model need to change every version? It’s a lot to ask for every plugin to upgrade every time you to. My #1 feature for R# 8 is a stable SDK which does not need plugin updates every release. @Ryan, Our intention is also to stabilize the SDK, however, losing some backward compatibility is a trade-off that is sometimes required. One of Matt’s roles is to make sure that by release time the majority of plug-ins are available and working, and he’s done a great job in doing so, even if that’s meant contributing with code himself. Unfortunately some, for one reason or another (and as you note yourself, we don’t control the projects), have not happened. Gallio is currently being worked on and they have our full support. missing Zen Coding Plugin … @Meixger: at the moment, the Zen Coding plugin is distributed in source form as part of the ReSharper SDK. I second that thought. It is a major issue that I have had to wait to adopt every recent Resharper release because the Unit testing tool my company uses (Gallio) is not ready for several months after Resharper is released. I agree it can be frustrating. We try our best to liaise with the third party authors to help get the plugins updated and released in good time, but the reality is that it is the author’s responsibility to actually produce the release. While we do talk to the plugin authors, it is always good for them to get feedback from actual users. A good course of action is to let the author know that you’re interested in a new version. Also, the vast majority of these plugins are open source, which is a fantastic opportunity to build your own version, and even contribute changes back to the project. For Gallio, you can add an issue in the issues list () requesting a new version supporting ReSharper 7 (it doesn’t look like anyone’s raised an issue yet) or you can simply download the source and build your own version – the source already provides support for ReSharper 7. How Zen-coding work in Resharper. The Zen-coding plugin is a sample currently available as part of the SDK (). Once you’ve installed the SDK, you need to build the sample and copy into %LOCALAPPDATA%JetBrainsReSharperv7.0plugins To use it, you should be able to type something like: ul>li*3 and it should then generate: <ul><li></li><li></li><li></li></ul> That is (assuming the html makes it through the filter) a ul element, with three li child elements.
http://blog.jetbrains.com/dotnet/2012/08/09/resharper-70-plug-ins/
CC-MAIN-2015-18
refinedweb
1,040
61.46
Except, this tooltip contains the password rules, and I want to use it in several places on my app. I don't want to create another custom attribute, I just want to bind the title to a value from my viewmodel. So I write: <input type="password" value. and, of course, it just works. That's what I love about the syntax of Aurelia. They don't have to think of every use-case, they built the right abstraction in the first place. FYI, if you get here looking for how to do the custom attribute, here's that code (thanks to Jeremy Danyow): import {inject} from 'aurelia-framework'; import $ from 'jquery'; import 'bootstrap'; @inject(Element) export class BootstrapTooltipCustomAttribute { constructor(element) { this.element = element; } bind() { $(this.element).tooltip(); } unbind() { ${this.element).tooltip('destroy'); } } 1 comment: Now, try to do it dynamic:) I mean title can change.
http://drdwilcox.blogspot.com/2016/06/i-love-aurelia-data-binding-always-just_24.html
CC-MAIN-2019-13
refinedweb
146
66.64
-- Haskell98! -- | Monadic and General Iteratees: -- incremental input parsers, processors and transformers -- -- System.IterateeM where import System.Posix import Foreign.C import Foreign.Ptr import Foreign.Marshal.Alloc import Data.List (splitAt) import Data.Char (isHexDigit, digitToInt, isSpace) import Control.Monad.Trans import Control.Monad.Identity import System.LowLevelIO -- | A stream is a (continuing) sequence of elements bundled in Chunks. -- The first two variants indicate termination of the stream. -- Chunk [a] gives the currently available part of the stream. -- The stream is not terminated yet. -- The case (Chunk []) signifies a stream with no currently available -- data but which is still continuing. A stream processor should, -- informally speaking, ``suspend itself'' and wait for more data -- to arrive. -- Later on, we can add another variant: IE_block (Ptr CChar) CSize -- so we could parse right from the buffer. data StreamG a = EOF | Err String | Chunk [a] deriving Show -- | A particular instance of StreamG: the stream of characters. -- This stream is used by many input parsers. type Stream = StreamG Char -- | Iteratee -- a generic stream processor, what is being folded over -- a stream -- When Iteratee is in the 'done' state, it contains the computed -- result and the remaining part of the stream. -- In the 'cont' state, the iteratee has not finished the computation -- and needs more input. -- We assume that all iteratees are `good' -- given bounded input, -- they do the bounded amount of computation and take the bounded amount -- of resources. The monad m describes the sort of computations done -- by the iteratee as it processes the stream. The monad m could be -- the identity monad (for pure computations) or the IO monad -- (to let the iteratee store the stream processing results as they -- are computed). -- We also assume that given a terminated stream, an iteratee -- moves to the done state, so the results computed so far could be returned. -- -- We could have used existentials instead, by doing the closure conversion -- data IterateeG el m a = IE_done a (StreamG el) | IE_cont (StreamG el -> IterateeGM el m a) newtype IterateeGM el m a = IM{unIM:: m (IterateeG el m a)} type Iteratee m a = IterateeG Char m a type IterateeM m a = IterateeGM Char m a -- | Useful combinators for implementing iteratees and enumerators -- liftI :: Monad m => IterateeG el m a -> IterateeGM el m a liftI = IM . return -- | Just like bind (at run-time, this is indeed exactly bind) infixl 1 >>== (>>==):: Monad m => IterateeGM el m a -> (IterateeG el m a -> IterateeGM el' m b) -> IterateeGM el' m b m >>== f = IM (unIM m >>= unIM . f) -- | Just like an application -- a call-by-value-like application infixr 1 ==<< (==<<) :: Monad m => (IterateeG el m a -> IterateeGM el' m b) -> IterateeGM el m a -> IterateeGM el' m b f ==<< m = m >>== f -- | The following is a `variant' of join in the IterateeGM el m monad. -- When el' is the same as el, the type of joinI is indeed that of -- true monadic join. However, joinI is subtly different: since -- generally el' is different from el, it makes no sense to -- continue using the internal, IterateeG el' m a: we no longer -- have elements of the type el' to feed to that iteratee. -- We thus send EOF to the internal Iteratee and propagate its result. -- This join function is useful when dealing with `derived iteratees' -- for embedded/nested streams. In particular, joinI is useful to -- process the result of stake, map_stream, or conv_stream below. joinI :: Monad m => IterateeGM el m (IterateeG el' m a) -> IterateeGM el m a joinI m = m >>= (\iter -> enum_eof iter >>== check) where check (IE_done x (Err str)) = liftI $ (IE_done x (Err str)) check (IE_done x _) = liftI $ (IE_done x EOF) check (IE_cont _) = error "joinI: can't happen: EOF didn't terminate" -- | It turns out, IterateeGM form a monad. We can use the familiar do -- notation for composing Iteratees -- instance Monad m => Monad (IterateeGM el m) where return x = liftI $ IE_done x (Chunk []) m >>= f = m >>== docase where docase (IE_done a (Chunk [])) = f a docase (IE_done a stream) = f a >>== (\r -> case r of IE_done x _ -> liftI $ IE_done x stream IE_cont k -> k stream) docase (IE_cont k) = liftI $ IE_cont ((>>= f) . k) instance MonadTrans (IterateeGM el) where lift m = IM (m >>= unIM . return) -- ------------------------------------------------------------------------ -- Primitive iteratees -- | Read a stream to the end and return all of its elements as a list stream2list :: Monad m => IterateeGM el m [el] stream2list = liftI $ IE_cont (step []) where step acc (Chunk []) = liftI $ IE_cont (step acc) step acc (Chunk ls) = liftI $ IE_cont (step $ acc ++ ls) step acc stream = liftI $ IE_done acc stream -- | Check to see if the stream is in error iter_report_err :: Monad m => IterateeGM el m (Maybe String) iter_report_err = liftI $ IE_cont step where step s@(Err str) = liftI $ IE_done (Just str) s step s = liftI $ IE_done Nothing s -- ------------------------------------------------------------------------ -- Parser combinators -- | The analogue of List.break -- It takes an element predicate and returns a pair: -- (str, Just c) -- the element 'c' is the first element of the stream -- satisfying the break predicate; -- The list str is the prefix of the stream up -- to but including 'c' -- (str,Nothing) -- The stream is terminated with EOF or error before -- any element satisfying the break predicate was found. -- str is the scanned part of the stream. -- None of the element in str satisfy the break predicate. -- sbreak :: Monad m => (el -> Bool) -> IterateeGM el m ([el],Maybe el) sbreak cpred = liftI $ IE_cont (liftI . step []) where step before (Chunk []) = IE_cont (liftI . step before) step before (Chunk str) = case break cpred str of (_,[]) -> IE_cont (liftI . step (before ++ str)) (str,c:tail) -> done (before ++ str) (Just c) (Chunk tail) step before stream = done before Nothing stream done line char stream = IE_done (line,char) stream -- | A particular optimized case of the above: skip all elements of the stream -- satisfying the given predicate -- until the first element -- that does not satisfy the predicate, or the end of the stream. -- This is the analogue of List.dropWhile sdropWhile :: Monad m => (el -> Bool) -> IterateeGM el m () sdropWhile cpred = liftI $ IE_cont step where step (Chunk []) = sdropWhile cpred step (Chunk str) = case dropWhile cpred str of [] -> sdropWhile cpred str -> liftI $ IE_done () (Chunk str) step stream = liftI $ IE_done () stream -- | Attempt to read the next element of the stream -- Return (Just c) if successful, return Nothing if the stream is -- terminated (by EOF or an error) snext :: Monad m => IterateeGM el m (Maybe el) snext = liftI $ IE_cont step where step (Chunk []) = snext step (Chunk (c:t)) = liftI $ IE_done (Just c) (Chunk t) step stream = liftI $ IE_done Nothing stream -- | Look ahead at the next element of the stream, without removing -- it from the stream. -- Return (Just c) if successful, return Nothing if the stream is -- terminated (by EOF or an error) speek :: Monad m => IterateeGM el m (Maybe el) speek = liftI $ IE_cont step where step (Chunk []) = speek step s@(Chunk (c:_)) = liftI $ IE_done (Just c) s step stream = liftI $ IE_done Nothing stream -- | Skip the rest of the stream skip_till_eof :: Monad m => IterateeGM el m () skip_till_eof = liftI $ IE_cont step where step (Chunk _) = skip_till_eof step _ = return () -- | Skip n elements of the stream, if there are that many -- This is the analogue of List.drop sdrop :: Monad m => Int -> IterateeGM el m () sdrop 0 = return () sdrop n = liftI $ IE_cont step where step (Chunk str) | length str <= n = sdrop (n - length str) step (Chunk str) = liftI $ IE_done () (Chunk s2) where (s1,s2) = splitAt n str step stream = liftI $ IE_done () stream -- ------------------------------------------------------------------------ -- | Iteratee converters for stream embedding -- The converters show a different way of composing two iteratees: -- `vertical' rather than `horizontal' -- -- The type of the converter from the stream with elements el_outer -- to the stream with element el_inner. The result is the iteratee -- for the outer stream that uses an `IterateeG el_inner m a' -- to process the embedded, inner stream as it reads the outer stream. type EnumeratorN el_outer el_inner m a = IterateeG el_inner m a -> IterateeGM el_outer m (IterateeG el_inner m a) -- | Read n elements from a stream and apply the given iteratee to the -- stream of the read elements. Unless the stream is terminated early, we -- read exactly n elements (even if the iteratee has accepted fewer). stake :: Monad m => Int -> EnumeratorN el el m a stake 0 iter = return iter stake n iter@IE_done{} = sdrop n >> return iter stake n (IE_cont k) = liftI $ IE_cont step where step (Chunk []) = liftI $ IE_cont step step chunk@(Chunk str) | length str <= n = stake (n - length str) ==<< k chunk step (Chunk str) = done (Chunk s1) (Chunk s2) where (s1,s2) = splitAt n str step stream = done stream stream done s1 s2 = k s1 >>== \r -> liftI $ IE_done r s2 -- | Map the stream: yet another iteratee transformer -- Given the stream of elements of the type el and the function el->el', -- build a nested stream of elements of the type el' and apply the -- given iteratee to it. -- Note the contravariance -- map_stream :: Monad m => (el -> el') -> EnumeratorN el el' m a map_stream f iter@IE_done{} = return iter map_stream f (IE_cont k) = liftI $ IE_cont step where step (Chunk []) = liftI $ IE_cont step step (Chunk str) = k (Chunk (map f str)) >>== map_stream f step EOF = k EOF >>== \r -> liftI $ IE_done r EOF step (Err err) = k (Err err) >>== \r -> liftI $ IE_done r (Err err) -- | Convert one stream into another, not necessarily in `lockstep' -- The transformer map_stream maps one element of the outer stream -- to one element of the nested stream. The transformer below is more -- general: it may take several elements of the outer stream to produce -- one element of the inner stream, or the other way around. -- The transformation from one stream to the other is specified as -- IterateeGM el m (Maybe [el']). The `Maybe' type reflects the -- possibility of the conversion error. -- conv_stream :: Monad m => IterateeGM el m (Maybe [el']) -> EnumeratorN el el' m a conv_stream fi iter@IE_done{} = return iter conv_stream fi (IE_cont k) = fi >>= (conv_stream fi ==<<) . k . maybe (Err "conv: stream error") Chunk -- ------------------------------------------------------------------------ -- | Combining the primitive iteratees to solve the running problem: -- Reading headers and the content from an HTTP-like stream --eM m (Either Line Line) line = sbreak (\c -> c == '\r' || c == '\n') >>= check_next where check_next (line,Just '\r') = speek >>= \c -> case c of Just '\n' -> snext >> return (Right line) Just _ -> return (Right line) Nothing -> return (Left line) check_next (line,Just _) = return (Right line) check_next (line,Nothing) = return (Left line) -- |_lines :: IterateeGM Line IO () print_lines = liftI $ IE_cont step where step (Chunk []) = print_lines step (Chunk ls) = lift (mapM_ pr_line ls) >> print_lines step EOF = lift (putStrLn ">> natural end") >> liftI (IE_done () EOF) step stream = lift (putStrLn ">> unnatural end") >> liftI (IE_done () stream) pr_line line = putStrLn $ ">> read line: " ++ line -- |. -- More generally, we could have used conv_stream to implement enum_lines. -- enum_lines :: Monad m => EnumeratorN Char Line m a enum_lines iter@IE_done{} = return iter enum_lines (IE_cont k) = line >>= check_line k where check_line k (Right "") = enum_lines ==<< k EOF -- empty line, normal term check_line k (Right l) = enum_lines ==<< k (Chunk [l]) check_line k _ = enum_lines ==<< k (Err "EOF") -- abnormal termin -- | Convert the stream of characters to the stream of words, and -- apply the given iteratee to enumerate the latter. -- Words are delimited by white space. -- This is the analogue of List.words -- It is instructive to compare the code below with the code of -- List.words, which is: -- -- >words :: String -> [String] -- >words s = case dropWhile isSpace s of -- > "" -> [] -- > s' -> w : words s'' -- > where (w, s'') = -- > break isSpace s' -- -- One should keep in mind that enum_words is a more general, monadic -- function. -- More generally, we could have used conv_stream to implement enum_words. -- enum_words :: Monad m => EnumeratorN Char String m a enum_words iter@IE_done{} = return iter enum_words (IE_cont k) = sdropWhile isSpace >> sbreak isSpace >>= check_word k where check_word k ("",_) = enum_words ==<< k EOF check_word k (str,_) = enum_words ==<< k (Chunk [str]) -- ------------------------------------------------------------------------ -- | Enumerators -- Each enumerator takes an iteratee and returns an iteratee -- an Enumerator is an iteratee transformer. -- The enumerator normally stops when the stream is terminated -- or when the iteratee moves to the done state, whichever comes first. -- When to stop is of course up to the enumerator... -- -- We have two choices of composition: compose iteratees or compose -- enumerators. The latter is useful when one iteratee -- reads from the concatenation of two data sources. -- type EnumeratorGM el m a = IterateeG el m a -> IterateeGM el m a type EnumeratorM m a = EnumeratorGM Char m a -- | The most primitive enumerator: applies the iteratee to the terminated -- stream. The result is the iteratee usually in the done state. enum_eof :: Monad m => EnumeratorGM el m a enum_eof iter@(IE_done _ (Err _)) = liftI iter enum_eof (IE_done x _) = liftI $ IE_done x EOF enum_eof (IE_cont k) = k EOF -- | Another primitive enumerator: report an error enum_err :: Monad m => String -> EnumeratorGM el m a enum_err str iter@(IE_done _ (Err _)) = liftI iter enum_err str (IE_done x _) = liftI $ IE_done x (Err str) enum_err str (IE_cont k) = k (Err str) -- | The composition of two enumerators: essentially the functional composition -- It is convenient to flip the order of the arguments of the composition -- though: in e1 >. e2, e1 is executed first -- (>.):: Monad m => EnumeratorGM el m a -> EnumeratorGM el m a -> EnumeratorGM el m a e1 >. e2 = (e2 ==<<) . e1 -- | The pure 1-chunk enumerator -- It passes a given list of elements to the iteratee in one chunk -- This enumerator does no IO and is useful for testing of base parsing enum_pure_1chunk :: Monad m => [el] -> EnumeratorGM el m a enum_pure_1chunk str iter@IE_done{} = liftI $ iter enum_pure_1chunk str (IE_cont k) = k (Chunk str) -- | The pure n-chunk enumerator -- It passes a given lift of elements to the iteratee in n chunks -- This enumerator does no IO and is useful for testing of base parsing -- and handling of chunk boundaries enum_pure_nchunk :: Monad m => [el] -> Int -> EnumeratorGM el m a enum_pure_nchunk str n iter@IE_done{} = liftI $ iter enum_pure_nchunk [] n iter = liftI $ iter enum_pure_nchunk str n (IE_cont k) = enum_pure_nchunk s2 n ==<< k (Chunk s1) where (s1,s2) = splitAt n str -- | The enumerator of a POSIX Fd -- Unlike fdRead (which allocates a new buffer on -- each invocation), we use the same buffer all throughout enum_fd :: Fd -> EnumeratorM IO a enum_fd fd iter = IM $ allocaBytes (fromIntegral buffer_size) (loop iter) where -- buffer_size = 4096 buffer_size = 5 -- for tests; in real life, there should be 1024 or so loop iter@IE_done{} p = return iter loop iter@(IE_cont step) p = do n <- myfdRead fd p buffer_size putStrLn $ "Read buffer, size " ++ either (const "IO err") show n case n of Left errno -> unIM $ step (Err "IO error") Right 0 -> return iter Right n -> do str <- peekCAStringLen (p,fromIntegral n) im <- unIM $ step (Chunk str) loop im p enum_file :: FilePath -> EnumeratorM IO a enum_file filepath iter = IM $ do putStrLn $ "opened file " ++ filepath fd <- openFd filepath ReadOnly Nothing defaultFileFlags r <- unIM $ enum_fd fd iter closeFd fd putStrLn $ "closed file " ++ filepath return r -- | HTTP chunk decoding -- Each chunk has the following format: -- -- > <chunk-size> CRLF <chunk-data> CRLF -- -- where <chunk-size> is the hexadecimal number; <chunk-data> is a -- sequence of <chunk-size> bytes. -- The last chunk (so-called EOF chunk) has the format -- 0 CRLF CRLF (where 0 is an ASCII zero, a character with the decimal code 48). -- For more detail, see "Chunked Transfer Coding", Sec 3.6.1 of -- the HTTP/1.1 standard: -- <> -- -- The following enum_chunk_decoded has the signature of the enumerator -- of the nested (encapsulated and chunk-encoded) stream. It receives -- an iteratee for the embedded stream and returns the iteratee for -- the base, embedding stream. Thus what is an enumerator and what -- is an iteratee may be a matter of perspective. -- -- We have a decision to make: Suppose an iteratee has finished (either because -- it obtained all needed data or encountered an error that makes further -- processing meaningless). While skipping the rest of the stream/the trailer, -- we encountered a framing error (e.g., missing CRLF after chunk data). -- What do we do? We chose to disregard the latter problem. -- Rationale: when the iteratee has finished, we are in the process -- of skipping up to the EOF (draining the source). -- Disregarding the errors seems OK then. -- Also, the iteratee may have found an error and decided to abort further -- processing. Flushing the remainder of the input is reasonable then. -- One can make a different choice... -- enum_chunk_decoded :: Monad m => Iteratee m a -> IterateeM m a enum_chunk_decoded = docase where docase iter@IE_done{} = liftI iter >>= (\r -> (enum_chunk_decoded ==<< skip_till_eof) >> return r) docase iter@(IE_cont k) = line >>= check_size where check_size (Right "0") = line >> k EOF check_size (Right str) = maybe (k . Err $ "Bad chunk size: " ++ str) (read_chunk iter) $ read_hex 0 str check_size _ = k (Err "Error reading chunk size") read_chunk iter size = do r <- stake size iter c1 <- snext c2 <- snext case (c1,c2) of (Just '\r',Just '\n') -> docase r _ -> (enum_chunk_decoded ==<< skip_till_eof) >> enum_err "Bad chunk trailer" r read_hex acc "" = Just acc read_hex acc (d:rest) | isHexDigit d = read_hex (16*acc + digitToInt d) rest read_hex acc _ = Nothing -- ------------------------------------------------------------------------ -- Tests -- Pure tests, requiring no IO> tell_iteratee_err "IO Err" fjque >> return () Right [] -> loop fjque buf Right sel -> process buf sel fjque -- get Fds from the jobqueue for the unfinished iteratees get_fds = foldr (\ (fd,iter) acc -> case iter of {IE_cont _ -> fd:acc; _ -> acc}) [] -- find the first ready jobqueue element, -- that is, the job queue element whose Fd is in selected. -- Return the element and the rest of the queue get_ready selected jq = (e, before ++ after) where (before,e:after) = break (\(fd,_) -> fd `elem` selected) jq process buf selected fjque = do let ((fd,IE_cont step),fjrest) = get_ready selected fjque n <- myfdRead fd buf buffer_size putStrLn $ unwords ["Read buffer, size", either (const "IO err") show n, "from fd", show fd] case n of Left errno -> unIM (step (Err "IO error")) >> loop fjrest buf Right 0 -> unIM (step EOF) >> loop fjrest buf Right n -> do str <- peekCAStringLen (buf,fromIntegral n) im <- unIM $ step (Chunk str) loop (fjrest ++ [(fd,im)]) buf -- round-robin tell_iteratee_err err = mapM_ (\ (_,iter) -> unIM (enum_err err iter)) -- Running these tests shows true interleaving, of reading from the -- two file descriptors and of printing the results. All IO is interleaved, -- and yet it is safe. No unsafe operations are used. testm1 = test_driver_mux line_printer "test1.txt" "test3.txt" testm2 = test_driver_mux print_headers_print_body "test_full2.txt" "test_full3.txt"
http://hackage.haskell.org/package/liboleg-2010.1.2/docs/src/System-IterateeM.html
CC-MAIN-2015-27
refinedweb
2,989
50.2
Getting Started This document introduces Touca SDK for JavaScript through a simple example. If you are new to Touca, consider reading our general quickstart guide first. Touca SDK for JavaScript is available as open-source on GitHub under the Apache-2.0 License. It is publicly available on NPM and can be pulled as a dependency using yarn or npm. npm install @touca/node In this tutorial, we will use Touca examples repository whose JavaScript examples already list this package as a dependency. Clone this repository to a local directory of your choice and proceed with building its JavaScript examples. git clone git@github.com/trytouca/examples.git "<YOUR_LOCAL_DIRECTORY>" cd "<YOUR_LOCAL_DIRECTORY>/js" yarn install yarn build For our first example, let us write a Touca test for a software that checks whether a given number is prime. You can find a possible first implementation in ./js/01_node_minimal/is_prime.ts of the examples repository. export function is_prime(input: number): boolean { for (let i = 2; i < input; i++) { if (input % i === 0) { return false; } } return 1 < input; } JavaScript. import { touca } from "@touca/node"; import { is_prime } from "./is_prime"; touca.workflow("is_prime_test", (testcase: string) => { const number = Number.parseInt(testcase); touca.check("is_prime_output", is_prime(number)); }); touca.run();: node 01_node_minimal/dist/is_prime_test.js -=" node 01_node_minimal/dist/is_prime_test.js -. node 01_node_minimal/dist/is_prime_test.js - JavaScript to test real-world software workflows.
https://touca.io/docs/sdk/js/quickstart/
CC-MAIN-2022-21
refinedweb
224
51.65
Just. Is it possible to access the wsdl document from a remote machine using the sql server user and not using NT-sql server user. Iam able to access using NT-sql server user BUT NOT THROUGH AN SQLUSER who has access permission set for endpoints. Thanks and Regards Sezhian.gk Hi Sezhian.gk, Regarding your question about accessing the WSDL document using a SQL Server user credentials, unfortunately, this is NOT possible at this time. We'll take your feedback into consideration for a future SQL release. Regarding using Perl to connect to the endpoint, please refer to an article written by my colleague up on MSDN, I have not tried it on a Linux box, but I would assume similar Perl behavior on both Windows and Linux. Regarding JAVA, you will again need to set the NT user credentials. Below is a snipet from a JAVA application we used to test (we used the tool to generate stub classes from the Simple WSDL document): org.tempuri.Interop_EPSoapStub binding; try { binding = (org.tempuri.Interop_EPSoapStub) new org.tempuri.Interop_EPLocator().getInterop_EP(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); junit.framework.Assert.assertNotNull("binding is null", binding); // Add credentials binding.setUsername("userName"); binding.setPassword("userPassword"); // Time out after a minute binding.setTimeout(60000); Thanks Jimmy! rgds SEzhian.gk is it possible to have a table/place to log every successful attempt to the web service? i might need to keep track when, what, who attempted my endpoint in my database. howyue, There are multiple ways to solve your scenario. You can log the info programmatically by adding code in the Stored Procedure (webmethod) to write this info to a table, which you can later query. An alternative method, is to use the SQL Server Profiler tool available with the SQL Server installation. The Profiler tool allows you to trace various things that is happening on the SQL instance. It should provide all the necessary traces you are looking for. If there is some trace you want but is currently missing from the Profiler tool, please feel free to send us the feedback. I am trying to do this with an ASP.Net application which does not generate a new class when the web reference is added. What do I need to do differently? Thanks, Brent Hi Brent, Please elaborate a little bit more on your situation. I'm assuming you are referring to writing an ASP.NET client application to connect to the backend Native Web Services endpoint. And, when adding the web reference, you are not seeing a class file generated for the web methods exposed on the endpoint. Please double check that the proper permissions have been granted to the user (most likely your user account) for the endpoint and stored procedures(webmethod), see. Potentially, one quick way to verify you have the proper permissions is to use a web browser and point it to the endpoint url (). You can search for the webmethod name in the server returned info. HTH, I'll preface this by saying I am very new to C# and ASP.Net, I am a db developer. I've implemented a class (WSData) for my SQL2005 Endpoints and throughout my application when I want to use them I declare a variable like: WSData ws = new WSData(); and then call my methods like: ws.functions.methodname(param1, param2) My wsdl is fine and contained in: App_Webreferences\aspendpointname\sqlpath.wsdl It all works fine with integrated security and clear ports using: System.Net.CredentialCache.DefaultCredentials But with Basic and SSL I keep getting 403:Forbidden. I assume I am not getting my my credentials into the SOAP header but the solution infers that there is a reference class which doesn't seem to exist with asp, only the wsdl file. My Class is below, any help you can provide is greatly appreciated, I am stumped. Sincerely, using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Net; /// <summary> /// Summary description for WSData /// </summary> [Serializable] public class WSData { private aspendpointname.sqlendpointname _ws = new aspendpointname.sqlendpointname(); public SqlSoapHeader.Security sqlSecurity = new SqlSoapHeader.Security(); public WSData() { //this works: //_ws.Credentials = System.Net.CredentialCache.DefaultCredentials; //my attempt at Basic/SSL which does not work: sqlSecurity.MustUnderstand = true; sqlSecurity.Username = "sqluser"; sqlSecurity.Password = "sqlpassword"; CredentialCache myCreds = new CredentialCache(); myCreds.Add(new Uri(_ws.Url), "Basic", new NetworkCredential("windowsuser", "windowspassword")); _ws.Credentials = myCreds; } public aspendpointname.sqlendpointname functions { get { return _ws; } } 403 generally implies that some level of permissions has not been granted. Looking at the sample code, it does not seem like the "SqlSoapHeader.Security" object is part of the "sqlendpointname" class. You will need to modify the generated class that was created from the WSDL document to include the following (as mentioned in the original post): Add the following member variable (as mentioned in Books Online) to the class generated when the web reference was added: public SqlSoapHeader.Security sqlSecurity; Add the following method markup (as mentioned in Books Online) to each and every method you wish to have SQL user authentication support: [System.Web.Services.Protocols.SoapHeaderAttribute("sqlSecurity")] From there, the WSData() code would look something like: _ws.sqlSecurity = new SqlSoapHeader.Security(); _ws.sqlSecurity.MustUnderstand = true; _ws.sqlSecurity.Username = "sqluser"; ... CredentialCache myCreds = new CredentialCache(); _ws.Credentials = myCreds; In a VS2005 website there is no generated class when a web reference is added. It somehow just uses the wsdl and discomap files in the App_WebReferences folder. When I add a web reference in a windows application it does generate a Reference.cs file so the provided solution can be implemented but when I add the web reference in a website there is no class generated so I have nothing to add the member variable to and nothing to add the method markup to. What am I missing? Brent, I had a chance to quickly look into how ASP.NET web site project in Visual Studio 2005 adds a web reference. Yes, it looks like it uses the WSDL to dynamically generate the proxy class. The SOAP header used for passing SQL user credentials to SQL Server is the same as the WS-Security header. It is potentially possible to install WSE 3.0 to automatically get this to work (). Below is what I quickly tried without using WSE 3.0. This is but one possible solution. What I did is modify the WSDL document that the ASP.NET project saved. Note: If you refresh the web reference any changes you make to the saved WSDL file WILL be lost. Warning aside, you'll need to update the WSDL file to add something like the following: 1) Add a namespace definition at the <wsdl:definitions> element: xmlns:wsse="" 2) In the <wsdl:types> element: <xsd:schema <xsd:complexType <xsd:simpleContent> <xsd:extension <xsd:attribute </xsd:extension> </xsd:simpleContent> </xsd:complexType> <xsd:complexType <xsd:sequence> <xsd:element <xsd:element </xsd:sequence> <xsd:complexType <xsd:element </xsd:element> <xsd:element </xsd:element> </xsd:schema> </wsdl:types> 3) Add an additional <wsdl:message> element to the <wsdl:message> section: <wsdl:message <wsdl:part </wsdl:message> 4) For the WebMethod that you are interested in supporting this header add the following to the <wsdl:binding><wsdl:operation><wsdl:input> element: <wsdl:input <soap:body <soap:header </wsdl:input> Now, in the .cs file you should get IntelliSense for the "Security" class and you can add code like: aspendpointname.sqlendpointname proxy = new aspendpointname.sqlendpointname(); proxy.Security = new aspendpointname.SecurityHeaderType(); proxy.Security.UsernameToken = new aspendpointname.UsernameTokenType(); proxy.Security.UsernameToken.Username = "sqluser"; proxy.Security.UsernameToken.Password = new aspendpointname.PasswordString(); proxy.Security.UsernameToken.Password.Value = "sqlpassword"; proxy.Security.UsernameToken.Password.Type = ""; At this point, you should be able to call the web method and the code will send the appropriate SOAP header to SQL Server. Thanks for the response, however this produces a 401:Unauthorized. Judging by earlier postings I assume this is because I am not sending the NT user / password with the request which seems necessary. Any thoughts? Yes, if you are getting a 401:Unauthorized, it is most likely eith the user does not have permissions to login to SQL Server or the application is not sending the NT user/password as part of the HTTP request. If the application is not sending the NT user credentials, you will likely need add something like the following to the code: CredentialCache myCreds = new CredentialCache(); myCreds.Add(new Uri(proxy.Url), "Basic", new NetworkCredential("userName", "pwd")); proxy.Credentials = myCreds; Please remember that the NT user needs to be a valid user for that machine (it can be a local user or a domain user). The SQL user credential within the WS-Security header needs to have permissions to the endpoint and associated SQL objects. If you are access to some network tracing tool or adding tracing code to ASP.NET, it will help in troubleshooting whether the application is issuing the correct request or if it is the server rejecting the request. Thank you so much, you really know your stuff! One thing I observed is that if the <soap:header (From your Sat May 19 2007 post) tag is in my methods in the wsdl file, my windows user does not need connect permissions to the endpoint or exec on the functions/ procedures but if that tag is not there it still works as long as the windows user has connect and execute permissions. Do you have any hints for a solution which will no require editing the wsdl file everytime the web references are updated? Again, thank you so much. I'm glad things worked out, even if it takes some extra coding. You are correct in that if you use the WS-Security header to pass in a SQL user credential, then the windows user specified on the HTTP request only needs to be a valid user credential and does not need to have SQL logon permission. We will use the SQL user credentials specified in the WS-Security header to logon to SQL Server. Currently, I do not have any solution for not requiring editing of the WSDL file. Note: I did not have a chance install WSE 3.0 and try your scenario again to see if by installing WSE 3.0, it will automatically generate code for sending WS-Security header. I am trying to set this up with an SSL port other than 443 but nothing seems to work. My code works fine using 443 but as soon as I change the "SSL_PORT = 443" line in my code to something other than 443, my server ceases to respond to the wsdl request and I get a "Cannot find server" error. My firewall is off. Is there a setting in SQL Server 2005 I need to change? Any assistance you could provide would be greatly appreciated. I would double check the configuration of Windows HTTP service. There were a couple of things that I did to make this work, but can't be sure if I needed to configure both or not. 1) Check that HTTP service is configured with the proper SSL certficate for the IP:Port combination. This can be done using the httpcfg.exe tool (sample syntax: httpcfg query ssl). If there isn't a SSL certificate configured for the Port, you can add the SSL certificate configuration by using "httpcfg set ssl ...". You may want to restart the HTTP service (net stop HTTP; net start HTTP). Note: you should stop SQL Server service first before stopping HTTP service. 2) If the above does not resolve the issue, please double check to see if the URL is reserved with the HTTP service. This can be done with "httpcfg query urlacl". If the URL is not reserved, please connect to SQL Server and execute the "sp_reserve_http_namespace" stored procedure (sample syntax: sp_reserve_http_namespace N''). The only other thing I did was since I had firewall running, I added a TCP port exception for the port I'm using for the SSL. For additional information on configuring SSL certificates for on HTTP service, please refer to the following MSDN topic For additional information on reserving URL namespace on HTTP service, please refer to the following MSDN topic Thanks Jimmy! I didn't have my ssl certificate configured for the port. The namespace reservation didn't seem to make a difference. Thanks again, Hai, I create a procedure and on that procedure i want to create a ENDPOINT. I am working in Client Machine.and when i execute this code i found an Error. -------------------- //prcjaj- procedure CREATE ENDPOINT prcjaj AS HTTP ( SITE='*', PATH='/JAJ', AUTHENTICATION=(BASIC), PORTS=(ssl) ) FOR SOAP (WEBMETHOD ''.'prcjaj'(NAME='JAJ.dbo.prcjaj'), LOGIN_TYPE = MIXED, WSDL=DEFAULT, SCHEMA = STANDARD An error occurred while attempting to register the endpoint 'prcjaj'. One or more of the ports specified in the CREATE ENDPOINT statement may be bound to another process. Attempt the statement again with a different port or use netstat to find the application currently using the port and resolve the conflict. I followed all steps and got success in each steps except in ssl certificate step. SSL certificate gets added successfully in the website but only an error like "the name on the certificate does not match with the web site name" after this error i created a ssl cert. with same name inside the certificate and try to consume the created end point remotely or locally but the exception remains there. I gave add to the popup window for security/settings, i am able to access the webmethod of the endpoint but it generates an exception like "the ssl certificate of server is not compatible with the procedure of consuming secure end point". Please try to resolve my problem... Now I am getting this exception "the underlying connection was closed: could not establish trust relationship for the ssl/tls secure channel" on trying to get data through published website from sql server 2005 using ssl-integrated-mixed login type http end point. Help plz... Thanks in advance -Radha Krishna Prasad Hi Ashis, By default, when you specify the "PORTS=(ssl)", SQL Server will attempt to bound to port 443. It is possible that IIS or another application is already listening on port 443. As the message suggested, you can run "netstat" from the command prompt to see which process is already listening on which port. C:\>netstat -ano Active Connections Proto Local Address Foreign Address State PID TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4 TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4 Once you know which application is already listening on port 443, you can either stop that application or change the SQL Server endpoint to listen on a different port. To specify a non-default port to listen on you will need to add "SSL_PORT" to the Endpoint syntax. So the endpoint syntax will look like: AS HTTP ( SITE='*', PATH='/JAJ', AUTHENTICATION=(BASIC), PORTS=(ssl), SSL_PORT=1000 ) FOR SOAP (WEBMETHOD ''.'prcjaj'(NAME='JAJ.dbo.prcjaj'), LOGIN_TYPE = MIXED, WSDL=DEFAULT, SCHEMA = STANDARD Hi Radha, It is a little confusing on the name in which the SSL certificate should be issued to. Hopefully this will help clear things up. Example: Machine name is "myMachine" The SSL certificate used on the SQL Server machine is issued to "myMachine.domain.com" The client application should then specify the following as the HTTP URL: "" If you were to specify: "" thinking that you are already in the same domain and can reach the machine, you will get the "the name on the certificate does not match with the web site name" error message you are seeing. The reverse is also true. So, if the SSL certificate is issued to "myMachine" and the URL you are specifying is "..." you will also get this error. NOTE: The SSL certificate name is suppose to be the same as the machine name. It has not relationship to the ENDPOINT name. Additional information on how to manage SSL certificates can be found at thanks for ur last reply.. I am facing another problem with it... I will go later for SSL-INTEGRATED-MIXED Login. Right now I have to do for BASIC-CLEAR. So can we not access a sql http endpoint from a proxy wall type LAN ? Please try to resolve it... Sorry, I hope I didn't confuse you. In you most recent post dated Dec. 29, 2007, you mentioned that you have to do for Basic-CLEAR endpoint. Unfortunately, SQL Server 2005 SOAP endpoints do not support BASIC authentication over CLEAR http. Basic authentication is only supported over SSL http. Mixed login is also only supported over SSL http. Assuming that the endpoint was created for BASIC auth and SSL, the WSDL can be retrieved at or Also, make sure the proxy/firewall has the endpoint port open to allow traffic to the endpoint. I am really very sorry for writing BASIC-CLEAR instead of INTEGRATED-CLEAR... I was not confused but did mistake in writing the last post. The issue is :-- I have to do for INTEGRATED-CLEAR--Port-80. Could you please help in this issue ? Regarding the HTTP 500/501 error, there may be a couple of possibilities: 1) WSDL support is not enabled on the endpoint (double check to make sure the endpoint syntax looks something like: ( WSDL=DEFAULT, ... 2) Try stopping IIS to see if somehow IIS is receiving the HTTP request instead of SQL Server BTW, which OS is SQL Server running on? Generally "Object reference not set to an instance of an object" is a client side error message that typically means no data received from the server to create the object. I recommend if possible, capture the HTTP network messages between your client and the server to see what is being sent to the server and what the server returns. It will help to ensure that the client sends the proper message to SQL Server. It will also help to figure out what SQL Server is having trouble with. If you must use INTEGRATED-CLEAR on port 80 and the SQL Server is running on a different domain from the client machines, one other possible method is: - both the client machine and SQL Server machine must be running Windows OS - create the same local user with the same password on both machines - instead of specifying Basic auth, you would specify NTLM: myCreds.Add(new Uri(proxy.Url), "NTLM", System.Net.CredentialCache.DefaultCredentials.GetCredential(new Uri(proxy.Url), "NTLM")); If you prefer to use Windows user logins instead of SQL Server user logins, you do not need to use the SqlSoapHeader.Security optional SOAP Header. Additional information about .Net Framework client authentication type setting please refer to Below is the Endpoint we created in a machine over LAN in our company: /****** Object: Endpoint [GetPerson] Script Date: 01/04/2008 11:00:54 ******/ CREATE ENDPOINT [GetPerson] AUTHORIZATION [sa] STATE=STARTED AS HTTP (PATH=N'/Person', PORTS = (CLEAR), AUTHENTICATION = (INTEGRATED), SITE=N'localhost', CLEAR_PORT = 8080, COMPRESSION=DISABLED) FOR SOAP ( WEBMETHOD 'PersonList'( NAME=N'[test].[dbo].[GetPerson]' , SCHEMA=DEFAULT , FORMAT=ALL_RESULTS), BATCHES=DISABLED, WSDL=N'[master].[sys].[sp_http_generate_wsdl_defaultcomplexorsimple]', SESSIONS=DISABLED, SESSION_TIMEOUT=60, DATABASE=N'test', NAMESPACE=N'', SCHEMA=STANDARD, CHARACTER_SET=XML) When we try to access the Endpoint from the same machine as, it returns the XML absolutely fine. However, when we try to access it from another machine over the LAN as, it returns a HTTP 400 Bad Request page. I do not quite understand the concept of granting Connect permissions to the Endpoint. In our case, what accounts should be granted permissions to the Endpoint? Hi Samik, In your sample, the endpoint is specified with "SITE = N'localhost'". This tells the HTTP listener to only route HTTP messages sent to "" to this endpoint. All other HTTP messages sent to "" or http://<IP address>/Person" will not be routed to this endpoint. The possible values for the "SITE" propery is as follows: [ SITE = { ' * ' | ' + ' | 'webSite' } ] Specifies the name of the host computer. If SITE is omitted, the asterisk is the default. If sp_reserve_http_namespace was executed, pass <hostpart> to the SITE keyword. For example, if sp_reserve_http_namespace N'' was executed, specify SITE='MyServer' in the CREATE ENDPOINT statement. * (asterisk) Implies that a listening operation applies to all possible host names for the computer that are not otherwise explicitly reserved. + (plus sign) Implies that a listening operation applies to all possible host names for the computer. webSite Is the specific host name for the computer. For additional information about how the "SITE" property affects endpoints, please refer to My recommendation is to specify '*' in development stages. When you want to lock down on security, specify the machine name as the "SITE" value. I did follow your steps, but issue remains same. The issue is: I am able to access the endpoint created on a live IP containing server with no firewall/proxy from any point those dont come under a proxy or firewall, but I am not able to access the endpoint from a LAN with proxy/firewall. Radha Krishna Prasad From your post dated Jan. 05, 2008, it seems that the same SQL Server SOAP endpoint is working fine if the client machine is not behind a proxy or firewall, but once the client machine is behind a proxy or firewall, things no longer works. At this moment, it looks like SQL Server is properly configured and working. The question is how come sometimes the network is causing client machine behind a proxy or firewall to fail accessing the same SQL Server. I highly suggest using a network trace tool to see the difference between a working client machine and a non-working client machine. Hopefully from there you can ask the network admin to help you troubleshoot the problem. Hello, I've followed the steps as outlined above. When when I test the web service using IE (by typing just so I get the description back), the browser asks me for a username and password. I supply the windows user/pasword that I've set up, but I get back a 403 error (not authorized) any Ideas on how to fix this? Thank you. Gustavo Can any one help to resolve my problem below ? I tried to access the CRM web service from the .net compact framework from a mobile application. When I intialise the crmservice and when I put Sevice.Execute(), it is throwing error that " An Unexpected Error Occurred" . When the code is run in ordinary Windows application, it is working fine. Can any one help me on this?I am using .net compact framework 2.0 with SP2 and windows mobile 6 professional emulator code is below : CrmAuthenticationToken token = new CrmAuthenticationToken(); token.AuthenticationType = 0; token.OrganizationName = "Orgcrm"; CrmService service = new CrmService(); service.CrmAuthenticationTokenValue = token; service.Url = ""; service.Credentials = System.Net.CredentialCache.DefaultCredentials; WhoAmIRequest req = new WhoAmIRequest(); WhoAmIResponse res = (WhoAmIResponse)service.Execute(req); ERROR : An Unexpected error occurred - System.web.Services.protocols.SoapException Hi Krithi, Unfortunately, the error message you are receiving is just a generic failure message. I suggest contacting the .Net Frameworks Compact team to see if there are difference in support between .Net Frameworks and Compact Frameworks. Here are some general web service troubleshooting ideas: - Narrow down to see if the issue is when sending the request or when receiving the response. - Capture the network traffic between the 2 machines to see what client and server are sending. -Jimmy From reading through these posts, it seems that a stand alone Java program may not be able to POST across the LAN to a SQL2005 endpoint, that is setup for NTLM. Let me know if that is correct. I have been trying to make this work, and was optimistic when I was able to view the WSDL page across the LAN by adding the Autenticator Class/code to my test program, and setting credentials in it. However, that uses the url.getcontent() method instead of the url.openconnection(), and write methods used for POST. Getting a java.io.IOException: Server returned HTTP response code: 500. If it should be possible to do the POST, do you have suggestions, on how to trap the full HTTP trafic being posted? I don't seem to be getting logged in the HTTPERR logfile. If you would like to receive an email when updates are made to this post, please register here RSS Trademarks | Privacy Statement
http://blogs.msdn.com/sql_protocols/archive/2005/11/03/488527.aspx
crawl-002
refinedweb
4,112
56.55
lsargent - 5:09 am on Feb 25, 2012 (gmt 0) I've got this figured out about half way. I'm trying to accomplish both adding a 1+ button to my site and adding organizational microdata for company name, address, phone number, etc I have all the item types & item properties set correctly in the html body for organizational data. I also have the appropriate item properties in the head tag for the 1+ button snippets. The confusing part is how to set the html tag above the head tag in my page. The Google 1+ setup page says: <!-- Update your html tag to include the itemscope and itemtype attributes --> <html itemscope But in the Google forum a Contributor was saying you don't actually add the itemscope or itemtype in the html tag, but rather in the div element in the page (which I do have setup correctly). She states to add the schema.org namespace: xmlns:schema="" ...in the html tag. Right now my html tag is displayed as: <html?
http://www.webmasterworld.com/printerfriendlyv5.cgi?forum=21&discussion=4422951&serial=4421585&user=
CC-MAIN-2013-48
refinedweb
172
71.55
This site uses strictly necessary cookies. More Information If I do something like this: public class FixFBXOptions : AssetPostprocessor { public void OnPostprocessModel(GameObject g) { // Never import materials by default. var modelImporter = assetImporter as ModelImporter; modelImporter.importMaterials = false; } } ... on adding an FBX to the project, it'll have no materials. That's fine and what I want. But if I then click 'import materials' and apply, the checkbox just gets un-checked and no materials are imported. The same thing happens using OnPreprocessModel. OnPreprocessModel What I really want is a way to run some code to set import options once, on a project member adding the asset to the project for the first time, but for that code to never run again and to let people change the options afterwards. Is that possible using AssetPostprocessor? I don't want to have to write a custom 'add asset to project' dialogue - I imagine that will end up being rather hacky. Note: this isn't the same as when an instance of Unity sees the file for the first time, so the trick I've seen of checking if the asset database can load the file I mark an asset as processed in AssetPostprocessor class 0 Answers Access MecAnim animation clips in a AssetPostprocessor 1 Answer How to skip already imported textures on AssetPostprocessor change? 3 Answers How do you add AnimClips at import time correctly? 1 Answer Grab one child of an imported FBX asset 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/1251171/can-assetpostprocessor-change-defaults-just-for-fi.html?sort=oldest
CC-MAIN-2021-49
refinedweb
247
52.9
Visual Studios 2017 Community or higher. Github: There are still a quite a few folk making ASP.NET pages using webforms that are resistant to making the jump to Entity Framework; specifically the new Core 2. I would highly advocate jumping on the wagon with Core 2 when you start your journey if, for nothing else, Razor pages. These are a blessing for anyone using Webforms up to 4.0 .NET in terms of getting your bearings, simplifying what needs to be done, and ease of use. Some reading: Background information .NET Core 2 helps standardize across platforms, opens up an advanced world of APIs, and is the big step forward past the MVC period. There is a better setup for file organization, and things are less 'magical' (seems to be the term being batted around). The Razor page CSHTML and CS code behind pairing really keep home the single functionality concept. You have a page, and what you do on that page is typically contained inside the code behind. Not in some other 'controller' file, or stashed elsewhere. You open up any given page and you should know where to find the functions. Easy-peasy in my books. The important part of Razor pages is they function super similar to an ASPX page. There's an HTML client side and a CS 'code behind' that should look familiar to most folk. The trick is Microsoft really opened up how you can tweak, change, add, and modify the page. You can add in middleware, set up extensions, change routing, and all sorts of complex tasks that would have taken a long path around the bush previously. With all that customization there comes a huge concern on how does one just make a page work. How can I show anything to a user, and maybe even shuffle data to a database. I will concede there is a bit of leg work to get things setup, but once that is done more advanced page additions become a breeze with repetition of concepts and design. Razor pages also do away with the complex folder structure of MVC. That always irked me when I was trying to update and old webform and smelled of too much extra work for something that should be simple. Razor views are all contained in one folder called 'Pages'. The display view and the code behind CS. The concept to keep in mind is this is MVVM.. Model to View to ViewModel. The way I wrapped my head around that was the concept that your Model generates on a page load. This is then given to the View (the client page) to work with on render. the View then gives back a View Model on a post for the code behind to interact with. Yeah yeah there maybe someone who complains about that mangled description but I kept that flow of events in my head when learning and it kept me orientated correctly. Much like MVC .NET Razor pages use the '@' sign EVERYWHERE in the View to get handles on models, C# code (like IF statements, FOR loops, etc) usage, and so on. If you know a bit of MVC, or look for help, it should work similar across the board. Read: Razor Syntax The only "magical" area that tripped me up were the use of "Tag Helpers" and naming multiple functions on post. Typically if you were to have only one Post on a page you wouldn't need a tag helper and your post function would look like this: public async Task<IActionResult> OnPostAsync() ... and your form's post's submit button would look like this: <input type="submit" value="Add" /> If you were to have multiple post options - be it with grid editing, adding data, deleting data, etc you just tweak each function name to add the 'asp-page-handler''s value and you are set. Two different forms's submits.. <button type="submit" asp-Delete</button> <input asp- Their corresponding post functions. See how the asp-page-handler information is added? ASP.NET now knows where to find corresponding functions for post actions! public async Task<IActionResult> OnPostDeleteAsync() { .. } public async Task<IActionResult> OnPostAddAsync() { .. } Outline For this tutorial a few things are going to be accomplished. First setting up a project. I'll borrow the setup for the default project, cut back on some of the cruft, and we should have a good platform to add our own functionlity. Second, I will add an 'in memory' database based off a simple user class. This DB will reside ONLY in memory and is recreated each time the project starts. A little magical, but for a quick example works extremely well. Third, I will show how to get data from this data table, dispaly it, and add to it. Makin the full rounds from the Model to the View, and the View back with the ViewModel. Tutorial 1. Start by opening up Visual Studios 2017. Go to File -> New Project -> Visual C# -> Web.. and click 'ASP.NET Core Web App. I happen to be on the .NET 4.6.1, but you future folk may have something newer. I give it a name, and a folder location. Clicking Ok brings up a new project template. Make sure the drop downs are set to .NET Core, and ASP.NET Core 2.0. Click 'web application', and then ok. Here is the basic template. You can certainly hit F5 and start it to see what is happening. If you have telemetry insights on this may take a few moments longer. 2. From here delete the contact and error pages.. we don't need those. Double clicking on the 'index' should open up the HTML side. Delete everything below the first six lines. I don't need it, and it will just get in the way. You can go a step further into the _layout and remove the nav bar line for the contact page as well. The _layout is something applied to all pages so if you need a footer, added javascript references, header info, menus, etc they should all go here. Great.. from here everything should still compile nicely. Let's dig into getting data to and from our database! 3. To start we need to add the application's database context. This will be omni-present for the project and will be the center point of pointing the project to the right tables for CRUD operations. Right click on the project in the Solution Explorer and click add -> new -> class. Call it 'AppDbContext'. Make sure it inherits DBContext, add the required Using, and a few basic functions. using Core2Walkthrough_Basic.Data; using Microsoft.EntityFrameworkCore; namespace Core2Walkthrough_Basic { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { } } } 4. Jump over to the 'startup.cs'. This is the key point where you can add the middle ware, extra functionality, and all sorts of bells and whistles to your project. For our needs we will add a service to start up in the 'configure services' function. This will setup an 'in memory database' to be used, and tie to to our AppDbContext. services.AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase("TestMemoryDB")); 5. Save all of that, and now create a folder called 'Data'. Inside create a class called 'USERS'. This should be a fairly one to one representation of any database. ASP.NET will us this as the 'create table' plans for an in memory database to hold our test data while running. Give it a few properties, save it, and we are done with the database part and setup work in general. using System; using System.ComponentModel.DataAnnotations; /* * About - Basic class to be made into an in memory db for the example. */ namespace Core2Walkthrough_Basic.Data { public class USERS { public int ID { get; set; } [Display(Name = "Name")] public string NAME { get; set; } public DateTime DATE_ENTERED { get; set; } } } The [Display(Name = "Name")] is called a 'data annotation'. Data annotations are great helpers to standardized your information across pages. In this case any label that needs to display a name for our property 'name' will use what is inside the "". It could be "Nam123e" and that is what would be shown. If nothing is there then it uses the property name. Sometimes that is ok, and sometimes you want something more user friendly. 6 Before we can get the page to display some data, head back to the AppDbContext and add one line for a property to link the DbContext to the USER data class. // The bridge between the db and data object to send data to. public DbSet<USERS> USER_DBSet { get; set; } 7. Let's get the data displayed and some user functionality built! Expand the index.cshtml and open up the cshtml.CS code behind. First things first - add a readonly variable for the database context. If I need DB interaction this is always my first line. Add a message to display to the user on a good save, a list of users to give to the View to display, a single instance of our user class to hold the data from the View's Model on the way back from post, and that's it. Again.. the list goes TO the client to be rendered. The BindProperty means on post anything added in there survives the journey back to be acted on. In this case a save. Easy so far.. a handle to our DB context, a string to show messages, a list to give to the page on render, and an object to get user info on the way back. This comprises the 'index model'. Add our constructor to set the DB context, and the 'on get async' does our first database interaction. Its only job is to get ALL the data from the context's USER and stash it in the list to be given to the client to render. One.. single.. line. The post is a little more complex. It checks if the model, as a whole, is valid. Gives a date to our single object back from the journey, adds it to the db context, which then saves it to the table in memory. If all goes well a happy message is displayed, and the page is refreshed.. which means the 'on get async' happens, all the data is loaded (even the new), and is shown back to the client. Pretty slick! namespace Core2Walkthrough_Basic.Pages { public class IndexModel : PageModel { private readonly AppDbContext _db; [TempData] public string Message { get; set; }// no private set b/c we need data back public IList<USERS> UserList { get; private set; }// private set so don't need to have data back.. just to show. [BindProperty] // survive the journey _BACK_ from the user. public USERS UserNew { get; set; }// private not set because the data is needed back //Constructor public IndexModel(AppDbContext db) { //Get the database context so we can move data to and from the tables. _db = db; } //When the page is being fetched, load some data to be rendered. public async Task OnGetAsync() { UserList = await _db.USER_DBSet.ToListAsync(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } //Snag the current date time. UserNew.DATE_ENTERED = DateTime.Now; //Add it to the News database set. _db.USER_DBSet.Add(UserNew); //Update it. await _db.SaveChangesAsync(); //Inform the user of much success. Message = $"User added!"; //Send it back to the admin page. return RedirectToPage(); } } } 8. Open up that CSHTML page and lets get some displaying to happen. Again, remember everything needs the @ sign to reference the model handed to the view. At the top we can show any messages from the model. Setup a table to display our data, and use a for loop to cycle though our list and display what is there. Finally have a form post setup with a single label for a name and a submit. The submit will trigger a post and anything in that textbox should be added to our in memory database. Notice the label. This will go back to our USER data class and check for any 'data annotations'. If there is something to be had for 'Display' this will use that text instead of the property name. @page @model IndexModel @{ ViewData["Title"] = "Home page"; } <h3><font color="lime"> @Model.Message</font></h3> @* Table to display the data *@ <table class="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>DATE_ENTERED</th> </tr> </thead> <tbody> @* Common for loop being used to help display HTML! *@ @foreach (var temp in Model.UserList) { <tr> <td>@temp.ID </td> <td>@temp.NAME</td> <td>@temp.DATE_ENTERED</td> </tr> } </tbody> </table> @*Entry for the user input*@ <form method="post"> <label asp-</label> <input asp- <input type="submit" value="Add" /> </form> 9. When it runs the grid shows no data from our in memory DB, but if when type in a name and click 'add' that changes! Congratulations.. you have a functioning Core 2 Razor project that shuffles data from a database to the client to render, and accepts posted data back to the database. An intermediate challenge would be to expand functionality, explore sessions, setup a connection to an existing database, and see about using custom queries instead of our DB context. ASP.NET - Razor Pages and Core 2. Advanced. 1 of 2 ASP.NET - Razor Pages and Core 2. Advanced. 2 of 2
https://www.dreamincode.net/forums/topic/408395-aspnet-razor-pages-core-2-and-entity-framework-basics/
CC-MAIN-2020-05
refinedweb
2,225
74.79
This message was posted using Email2Forum by ShL77. This message was posted using Email2Forum by ShL77. HI, Can you please provide me sample code ,how to create a document and insert objects like ppt/excel/tst/pdf into ms word document. I am struck with this from last 15days. Thanks in Advance. Hi, <?xml:namespace prefix = o Thank you for your interest in Aspose.Words. Unfortunately, inserting new OLE objects into Word documents and updating existing OLE objects is not supported at the moment. Inserting an OLE object usually requires the host application and probably cannot be done by Aspose.Words. What is supported is preserving OLE objects in documents. That is if you open an MS Word document and then save it (possibly in another MS Word format) then OLE objects are preserved. You can also access objects programmatically, extract their data and preview image. However, creating new OLE objects is not supported. Best regards. The issues you have found earlier (filed as WORDSNET-1206) have been fixed in this .NET update and this Java update. This message was posted using Notification2Forum from Downloads module by aspose.notifier. (2)
https://forum.aspose.com/t/reg-embedding-of-object-in-ms-word-using-java/73698
CC-MAIN-2022-21
refinedweb
190
50.73
The BPEL validator is designed to validate BPEL 2.0 source files. In addition the BPEL validator checks the executable BPEL processes - support for abstract processes is not implement. The validator code is in the plugin org.eclipse.bpel.validator which must be present for validation support to be included. In either situation, the validator is run "on save" of a BPEL resource and it produces a list of markers as a result on the resources which have errors in them (which are primarily the BPEL resources). The validator plugin defines a "BPEL marker" which is essentially a problem marker. As all markers in Eclipse these are displayed in the Problem View . The resulting markers are shown in text editors and in the BPEL editor and doubleclicking the error in the Problem View will navigate to the problem location. The general approach was to write the validator with no direct dependency on Eclipse, the EMF BPEL model, or other workbench things. The reason was that it might be useful in other places - so no direct dependency ... Having said that, the stake in the ground was a simple INode interface to the model nodes - your basic "tree" node type of concept. This adapts very easily to DOM nodes (into which BPEL source is transformed inititially), and to a slightly lesser extend to EMF object nodes, since they do, for the most part, follow that pattern. The leap of faith here is that any BPEL entity model would follow that type of a pattern ("toma-toe" vs. "tomato") and that suitable adapters can be build if needed. Validation then becomes a two pass walk through this adapted model tree where validators are written to the specific BPEL model nodes (so there is a VariableValidator , an UntilValidator , a WhileValidator , etc). The input to the validator is a starting node and something we call IModelQuery (explained later), and the output is a list or problems that have been found. Why a 2 pass walk ? Because walking is simple and predictable and the 1 st pass captures certain state that is only useful on the 2 nd pass. The code is actually so simple, that it might as well be included here. Take a look at org.eclipse.bpel.validator.model.Runner public class Runner { /** The root node from where validation should be started */ INode fRoot; /** The query interface to our model */ IModelQuery fModelQuery; /** empty list of problems */ IProblem[] fProblems = {}; /** * Return a brand new shiny instance of a runner. The runner's purpose is to validate * the nodes in the tree starting at node passed. * * @param query the model query * @param root the root node. */ public Runner ( IModelQuery query, INode root) { fRoot = root ; fModelQuery = query; } /** * Perform the validation run. * * @return list of problems found. */ public IProblem[] run () { // Create a depth first iteration from the root node ArrayList iteratorList = new ArrayList (32); ArrayList validatorList = new ArrayList (256); // start at the root node iteratorList.add(fRoot); // 1. Generate the list of validators to call, in order while (iteratorList.size() > 0) { INode nextNode = iteratorList.remove(0); Validator validator = nextNode.nodeValidator(); if (validator != null) { validatorList.add(validator); validator.setModelQuery(fModelQuery); } // the facaded object will tell us what children to include in the walk List children = nextNode.children(); if (children.size() > 0) { iteratorList.addAll(0, children); } } // Pass 1 for(Validator validator : validatorList) { validator.validate(Validator.PASS1); } ArrayList problems = new ArrayList ( 64 ); // Pass 2 // On the validators that have been run, perform the final rule pass. for(Validator validator : validatorList) { validator.validate(Validator.PASS2); for(IProblem problem : validator.getProblems() ) { problems.add (problem); } } return problems.toArray( fProblems ); } } Some checks can be made using only this simple INode model. For example, can this node have that node as a child, and are certain attributes set on a given node. Other checks are a little more tricky. For example, how do you determine the type of a variable ? Well, you have to lookup it up someplace. So the question becomes where and how ? From the perspective of the validator, this becomes an interface that it will query against the actual implementation model (we called it IModelQuery ). So the validator code would say, lookup this XSD type, and the implementor of the interface will perform the query against the prevailing models. The return of the "lookup this XSD type" is an INode which adapts the actual model node (either EMF or DOM). The validator code can then answer simple questions about this returned node via its INode interface. For example: are you resolved , or do you exist ? Type compatibility checks are also delegated to IModelQuery and are answered by the implementing model using whatever means it has. XPath expressions are a little tricker in that you have to walk the XPath expression trees. In path expressions, you may know what variable is being used (and hence you can query its type from the model), then walk the path expression. Again an abstraction of that concept is present in the model query interface so the validator code says: can I make the next step while the implementation of it will say yes or no . Once a problem is found, a message is generated and the appropriate information is put into a problem and then the issue becomes how to pin the problem to the right location. Once again this is delegated to the IModelQuery interface which will fill the appropriate items like EMF paths, XPaths, line numbers, etc, that will help pin the problem to a particular location in the entity model. Rules are just special methods on a validator object which may be annotated and are discovered once (by reflection). The only 2 run-time things that are interesting about a rule method on a validator object are 2 items: The full rule annotation is shown below. The other fields of the annotation are used for generating completeness documentation from the validator code. package org.eclipse.bpel.validator.model; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ARule { /** The date in which this rule was added */ String date() default "01/01/1970"; /** The static analysis reference code * @return the static analysis code. */ int sa () default 0; /** Brief description of the rule */ String desc() default "No description"; /** The author to bug about this */ String author() default "Unknown"; /** Tags are used for marked execution of rules */ String tag () default "pass1"; /** the order in which the rule will be executed */ int order () default 0; }A VariableValidator segment is shown below. Here we check to make sure that a variable has at least a messageType, type, or element set. There is a rule to check the NCName of the variable (no dots) and a rule to check the message type. ... /** * Rule to check the name of the variable. */ @ARule( author = "michal.chmielewski@oracle.com", date = "9/14/2006", desc = "Checks that variable NCName further does not contain a period (.) in the name.", sa = 24 ) public void rule_CheckName_1 () { // Must be a valid NCName ... mChecks.checkNCName(mNode, ncName, AT_NAME ); IProblem problem ; // ... and not contain a . if (ncName.indexOf('.') >= 0) { problem = createError(); problem.setAttribute(IProblem.CONTEXT, AT_NAME); problem.fill("BPELC_VARIABLE__NO_DOT", //$NON-NLS-1$ ncName); } } /** * Rule to check the type of the variable. * * It can be either: * 1) MessageType * 2) Element * 3) Type * * Only one must be defined, more then one cannot be defined. * */ @ARule( author = "michal.chmielewski@oracle.com", date = "9/14/2006", desc = "Variable type specification (either element, messaageType, or type).", sa = 25 ) public void rule_CheckType_2 () { int typeCount = 0; IProblem problem; // Check messageType String messageType = mNode.getAttribute(AT_MESSAGE_TYPE); if (messageType != null) { typeCount += 1; fMessageTypeNode = mModelQuery.lookup(mNode, IModelQuery.LookupNode.MESSAGE_TYPE, messageType); } // Check element String element = mNode.getAttribute(AT_ELEMENT); if (element != null) { typeCount += 1; fElementNode = mModelQuery.lookup(mNode, IModelQuery.LookupNode.XSD_ELEMENT, element ); } // Check Type (XMLType) String type = mNode.getAttribute ( AT_TYPE ); if (type != null) { typeCount += 1; fTypeNode = mModelQuery.lookup(mNode, IModelQuery.LookupNode.XSD_TYPE, type ); } // Missing and too many types if (typeCount == 0) { problem = createError( ); problem.setAttribute(IProblem.CONTEXT, AT_TYPE); problem.fill( "BPELC_VARIABLE__NO_TYPE", ncName); //$NON-NLS-1$ } else if (typeCount > 1) { problem = createError( ); problem.setAttribute(IProblem.CONTEXT, AT_TYPE); problem.fill( "BPELC_VARIABLE__NO_TYPE", ncName); //$NON-NLS-1$ } } /** * Check message type node */ @ARule( sa = 10, desc = "Make sure that Message Type is visible from the import(s)", author = "michal.chmielewski@oracle.com", date = "01/25/2007" ) public void rule_CheckMessageTypeNode_4 () { if (fMessageTypeNode == null) { return ; } mChecks.checkAttributeNode (mNode, fMessageTypeNode, AT_MESSAGE_TYPE, KIND_NODE ); setValue("type",fMessageTypeNode); } ... package org.eclipse.bpel.validator.model; import javax.xml.namespace.QName; /** * @author Michal Chmielewski (michal.chmielewski@oracle.com) * * @param The of the factory * @date Jan 5, 2007 * */ public interface IFactory { /** * Generic factory to create something based on a QName. * * @param qname the QName of the node. * @return the node validator for this QName */ T create ( QName qname ) ; } For a list of rules and coverage of the static analysis checks look here . Back to the top
http://www.eclipse.org/bpel/developers/validator/
CC-MAIN-2018-13
refinedweb
1,464
57.67
I am working on a program that will simulate a simple student information system. The program will need to behave as follows: a - add a student b - display all student information c - display a single students information d - generate a grade report q - quit Currently I am working on the "add a student" function. The process I must follow is as follows: 1. Prompt the user to add the name of a student (Last, First). 2. The addUser() function will call the checkUser() function to open a text file and search to see if that student exists. 3. If the user does not exist, a generateID() function is called that will generate a random, five digit ID. 4. Finally, the addUser() function will prompt the user to enter a series of test scores and homework scores. All information (name, ID, scores) is then written to the student.txt file. Simple enough. However, I am trying to test out a few lines of code that will actually search the text file for me. I need it to be in two separate functions (hence why I have divided it up), so here is my code as of now: and my student.txt file is as follows:and my student.txt file is as follows:Code:#include <iostream> #include <fstream> #include <string> using namespace std; int search(void); int main (void) { cout << search() << endl; return 0; } int search(void) { fstream checkStream; string searchString; string lineOfText; cout << "Please enter a valid name to search for: "; getline(cin, searchString); checkStream.open("student.txt", ios::in); for(;;) { getline(checkStream, lineOfText); if (checkStream.eof()) break; if (lineOfText.find("searchString", 0) != string::npos) { return 1; break; } } cout << "Done searching..." << endl; checkStream.close(); return 0; } However, my code will not output a found message when the string is found. Something is not being passed correctly. Can anyone give me some insight on this problem?However, my code will not output a found message when the string is found. Something is not being passed correctly. Can anyone give me some insight on this problem?Code:Sparrow, Jack Turner, Will Snyder, Quinn Snyder, Melody Basset, Theodore q.
https://cboard.cprogramming.com/cplusplus-programming/94995-using-fstream-find.html
CC-MAIN-2017-09
refinedweb
356
64.51
![if !(IE 9)]> <![endif]> Recently, while telling you about check of another project, I have constantly repeated that it is a very quality code and there are almost no errors in it. A good example is analysis of such projects as Apache, MySQL and Chromium. I think you understand why we choose such applications for analysis. They are known to all of us while nobody wants to hear about horrible things found in the diploma design of student Jack. But sometimes we check projects that just come to hand. Some of such projects leave painful impressions in my delicate and vulnerable soul. This time we checked Intel(R) Energy Checker SDK (IEC SDK). Intel Energy Checker SDK is a small C project containing just 74500 lines of code. Compare this number to the WinMerge project's size of 186 000 lines or size of the Miranda IM project together with the plugins (about 950 000 lines). By the way, while we are just in the beginning of the article, try to guess how many 'goto' operators there are in this project. Have you thought of a number? If yes, then we go on. All in all, this is one of those small projects unknown to a wide audience. When I look at a project of that kind, the following analogy occurs to me. You may walk on good familiar streets for a long time without seeing any puddles. But as you make a turn and look into a yard, you just not only see a puddle but a puddle so big that you don't understand how you can pass it without getting your feet wet. I wouldn't say that the code is horrible, there are cases much worse. But look at it yourself. There are only 247 functions in the whole project. You will say it's few, won't you? Of course, it's few. But the size of some of them embarrasses me. Four functions have size of more than 2000 lines each: V553 The length of 'pl_open' function's body is more than 2000 lines long. You should consider refactoring the code. pl_csv_logger productivity_link.c 379 V553 The length of 'pl_attach' function's body is more than 2000 lines long. You should consider refactoring the code. pl_csv_logger productivity_link.c 9434 V553 The length of 'main' function's body is more than 2000 lines long. You should consider refactoring the code. cluster_energy_efficiency cee.c 97 V553 The length of 'main' function's body is more than 2000 lines long. You should consider refactoring the code. pl2ganglia pl2ganglia.c 105 The following method of getting the length of a directory's name is also significant: #define PL_FOLDER_STRING "C:\\productivity_link" #define PL_PATH_SEPARATOR_STRING "\\" #define PL_APPLICATION_NAME_SEPARATOR_STRING "_" ... pl_root_name_length = strlen(PL_FOLDER_STRING); pl_root_name_length += strlen(PL_PATH_SEPARATOR_STRING); pl_root_name_length += application_name_length; pl_root_name_length += strlen(PL_APPLICATION_NAME_SEPARATOR_STRING); pl_root_name_length += PL_UUID_MAX_CHARS; pl_root_name_length += strlen(PL_PATH_SEPARATOR_STRING); I understand that this fragment is not crucial to speed and there's no reason to optimize the string length calculation. But just from the mere love to art, the programmer could have created a macro "#define STRLEN(s) (sizeof(s) / sizeof(*s) - 1)". My sense of beauty suffers even more because of strings containing "C:\\". The following macros alert me: #define PL_INI_WINDOWS_FOLDER "C:\\productivity_link" #define PL_INI_WINDOWS_LC_FOLDER "c:\\productivity_link" #define PLH_FOLDER_SEARCH _T("C:\\productivity_link\\*") However, this code does what it should and we won't focus our attention on the programming style. It is the number of errors found by PVS-Studio in a project of such a small size - this is what scares me most. And keep in mind that far not all the 74000 code lines were checked. About one third of the code is intended for LINUX/SOLARIS/MACOSX and is stored in #ifdef/#endif code branches that were not checked. The impassible wood of #ifdef/#endif's is just a different story but I promised not to speak of code design anymore. If you wish, you may look through the source codes yourselves. The code of IEC SDK has collected a diverse bunch of mistakes one can make when handling arrays at the low level. However, mistakes of this kind are very typical of the C language. There is code addressing memory outside an array: V557 Array overrun is possible. The '255' index is pointing beyond array bound. pl2ganglia pl2ganglia.c 1114 #define PL_MAX_PATH 255 #define PL2GANFLIA_COUNTER_MAX_LENGTH PL_MAX_PATH char name[PL_MAX_PATH]; int main(int argc, char *argv[]) { ... p->pl_counters_data[i].name[ PL2GANFLIA_COUNTER_MAX_LENGTH ] = '\0'; ... } Here we deal with a typical defect of writing the terminal zero outside the array. The code must look this way: p->pl_counters_data[i].name[ PL2GANFLIA_COUNTER_MAX_LENGTH - 1 ] = '\0'; There are errors of structure clearing. V568 It's odd that the argument of sizeof() operator is the '& file_data' expression. pl_csv_logger productivity_link_helper.c 1667 V568 It's odd that the argument of sizeof() operator is the '& file_data' expression. pl_csv_logger productivity_link_helper.c 1831 V512 A call of the 'memset' function will lead to underflow of the buffer 'pconfig'. pl_csv_logger productivity_link_helper.c 1806 Here is an example of such incorrect emptying: int plh_read_pl_folder(PPLH_PL_FOLDER_INFO pconfig) { ... WIN32_FIND_DATA file_data; ... memset( &file_data, 0, sizeof(&file_data) ); ... } The code intended for file search will work badly when you use the WIN32_FIND_DATA structure with rubbish inside it. But I suspect that hardly anybody is interested in the Windows version of this work of programming art. For instance, the code compiles in the "Use Unicode Character Set" mode although it is not fully intended for this. It seems that nobody ever thought of this - they just created the project for Visual Studio and the "Character Set" setting by default defines use of UNICODE. As a result, there are a dozen of fragments where strings are cleared only partially. I'll cite only one sample of such code: V512 A call of the 'memset' function will lead to underflow of the buffer '(pl_cvt_buffer)'. pl_csv_logger productivity_link_helper.c 683 #define PL_MAX_PATH 255 typedef WCHAR TCHAR, *PTCHAR; TCHAR pl_cvt_buffer[PL_MAX_PATH] = { '\0' }; int plh_read_pl_config_ini_file(...) { ... ZeroMemory( pl_cvt_buffer, PL_MAX_PATH ); ... } Well, there are, however, places where disabling UNICODE won't help. Something strange will be printed here instead of text: V576 Incorrect format. Consider checking the second actual argument of the 'wprintf' function. The pointer to string of wchar_t type symbols is expected. producer producer.c 166 int main(void) { ... char *p = NULL; ... #ifdef __PL_WINDOWS__ wprintf( _T("Using power link directory: %s\n"), p ); #endif // __PL_WINDOWS__ ... } Let me explain this. The wprintf function waits for a string of the "wchar_t *" type while it is a string of the "char *" type that will be passed to it. There are other errors and small defects similar to this one: V571 Recurring check. The 'if (ret == PL_FAILURE)' condition was already verified in line 1008. pl_csv_logger pl_csv_logger.c 1009 if(ret == PL_FAILURE) { if(ret == PL_FAILURE) { pl_csv_logger_error( PL_CSV_LOGGER_ERROR_UNABLE_TO_READ_PL ); I see no reason in enumerating all the defects we have found. If somebody of you wants, I may give you a registration key to check the project and study the messages. I will also send error descriptions to SDK's authors. Do you remember I asked you to think of a number of 'goto' operators found in the project? So, I think your number is far from the truth. There are 1198 goto operators altogether in the project, i.e. one goto operator for every 60 code lines. And I thought that style had been forgotten for a long time. Well, and what did the author actually want to say by writing this article? Intel URGENTLY needs to pay the greatest attention to PVS-Studio. :-) Dear Andrey and PVS-Studio team, I first want to re-iterate my thank you for bringing to my attention my code's imperfections. Using your tool was really a great opportunity to improve the code's quality. Error humanum est, does apply to all of use, and especially to me in this case! I wrote almost all of the Energy Checker code so I think that it could be interesting to share my experience with your tool with your potential customers. Beside the great insight it provides - I will come back to this later on - I really appreciated the good integration into Microsoft Visual Studio 2005. This is important to me because I could use the software as-is, "out of the box" and work to remove my bugs immediately. On the downside, I would essentially quote the speed of the analysis. I believe that your company is working on improving it, so I am confident that the use of PVS-Studio will be even smoother in the future. Now let's get to the point. PVS-Studio slapped me on the hand for my mistakes. And this is what I expect from such software. Sure our code runs OK, with good performance and fulfilling its role (until the next bug report, of course). But in many cases, I was feeling guilty that that some code section just work because I was lucky. Applying the correction, makes them work because they are correct now. And when such mistake happens to be in a macro, it is a great pleasure to see the error count drop down drastically just after an incremental analysis. Another mistake of mines that struck me was that copy-and-past can be a false friend. It helps to speed up crafting a new section of code, but you need to be very vigilant doing so. Obviously in some cases, I was not enough vigilant. PVS-Studio woke me up. Again, thank you for your feedback, your software's insight and for letting me try PVS-Studio. Jamel Tayeb, IEC SDK ...
https://www.viva64.com/en/b/0106/
CC-MAIN-2018-17
refinedweb
1,595
65.12
Zach McCormick Data-driven engineering strategist. Consultant at Trailblazing Technology, Inc. MESSAGE ZACH 5.0 2 Sessions $30.00 For every 15 minutes). EXPERTISE I understand almost* every feature of Python 2 and 3. I've used it for both web development (Django and Flask), data mining/scraping (Celery, Scrapy), and data science/machine learning (scikit-learn, OpenCV) *The only things that I would have issues debugging are newly introduced Python coroutines for asynchronous programming in Python (i.e. "async def my_function():... await some_thing"). I started learning Android when it was first released to the public. I've developed numerous apps as freelancer (many for music festivals, many for restaurants, coffee shops, etc., and several feature-specific ones such as an app for using the camera to detect neonatal jaundice or an app using bluetooth piconets to establish communication networks when other connectivity is down). I also extensively know about the Android OS and have modified all layers (C/C++ Linux core to Java framework) to implement a rules engine on top of the OS to enforce rulesets to enable/disable functionality based on contextual information like location, connectivity, time, authentication, etc. My experience with Java is largely with Android, but I've built a few apps with Java/Spring as well, and am intimately familiar with Jetty and Tomcat (and JBoss/Websphere tangentially) for deploying them. I am intimately familiar with the inner workings of the JVM and have modified JVM internal code to support interesting features (such as applying machine learning to instruction processing to increase branch prediction offline for the model to be applied online). I have worked with the Android OS in C++ modifying bits and pieces of the kernel + supporting tools (such as making custom gcc and gdb toolchains work for ARM/Android devices). I have worked with the Android OS in C++ modifying bits and pieces of the kernel + supporting tools (such as making custom gcc and gdb toolchains work for ARM/Android devices). I regularly use different flavors of SQL for relational DB work with web applications and occasionally for mobile applications. My expertise lies in general features of Postgres and MySQL, with some experience with writing external functions and using plugins (like postgres-fdw or MySQL query rewrite plugins) I have used Django for 3 years in web app development, for both multi-site and single-site, APIs, and regular Django sites. I've used nearly every templating system and have created frameworks within Django for both infrastructure and feature needs. Nearly everything that I have done on the web has been hosted with AWS. I am familiar with VPC, EC2, Elastic Beanstalk, RDS, and many of the managed services AWS offers. I always use Git as my version control system of choice. I can normally solve almost all Git problems, including sometimes bringing repositories back from the dead (i.e. git reset --hard) Nearly everything that I have done on the web has been hosted with AWS. I am familiar with VPC, EC2, Elastic Beanstalk, RDS, and many of the managed services AWS offers. I am skilled at Ubuntu/Debian server administration and have set up numerous servers for different reasons. Web server deployments and intranet setup are my two specialties. REVIEWS Average Rating 5.0 (1 rating) Awesome mentor! 1 Pretty good 0 Could've been better 0 Needs improvement 0 Unsatisfactory 0 VIEW MORE REVIEWS It was the first session for the both of us, and it went well! I presented a problem, and Zack was able to identify that my environment was not set up properly. He instructed me to re-install everything, and showed me how to get the bot running. A suggestions for everyone on here, use Zoom's Recording features so you can refer back to your session! Thanks Zach! 3Q Jul 13, 2016 Codementor On-demand Marketplace for Software Developers
https://www.codementor.io/zachmccormick
CC-MAIN-2017-13
refinedweb
646
53
No, don't trouble yourself. Instead, I would appreciate if you could try applying this patch (to the current RB-1.7 head): Advertising diff --git a/CMakeLists.txt b/CMakeLists.txt index 00c51cf..5c22704 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -147,6 +147,10 @@ if (CMAKE_COMPILER_IS_CLANG OR CMAKE_COMPILER_IS_APPLECLANG) APPLECLANG_VERSION_STRING VERSION_GREATER 6.1) add_definitions ("-Wno-unused-local-typedefs") endif () + if (CLANG_VERSION_STRING VERSION_EQUAL 3.9 OR CLANG_VERSION_STRING VERSION_GREATER 3.9) + # Don't warn about using unknown preprocessor symbols in #if'set + add_definitions ("-Wno-expansion-to-defined") + endif () endif () I don't have 3.9 installed, so I can't easily test it myself. This should at least disable the warnings, and then we can fix the code at our leisure, ideally waiting until after homebrew adds a llvm39 package so it's easy for me to test as I go. If this works for you, I'll merge it. > On Oct 12, 2016, at 9:37 AM, Ashley Retallack <ashley.retall...@gmail.com> > wrote: > > Cool, > > Well I can start looking in to it if you like in the mean time I'll use a > lower version. > > Cheers > > Ash > > On 12 October 2016 at 16:15, Larry Gritz <l...@larrygritz.com > <mailto:l...@larrygritz.com>> wrote: > I haven't tried clang 3.9 (though I use 3.8 regularly). > > Ugh, that's unfortunate. There are many places where we say things like > > #if A_SOMETIMES_DEFINED > 3 > > instead of the more verbose > > #if defined(A_SOMETIMES_DEFINED) && A_SOMETIMES_DEFINED > 3 > > I used to think the former was illegal but recently discovered that all the > compilers seem to accept it without complaint and figured maybe it was fine > all along and it was my understanding of C++ that was wrong. So I got in the > habit of preferring this compact form and using it frequently. But this error > implies that it was wrong all along and the compilers were very forgiving, > but perhaps in the ever-tightening warning landscape it has finally fallen. > > We'll need to scour the whole codebase for constructs like that and replace > them with the wordier version. > > Thanks for the alert. > > > On Oct 12, 2016, at 7:27 AM, Ashley Retallack <ashley.retall...@gmail.com > > <mailto:ashley.retall...@gmail.com>> wrote: > > > > Hi all, > > > > Was wondering if anyone has tried building oiio 1.7 with clang 3.9.0. > > > > I've been trying and get the following: > > > > src/include/OpenImageIO/hash.h:54:37: error: macro expansion producing > > 'defined' has undefined behavior > > [-Werror,-Wexpansion-to-defined] > > #if OIIO_CPLUSPLUS_VERSION >= 11 || OIIO_MSVS_AT_LEAST_2013 > > > > I can successfully build with gcc 4.8.4, just wanted to try and get clang > > working. > > > > Any help much appreciated. > > > > Ash > > _______________________________________________ > > Oiio-dev mailing list > > Oiio-dev@lists.openimageio.org <mailto:Oiio-dev@lists.openimageio.org> > > > > <> > > -- > Larry Gritz > l...@larrygritz.com <mailto:l...@larrygritz.com> > > > _______________________________________________ > Oiio-dev mailing list > Oiio-dev@lists.openimageio.org <mailto:Oiio-dev@lists.openimageio.org> > > <> > > _______________________________________________ > Oiio-dev mailing list > Oiio-dev@lists.openimageio.org > -- Larry Gritz l...@larrygritz.com _______________________________________________ Oiio-dev mailing list Oiio-dev@lists.openimageio.org
https://www.mail-archive.com/oiio-dev@lists.openimageio.org/msg03880.html
CC-MAIN-2018-05
refinedweb
505
51.85
The.. Comments are marked by # characters. Each non comment line represents one polyinstantiated directory. The fields are separated by spaces but can be quoted by " characters also escape sequences \b, \n, and \t are recognized. The fields are as follows: polydirinstance_prefixmethodlist. mntopts=value - value of this flag is passed to the mount call when the tmpfs mount is done. It allows for example the specification of the maximum size of the tmpfs instance that is created by the mount call. See mount(8) for details.. #/ level root,adm /var/tmp /var/tmp/tmp-inst/. pam_namespace(8), pam.d(5), pam(7) The namespace.conf manual page was written by Janak Desai <janak@us.ibm.com>. More features added by Tomas Mraz <tmraz@redhat.com>.
https://www.commandlinux.com/man-page/man5/namespace.conf.5.html
CC-MAIN-2020-10
refinedweb
124
61.63
22 August 2012 06:23 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The country’s naphtha output decreased by 8.6% year on year to 2.17m tonnes in July, while its total output in the first seven months of the year declined by 1.6% year on year to 17m tonnes, the data showed. Ethylene output declined by 6.7% year on year to 1.20m tonnes in July, while its total output in January-July dropped by 3.8% to 8.78m tonnes compared with the same period a year earlier, according to data from China Petroleum and Chemical Industry Federation (CPCIF). Benzene output decreased by 6.4% year on year to 497,000 tonnes in July, while its total output in January-July fell by 0.4% to 3.68m tonnes compared with the same period a year earlier. China’s crude oil output in July, however, increased by 1.4% year on year to 17m tonnes in July and its total output in January-July rose by 1.7% year on year to 118m tonnes. Prices for 65 products covered by ICIS Chemease, an ICIS Service in Bulk soft-foam polypropylene glycol (PPG) showed the largest price increase of 10% while polymer methyl di-p-phenylene isocyanate (MDI) showed an increase of 7%. Phthalic anhydride (PA) and toluene di-isocyanate (TDI) both increased by 3% each, according to data from Chemease. Butadiene prices saw the largest decrease of 13%, while prices for oil-extended styrene butadiene rubber (SBR) and butadiene rubber (BR)-9000 fell by 8% and 7% respectively. ?xml:namespace> Source: CPC
http://www.icis.com/Articles/2012/08/22/9588854/chinas-major-petrochemical-july-output-declines-on-weaker.html
CC-MAIN-2014-15
refinedweb
267
68.36
An opinionated URL change handler for Cerebral cerebral-module-router An opinionated URL change handler for Cerebral 1.x For Cerebral 2 use @cerebral/router instead. How to use How it works The Cerebral Router is one of the least invasive routers out there. You can attach the router module to already written cerebral application and it will just work. And you will be able to disable router completely in environments where you do not need it at all(eg, React Native app). Though we are making few considerations: - Signal bound to route should be treated as potential entry point. Make sure that your signal would be able to run on app start. - Your app will prepare initial state either during server side rendering or within signals ran in sync with modulesLoadedevent. Addressbar updates while navigating an app Router listens to signalTrigger and signalStart events. Addressbar will be updated if signal is bound to route in config. Router uses url-mapper's stringify method to get url from given route and signal payload. Trigger correspondent signal with payload while normal app startup Router listens to modulesLoaded event and schedules correspondent signal trigger if there was no predefined signal execution (see below). Router uses url-mapper's map method to get matched signal and payload to pass. Matched signal trigger would be delayed until signals started by other modules on modulesLoaded event is finished, if any. Trigger correspondent signal on history traversal (back and forward navigation) Router listens history traversal events using addressbar library. It would trigger matched signal if url has changed. Just works with devtools time traveling and recorder Both devtools and recorder uses internal cerebral mechanism of predefined signal run. Router will update addressbar if any predefined signal was bound to route. So your addressbar will be kept in sync even using recordings and time travel debugging. Routes config Routes config is object passed as first argument. Use path-to-regexp format routes as keys and signal name to bound as value. Use '/*' as key to make a catch all route definition. You can nest config object. Route will be concatenation of keys: Router({ '/foo': 'foo', // `/foo` <==> `foo` '/bar': { '': 'bar', // `/bar` <==> `bar` '/baz': 'baz' // `/bar/baz` <==> `baz` } }) Application startup As said before router will autodetect any signal ran in sync with modulesLoaded event. Router will not trigger if there was remembering of state occured before modulesLoaded event. We strongly recommend not to run your initial signals in that case too. You can set some isLoaded flag in state store within initial signal and chech it before run. Or remove modulesLoaded event listener if there was predefinedSignal emitted. import NewTodo from './modules/NewTodo'; import List from './modules/List'; import Footer from './modules/Footer'; import appStarted from './signals/appStarted'; export default (options = {}) => { return (module, controller) => { module.modules({ new: NewTodo(), list: List(), footer: Footer() }); module.signals({ appStarted }) function init () { controller.getSignals().app.appStarted({}, { isSync: true }); } controller.once('predefinedSignal', function () { controller.removeListener('modulesLoaded', init) }) controller.once('modulesLoaded', init) }; }
https://reactjsexample.com/an-opinionated-url-change-handler-for-cerebral/
CC-MAIN-2018-05
refinedweb
496
58.99
Answered by: CS0246: The type or namespace name 'Constants' could not be found I'm using Visual Web Express and i'm including a c# file named Constants to access the common functionalities. The C# file is included in App_Code directory and when i access the c# file using the code below it shows the error: Compiler Error Message: CS0246: The type or namespace name 'Constants' could not be found (are you missing a using directive or an assembly reference?) public partial class _Default : System.Web.UI.Page Line 20: { Line 21: Constants cons = new Constants(); Line 22: ArrayList fileContents = new ArrayList(); Line 23: string connString = ""; What is the problem??? How to use the c# file in App_Code directory??Friday, February 24, 2006 1:57 PM Question Answers You must specify the namespace in your usings or explicit specify it by decleration: With using keyword SpecificFriday, February 24, 2006 2:01 PM All replies You must specify the namespace in your usings or explicit specify it by decleration: With using keyword SpecificFriday, February 24, 2006 2:01 PM The Visual WebDeveloper Express Edition does not generate any namespace for any file or form.If i use a common namespace called as Transaction and if i put all code inside that for all the files including the c# file inside App_Code and if i use using Transaction; namespaceTransaction {public partial class _Default : System.Web.UI.Page {Constants cons = new Constants(); Then an error showing Transaction not found. Tell me how to use the namespace for files inside App_Code and those files which are outside App_Code and .aspx files.???What is the actual problem which i encounter in Web Express Edition. Also without any namespace if i run using inbuilt Asp.Net development server it is running.Only in iis if i run using it is showing the error. Willfin David.Saturday, February 25, 2006 3:21 AM For those who are interested in... I was encountering exactly the same problem and had to apply an unpleasantly dirty solution to evade that problem. Following situation: * IIS-Web called SampleWeb * APP_CODE contains the file Sample.cs * Subdirectory inside the root directory called SubDir1 --> this subdirectory is declared as separate "Application" inside the IIS6.0 Settings (you know, the folder icons becomes a gear wheel) When I create a common WebForm-File, e.g. Test1.aspx inside the root folder of the web site and refer to the .cs-file as SampleMySample = new Sample(); the pretty Test1.aspx file works like a charm - no error messages, nothing - pure beauty. And now the funny part of the story: When I conduct the same procedure (exactly the same way) INSIDE the subdirectory SubDir1 that painful error message CS0246: The type or namespace name 'Sample' could not be found I was trying around different approaches (using namespaces, adding assemblies, etc.) , but it didn't work. The only way I could get rid of that error was to place the file outside the SubDir1 -subdirectory (directly in the root dir). By the way: I cannot remove the Application-settings off the SubDir1-subdirectory due to uncountably many legacy reasons. I don't particularly expect a solution for that anomaly, but somehow or other it would be greatly interesting to hear any kind of suggestion. To all the anguished poor souls called C# developers.Tuesday, February 20, 2007 5:04 PM - If I am not wrong , each application needs its own App_Code folder. So maybe to copy the App_Code folder from root to your SampleWeb folder solves your problem.Wednesday, March 07, 2007 8:16 AM
https://social.msdn.microsoft.com/Forums/en-US/1abe3ef9-999c-477f-9296-78fc353006b0/cs0246-the-type-or-namespace-name-constants-could-not-be-found?forum=Vsexpressvcs
CC-MAIN-2015-32
refinedweb
597
52.39
Teaching Languages# COMMENTS Java’s never been my favorite language either for using or for teaching. As a programmer, after starting with languages like Fortran and Pascal, I really cut my teeth with C. More recently, Python has been my go to language to get real work done. From a teaching point of view most languages have good points and bad ones. When the AP class went from Pascal to C++ I lamented losing the simplicity and the low cost of entry. On the other hand, C++ gave us objects (not that I’m a big OOP guy), separate files, the ability to use tons of real world libraries and more. Moving to Java simplified things in a number of ways but removed memory management. If we didn’t teach that along with the stack frame in our Systems class, I think our kids would be missing something very important. I was reminded of some of Java’s limitations as a teaching language over the past couple of days. As posted earlier, I had my AP students create their own class to mimic the Java ArrayList. Before introducing the ArrayList in Java, I wanted to introduce generics: public class myList Turns out, you can no longer do this. After doing some searching, there does appear to be a way to get this effect but it was certainly not something I wanted to do with my classes. I was looking for something more pedagogically sound - an easy way to show the concept and a way to springboard to an ArrayList. Oh well… So, we finished ArrayLists and I was mapping out a plan for Monday. I thought Radix sort would be cool – we already introduced using an array to tally votes when we did the mode. This seemed to be a natural extension. It would combine Arrays and ArrayLists and illustrate when each is appropriate. First the kids would set up an array of 10 buckets, each being an ArrayList: public class Buckets { ArrayList Unfortunately, Java type safety once again reared its ugly head. OK, maybe not ugly to a programmer, but ugly to a teacher. You can’t do it. You can do it with an old school ArrayList without the generic: ArrayList[] buckets = new Arraylist[10]; but of course, this leaves you open to type mismatch problems. Once again, Java provides a convoluted workaround that might be fine for a professional programmer, but for a student, it would be nuts. I might go ahead with the Radix sort lesson anyway, we’ll see, but it would be nice if I could teach this level of course without having to fight the implementation language.Tweet
https://cestlaz.github.io/posts/2013-11-23-teaching-languages/
CC-MAIN-2020-10
refinedweb
445
69.11
James Houghton; April 8th, 2014 houghton@mit.edu One of the challenges of dealing with GDELT is that its size makes implementation in a SQL database challenging. It is easier (although slower) to extract a subset of the data that we wish to work with, and do our actual data investigation afterwards. If we're interested in data broken down by date, we have it easy: GDELT files are provided this way. If instead we want to look at a single country, we have some work to do. This notebook parses through each of the GDELT files, one at a time, extracts the relevant lines, and exports them again to a smaller set of csv files. It then gives the option to load these files into a Pandas DataFrame, pickle the result, and remove the intermediate files. There are certainly more computationally efficient methods for doing this, but this one works well enough. import requests import lxml.html as lh gdelt_base_url = '' # get the list of all the links on the gdelt file page page = requests.get(gdelt_base_url+'index.html') doc = lh.fromstring(page.content) link_list = doc.xpath("//*/ul/li/a/@href") # separate out those links that begin with four digits file_list = [x for x in link_list if str.isdigit(x[0:4])] In this example, we pull out all of the rows with a specific country code, and create a set of files which mirrors that of GDELT itself in quantity and format. Each output file is smaller than its corresponding input file. As we're pulling out rows based upon location, we'll use GDELT cells: These use the FIPS country codes, for inconvenience. The general algorithm we will follow can be loosely described as: - Check and see if the files are available locally (We assume we can afford to keep a local copy of the compressed files, so that we don't have to continually ping the gdelt server.) - If not, get the files from the web - Unzip the compressed raw GDELT file - For each resulting CSV file (probably only one) - Create and open an output file - For each line of the input file - Read into a string - Split string by tab delimiter - Check for the desired values in the appropriate list indexes - If they are not there, continue the loop - If the are there, write the line to the output file - Increment a current-file counter - Close the input and output files - Delete the input file We reset the infilecounter and outfilecounter external to the main algorithm cell so that if the algorithm encounters an error, and quits, we can pick up where we left off. We choose to check for the files, and potentially download them once for each file that we try to open, as opposed to doing all file collection in advance. That way, we can start to run additional code as soon as possible. This will help with debugging as we'll "fail fast". Remember to set the local_path to somewhere you're happy to store large files. infilecounter = 0 outfilecounter = 0 import os.path import urllib import zipfile import glob import operator local_path = '/Users/me/Desktop/GDELT_Data/' fips_country_code = 'UK' for compressed_file in file_list[infilecounter:]: print compressed_file, # if we dont have the compressed file stored locally, go get it. Keep trying if necessary. while not os.path.isfile(local_path+compressed_file): print 'downloading,', urllib.urlretrieve(url=gdelt_base_url+compressed_file, filename=local_path+compressed_file) # extract the contents of the compressed file to a temporary directory print 'extracting,', z = zipfile.ZipFile(file=local_path+compressed_file, mode='r') z.extractall(path=local_path+'tmp/') # parse each of the csv files in the working directory, print 'parsing,', for infile_name in glob.glob(local_path+'tmp/*'): outfile_name = local_path+'country/'+fips_country_code+'%04i.tsv'%outfilecounter # open the infile and outfile with open(infile_name, mode='r') as infile, open(outfile_name, mode='w') as outfile: for line in infile: # extract lines with our interest country code if fips_country_code in operator.itemgetter(51, 37, 44)(line.split('\t')): outfile.write(line) outfilecounter +=1 # delete the temporary file os.remove(infile_name) infilecounter +=1 print 'done' We may be content to use the data we just sampled into csv files in its present state. However, if we are working in python, it is convenient to load them into a DataFrame, save that DataFrame to a pickle, and delete the temporary files. This can save space on the disk, and make our future analysis of the data more simple. Our algorithm here is simple - we build dataframes out of each of the temporary files, and then merge them into one big dataframe. We save that big dataframe, and delete the temporary files. We use a helper file here which lists the column names. You can download the file to your working directory with this link: import glob import pandas as pd # Get the GDELT field names from a helper file colnames = pd.read_excel('CSV.header.fieldids.xlsx', sheetname='Sheet1', index_col='Column ID', parse_cols=1)['Field Name'] # Build DataFrames from each of the intermediary files files = glob.glob(local_path+'country/'+fips_country_code+'*') DFlist = [] for active_file in files: print active_file DFlist.append(pd.read_csv(active_file, sep='\t', header=None, dtype=str, names=colnames, index_col=['GLOBALEVENTID'])) # Merge the file-based dataframes and save a pickle DF = pd.concat(DFlist) DF.to_pickle(local_path+'backup'+fips_country_code+'.pickle') # once everythin is safely stored away, remove the temporary files for active_file in files: os.remove(active_file)
http://nbviewer.ipython.org/github/JamesPHoughton/Published_Blog_Scripts/blob/master/GDELT%20Wrangler%20-%20Clean.ipynb
CC-MAIN-2015-14
refinedweb
896
53.61
Java programming language version of the codelab. The version in the Kotlin Java, object-oriented design concepts, and Android Development Fundamentals. In particular: RecyclerViewand adapters - SQLite database and the SQLite query language - Threading and ExecutorService - It. This codelab provides all the code you need to build the complete app.. Otherwise, you may have to wait until all the updates are done. - An Android device or emulator.). - Add the following compileOptionsblock inside the androidblock to set target and source compatibility to 1.8, which will allow us to use JDK 8 lambdas later on: compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } - Add the following code to the end of the dependenciesblock: //: ext { roomVersion = '2.2.1' archLifecycleVersion = '2.2.0' coreTestingVersion = '2.1.0' materialVersion = '1.0.0' } - Sync your project. The data for this app is words, and you will need a simple table to hold those values: Architecture components allow you to create one via an Entity. Let's do this now. - Create a new class file called Word.. - Update your Wordclass with annotations as shown in this code: @Entity(tableName = "word_table") public class Word { @PrimaryKey @NonNull @ColumnInfo(name = "word") private String mWord; public Word. - We need to not run the insert on the main thread, so we use the ExecutorServicewe created in the WordRoomDatabaseto perform the insert on a background thread.. Implement the ViewModel Create a class file for WordViewModel and add this code to it:); } }. floating action button (FAB)‘s. -. Create after setContentView:. (). Here is the code for creating the callback within the WordRoomDatabase class. Because you cannot do Room database operations on the UI thread, onOpen()Open(@NonNull SupportSQLiteDatabase db) { super.onOpen WordViewModel mWord: mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class); Also in onCreate(), add an observer for the LiveData returned by getAlphabetized); } }); Define a request code as a member of the MainActivity: public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;); } }); Now, run your app! When you add a word to the database in NewWordActivity, the UI will automatically update. Now that you have a working app, let's recap what you've built. Here is the app structure again: >>IMAGE-master, which contains the complete app.
https://codelabs.developers.google.com/codelabs/android-room-with-a-view?hl=en
CC-MAIN-2020-45
refinedweb
359
51.34
qdragenterevent.3qt - Man Page Event which is sent to the widget when a drag and drop first drags onto the widget Synopsis #include <qevent.h> Inherits QDragMoveEvent. Public Members QDragEnterEvent ( const QPoint & pos ) Description The QDragEnterEvent class provides an event which is sent to the widget when a drag and drop first drags onto the widget.. Member Function Documentation QDragEnterEvent::QDragEnterEvent ( const QPoint & pos ) Constructs a QDragEnterEvent entering at the given point, pos. Warning: Do not create a QDragEnterEvent yourself since these objects rely on Qt's internaldragenterevent.3qt) and the Qt version (3.3.8). Referenced By The man page QDragEnterEvent.3qt(3) is an alias of qdragenterevent.3qt(3).
https://www.mankier.com/3/qdragenterevent.3qt
CC-MAIN-2022-40
refinedweb
111
50.33
Hello. Hello. indent preformatted text by 4 spaces #include <UbidotsESP8266.h> #include <SoftwareSerial.h> #define SSID "Claro_6215" #define PASS "93kZhk6a3K" #define TOKEN "1QateDd1HugnbetO5uybBZFpgsQKvD" #define ID "581662d27625421efe3cb142" Ubidots client(TOKEN); void setup() { Serial.begin(115200); client.wifiConnection(SSID,PASS); } void loop() { float value =+ 1; client.add(ID,value); client.sendAll(); } We were verifying and the problem is that the ESP8266’s firmware was recently updated by the library’s provider and AT command’s baud speed was upgraded and it is not working properly with the Arduino Software Serial Library, because Ubidot’s Library uses virtual ports and at high baud rates the new firmware produces noise and right now the communication cannot be set between the ESP and the Arduino using only a written code in an Arduino Sketch. Because the third party ESP’s firmware library doesn’t rest on us, it is a bit difficult for us to solve easily the issue, we highly recommend to our users to use an Arduino Board with two hardware serial ports and not to virtualizate the ports in order to set properly the baud rate without any kind of noise, you can use an Arduino Duemilanove or Mega for having more hardware serial ports Available. We will be working for trying to solve the issue, but the solution is not trivial and it can take us some time so we gently recommend you to implement your code with a different board or trying a search for an older ESP library firmware." Best regards, Catalina M. Hi @Kath Thanks for your answer. I am not connecting the ESP8266 and the Arduino. I am working only with the ESP8266. Is it the same problem? Thanks. According to you, also with @bhargavi at this post, and @Metavix in this another post, I try to conclude that we have a problem between Arduino UNO and the actually ESP8266 firmware. I want to make projects with the ESP8266 because it is a cheap device for IoT, but if I could find another device with a better perfomance, I wouldn’t have any problem to change it. I had also the same problems exposed at the three forums I said before. According to your recommendation, an Arduino MEGA is a better option, but: how do we connect the pins of the ESP8266 on it? The UbidotsESP8266 library is the same? Because you talked about some virtual ports and serial ports… Also, according to the devices that UBIDOTS talk about here, I would like to know which of them you would recommend for having a good experience with Ubidots? I have some clients waiting for some projects and I would like to make them with Ubidots. I am attentive and thanks a lot! Best regards, Sebastian Morales
https://ubidots.com/community/t/solved-esp8266-error-at-cipmode/623
CC-MAIN-2021-43
refinedweb
459
58.62
This page covers Tutorial v2. Elm 0.18. Update Finally we need to account for the new messages in our update function. In src/Update.elm: Add a new imports: import Commands exposing (savePlayerCmd) import Models exposing (Model, Player) import RemoteData New messages Update branches to update to handle the newly created messages: update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ... Msgs.ChangeLevel player howMuch -> let updatedPlayer = { player | level = player.level + howMuch } in ( model, savePlayerCmd updatedPlayer ) Msgs.OnPlayerSave (Ok player) -> ( updatePlayer model player, Cmd.none ) Msgs.OnPlayerSave (Err error) -> ( model, Cmd.none ) ChangeLevel In ChangeLevel we first update the level attribute for the given player and then return a command savePlayerCmd to save it. OnPlayerSave When we get OnPlayerSave back we pattern match so we handle the success and failure case differently. On the failure case we are just discarding the error and leaving the model as it was. This is not great but for simplicity we will do it like this. In the success case we are calling a helper function updatePlayer to update the changed player, we will write this function next. Update the player Add a helper function to update the player: updatePlayer : Model -> Player -> Model updatePlayer model updatedPlayer = let pick currentPlayer = if updatedPlayer.id == currentPlayer.id then updatedPlayer else currentPlayer updatePlayerList players = List.map pick players updatedPlayers = RemoteData.map updatePlayerList model.players in { model | players = updatedPlayers } This function is called after we get an updated player from the API. This function needs to swap an existing player in our model for the updated player coming from the API. We don't know what is in model.players, it could be RemoteData.Loading or RemoteData.Success players or some other case. So first we need to account for this. RemoteData provides a map function that only applies when we have RemoteData.Success. We use this in updatedPlayers. updatePlayerList will only be called if model.players is RemoteData.Success players. updatePlayerList is a function that maps over a list of players and swaps the updated player. Try it This is all the setup necessary for changing a player's level. Try it, go to the edit view and click the - and + buttons. You should see the level changing and if you refresh your browser that change should be persisted on the server. Up to this point your application code should look.
https://www.elm-tutorial.org/en/08-edit/05-update.html
CC-MAIN-2019-04
refinedweb
397
51.14
Ticker sample program in J2ME By: Manoj Kumar Printer Friendly Format A ticker is an object that provides scrolling text across the top of the display. A Ticker is associated with the display, not with the screen. You place a Ticker on a screen using the Screen.setTicker(Ticker t) method, as shown in the code below. You can associate the same Ticker object with multiple screens, however. The implementation renders the Ticker on some constant portion of the display, in this case at the top of the display. Ticker is not an Item. Its derivation directly from java.lang.Object gives you a clue as to why a Ticker can be tied to the display and not to a screen. It doesn't need to be derived from Item, because it really is not something that is placed in a Form. // Ticker demo source code.Ticker; import javax.microedition.lcdui.Form; /** This class demonstrates use of the Ticker MIDP UI component class. @see javax.microedition.lcdui.Gauge */ public class TickerDemo extends Form implements CommandListener { private String str = "This text keeps scrolling until the demo stops..."; private Ticker ticker = new Ticker(str); private Command back = new Command("Back", Command.BACK, 1); private static Displayable instance; /** Constructor. */ public TickerDemo() { super("Ticker demo"); instance = this; addCommand(back); setTicker(ticker); setCommandListener. Thanks ! View Tutorial By: Swaran at 2010-02-02 23:50:13 2. thanks i am fresher to j2me i understand the conce View Tutorial By: anusha at 2010-04-20 00:32:10 3. It worked. Thank U! View Tutorial By: Abhijit Kurane at 2010-12-27 11:01:48 4. thanks for the definition...more power :) View Tutorial By: saluki at 2011-07-19 05:36:00
http://www.java-samples.com/showtutorial.php?tutorialid=426
CC-MAIN-2018-43
refinedweb
287
59.8
There should be default action settings for each direction which can override current settings RESOLVED FIXED in Firefox 20 Status () People (Reporter: tomfyuri, Assigned: emk) Tracking ({regression}) Points: --- Firefox Tracking Flags (firefox17 wontfix, firefox18 wontfix, firefox19 wontfix, firefox20 fixed, firefox-esr10 unaffected, firefox-esr17- affected) Details Attachments (1 attachment, 4 obsolete attachments) User Agent: Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/17.0 Firefox/17.0 Build ID: 20120810012545 Steps to reproduce: I tried downloading and installing every build that came out in august and any build after 12th august (including 12th august) has a regression with option mousewheel.horizscroll.withnokey.action for me, setting it in about:config makes no difference and I can't press mouse4/mouse5 and go back/next pages. So either I use last build and have to hold shift all time or i use build before 12th august, set mousewheel.horizscroll.withnokey.action (numlines,sysnumlines) to my likings and enjoy using mouse4 and mouse5 for go back/next pages. I'm using Linux 32bit. Regression between these builds: 11 august: 12 august: This is my first firefox bug-report ever. Actual results: mousewheel.horizscroll.withnokey.action regression in firefox-nightly after 11th august 2012. It doesn't respond however value you change it to. Expected results: It was fine before 12th august 2012. Severity: normal → minor Keywords: regression That's expected. Wheel related prefs are completely rewritten due to implementing D3E wheel event. The new prefs are documented here: Hello, I read the page with the documentation of the changes. I used mousewheel.withnokey.action set to 1 to scroll entire pages like page up and page down. Is this not possible anymore or can this emulated (kind of) with ne new setting scheme? Kind Regards Konsti As I see it, in Firefox 17.0 it's now impossible to do history back/forward with the horizontal scroll wheel (or tilt wheel, which are fairly common). If it's still possible to have an effect of mousewheel.horizscroll.withnokey.action=2 with the new scheme, please tell us how. Otherwise it's a usability regression and the bug should be reopened. Running Firefox 17.0 and mousewheel.horizscroll.withnokey.action=2 doesn't work. It was like this all this time. Since I made this report... Wasn't this like, new feature? In other words, horizscroll and vertiscroll CAN'T have separate actions now. I kinda got used to it now. :) Hardware: x86 → All Reopening to ask an opinion. Nakano-san, what do you think about this? Indeed both deltaX and deltaY can be non-zero about a device such as touchpad or trackball, it is not a reasonable assumption about a tilt-wheel IMO. Status: RESOLVED → UNCONFIRMED Resolution: INVALID → --- (In reply to Masatoshi Kimura [:emk] from comment #6) > Indeed both deltaX and deltaY can > be non-zero about a device such as touchpad or trackball, it is not a > reasonable assumption about a tilt-wheel IMO. I'm not sure which problem do you worry about. Current implementation uses widget::WheelEvent::GetPreferredIntDelta() for deciding which delta value should be used for history-go-back/forward and zoom-in/out. I'm not sure if this is the best algorithm for all devices all over the world. But I think it doesn't make sense that we separate the action handling in XP level. And also, some touch pad devices may dispatch WM_MOUSEWHEEL and WM_MOUSEHWHEEL for an action (diagonal scroll operation). We cannot detect the differences. If you have better idea of the method, let's use it. Component: Untriaged → Event Handling Product: Firefox → Core Version: 17 Branch → Trunk Ah, do you meant that we should separate the action prefs to x and y? If you have some good idea, I'd like to take it. Tom: Although, I'm not familiar with Linux, if you could map button8/9 to the operation only on Firefox, you could use horizontal wheel action as back/forward button: We don't have to detect whether the device is touch pad. The settings will not be enabled unless users modify the about:config, and users will know whether their device is touch pad or not. However it's done, I would be very grateful if this functionality is returned. I am not upgrading some of my computers specifically because of this issue. Thank you. Okay, I think we should add mousewheel.*.action.override_[xyz]. It can take same values as mousewheel.*.action and -1. If the value is -1, it does NOT override the current setting. If I had time, we'd do this. But I have some more important work for now. If somebody wants to do this, feel free to take this. I will give some advice. Severity: minor → enhancement Status: UNCONFIRMED → NEW Ever confirmed: true OS: Linux → All Summary: mousewheel.horizscroll.withnokey.action regression between 11th august and 12th august in firefox-nightly → There should be default action settings for each direction which can override current settings Oh, so the problem that touchpad side scrolling uses same keycodes as mouse's wheel tilt? That's pretty annoying... isn't there a way of telling if it's a mouse or touchpad? On Windows, it really depends on your mouse driver. Sometimes it generates keycodes, sometimes it generates scroll message, and sometimes it generates horizontal wheel message. Using linux here :) - I added only .override_x because I counldn't imageine a read-world use case of overrides for other directions. It looks a bit overgeneralization to me. Also, old prefs provide only settings for vertical/horizontal. Furthermore, the current ComputeActionFor function doesn't even consider deltaZ! If you disagree, please teach me why .override_[yz] is useful. - Fixed an unspecified behavior. Implementations may remove the if-statement testing the range of Action values for similar reason to the following code: bool b = <an int value>; // The condition will never hold, so the if-statement may be removed. if (b != true && b != false) { ... } - Using MOZ_ENUM_TYPE to save the space. Attachment #688441 - Flags: feedback?(masayuki) Reporter or commenters: Please report if the test build fixed the problem: 1. Install the test build from <> 2. Set "mousewheel.default.action.override_x" to integer value 2. Flags: needinfo? Works for me. (I also had to invert mousewheel.default.delta_multiplier_x to get the expected direction.) Flags: needinfo? Comment on attachment 688441 [details] [diff] [review] Implement mousewheel.*.action.override_x Thank you, Kimura-san. I think that your patch looks almost great. But: > +; And... > - return (mActions[INDEX_DEFAULT] == ACTION_SCROLL) ? ACTION_SCROLL : > + return (actions[INDEX_DEFAULT] == ACTION_SCROLL) ? ACTION_SCROLL : > ACTION_NONE; Please fix the indentation level of ACTION_NONE. Attachment #688441 - Flags: feedback?(masayuki) → feedback+ (In reply to Masayuki Nakano (:masayuki) (Mozilla Japan) from comment #20) > > +; Good idea. I've adopted it except for using std::abs instead of NS_ABS which has been replaced by bug 817574. Attachment #688441 - Attachment is obsolete: true Attachment #688727 - Flags: review?(bugs) Oops, why don't you add the prefs to all.js? Such hidden prefs will probably cause similar bug reports since they won't find the prefs in about:config. (In reply to Masayuki Nakano (:masayuki) (Mozilla Japan) from comment #23) > Oops, why don't you add the prefs to all.js? Such hidden prefs will probably > cause similar bug reports since they won't find the prefs in about:config. Ugh, I saw only the top of attachment 650059 [details] [diff] [review] and misunderstand mousewheel.horizscroll.*.action wasn't defined in the pref. Added .override_x prefs back to all.js. Attachment #688979 - Flags: review?(bugs) Comment on attachment 688727 [details] [diff] [review] Implement mousewheel.*.action.override_x This all needs some comments. It is pretty unclear how mActionsX is different from mActions Comment on attachment 688727 [details] [diff] [review] Implement mousewheel.*.action.override_x So, I'd like to see comments explaining why X is special and what mActionsX is about, and also some tests. No need for tons of tests, but some test to prevent accidental regressions. Attachment #688727 - Flags: review?(bugs) → review- Folded two patches and added tests and comments. Try result: Attachment #688727 - Attachment is obsolete: true Attachment #688979 - Attachment is obsolete: true Attachment #689962 - Flags: review?(bugs) Comment on attachment 689962 [details] [diff] [review] Implement mousewheel.*.action.override_x, v3 Could you perhaps rename mActionsX to mOverriddenActionsX or mOverrideActionsX Attachment #689962 - Flags: review?(bugs) → review+ patch for check in Attachment #689962 - Attachment is obsolete: true Attachment #690028 - Flags: review+ Thank you, Kimura-san. This must help bug 819252. Requesting tracking-firefox-esr17 ?. However, I'm not sure whether this should be fixed on ESR branch. If there are some users in this trouble, they feel inconvenience. If the environment is in a company or an organization, they may not be able to use non-ESR build. The patch's risk isn't high, I think. Assignee: nobody → VYV03354 Status: NEW → ASSIGNED status-firefox-esr10: --- → unaffected status-firefox17: --- → wontfix status-firefox18: --- → wontfix status-firefox19: --- → wontfix status-firefox20: --- → affected status-firefox-esr17: --- → affected tracking-firefox-esr17: --- → ? Target Milestone: --- → mozilla20 Status: ASSIGNED → RESOLVED Closed: 7 years ago → 7 years ago Resolution: --- → FIXED This doesn't meet criteria for ESR landings, if there were reports of significant user pain on ESR deployments we could consider for uplift but wouldn't do so without cause. Which reports of significant pain do you need? :) I can report mine. I upgraded from esr10 to esr17 and had to go back, because esr17 was hardly usable for me due to exactly this issue, because this is a regression in esr17 compared with esr10. But esr10 is not supported anymore, so I'm basically lost, together with all our users... ;) For those of you stuck with esr17 on Linux: Avian's solution of remapping the pointer buttons works for me: Component: Event Handling → User events and focus handling Type: enhancement → defect
https://bugzilla.mozilla.org/show_bug.cgi?id=786120&amp;GoAheadAndLogIn=1
CC-MAIN-2019-30
refinedweb
1,634
58.89
09 January 2014 14:48 [Source: ICIS news] TORONTO (ICIS)--Canadian Natural Resources (CNR) has decided to retain its Montney shale gas assets in ?xml:namespace> Last year, CNR said that it may seek to sell part of Montney outright or find a partner with expertise in liquefied natural gas (LNG) to jointly develop them. In an update on Thursday CNR said that it received a number of expressions of interest for the assets which hold “contingent resources” of about 6.7 trillion cubic feet of gas. “However, none of the expressions were of sufficient merit to complete a transaction at this time, and as such, the company has elected to retain the acreage,” it said. CNR holds one of the largest Montney land positions with over 1m net acres,
http://www.icis.com/Articles/2014/01/09/9742144/canadian-natural-resources-decides-to-retain-canada-shale-assets.html
CC-MAIN-2015-11
refinedweb
130
58.62
1. Making your first figure This tutorial page covers the basics of creating a figure using PyGMT - a Python wrapper for the Generic Mapping Tools (GMT). It will only use the coast method for plotting. Later examples will address other PyGMT methods. Setting up the development environment PyGMT can be used in both a Python script and a notebook environment, such as Jupyter. The tutorial’s recommended method is to use a notebook, and the code will be for a notebook environment. The first step is to import pygmt. All methods and figure generation is accessible from the pygmt top level package. import pygmt Creating a figure All figure generation in PyGMT is handled by the pygmt.Figure class. Start a new figure by creating an instance of this class: fig = pygmt.Figure() To add to a plot object ( fig in this example), the PyGMT module is used as a method on the class. This example will use the coast method, which can be used to create a map without any other methods, modules or external data. The coast method plots the coastlines, borders, and bodies of water using a database that is included in GMT. First, a region for the figure must be selected. This example will plot some of the coast of Maine in the northeastern US. A Python list can be passed to the region parameter with the minimum and maximum X-values (longitude) and the minimum and maximum Y-values (latitude). For this example, the minimum (bottom left) coordinates are (N43.75, W69) and the maximum (top right) coordinates are (N44.75, W68). Negative values can be passed for latitudes in the southern hemisphere or longitudes in the western hemisphere. In addition to the region, an argument needs to be passed to coast to tell it what to plot. In this example, coast will be told to plot the shorelines by passing the Boolean value True to the shorelines parameter. The shorelines parameter has other options for finer control, but setting it to True uses the default values. To see the figure, call pygmt.Figure.show. Out: <IPython.core.display.Image object> Color the land and water This figure plots all of the coastlines in the given region, but it does not indicate where the land and water are. Color values can be passed to land and water to set the colors on the figure. When plotting colors in PyGMT, there are multiple color codes, that can be used. This includes standard GMT color names (like skyblue), R/G/B levels (like 0/0/255), a hex value (like #333333), or a graylevel (like 50). For this example, GMT color names are used. fig = pygmt.Figure() fig.coast( region=[-69, -68, 43.75, 44.75], shorelines=True, land="lightgreen", water="lightblue", ) fig.show() Out: <IPython.core.display.Image object> Set the projection This figure now has its colors set, but there is no projection or size set for the map. Both of these values are set using the projection parameter. The appropriate projection varies for the type of map. The available projections are explained in the projection gallery. For this example, the Mercator projection is set using "M". The width of the figure will be 10 centimeters, as set by "10c". The map size can also be set in inches using “i” (e.g. a 5 inch wide Mercator projection would use "M5i"). fig = pygmt.Figure() fig.coast( region=[-69, -68, 43.75, 44.75], shorelines=True, land="lightgreen", water="lightblue", projection="M10c", ) fig.show() Out: <IPython.core.display.Image object> Add a frame While that the map’s colors, projection, and size have been set, the region that is being displayed is not apparent. A frame can be added to annotate the latitude and longitude of the region. The frame parameter is used to add a frame to the figure. For now, it will be set to "a" to annotate the axes automatically. fig = pygmt.Figure() fig.coast( region=[-69, -68, 43.75, 44.75], shorelines=True, land="lightgreen", water="lightblue", projection="M10c", frame="a", ) fig.show() Out: <IPython.core.display.Image object> Add a title The frame parameter can be used to add a title to the figure. The title is set with by passing "+t" followed by the title (e.g. setting the map title to “Title” would be "+tTitle"). To pass multiple arguments to frame, a list can be used, as shown in the example below. This format uses frame to set both the axes gridlines and the figure title. If the figure title has any spaces, the string to set the title needs to be wrapped in single-quotes, while the actual title is set in double quotes (e.g. setting the title to “A Title” would use the syntax '+t"A Title"'. fig = pygmt.Figure() fig.coast( region=[-69, -68, 43.75, 44.75], shorelines=True, land="lightgreen", water="lightblue", projection="M10c", frame=["a", "+tMaine"], ) fig.show() Out: <IPython.core.display.Image object> Additional exercises This is the end of the first tutorial. Here are some additional exercises for the concepts that were discussed: Make a map of Germany using its ISO country code (“DE”). Pass the ISO code as a Python string to the regionparameter. Change the color of the land to “khaki” and the water to “azure”. Change the color of the lakes (using the lakesparameter) to “red”. Create a global map. Set the region to “d” to center the map at the Prime Meridian or “g” to center the map at the International Date Line. When the region is set without using a list full of integers or floating numbers, the argument needs to be passed as a Python string. Create a 15 centimeter map using the Mollwide (“W”) projection. Total running time of the script: ( 0 minutes 6.007 seconds) Gallery generated by Sphinx-Gallery
https://www.pygmt.org/latest/get-started/first_figure.html
CC-MAIN-2022-27
refinedweb
979
66.64
SchemaType typeOfSchema = new SchemaType(); typeOfSchema.LoadAll(); //Create an instanc of schema Type Collection SchemaTypesCollection typeOfSchemaCollection = new SchemaTypesCollection(); typeOfSchemaCollection.Add(typeOfSchema); public SchemaType(Int32 ID, String Description, DateTime CreateDate) { this.ID = ID; this.Description = Description; this.CreateDate = CreateDate; } public class SchemaTypesCollection : CollectionBase, IEnumerable, IEnumerator { private int index = -1; public SchemaTypesCollection() { this.index = -1; } public void Add(SchemaType schemaType) { /* * Example for applying business Logic * */ if (schemaType != null) { throw new Exception("Your passed SchemaType Object is null"); } /* * Normal behaviour of a Collection */ this.List.Add(schemaType); } public void Remove(SchemaType schemaType) { this.List.Remove(schemaType); } public SchemaType this[int index] { get { return (SchemaType)this.List[index]; } set { this.List[index] = value; } } #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return this; } #endregion #region IEnumerator Members public Object Current { get { return this.List[index]; } } public bool MoveNext() { this.index++; return (this.index < this.List.Count); } public void Reset() { this.index = -1; } #endregion public void Save(SchemaTypesCollection collection) { try { /* * Insert all items of */ } catch (Exception e) { /* * if you get an error in between Rollback */ throw e; } more than one instance of a class. You could create an AddRange method: Open in new window And it has up to 10 rows Open in new window Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface. But : the AddRange... is not implemented in the class public void AddRange(IEnumerable<Schem { this.List.AddRange(range); } Is there a reason that you need inheritance and CollectionBase, rather than List<SchemaType>? need to update lot of classes... looking for a Short if there is any.. How can I use LIST<SchemaType> to solve this problem Can you show me the LoadAll method from this line? typeOfSchema.LoadAll() Open in new window Here is a suggested change showing some C# concepts: Open in new window Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial Thanks for the post.. Will have a look at it .. Load all is the problem Regards
https://www.experts-exchange.com/questions/28240687/Load-class-object-into-a-collection.html
CC-MAIN-2018-39
refinedweb
374
61.02
On Dec 22, 2010, at 5:58 PM, Gregg Tavares (wrk) wrote: > > > ...I'll stop with the iOS stuff after this, promise :-D I just want to clarify for my own edification. Cool and I'll stop answering after this :-) > > iOS can and never will be able to print? If it can then it will have access to the pixels. Even if it means re-directing the printer to memory, printing, and grabbing the pixels from the result. Yes, it can print. That's a system level function. How and where it gets its pixels to print is none of my business. > > iOS can currently take a screenshot at any time. It seems like their must be some way of exploiting that to get the pixels back, even if it means writing a .PNG to memory and then loading and decompressing it. System level function. The notion of reading and decoding a PNG image as a way of getting the current drawing buffer is not practical. > > There is some connection between JavaScript, the DOM and the object in the compositor that manages the bits since JavaScript can move the DOM object and see the results. While it might not be able to get the bits directly, it seems like it should be possible to bind an FBO and ask that object to render. That will copy that object to the FBO at which point you can call readPixels on it to get the contents. That's how preserveDrawingBuffer=true would most likely be implemented. It's an extra expense which the author would incur if this feature is enabled. > > So, one way or another I still kind of feel like their is a way to make readPixels, toDataURL, drawImage and texImage2D to always work even in iOS when preserveDrawingBuffer is false. > > but, assuming it's going to stay the way it is it still seems like what you get from those 4 functions needs to be defined at all times. At least it seems like the spec needs to define that they do not fail. Ie, they return something the size of the canvas. They do not throw, they do not generate errors and and they do not return unexpected sizes. The spec currently states that the color buffer (the only buffer directly accessible) would return (0, 0, 0, 0). ----- ~Chris cmarrin@apple.com ----------------------------------------------------------- You are currently subscribed to public_webgl@khronos.org. To unsubscribe, send an email to majordomo@khronos.org with the following command in the body of your email:
https://www.khronos.org/webgl/public-mailing-list/archives/1012/msg00293.php
CC-MAIN-2015-48
refinedweb
421
73.17
If you are familiar with JavaScript or Web Development then you must have heard about npm. NPM helps us to manage packages and dependencies in our projects. So, while learning a JavaScript framework the knowledge of npm would be really useful to learn it in an easier manner. In this series of articles, we aimed to cover the following topics: - Objects and Array methods Asynchronous JavaScript and Fetch API NPM and import/export modules in JavaScript (this article) Let's first start with NPM: NPM What is NPM? NPM is the default package manager for node. It is used to install, share, and manage javascript packages in a project. NPM has three components: The website (Using the website we can find, share, and view packages) The Command Line Interface (CLI) (The CLI is the component that helps us in managing our packages) The registry (The npm registry is the database where all the packages exist, we can download packages published by other developers and can also publish our own packages to the registry) Note: NPM can also be used to publish and manage private packages. A package is simply a program that performs one or more operations. How to Install npm? NPM comes pre-installed with node.js. So, you don't need to worry about installing it manually, you just have to install node.js on your system. To install node.js, visit, and install its LTS (Long Term Support) version. After installation, use the commands shown below to check if they are installed: // to check nodejs's version node -v or node --version // to check npm's version npm -v or npm --version This will result in something like this: Checking for node's and npm's version package.json The package.json file is like the manifest of your project. It makes it easier to install and manage packages. It consists of all the metadata of the project that will be useful while sharing the project with other developers. According to the official docs: A package.json file: lists the packages your project depends on specifies versions of a package that your project can use using semantic versioning rules makes your build reproducible, and therefore easier to share with other developers How to create a package.json file? To create a package.json file, run npm init in the root folder of your project. After running this command, it asks you for some data about your project, you can choose to answer them or just press enter to set the data values to default. Here is an example of the same: Create package.json file You can also execute the command npm init -y to create the package.json and it will create the file by itself by setting all the data to default. Here is the example for the execution of this command: Create package.json using ‘npm init -y' So, you can notice that this file contains some important data like name, description, versions, and author, etc about our project. Important npm commands Here we will learn about some of the useful npm commands. Let's first learn about installing packages from npm. Installing an NPM package To install an npm package simply run the command: npm install For example, let's install *lodash*: Install an npm package After the installation, the project folder structure should look like this: Project's folder structure So, we can notice that we have a new folder named node_modules and file named package-lock.json. The node_modules folder contains the package and all its dependencies (i.e the programs and files on which our package depends for its working) while the package-lock.json file holds the exact versioned dependency tree. So, with that being installed in your project, you can now use lodash and its functions in your project. **Note: **To install a package globally, simply append -g or --global to the command. To understand this, let's install *nodemon* globally: Installing npm modules globally As you can see, I already had it on my system, so the package was only updated. Note: Any package that you want to use in your project should be installed locally. Any package that you want to use from the command line or CLI should be installed globally. package.json file So, you can notice that lodash is added to the dependencies list in the package.json file but nodemon wasn't added as it was installed globally. Now, if you notice, there is another key named devDependencies which is empty. Let's understand what it is. We can also install packages that are only intended to be used in the development phase of our project and not in the production phase. These packages are known as devDependencies. To install a devDependency append --save-dev to the command. Let's install *eslint* as a dev dependency: Installing a devDependency If you now notice the package.json file then it should look like this: package.json file So, eslint got added to the devDependencies list. Install a specific version of the package To install a specific version of the package add the version to the package like: npm i Installing a specific version of the package So, if you now notice the version of lodash in your package.json then it should be: snippet from package.json file Updating an npm package To update a specfic npm package simply run npm update Updating an npm package So, now lodash will be updated to the latest version: snippet from package.json file Note: To update a global package run npm update Uninstalling an npm package To uninstall an npm package use the following command: npm uninstall <package-name> Uninstalling an npm package This will remove the package and its dependencies (if they are not being used by any existing project). Installing packages from package.json When you are working in a team and want to share your project with your peers then you should not share the complete node_modules folder as sharing only the package.json and package-lock.json will do the job, as it consists of all the data related to your project and its packages along with their versions. To install packages from the package.json file run: // Install packages from package.json npm install or npm i Installing packages from package.json This will automatically install all the packages and dependencies required for the working of your project. Note: npm was originally made for node but the frontend community has also adapted it. We can't directly use an npm package in the script tag, for that we need to use tools like webpack, and parcel. But these tools are not necessary to learn before getting started with any framework as nowadays most of the frameworks provide tools to get started without troubling yourself with webpack or parcel. Examples of such tools are react-cra and vue-cli. If you wish to learn more about package-lock.json then this video is a great watch. With that, we have covered the first topic of our article, let's now move on to the next topic which is import/export modules in JavaScript. Import/Export modules in JavaScript What are JavaScript modules and why do we need to use them? JavaScript modules are files that are used to perform some specific operations that can be added/removed into the main program without disrupting it. We use modules as it makes our code more re-usable, helps to split functionalities into smaller files, and also to eradicate naming conflicts while writing code. We can export some code from one module and import the same in another module. This way we will be able to separate code which is meant for a specific purpose in their own files and can use them in the main program. Here we will talk about ES6 modules and ways to import/export them. Remember: If you do not export some specific code from a file then it can't be imported or used in the other file. To understand the concept of importing and exporting modules, let's consider the example of an appliance without a plug. Now, obviously, in this state, the appliance doesn't work. To make it work we will have to add a plug to it and connect it to the socket. In the case of modules, the appliance is the module itself, now, when you add an export statement in a module then you are basically adding a plug to the appliance and when you import the value of the module from another module then you are connecting the plug into the socket. Importing and exporting a module Exporting To export anything from the module we use the export keyword. We can export our code using the following ways: Named export (zero or more exports per module) Default export (only one per module) Let's see how they work: // 1. Named export // a) Exporting one by one const ids = [1, 2, 3, 4]; // Not availiable outside this file export const users = ['Ajay', 'Akash', 'Raman']; export const tasks = ['write article', 'practice', 'read docs']; /* Here, we are exporting the variables one by one in their declaration but, we can also export them in a single line as: */ // b) Exporting in a single line const users = ['Ajay', 'Akash', 'Raman']; const tasks = ['write article', 'practice', 'read docs']; export { users, tasks }; // 2. Default export // a) exporting with the defination export default function logUser(user) { console.log(user); } /* OR */ // b) Exporting at the end of the file function logUser(user) { console.log(user); } export default logUser; So, we can notice that the named export is useful to export multiple values but using the default export can be used to export only one value. Importing To import the exported content of one module into another module we use the import keyword. Also, we need to mention the relative or absolute (if the project has the configuration) path to that module. Based on the different types of exports we can have the following types of imports: Importing single or multiple named exports from the module Importing defaults Let's see how they work: // 1. Import one or more named exports from the module // Syntax import { <named_export_value> } from '<path_of_module_from_current_module>'; // path can be relative or absolute depending upon the configuration of the project // For Example: import { users, tasks } from './export.js'; // This will import the users and tasks arrays into the current module // 2. Import default // Syntax import <default_export_value> from '<path_of_module_from_current_module>'; // path can be relative or absolute depending upomn the configuration of the project // For Example: import logUser from './export.js'; // This will import the function logUser into this module So, we can notice that the named import is useful to import multiple values but using the default import can be used to import only one value. Importing from an npm package We can import functions and code from an npm package using the following syntax: // To import a default export import <default_value> from '<package-name>'; /* OR */ // To import a named export import { <named_export_value> } from '<package-name>'; view raw Now, as you can notice that we didn't use the relative path here due to which webpack decides that it has to import the function/value from the node_modules folder. Let's understand how to import the npm packages using the lodash example: import lodash from "lodash"; // We can also import specific functions using the format: import { isArray } from "lodash"; // We can also import other files or JS entry points from a package: import map from "lodash/map"; So, you can observe that we didn't use the file's extension in the last import statement, we can import without the file extension if it is a .js file. For all other file formats, we will have to specify the file extension. Note: By default webpack only allows to import javascript files but we can configure it to import CSS and other files. Here is a simple example to understand the concept in a better way. Feel free to play and experiment with the sandbox. With that, we have covered all the topics of this article as well as this series. I hope this series helped you in some manner to learn the useful concepts in JavaScript that one should know before learning any JavaScript framework. As always, to end this one I will leave you guys with a simple React Component that uses the above concepts: A simple React Component Also, check out the previous parts (in case you haven't): Things to learn before learning a JavaScript framework (part 1) *So, In this series of articles, I will try to explain some of those features and concepts which I feel are really…*medium.com Object and Array methods to learn before JavaScript frameworks (part 2) The different types of methods that can be applied to Objects and Arrays in JavaScriptmedium.com Asynchronous JavaScript to learn before JavaScript Frameworks (part 3) An insight to asynchronous javascriptmedium.com In case you want to connect with me, follow the links below: LinkedIn | GitHub | Twitter
https://plainenglish.io/blog/how-to-use-npm-and-import-export-modules-in-javascript
CC-MAIN-2022-40
refinedweb
2,191
59.53
Thanks, it works now :) cheers On Thu, May 8, 2008 at 11:23 PM, Christopher Lamey <clamey@localmatters.com> wrote: > If you set useStatementNamespaces to 'false', you will not be able to use > the 'ns.query' notation - you are disabling the feature. > > If you set useStatementNamespaces to 'true', you are enabling the feature > and can use the 'ns.query' notation. > > On 5/8/08 2:56 PM, "Filipe David Manana" <fdmanana@ieee.org> wrote: > > > Ah! > > > > So, even with false (default) for the useStatementNamespaces setting, I > > will be able to use the Namespace.queryName notation? right? > > > > thanks a lot > > > > On Thu, May 8, 2008 at 10:24 PM, Christopher Lamey < > clamey@localmatters.com> > > wrote: > > > >> Hello, > >> > >> Yes you can. > >> > >> Please see page 10 of the iBATIS PDF, specifically the section on > >> useStatementNamespaces for details. > >> > >> Cheers, > >> Chris > >> > >> > >> On 5/8/08 1:47 PM, "Filipe David Manana" <fdmanana@ieee.org> wrote: > >> > >>> Hi, > >>> > >>> In my app I have several sql maps (each one in a separate xml file). > Each > >>> sql map has a diferent purpose, so each one has a different namespace. > >>> It happens that I have different sql maps (different namespaces) with > >>> queries (select) that have the same ID. When I use SqlMapClient method > >> like > >>> queryForObject, > >>> can I specify something like "Example.getNames" as the query name? > Where > >>> Example is the namespace and getNames is the query ID. > >>> > >>> cheers > >> > >> > > > > -- Filipe David Manana, fdmanana@ieee.org "The cruellest lies are often told in silence."
http://mail-archives.apache.org/mod_mbox/ibatis-user-java/200805.mbox/%3Ccadf1c690805090058l4a163379gc7f7a11d63dabb6e@mail.gmail.com%3E
CC-MAIN-2017-39
refinedweb
240
68.26
It’s different than Python, but S3 isn’t that bad. Before writing this blogpost I did very little with object oriented code in R. I never really saw it as a useful feature because I am mostly using R as an analysis tool. The power of R comes partly from the fact that other people have done this work for you. Recently though, I’ve been tasked to write a custom machine learning library that needed to support the predict function. This document will describe the simplest machine learning method ever and some quick details on how to implement it in R via object oriented coding. This post is heavily inspired by this pdf and this tutorial. My goal is to have a similar document but a bit shorter to make it easier for my own reference. I will try to compare python to R wherever possible such that other people may find it useful too. Where python has dictionaries, R has lists. obj <- list(a = 1, b = 2) Instead of having methods within these objects, R uses functions that can accept many different types of objects. Notice below that I am using the same function on a list as I am on a dataframe. > names(obj) # "a" "b" > names(ChickWeight) # "weight" "Time" "Chick" "Diet" Where python has polymorphism, R (and Julia by the way) has multiple dispatch. Methods do not belong to objects, they belong to functions. Instead of binding a method to an object, R allows you to write many functions that share the same name but refer to different objects. For example, if you want to check out what objects can be handed to summary: > methods(summary) [1] summary.aov summary.aovlist* summary.aspell* [4] summary.check_packages_in_dir* summary.connection summary.data.frame [7] summary.Date summary.default summary.ecdf* ... You could also check for all methods that below to a certain class. > methods(class = "Date") [1] - [ [[ [<- + as.character [7] as.data.frame as.list as.POSIXct as.POSIXlt Axis c [13] coerce cut diff format hist initialize [19] is.numeric julian Math mean months ... If the function mean() were called on a Date object it would internally call mean.Date(). To keep track of what method a function should use R looks at the name of the function. In the case of mean.Date() the S3 class in R would recognize that the function mean can be used for Date by looking at the name. A silly example; foo.bar() would allow R to recognize that the function foo can be used on a bar object. This should feel very odd if you are a python programmer because it puts a lot of functions in the global namespace. Let’s create an object of type foo again, just to be explicit. obj <- list(a = 1, b = 2) class(obj) <- 'foo' > class(obj) "foo" We will now create a method mean.foo which will be called by the generic function mean if it is passed an object of class foo. mean.foo <- function(x){ (x$a + x$b)/2 } > mean(obj) 1.5 The only thing missing right now is a way to generate our own generic function. Just like mean was a generic function here, we might want to create a generic function that can be used on multiple objects. f <- function(x) UseMethod("f") f.foo <- function(x){ paste(x$a, "and", x$b, "are in this foo obj") } f.numeric <- function(x){ paste("this numeric has value", x) } > f(obj) [1] "1 and 2 are in this foo obj" > f(2) [1] "this numeric has value 2" I want to make a model that assumes a continous variable \(y\) and a discrete input \(X\). It will average \(y\) over all the \(X\) combinations. To create this machine learnin model I want a generic function that returns an object with a class. As long as I create a function via UseMethod that returns a list with an assigned class this should work. library(dplyr) aggmod <- function(x, ...) UseMethod("aggmod") aggmod.default <- function(form, data, ...){ res <- list() agg <- aggregate(formula = form, FUN = mean, data = data) colnames(agg) <- c(form %>% all.vars %>% tail(-1), "pred") res$agg <- agg res$call <- match.call() res$formula <- form res$fitted.values <- data %>% left_join(res$agg) %>% .$pred res$y <- data %>% select_(form %>% all.vars %>% head(1)) res$residuals <- res$y - res$fitted.values res$mae <- mean(sum(abs(res$residuals)/length(res$residuals))) res$mse <- mean(sum(res$residuals^2)/length(res$residuals)) class(res) <- "aggmod" res } The .default method can be seen as a constructor. When we call aggmod() function it will point to the aggmod.default method and return a list of class aggmod. This object still needs some utility generics. Currently, this object has no pretty print representation and can also not be passed into the predict function. print.aggmod <- function(x, ...){ cat("Call:\n") print(x$call) cat("\nMSE:") print(x$mse) cat("MAE:") print(x$mae) } predict.aggmod <- function(x, newdata = NULL, ...){ if(is.null(newdata)) return(fitted(x)) newdata %>% left_join(x$agg) %>% .$pred } With this in place, it starts to feel like using the lm function. modl <- aggmod(weight ~ Time + Diet, ChickWeight) > modl %>% print Call: aggmod.default(form = weight ~ Time + Diet, data = ChickWeight) MSE:[1] 631109.7 MAE:[1] 11692.11 > predict(modl, newdata = ChickWeight %>% sample_n(5)) Joining by: c("Time", "Diet") [1] 187.70000 47.25000 79.68421 64.50000 66.78947 I found this exercize very helpful in understanding the R way of dealing with objects. If you are from a different programming language this may feel like a very strange way of doing things but it has it’s benefits. By allowing our code to be written this way, we can do the following; formulas <- c(weight ~ Time, weight ~ Time + Diet, weight ~ Diet) ml_methods <- list(lm, aggmod) df <- data.frame(variables = as.character(), model = as.character(), median_mse = as.numeric()) mse <- function(x,y){ diff <- x - y mean(sum(diff^2)/length(diff)) } for(f in formulas){ for(m in ml_methods){ mod <- m(f, ChickWeight) df <- df %>% rbind(data.frame( variables = f %>% all.vars %>% tail(-1) %>% paste(collapse=' '), model = mod$call %>% as.character %>% .[1], median_mse = mse(mod %>% predict, ChickWeight$weight) )) } } Having a generic predict allows an R user to focus on the statistics because there is a common expectation of how an object should interact with it. Not all programmers will like this style, some may say that it offers too much sugar. Another example of things that feel trippy to programmers; `%+%` <- function(a, b){ paste(a,b, sep ='') } > 'a' %+% 'b' %+% 'c' [1] "abc" Where python can make use of polymorphism for it’s operators, R imposes different rules, but allows you to write your own operators. Most statistician will enjoy this because this syntax allows them only worry about doing statistics with code that feels natural to them.
https://koaning.io/posts/custom-machine-learning-objects-in-r/
CC-MAIN-2020-16
refinedweb
1,146
66.84
Opened 3 years ago Closed 3 years ago #12943 closed bug (fixed) BFS ioctl BFS_IOCTL_UPDATE_BOOT_BLOCK integer overflow leading to code execution Description In BFS ioctl BFS_IOCTL_UPDATE_BOOT_BLOCK implementation: if (update.offset < offsetof(disk_super_block, pad_to_block) || update.length + update.offset > 512) return B_BAD_VALUE; The check on "update.length + update.offset > 512" can overflow 32-bit int. In which case, it will happily memcpy() to an arbitrary memory address. Sample code: #include <stdio.h> #include <fcntl.h> #include <errno.h> struct update_boot_block { unsigned offset; void *data; unsigned length; }; int main() { int fd, ret; char data[0x1000] = {0}; struct update_boot_block block; memset(data, 0x42, sizeof(data)); block.offset = -0x1000; block.length = 0x1000; block.data = &data; fd = open("/boot/", O_RDONLY, 0); ret = ioctl(fd, 14204, &block, sizeof(block)); } This will overwrite some kernel memory with 0x42. (Is it even a good idea to let anyone update the boot block?) Change History (2) comment:1 by , 3 years ago comment:2 by , 3 years ago Note: See TracTickets for help on using tickets. This is used by makebootableto make the system bootable. This can be removed if we implement getting the partition offset from the BIOS instead of hardcoding it inside the partition boot code.
https://dev.haiku-os.org/ticket/12943
CC-MAIN-2019-39
refinedweb
198
60.21
Please find attached project for the Freedom KAE132 board that I was experimenting. I copied some code from previous LPC1549 project, including ring buffer that I was trying to adopt for this project. It complie without error so far. I need to integrate UART library into ringbuffer. I copied over the uart.c and uart.h from the SD32 design studio (S32_SDK_KEA_1_0_0) into the 102_Library. 1) I could not find example UART based code (with interrupt) that make use of uart.c and uart.h. Can u provide demo code based on that? 2) When included in the project, it reported warning on UART_CheckFlag(), see below. I'm not familar with this type of error. 3) What this local function: void UART_InitPrint(void); It not in the uart.c arm-none-eabi-gcc "@100_Common/Convert.args" -MMD -MP -MF"100_Common/Convert.d" -MT"100_Common/Convert.o" -c -o "100_Common/Convert.o" "../100_Common/Convert.c" ../102_Library/uart.c: In function 'UART_CheckFlag': ../102_Library/uart.c:313:36: warning: passing argument 1 of 'UART_GetFlags' from incompatible pointer type u16StatusFlags = UART_GetFlags(pUART); ^ ../102_Library/uart.c:287:10: note: expected 'UART_MemMapPtr' but argument is of type 'struct <anonymous> **' uint16_t UART_GetFlags(UART_MemMapPtr pUART) ^ /*****************************************************************************//*! * * @brief check whether the specified flag is set. * * @param[in] pUART base of UART port * @param[in] FlagType flag type * * @return * 1, flag is set * 0, flag is clear * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t UART_CheckFlag(UART_MemMapPtr *pUART, UART_FlagType FlagType) { uint16_t u16StatusFlags = 0; u16StatusFlags = UART_GetFlags(pUART); return (u16StatusFlags & (1<<FlagType)); } I wish to wirthdraw this including the zip file. BTW: I have deleted the zip file. I found out that S32_SDK_KEA_1_0_0 library is outdated (and should not be included). I using updated libarty in Quick Start Package v5. Should the Quick Start Package v5 replace the S32_SDK_KEA_1_0_0 library in S32 Design Studio kit?, or have S32_SDK_KEA_5_0_0 library How to delete this question? Thanks.
https://community.nxp.com/thread/441820
CC-MAIN-2018-43
refinedweb
309
60.92
NameNode and DataNode :HDFS cluster has two types of nodes operating in a master−slave pattern: a namenode (the master) and a number of datanodes (slave/worker).Namenode stores metadata and datanode deals with actual storage. Datanodes are the workhorses of the filesystem and it stores files in smaller blocks(default size 128 MB). Namenode manages the file-system namespace.Namespace/name-system consist of files and directories.Files and directories are represented on the namenode by inodes(Inode is a data structure used to represent a file system object file or directories in tree structure). Inodes stores all information about files or directory such as permissions, modification and access times,namespace and disk space quotas. Namenode maintains file-system tree and its metadata for all files and directories in tree. Inodes and memory blocks which stores metadata of namespace is called image(fsimage). Namenode stores image in RAM and persistent record of image is stored in namenode's local file system called checkpoint. Along with the checkpoint, namenode maintains a write ahead log file called journal, in its local file system. - Any changes made in HDFS is tracked in journal and journal size keep on growing unless changes is persisted and merged with checkpoint. - Block locations are not stored persistently because on system start-up, this information is obtained from datanode. - NameNode does not change checkpoint file, on start of namenode namespace image is loaded from checkpoint and new checkpoint and journal is created in native file system. - In order to increase reliability and availability, replicated volume of checkpoint and journal is stored in local servers. - When a datanode initializes and joins with namenode namespace ID is assigned to it and namespace ID is persistently stored in all datanodes. Namespace ID is used to maintain file system integrity. - When a system start, all datanodes of cluster sends handsake message to namenode to prove its identity that datanode belong to given namenode namespace.If namenode finds that namespace ID is not correct for any datanode then that datanode is not allowed ot join cluster and datanode shut-down automatically. Thus, namespace ID restrict datanode with differenct namespace ID to join cluster.On successful handshake process, datanode is registered with namenode and become part of hadoop cluster. - Storage ID is assigned to each datanodes when it joins a namenode the very first time and it is never changed after that.The storage ID is an internal identifier of the DataNode. - Since namenode does not store block location, when datanodes are registered with namenode they send block report to namenode. Block report contains block ID, generation stamp and block length for each block replicas datanode possess. Datanode periodically(every hour)send block report to namenode and give updated view of blocks in cluster. - Along with block report datanodes send light weight message(called Heartbeat) to namenode to mark their presence and blocks existence in cluster. The default heartbeat interval is three seconds. What happens if namenode does not receive heartbeat from some datanode ? If the namenoode does not receive a heartbeat from a datanode in ten minutes the namenode marks the datanode to be dead and the block replicas hosted by that datanode to be unavailable. Block replication operation is initiated by namenode for all blocks that were present in dead datanode. - Heartbeat message contains information about total storage capacity of datanode, fraction of space in use so heartbeat message helps namenode in load balancing and block allocation decision. - Nameode does not send message to datanode directly. It send response of heartbeat and instruct datanode to provide block report, replicate blocks, shut down node, etc. - Maintain a standby node called secondary namenode in different server other than where namenode is existing - Copy the image and log files to remote server periodically and when failure occur read from this location and recover. How does secondary namenode act as standby node for name node ?/What is use of secondry namenode in hadoop cluster ?/What is checkpoint node ? Any changes to HDFS is first logged in journal and it grows until its merged with checkpoint and new journal is created. Consider a situation, when hadoop cluster has not been started for months and log file has is very huge. When cluster restarts, namenode need to restore image(metadata of file system) from checkpoint created earlier and merge it with journal. The time taken to restart will depend on size of journal. Here comes secondary namenode for rescue.Secondary namenode is managed on different server other than namenode. The main purpose of using secondary namenode is to periodically merge journal with checkpoint and create new journal and checkpoint. Steps which secondary namenode follows are : - Secondary namenode downloads both checkpoint and journals from namenode . - Merge both of them locally and create new checkpoint and empty journal - Updated checkpoint is returned to namenode Note: Secondary namenode does not act as namenode when namenode failure occurs. Its just matter of naming convention which creates confusion.Secondary namenode is also termed as checkpoint-node. Thanks for providing such great and useful informations on your blog.update more data later. Hadoop Training in Chennai Big data training in chennai Big Data Training in Anna Nagar JAVA Training in Chennai Python Training in Chennai Android Training in Chennai hadoop training in Annanagar big data training in chennai anna nagar Big data training in annanagar Great Article Artificial Intelligence Projects Project Center in Chennai JavaScript Training in Chennai JavaScript Training in Chennai These contents are very helpful for freshers. This post is having depth content about this topic and Thank you. Keep doing...!!! Embedded System Course Chennai Embedded Training in Chennai job Openings in chennai Unix Training in Chennai Linux Training in Chennai Social Media Marketing Courses in Chennai Tableau Training in Chennai Excel Training in Chennai Embedded Training in Annanagar Hello Admin! Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today.. Hey! DigiPeek is the best SEO & Link Building Service Provider In The World. I have 7+ Years Experience To Build SEO, Backlinks & Improve Website Ranking. If you need Profile Backlinks, Forum Backlinks, Dofollow Backlinks, Manual Backlinks, Trusted SEO Backlinks, Increase Domain Rating Then You Will Contact Me. I am glad to help You! Let's TRY! So informative. I was searching like this for a few days. Thank you for sharing this information. second hand mobile phones for sale
https://www.devinline.com/2015/03/namenode-datanode-and-secondary-namenode.html
CC-MAIN-2021-25
refinedweb
1,086
55.24
Arduino Microcontroller: How to Use I2C, SPI, and UART The Arduino microcontroller is a versatile microcontroller, a true workhorse for many do it yourself projects. It has enough pins to connect several sensors and actuators. When building more complex system, you need to have a means for communicating with other microcontrollers or even single board computers. In the last article, I explained the main protocols that are available on the Arduino and the Raspberry Pi: 1-Wire, I2C, SIP, UART. In this article, we will explore the libraries that are used to establish the connection with these protocols. Each library will be presented with its name, short description of its function, and a code example to get you up and running in minutes. This article originally appeared at my blog. I2C The I2C protocol is the preferred protocol for interacting with other MCUs (for brevity I will use MCU to refer to both microcontrollers and single board computers). The Arduino IDE comes bundled with the Wire.h library. Lets see an example. The following program starts an IC2 master node. #include <Arduino.h> #include <Wire.h>#define IC2_CLIENT 0x23void setup() { Wire.begin(); Serial.begin(9600); }void loop() { Wire.beginTransmission(IC2_CLIENT); Wire.write("Server Request"); Wire.endTransmission(); delay(3000); } The I2C client node will listen for incoming messages, and print them on the serial output. #include <Arduino.h> #include <Wire.h>#define MY_I2C_ADDRESS 0x23void setup() { Wire.begin(MY_I2C_ADDRESS); Serial.begin(9600); }void loop() { if (Wire.available()) { char c = Wire.read(); Serial.print(c); } } This is just a basic example. The library also provides a mean to define non-blocking handler methods that are executed when data is available. And there are also methods to govern how the server requests to read data from its connected clients. SPI SPI connections can be made with the official SPI library Spi.h. This library provides extensive configuration options that reflect the complexity of the SPI protocol. It starts with configuring the maximum connection speed for all devices, whether messages will be exchanged with MSB or LSB, and how the voltage levels of the Clock and Data Channels are set. Let’s take a look at an example, inspired by the official example. #include <Arduino.h> #include <SPI.h>#define CLIENT_SELECT_PIN = 10 #define CLIENT_REGISTER_ADDRESS = 0x10;void setup() { pinMode(CLIENT_SELECT_PIN, OUTPUT); SPI.begin(); }void loop() { delay(1000); writeToSpiClient(0x10, millis()); }void writeToSpiClient(char& buffer, int value) { delay(100); SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0)); SPI.transfer(buffer,value); SPI.endTransaction(); digitalWrite(CLIENT_SELECT_PIN, HIGH); delay(100); } The basic steps are: - Define the pin layout - Start the SPI server with SPI.begin() - Wrap any transaction in SPI.beginTransaction()and SPI.endTransaction() - Use SPI.transferto send and receive data at the same time UART The final protocol is basic UART. Serial communication over the USB port always uses this protocol, and in addition, you can also wire another device using the RX TX Pins of the Arduino. To open the UART connection, you need to define the baud rate, a technical term for the number of characters that can be send. Once established, you can read and write any character-based data. The following program sends configures the baud rate to 9600. It will then send the "Hello UART" exactly one time to any connected client. Then, it will listen for any incoming data, and store it in a variable called msg. #include <Arduino.h> #include <stdbool.h>string msg; bool only_once = true;void setup() { Serial.begin(9600); }void loop() { (if only_once) { only_once = false; Serial.send("Hello Client"); } if (Serial.available()) { char c; while (c = Serial.read()) { msg += c; } } } Conclusion Connecting your Arduino to other MCUs can be done with three different protocols: I2C, SPI and UART. These protocols are implemented as libraries to handle the details of the individual protocols. To my surprise, each protocol is handled by a built-in library. Using them follows the same schema: Opening a connection, then begin the transmission (direct, or select the receiver first), and closing the connection. Which method you use depends on the available protocols of the connected device, and also which transmission speeds you need.
https://admantium.medium.com/arduino-microcontroller-how-to-use-i2c-spi-and-uart-d19d5f76c983
CC-MAIN-2022-05
refinedweb
687
50.63
New Modeler for Flash Builder 4.5 AvailableMike Peterson May 31, 2011 6:05 AM Modeler 3.11 works with Flash Builder 4.5 and Livecycle Data Services 3.1. It is available for download here: Modeler 3.11 Release Notes Install Modeler 3.11 into Flash Builder 4.5 Mac-only preliminary setup Note: These steps are only required when you run Flash Builder in stand-alone mode. - Shut down Flash Builder if it is running. - Open up the Flash Builder installation directory in Finder. - Open up the FB_INSTALL_DIR\eclipse\configuration folder. Note: There are two configuration folders, one in the FB_INSTALL_DIR and one in - FB_INSTALL_DIR\eclipse. Make sure you use the configuration folder in FB_INSTALL_DIR\eclipse. - Edit the config.ini file in a text editor. - Remove the following lines from the file: osgi.configuration.area=@user.home/Documents/Adobe Flash Builder Burrito Preview/cascaded/286922/configuration osgi.shared.configuration.area=file\:configuration osgi.configuration.cascaded=true - Start Flash Builder. Installing the Modeler on Mac or Windows - Open Flash Builder 4.5. On Windows 7, you must run Flash Builder as admininstrator. - Open the Help > Install New Software… menu. - Click on the Add button. - Click on the Archive button - Navigate to the directory that contains the FB4.5_Adobe_Application_Modeling_plugin_3.1.1.zip file. - Select the FB4.5_Adobe_Application_Modeling_plugin_3.1.1.zip file. - Click Open. - Click OK. - Check the checkbox next to Adobe Data Model Components for Flash Builder. - Click Next. Flash Builder has some of the components already, so the request is modified so that these components will be updated instead. - Click Next again. - Accept the License Agreement. - Click Finish. - If prompted with a security warning about unsigned software, click OK to continue with the installation. - When prompted, restart Flash Builder. - Complete the workaround to the first item in Known Issues below. Configuring RDS in Flash Builder - Start Flash Builder. - Open up the preferences screen from the menu option. Windows: Help > Preferences Mac: Flash Builder > Preferences - Navigate to Adobe > RDS Configuration in the left-hand tree. - Select the LCDS (localhost) RDS Server under Currently Configured RDS Servers. - Change the context root to be lcds-samples or whatever web app you are using. - Click the Test Connection button. If RDS is set up correctly, you should see a dialog that says "Test connection was successful". Known Issues - The fiber.swc file in LiveCycle Data Services 3.1 is incompatible with Modeler 3.11. By default, new Flex projects for LiveCycle Data Services in Flash Builder use the fiber.swc file in the WEB-INF\flex\libs directory of the target web application. This version of the fiber.swc file is missing a new method that is required for ActionScript code generation when working with Modeler 3.11. This version of the fiber.swc file is missing a new method that is required for using the model-driven form. When you try to use the model-driven form in an application, you will get an error that contains the following text: Method marked override must override another method. To work around this issue, replace the the fiber.swc file in the WEB-INF\flex\libs directory with a copy of the fiber.swc file from the FB_INSTALL_DIR\eclipse\plugins\com.adobe.flexbuilder.project_4.5.0.308971\fiberSwcs\4.5\l ibs directory. - Deploying a model that contains one of the following objects results in an XML parsing error from the LiveCycle Data Services server, and the model cannot be deployed: - A service that contains a function with parameters (arguments); this includes a service generated from an introspected remoting destination - An entity that contains a method with parameters Message was edited by: Mike Peterson 1. Re: New Modeler for Flash Builder 4.5 Availablegeneraldelivery Jul 14, 2011 5:00 PM (in response to Mike Peterson) Hi Mike, thanks for this post. Any work arounds for the second known issue ? 2. Re: New Modeler for Flash Builder 4.5 Availableflexzzz Jul 17, 2011 8:44 PM (in response to Mike Peterson) Dear Mike, Have you ever encountered the issue about FB 4.5 channel set authentication to work with model driven? In my test code, it calls "channelSet.login" before data service dynamic method generated, for instance "getAll()". It produces an error "Could not initialize DataService." But when I try to not call channelSet.login then getAll works. LCDS debug console, service destination description will be automatically loaded for first time call getAll without any problem but if we call channelSet.login before getAll method, the destination description won't be loaded so getAll method cannot be fired. Same test code is working well with FB 4.1. By the way, the new modeler 3.11 interface seems missing custom "filter method" for entity as we got in prior version. Best, Timmy 3. Re: New Modeler for Flash Builder 4.5 AvailableMike Peterson Jul 18, 2011 10:02 AM (in response to flexzzz) Can you please send me a private message with a zip file (as an attachment) of the Flex project that demonstrates the issue with ChannelSet.login? I'm not sure what you are mean about a filter method. Do you mean the filter element of the modeling language? If so, you can definitely use filters in Modeler 3.1.1. In Design view, you can drag them from the tool palette or right click on an entity to add them. - Mike 4. Re: New Modeler for Flash Builder 4.5 Availableflexzzz Jul 27, 2011 7:09 AM (in response to Mike Peterson) Dear Mike, Here is simple test code. On server side, just config tomcat custom authentication. <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns: <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.FlexEvent; import mx.messaging.ChannelSet; import mx.messaging.config.ServerConfig; import mx.rpc.AsyncResponder; import mx.rpc.AsyncToken; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; [Bindable] public var cs:ChannelSet = ServerConfig.getChannelSet("my-rtmp"); protected function application1_creationCompleteHandler(event:FlexEvent):void { //csResponder.token=cs.login('tomcat','tomcat'); } protected function button1_clickHandler(event:MouseEvent):void { // TODO Auto-generated method stub getAllResult.token = usersService.getAll(); } protected function button2_clickHandler(event:MouseEvent):void { csResponder.token=cs.login('tomcat','tomcat'); } ]]> </fx:Script> <fx:Declarations> <s:CallResponder <s:CallResponder <ds:UsersService </fx:Declarations> > <s:AsyncListView </mx:DataGrid> <s:Button <s:Button </s:Application> Thanks Timmy 5. Re: New Modeler for Flash Builder 4.5 Availabledlwelden Jul 28, 2011 9:19 AM (in response to Mike Peterson) Total newbie with LCDS and Flash Builder. Running FB 4.5 with SDK 4.5.1 and Modeler 3.1.1 for a Flex Mobile Project. I installed lcds31 for Windows with integrated Tomcat server. I did not find folder FB_INSTALL_DIR\eclipse\plugins\com.adobe.flexbuilder.project_4.5.0.30 8971\fiberSwcs\4.5\libs but did find what appears to be the equivalent (FB_INSTALL_DIR\eclipse\plugins\com.adobe.flexbuilder.project_4.5.1.313231\fiberSwcs\4.5\libs) so I copied in that folder's fiber.swc to LCDS. My project is still getting the following errors: Unable to resolve resource bundle "data" for locale "en_US". TBOB-POC Unknown Flex ProblemUnable to resolve resource bundle "fiber" for locale "en_US". TBOB-POC Unknown Flex ProblemGoogle search reveals that this is not an unknown problem, but I have not found a definitive explanation of how I can resolve this. Are there updated SWCs that need to be copied into the WEB-INF/flex/locale/en_US folder or do I need to add another folder to my compile path or what?Any help is much appreciated as the POC for using Adobe for mobile development at my company depends on getting this working. 6. Re: New Modeler for Flash Builder 4.5 Availabletomj Jul 28, 2011 11:58 AM (in response to dlwelden) Hello, You are missing the swc resource bundle libraries, which can be found along with the rest of the LCDS Actionscript libraries in lcds\resources\lcds_swcs\FlexSDK4\frameworks. Specifically you need the files in the "locale" directory on your link line in Flash Builder - fds_rb.swc and fiber_rb.swc. If you create a new Flex project and on the second panel ("Server Settings") select the "Java" type, and the LiveCycle Data Services ES radio button, you can then point to the default LCDS web application and Flash Builder will correctly set up all the libraries you need to do LCDS development in Flex. Hope that helps. Tom 7. Re: New Modeler for Flash Builder 4.5 Availabledlwelden Jul 28, 2011 12:14 PM (in response to tomj) Thanks for the quick reply! That does seem to have resolved the issue. If that was in the installation and configuration info, I did not find it. Much obliged!
https://forums.adobe.com/thread/858728
CC-MAIN-2018-30
refinedweb
1,470
52.46
/* * global data but it is a `private_extern' in the * shared library so that its address and size can change. */ #if defined(__APPLE__) /* * _res is declared to be the same size as struct __res_9_state * This allows both the BIND-8 library in libSystem (this one) * and the new BIND-9 library in libresolv to share the same * structure. We ues the __res_9_state's _pad variable to store * a version number when _res have been initialized by the BIND-9 * library, and take precautions to make them work together. */ #ifdef __LP64__ #define RES_9_STATE_SIZE 552 #else #define RES_9_STATE_SIZE 512 #endif char _res[RES_9_STATE_SIZE] = {0}; int _net_stayopen = 0; #endif
http://opensource.apple.com/source/Libinfo/Libinfo-330.7/dns.subproj/res_data.c
CC-MAIN-2016-44
refinedweb
105
63.22
The introduction of generics into the Java programming language will alleviate the need for the explicit cast and the potential for a runtime ClassCastException in Listing 1. The intent is that type inconsistencies can be caught for the most part (see "The Hard Parts: Pitfalls and Complexities of Generics") at compile-time rather than runtime. So let's jump in and get our feet wet with some example code using genericity. For the first example, see Listing 2, in which we rewrite the code in Listing 1 using the new generics features. Listing 2 Collections example with genericity 1 protected void collectionsExample() { 2 ArrayList<String> list = new ArrayList<String>(); 3 list.add(new String("test string")); 4 // list.add(new Integer(9)); this no longer compiles 5 inspectCollection(list); 6 } 7 8 9 protected void inspectCollection(Collection<String> aCollection) { 10 Iterator<String> i = aCollection.iterator(); 11 while(i.hasNext()) { 12 String element = i.next(); 13 } 14 } The first thing to notice is the new syntax we used on line 2 to create an instance of ArrayList. In Java 1.5, the ArrayList (and most other classes in the Collections API) will become a generic or parameterized type. A parameterized type is a class that defines a set of types (T1, T2...Tn) that must be provided for each valid declaration. Listing 3 shows part of the new class definition for ArrayList. Listing 3 Partial java.util.ArrayList source 1 public class ArrayList<E> extends AbstractList<E> { 2 // details omitted... 3 public void add(E element) { 4 // details omitted 5 } 6 public Iterator<E> iterator() { 7 // details omitted 8 } 9 } The E in "class ArrayList<E>" is defined as a type variable. This type variable is an unqualified identifier; it does not explicitly specify a type; it serves as a placeholder for a type to be defined when the ArrayList is used. On line 2 of Listing 2, we declare an instance of an ArrayList and bind the type String to the type variable E with the syntax "new ArrayList<String>()". As such, when the method public boolean add(E o) {...} is called on this instance, E is logically bound to the String type as if the method had been declared as follows: public void add(String element) { ... } Because the type variable "T" is used throughout the new implementation of ArrayList, all methods that previously would have taken an Object as a parameter or returned an Object are now constrained by the parameter type. You can see the results of this in our example code. In line 4 of Listing 2, where we try to add an Integer to our ArrayList<String>, we get a compile-time error. When extracting elements from our collection in line 12, we are able to retrieve elements without the type cast required in our first example, Listing 1. In effect, our instance of ArrayList<String> behaves as if it were coded to contain only instances of String. A major goal in adding generics to Java is to "increase type safety without type variation." Otherwise stated, the intent is to enable more compile-time type checking through more declarative interfaces without requiring the developer to code different classes for different scenarios, such as an "ArrayList of String" versus an "ArrayList of Integer." From this notion, we can see that an "ArrayList<String>" is essentially a new type, and is treated by the compiler as such. Based on this simple example, we can see the following benefits of genericity: We now have Collections that are type safe (restricted to contain elements of a single type) without type variation. For example, in line 4 of Listing 2, any attempt to add an element of a type other than String to this collection will cause a compile-time error. Type casts are now implicit rather than explicit. With a homogeneous collection of Strings, retrieval of any element within the Collection no longer requires an explicit cast (see line 12 of Listing 2). The Java language is now more declarative and provides stronger interface contracts. Line 9 of Listing 2 makes it very clear to the client (caller) of the inspectCollection(...) method that a "Collection of Strings" is the required parameter type. Type mismatch errors are caught at compile-time rather than at runtime. Constraining Type Variables Though many generic classes are designed to work with any class (or, more correctly, Object and its descendants), type parameters can be constrained using the following syntax: public class C1<T extends Number> { } public class C2<T extends Person & Comparable> { } In the first example, the type passed as a parameter to C1 must be Number or a subclass of Number. In the second example, the type parameter must extend Person and implement Comparable.
http://www.informit.com/articles/article.aspx?p=170176&seqNum=2
CC-MAIN-2020-10
refinedweb
790
52.39
Sometimes you need to use really big numbers — and 32 bits just won’t cut it. Fortunately, the gcc compiler has this covered; its “long long” type supports signed and unsigned 64-bit integers. The difference is huge — whereas unsigned 32-bit integers are limited to 0-4,294,967,295, 64-bit integers can go all the way up to 18,446,744,073,709,551,615. These numbers can be used in C as shown in this example: #include <stdio.h> int main(){ //Variable declaration unsigned long long int myNumber = 1; int power; //For loop for(power = 0; power < 63; power++){ printf(“Power: %d Number: %llu\n”,power,myNumber); myNumber = myNumber * 2; }//for return(0); }//main()
http://www.paleotechnologist.net/?p=3521
CC-MAIN-2018-22
refinedweb
118
60.24
In the last post, we had started to design a movie recommendation engine using the 20 million ratings dataset available from MovieLens. We started with a Content Based Recommendation approach, where we built a classification/regression model for each user based on the tags and genres assigned to each movie he has rated. The assumption behind this approach is that, the rating that an user has given to a movie depends on the characteristics of the movie such as the genre, actors, year of release etc. and his affinity towards those characteristics. But it is not always so, as we have found out that, users tend to watch and rate movies similar to other users who have watched and rated multiple movies in common between them, probably due to some social network effect. Approaches that provide recommendations based on similarity between users or movies such as Collaborative Filtering performs better than the Content Based approach. In this post, we would be looking into the Matrix Factorization approach for recommendations. In the MF approach, we discover the common latent factors that movies have/don't have and users prefer/don't prefer. These are called latent factors because, we don't have explicit information about these factors but only inferred from ratings. For e.g. if a movie is tagged as a "Horror" movie and an user has specified that he likes "Horror" movies in his preferences, then "Horror" factor is not latent as it is explicitly stated by both the movies and the users. The latent factors may or may not be interpretable easily. Latent Factors in 2 Dimensions (Male/Female and Serious/Lighthearted). For e.g. let their be a set of 3 movies that a set of 5 users who have watched all of them. Then their must be some common factors between these movies as well as these users. The common factors could be Johnny Depp, sci-fi, sequels, age group etc. Then the users might like Johnny Depp, like sci-fi, have watched the prequels, belong to the same age-group and so on. As you see that we have not explicitly introduced these factors but they could be learnt by the model. But again the interpretation of the factors could completely be wrong, and the reason that the users have watched all 3 of these movies could be that they are friends or roommates. Thus our model should not depend on whether we are able to interpret these factors correctly, but only on whether the factors are able to explain the ratings approximately well. Given the ratings matrix R of dimension NxM (where N is the number of users and M is the number of movies), the MF approach tries to find two matrices P, of dimension NxK and Q, of dimension MxK such that: R = PQT, where K is the number of latent factors. P is the matrix of user vs. latent factors, i.e. how strongly an user is aligned towards these factors. Q is the matrix of movie vs. latent factors, i.e. how strongly a movie captures these factors. Decomposition of Ratings Matrix into Latent Factor Components. Note that we do not want the learnt matrices P and Q to exactly reproduce R, because then the unrated entries will remain unrated or become 0's. We want the product to approximate R with some R' : Once we have computed the matrices P and Q, then the unknown entries can be computed as follows : , where is the (i, k)-th entry in matrix P and is the (k, j)-entry in matrix QT. The MF approach is somewhat similar to the Content Based Linear-Regression approach. Recall that in the linear regression approach, we created a movie-tag matrix X, of dimensions MxD, where D is the number of tags, and then we fitted a linear regression model for each user. For the i-th user, the ratings were given as : = where is the rating given by user i to movie j, is the entry for the (k, j)-th cell in the movie tag matrix X and are the weights corresponding to the tag k for the user i. Note that this expression is very similar to the expression for with latent matrices P and Q, where the matrix X corresponds to Q and the weights corresponds to P. Only difference is that, in the linear regression approach we already knew X and only had to learn the weights . Whereas with MF, we neither know P nor Q and need to learn both simultaneously. Thus now we have (N + M)*K number of unknown variables to determine. The number of linear equations to solve is equal to the number of known ratings in the matrix R. Thus this is an underdetermined system because the number of equations to solve is less than the number of unknown variables. If there were no unknown ratings in the matrix R, then we could have solved the linear system of equations exactly. But a ratings matrix without any unknown ratings is of no use to us unless we want to obtain only the latent factors. Assuming that the ratings matrix is full or we fill the unknown ratings with the average of known ratings for that movie (imputation), then one can obtain the latent factor matrices P and Q using the Singular Value Decomposition (SVD) technique. Given a matrix A of dimensions NxD, SVD decomposes A as follows: A = USVT where U is a NxN matrix, S is a NxM diagonal matrix and V is a MxM matrix. Both U and V are orthogonal matrices. The diagonal matrix S contains the singular values of A along its diagonal. If the rank of matrix A is r <= min(N, M), then only the first r values along the diagonal of S is non-zero, rest all are zero. The singular values along the diagonal is ordered is descending order, i.e. S00 >= S11 >= ... >= Srr If we compute the following AAT = USVTVSTUT, since V is orthogonal, thus VTV = I and thus AAT = USSTUT, SST is nothing but the squares of the singular values [S200 , S211 , ... , S2rr]. Recall that any square symmetric and real valued matrix X of dimensions MxM can be written as X = QLQT, where the columns of Q are the eigenvectors of X and the diagonal matrix L contains the eigenvalues of X along its diagonal. Now since AAT is also a square symmetric matrix and AAT = UYUT, where Y = SST, it implies that columns of U contains the eigenvectors of AAT and the singular values of A are the square root of the eigenvalues of AAT . Similarly one can compute ATA = VSTUTUSVT = VYVT, and show that the columns of V contains the eigenvectors of ATA. Note that since the rank of matrix A is r, it implies that the maximum number of latent factors possible (linearly independent eigenvectors) is r. Thus if we consider S to be a rxr diagonal matrix, take only the first r columns of U i.e. Ur is now of dimension Nxr and take the first r columns from V, i.e. VrT is now of dimension rxM, then A can be written as: A = UrSrVrT Now if we consider P = UrSr1/2 and Q = VrSr1/2, then P is of dimension Nxr and Q is of dimension Mxr, then A can be written as A = PQT. Thus our ratings matrix R can be factorized as R = PQT, where the user-latent factor matrix P = UrSr1/2 and movie-latent factor matrix Q = VrSr1/2 where Ur, Sr and Vr are the components of the SVD decomposition of R, taking only the r non-zero singular values (latent factors). Generating a random normal matrix N(0,1) of dimensions 4x5 in python: import numpy as np a = np.random.randn(4, 5) print a [[]] Then compute the components Ur, Sr and Vr using the SVD of the matrix a: u, s, vt = np.linalg.svd(a, full_matrices=False) print u print s print vt u [[-0.66244007 -0.14620624 -0.28178952 0.67852159] [-0.7241735 0.11299258 0.00575221 -0.68027372] [ 0.18772633 0.1214737 -0.95642687 -0.18775145] [-0.03879077 0.97524384 0.07621824 0.20392524]] s [2.6195574 1.41049797 0.74391795 0.20018552] vt [[-0.52540938 0.79741686 0.03207695 -0.28758935 0.06583898] [ 0.02126017 -0.27073661 -0.21980786 -0.66231373 0.66277803] [-0.84653401 -0.51681081 0.02217042 0.09804947 -0.07862272] [ 0.03155047 -0.05726469 0.96633489 -0.05297752 0.24313698]] Note that the rank of the matrix is 4 because min(4, 5) = 4. Then compute the matrices P and Q as follows: s1 = np.diag(s) p = np.dot(u, s1**0.5) q = np.dot(s1**0.5, vt) print p print q P [[-1.07216236 -0.17364095 -0.24304538 0.30358478] [-1.17207819 0.13419494 0.00496132 -0.30436872] [ 0.30383595 0.1442675 -0.82492466 -0.08400394] [-0.06278304 1.15824237 0.06573875 0.09124043]] Q [[-0.85037754 1.29062292 0.0519167 -0.4654647 0.10656069] [ 0.02524951 -0.32153868 -0.26105346 -0.78659284 0.78714427] [-0.73014133 -0.44575283 0.01912213 0.08456833 -0.06781263] [ 0.01411634 -0.02562142 0.43235849 -0.02370325 0.10878458]] We can verify that PQT gives back our original matrix a: np.dot(p, q) array([[]]) But there are several challenges with this approach: - Computing SVD requires knowing the full matrix R. If we fill the unknown ratings with imputed values from average ratings, the predicted ratings are not that good. - The complexity of SVD computation is O(min(N2M, NM2)). Given that N (number of users) could be in millions and M (number of movies) also could be in several thousands, computing SVD on the full imputed matrix is wastage of space and running time. - Since the rank of the full matrix R' could be in several thousands (20-50K), but the number of "useful" latent factors could be much less ~500, we don't need to compute the latent factor matrices with full rank, but reduced rank k = 500. - The optimal value of reduced rank k << r can be chosen using the following criteria: = 0.95" />, ATruncated = UkSkVkT - This is known as Truncated SVD. Python functions for getting a matrix of reduced rank after SVD. Note that although the rank of the new matrix is less than r i.e. < min(N, M), but the dimensions of the new matrix is the same as the original matrix. def get_truncated_rank(s, acceptance_ratio=0.95): s_sum_sq = np.sum(s**2) r = min(a.shape[0], a.shape[1]) for k in range(1, r + 1): sk = s[:k] sk_sum_sq = np.sum(sk**2) if float(sk_sum_sq)/s_sum_sq >= acceptance_ratio: return k return r def get_reduced_rank_matrix(a): u, s, vt = np.linalg.svd(a, full_matrices=False) k = get_truncated_rank(s) print k uk, sk, vkt = u[:,range(k)], np.diag(s[:k]), vt[range(k),:] return np.dot(np.dot(uk, sk), vkt) Original 10x5 matrix of rank 5 [[-0.49068061 -0.9511035 -0.29747854 0.38704866 -0.5231572 ] [ 0.12211881 0.70603132 -1.10839293 -0.311787 0.11332492] [ 1.56766408 -0.57486759 1.25176635 -0.29809648 0.47678418] [-1.09934274 0.43489352 0.11940306 -0.16246338 -0.75328974] [-0.29756537 -0.98728997 -0.29510109 0.93565654 -1.39858189] [-0.67094911 -0.91362783 1.14857474 0.12041214 0.45741434] [ 0.34530484 -1.23295696 0.45495699 0.04401526 -0.91377875] [-0.30555599 -0.64147676 -0.16349685 0.70730611 -1.22413623] [-1.57833146 -0.76579262 0.63032095 0.11872791 0.82668229] [-0.540997 0.35148116 -0.80480644 0.97053772 -0.78488335]] Reduced rank matrix of rank 4 [[-0.46150266 -0.83624914 -0.19300256 0.62281513 -0.48798781] [ 0.15803602 0.84741373 -0.97978602 -0.02156528 0.15661741] [ 1.547334 -0.65489369 1.1789715 -0.4623695 0.4522795 ] [-1.08705211 0.48327364 0.1634115 -0.06315143 -0.73847533] [-0.3041663 -1.0132735 -0.31873672 0.88231904 -1.40653827] [-0.68520739 -0.96975328 1.09752085 0.00520101 0.44022825] [ 0.38303915 -1.08442184 0.59007028 0.34891964 -0.86829603] [-0.31413073 -0.67522989 -0.1942 0.63801962 -1.23447172] [-1.57437555 -0.75022082 0.64448566 0.15069282 0.83145051] [-0.59155926 0.15245084 -0.98585213 0.56197966 -0.84582813]] Python function for getting a dimension reduced matrix (similar to PCA dimensionality reduction). def reduce_dimension(a, k=10): u, s, _ = np.linalg.svd(a, full_matrices=False) uk, sk = u[:,range(k)], np.diag(s[:k]) return np.dot(uk, sk) print reduce_dimension(a, 2) Dimensionality Reduced matrix. (of dimensions 10x2) [[-1.12417244 -0.41135465] [ 0.23754468 1.26301679] [ 1.29629456 -1.35157959] [-0.78276953 0.33160769] [-1.84564669 -0.35711333] [-0.10744961 -1.48758873] [-0.74887017 -1.09900671] [-1.49468627 -0.21703858] [-0.3753158 -1.04722398] [-1.25498373 0.88466669]] With missing ratings, instead of doing SVD with imputations, we can directly work with only observed ratings. Similar to finding solutions for underdetermined linear system of equations, we will use least squares fitting method for finding the unknowns. i.e. for the observed true ratings , find the values of and , such that: is minimized. Note that in the above loss function, the summation is over only those pairs (i, j) for which there is an observed rating. This is the loss function that we want to minimize. As with most machine learning systems, in order to reduce overfitting, we must add regularization to the above loss: , after adding L2 regularization. where is a constant for the regularization term. One can solve the above loss minimization problem using the Gradient Descent technique: and Define The partial derivatives of the loss w.r.t. the unknowns (the constant 2 has been omitted): and In the first equation, the summation is over all movies rated by user i and in the second equation, the summation is over all users who have rated movie j. In Stochastic Gradient Descent (SGD), instead of iterating over all movie ratings in each epoch, we randomly sample a single movie rating, and then update the corresponding row from P and column from Q that gives the corresponding rating. The final update equations are as follows (the superscript t denotes the epoch number): and Instead of sampling only a single rating in each epoch, we can randomly sample a batch of ratings for efficiency purpose. This is known as Batch Gradient Descent. With our 20 million ratings from the MovieLens database, first we prepare the training and validation data. We randomly selected 5000 ratings for validation and kept the remaining for training purposes. from collections import defaultdict import numpy as np import os, random import pandas as pd) random.shuffle(uid_mid_pairs) validation_data, training_data = uid_mid_pairs[:5000], uid_mid_pairs[5000:] For our P and Q matrices, we need a way to map the user ids and the movie ids to corresponding rows in the matrices P and Q respectively. uid_map, mid_map = dict(), dict() user_id, movie_id = sorted(list(set(user_id))), sorted(list(set(movie_id))) for idx in range(len(user_id)): uid_map[user_id[idx]] = idx for idx in range(len(movie_id)): mid_map[movie_id[idx]] = idx Next we define the function for getting the errors from the predicted model, i.e. given a P and a Q matrix, and the set of ratings for which we want to compute the error, the function computes the predicted rating as: Then we simply subtract this from the true rating to get the error: . def get_ratings_errors(p, q, uid_map, mid_map,) return true_ratings - preds Note that, we are using the maps to map back the user and movie ids to corresponding rows and columns in P and Q respectively. Now we come to the training part. Since initially we do not know P and Q, we randomly initialize them from the N(0,1) distribution. From multiple experiments and observations, I found out that vanilla SGD (the standard one) is pretty slow in convergence. So I had used momentum to speed up the convergence a bit. Finally I went with the Adam algorithm for optimization. - Parameter update methods as described in the cs231n tutorial. - Overview of gradient descent optimization algorithms. def init_matrices(num_users, num_movies, latent_dim=128): p, q = np.random.randn(num_users, latent_dim), np.random.randn(num_movies, latent_dim) pm, qm = np.zeros((num_users, latent_dim)), np.zeros((num_movies, latent_dim)) pv, qv = np.zeros((num_users, latent_dim)), np.zeros((num_movies, latent_dim)) return p, q, pm, qm, pv, qv def train_sgd_adam(training_data, validation_data, uid_map, mid_map, batch_size=32, max_tol_loss=0.5): eta, lambdas = 0.001, 0.1 beta1, beta2 = 0.9, 0.999 eps = 1e-8 p, q, pm, qm, pv, qv = init_matrices(len(uid_map), len(mid_map), 128) num_iter = 0 while True: num_iter += 1 if num_iter % 1000 == 0: errs_validation = get_ratings_errors(p, q, uid_map, mid_map, validation_data) rmse_loss = np.sqrt(np.mean(errs_validation**2)) print rmse_loss if rmse_loss < max_tol_loss: break selected_pairs = random.sample(training_data, batch_size) errs_train = get_ratings_errors(p, q, uid_map, mid_map, selected_pairs) errs_train = errs_train.reshape((errs_train.shape[0], -1)) p_idx, q_idx, true_ratings = map(list, zip(*selected_pairs)) p_idx = [uid_map[x] for x in p_idx] q_idx = [mid_map[x] for x in q_idx]) return p, q Note that the Adam optimizer requires additional auxiliary matrices "pm", "pv", "qm", "qv", which are initialized with all zeros. In each iteration, we randomly select 32 ratings from the training data, compute their errors in prediction, compute the gradients and then update the variables accordingly. To assess how the model is learning, after each 1000 iteration, I am computing the RMSE error on the validation data. Stop iterating when RMSE loss on validation data is lower than maximum tolerable loss. Since the validation data is out of sample for the training data, we need optimum regularization trade-off for the model to learn well. If the regularization constant is too less, then the models P and Q perform well on the training data but generalizes poorly on the validation data. Recall that in the CF approach, we had normalized the ratings for each user (by subtracting the mean and dividing by std. dev.) due to inconsistent ratings. In the Matrix Factorization approach we can incorporate these factors into the model itself. Thus the normalization factors are learnt by the model. Each rating can be thought of being composed as: mean rating + bias of user + bias of movie + latent factors common to both user and movie. The updated ratings equation: where is the mean rating on the dataset, which is around 3.52, is the bias of an user i.e. some users tend to give high ratings (3,4,5) while some users tend to give low ratings (1,2,3). is the bias for a movie i.e. some movies tend to get very high ratings due to promotion and marketing. One can remove the constant 'mean rating' component from the equation and let the other three components learn that. But that might lead to some additional number of iterations. In order to incorporate bias terms in our code, we modify the 'get_ratings_error' function to add the additional factors. def get_ratings_errors(p, q, uid_map, mid_map, bias_u, bias_m, mean_rating,) preds += bias_u[p_idx] + bias_m[q_idx] + mean_rating return true_ratings - preds We also need to initialize the bias vectors for both users and movies. The biases are all initialized with all zeros. def init_biases(num_users, num_movies): bias_u, bias_m = np.zeros((num_users)), np.zeros((num_movies)) b1m, b2m = np.zeros((num_users)), np.zeros((num_movies)) b1v, b2v = np.zeros((num_users)), np.zeros((num_movies)) return bias_u, bias_m, b1m, b2m, b1v, b2v The additional terms are required for Adam optimization similar to the latent matrices P and Q. We also need to update the bias terms as follows: selected_pairs = random.sample(training_data, batch_size) errs_train = get_ratings_errors(p, q, uid_map, mid_map, bias_u, bias_m, mean_rating, selected_pairs) p_idx, q_idx, true_ratings = map(list, zip(*selected_pairs)) p_idx = [uid_map[x] for x in p_idx] q_idx = [mid_map[x] for x in q_idx] u, v = bias_u[p_idx], bias_m[q_idx] gradb1, gradb2 = -(errs_train - lambdas * u), -(errs_train - lambdas * v) b1m[p_idx] = beta1 * b1m[p_idx] + (1 - beta1) * gradb1 b1v[p_idx] = beta2 * b1v[p_idx] + (1 - beta2) * (gradb1**2) bias_u[p_idx] += -eta * b1m[p_idx]/(np.sqrt(b1v[p_idx]) + eps) b2m[q_idx] = beta1 * b2m[q_idx] + (1 - beta1) * gradb2 b2v[q_idx] = beta2 * b2v[q_idx] + (1 - beta2) * (gradb2**2) bias_m[q_idx] += -eta * b2m[q_idx]/(np.sqrt(b2v[q_idx]) + eps) errs_train = errs_train.reshape((errs_train.shape[0], -1))) With 64 latent factors, the RMSE loss varies between 0.78 to 0.85 for the validation data set. Note: Once can try to reduce the validation error by reducing the regularization constant whenever the RMSE error gets 'stuck'. But that might work with only an instance of validation data. There is another popular method for finding the solution for the unknowns known as the Alternating Least Squares (ALS). Instead of finding the updated values of both and simultaneously as in SGD, in ALS, we alternately fix either of or to be a constant and then update the value of the other and repeat this until convergence. For e.g. in round 1, we fill matrix Q with some random values sampled from a normal distribution N(0,1). Then the values in the loss function becomes a constant for us. We only need to find the values for . Note that this is same as finding the coefficients in a linear regression problem. One can use SGD here too, but we can directly compute the values i.e. latent factor vector for user i, as follows: Compute , X is a KxM matrix. where the summation is over all movies user i has rated. After we have updated the matrix P, in the next round, we fix the values of to the ones computed in the last iteration and proceed to update the unknowns for Q, i.e. Compute , Y is a KxN matrix. where the summation is over all users who have rated movie j. Moore-Penrose Pseudoinverse. We repeat this process until the values of P and Q stops changing by more than some threshold. With limited resources and for scalability reasons it is advisable to compute and using SGD technique instead of costly matrix operations like , or their inverses. For 1 million users, would be of size 1012. The advantage of ALS method over SGD is that the calculations for the and can be parallelized. In our SGD method, the current update for depended on the last update for , while the last update for depended on the last to last update for and thus each cannot be independently updated. Practical Recommendations for ALS. Whereas in ALS, since in each round, we hold either one of or constant, thus each or is independent in alternating rounds. Before ending this post, I would like to point out that MF should be the preferred approach for a recommendation engine due to the following reasons: - Scalability - In Content based approach, we require a model for each user. Thus with a million users, we would have a million models. - In CF approach, we needed to compute pairwise similarities between every pair of users or movies which is O(N2). - In MF approach, we only need to compute two matrices P and Q. We have seen that even with very less number of latent factors (64) we are able to generate good enough RMSE scores on the validation data. - With SGD optimization (+Adam), we can easily train with 20 million ratings in under 3-4 hours and compute predicted ratings for all unrated movies. - If we use ALS, then we can parallelize the computations also. We cannot parallelize user or item based CF effectively. - Speed of Prediction - In CF based approach, we cannot produce prediction at run time because at run time we need to perform pairwise computations to find similar users or movies, which is not feasible. - In MF approach, if we can keep track of all movies an user has not rated yet, then we can produce predictions at run time very fast. Edit: I realized that the number of iterations to convergence of the Adam method could be reduced by selecting the initial random matrices P and Q well. If we use the model without the bias terms i.e. Then we can choose the values of P and Q in a way such that their dot products are close to the mean rating of 3.52. For e.g. if I choose all of P and Q to be some 'x', then any dot product would be where K is the number of latent dimensions. Thus if I choose the random values for P and Q from the following normal distribution: Then all dot products would approximately be close to 3.52 and the starting validation error would be quite close to the true error. def init_matrices(num_users, num_movies, mean_rating, latent_dim=128): mu = np.sqrt(mean_rating/latent_dim) p = np.random.normal(mu, 0.001, num_users * latent_dim).reshape((num_users, latent_dim)) q = np.random.normal(mu, While in the case of the model already with the mean rating and bias terms, i.e. The values of P and Q should be chosen to be close to 0 as much as possible to keep the initial errors as low as possible. def init_matrices(num_users, num_movies, mean_rating, latent_dim=128): p = np.random.normal(0.0, 0.001, num_users * latent_dim).reshape((num_users, latent_dim)) q = np.random.normal(0.0, Go to Part 3 to know about SVD++ technique. External References: --[Netflix].pdf --[Koren-and-Bell].pdf - Categories: AI, DESIGN, MACHINE LEARNING, PROBLEM SOLVING Tags: Alternating Least Squares, Least Squares, Matrix Factorization, Recommendation System, Singular Value Decomposition, Stochastic GRadient Descent
http://www.stokastik.in/designing-movie-recommendation-engines-2/
CC-MAIN-2018-47
refinedweb
4,252
61.77
Agenda Jonathan: I was wondering which issues we could leave open as we take Core and SOAP binding to LC ... I'd like to walk into the F2F knowing which issues we need to close Mark: we'll be discussing this later in this call then Minutes are at Mark: Umit wanted to clarify something she said Minutes accepted with Umit's amendment Mark: I saw that Gudge did the schema AI ... did you see the original version of the schema? Gudge: sorry, I didn't and started from scratch ... we will approve it next week Jonathan is reminded of his IRI AI Mark: we'll be meeting Sunday-Tuesday next week ... we will go to Bob's for dinner on Sunday Bob goes over the yummy menu (including stinky cheese) Bob, Mark and Hugo discuss details An email will be sent out to the WG Mark: you will need somebody to get in, so please be prompt ... call Philippe or myself if you're late ... we'll have a meeting with the TAG; Paul will be presenting Addressing and our issues to the TAG Paul: I'll try to have slides early ... I'd be interested in pointers from people Mark: with regards the April F2F, we're looking at 19-20 April ... having not heard any push back, those dates are now final ... we'll be sending admin details soon ... for June, we're still looking at Berlin on 30 May ... we're looking at co-hosting with WSDWG again Jeff: I'd prefer the end of the week Hugo presents Proposed: Misalignment of treatment of reply messages and fault messages; Issue accepted; owner is Hugo Friendly amendment is: Mark: please have a look at this this week, and we can close this next week <mnot> new modules: Hugo presents Definition of SOAP 1.2 (and 1.1) modules; Mark: I'd like to make this a proposal for issue i022 Hugo presents "Binding of message addressing properties in the SOAP underlying protocol"; Mark: do you want this to be folded under i022? Hugo: no preference Greg: I prefer a separate issue Hugo is the owner of the new issue <mnot> proposed issue: what is a logical address? Anish presents "What is a logical address?"; Mark: any problem with putting this on the issues list? Gudge: what's the difference between logical and dereferenceable? Jeff: what's the difference between logical and physical? Gudge: that the address may not be the physical one <TomRutt> I agree this is an important issue as the spec stands <pauld> for the most part liked anish's proposal, though i'm unsure about what dereferencable really means. Anish: I'm getting a lot of questions about "logical address" ... we should at the minimum define it Dave: WebArch defines what dereferenceable means, so I think it would be good to reuse the term, and I do agree that there is some confusion around this <uyalcina> you missed me David. I know what deferenceable means. I am just trying to understand the logical address vs. a dereferanceable address Umit: I agree there is an issue Tom agrees Issue is added to the issues list; Anish is the owner <uyalcina> there is an issue with the wording in the text with respect to what logical address means. <pauld> just looked at the web-arch, using 'dereferencable' looks good! Anish: I will add more references, e.g. to WebArch in my proposal Mark: my thinking was that we needed to close issue i004, i007 ... i017 is WSDL specific ... what about i020? Anish: I think that this is WSDL specific Mark: i021 is WSDL specific ... i022 need to be closed ... so do i024 and i26 ... i041 can wait ... i042 and i43 need to be closed ... i048 too ... all the new issues need to be closed Jonathan: what can we do about i022? Mark: it's unclear right now Greg: i022 certainly has a relationship with the WSDL document Mark: on the last call, the TF thought that we didn't need any big changes Mark: we're missing an AI from Marc <mnot> Gudge presents Mark: is there a relationship with i007 with regards to the text about intermediaries? Gudge: my understanding is that i007 is about targeting nodes, not tampering with default values and XML representations Anish: this isn't specific to Addressing, right? Gudge: the particularity is default values Gudge: these are our headers Hugo: if all specs defining headers need to do that, is there anything wrong with SOAP? Gudge: we have default values, which is where the issue is ... to work around this, we would need to define a C14N transform Anish: does that only apply to forwarding intermediaries? Gudge: agreed Mark: are people comfortable with this? could we close i004 with this? ... I know Marc and Paco had other ideas in mind Considering Gudge's proposal with Anish's amendment about forwarding intermediaries Greg: do we say that it means to sign an EPR? Gudge: no, because I couldn't get some agreement around that with the people I talked to ... there are different feelings about what needs to be done to secure EPRs Mark: one thing to consider is whether this is good for us; if we need more than this, we may be able to do something as an extension later ... let's wait for Marc and Paco to see if they want to add something to this; we'll decide on this early in the F2F Jonathan presents <mnot> Mark: would anyone object to closing i042 with this proposal? None RESOLUTION: Issue i042 closed with <scribe> ACTION: Editors to integrate Marc hasn't done his AI Chair will ping Marc <mnot> Hugo made a proposal for addressing the first part of the issue: Mark: do people think that targetting is a good idea? Anish does <mnot> Mark: Glen has a proposal, but it's not detailed enough IMO ... would anyone would like to expand on this proposal? Jonathan: I'm confused about it <scribe> ACTION: Hugo to make his proposal about i007 clearer Mark: we have a TF looking at the relationship between SOAP, Addressing, and WSDL ... Hugo raised 2 related issues ... what do we need to do to close i022? Greg: I want to know what portion goes as SOAP messages, and what portion goes as transport messages [scribe poorly paraphrasing] ... I am wondering if we should move a portion of the SOAP document in the WSDL document ... that may mean being able to delay the decision on i022 beyond next week Mark: you would like to have transport-specific wording in the SOAP spec? Greg: yes ... I have heard different things about the current SOAP binding ... I think that we need to call a specific behavior out Anish: do you think that the binding satisfies what we need? Greg: yes Anish: my interpretation was that, for SOAP 1.2, the current transport binding wasn't enough <uyalcina> +1 to Anish, this is my understanding as well Anish: for 1.1, because of the WS-I interpretation, one-way is covered ... this isn't the case for 1.2 Greg: but this is for one-way, not for req-resp Umit: the discussion was around whether the WSDWG should define a new SOAP binding Greg: I'm hoping that we can discuss options at the F2F, and choose the bare minimum to get out of this Mark: are you talking about LC or CR? Greg: CR; it would be nice to have them fixed for LC [confusion around LC/CR] Mark: do people think that we can ship documents as LC drafts with the resolution of these issues? ... if not, can we have this solved in other drafts? Jonathan: I think we'll be able to ship our LC drafts ... I'm not sure that we would even need to publish other drafts as Recs Umit: it seems to me that we have SOAP and WSDL issues, not Addressing ones Mark: what do we need to do to close i022? ... Greg wants to see info from the TF ... Hugo wants us to define a SOAP module ... anything else? Nothing Mark: have people had a chance to look at Hugo's proposals? Jonathan: I don't see anything wrong with it, but I'd like a little more time Mark: let's talk about it next week Mark: in the most recent proposal, I didn't see a way to differentiate referenced vs. included metadata Rebecca: but you could put a URI in the metadata section <TomRutt> the definer of the metadata namespace determines the semantics Anish: I thought that the difference was service QName vs. service element Mark: do we want to have a discussion about whether there should be a generic mechanism for doing self-Contained vs. referenced metadata? Umit: it all depends on the element you put in there Mark: Rebecca, would you be comfortable dropping i024 in favor of i026 which encompasses this? <anish> i thought rebecca was interested in having the complete wsdl inlined in an EPR Rebecca: no, we have a specific proposal Mark: we would need a concrete proposal by next week then Rebecca: would you like me to split the proposal i026 into 2? Mark: if this is what you want, yes Jonathan: what does it look like to reference metadata in your proposal? Rebecca: we're proposing a generic metadata bucket Umit: we're using QNames for service names, as an example Mark: the way I understand i024, it's about providing a generic mechanism to refer to any type of metadata <RebeccaB> Sorry - I just lost my phone connection Anish: I remember that Rebecca wanted to have a whole WSDL in an EPR Mark: my understanding was really about a generic mechanism Jonathan: I'm confused; maybe we should be discussing i026 first Umit: I think that Rebecca got it right; for i024, we're providing a generic metadata bucket; for i026, we're using it for multiple endpoints Rebecca confirms Mark: I think it would be helpful to have a separate proposal for i024 ... otherwise it's hard to differentiate them Mark: we have a detailed proposal Jonathan: I have ideas for a friendly amendment; I'd like to take it up next week Dave: the notion about putting metadata in a metadata container doesn't make sense to me ... in order to differentiate data and metadata, we would need to have something in the spec to talk about how to use this ... we already have a pretty open extensibility model Anish: we have wording in the spec (section 2.3) about metadata comparison ... we already have an issue on EPR comparison ... depending on its resolution, we would need this or not Umit: I agree with Anish, and I would tend to agree with Dave too Mark: maybe the authors of the proposal would want to provide an updated proposal Anish: certainly, there is a dependency on the EPR comparison issue I have made the request to generate hugo
http://www.w3.org/2002/ws/addr/5/02/21-ws-addr-minutes.html
crawl-001
refinedweb
1,841
66.98
Is there any way to extend the lookup table to have more than one value against a key? Announcements Hi, I installed Cache2015. I went to %SYS namespace and d ^JOBEXAM it shows around 12 background jobs running. Can i know what is the purpose of that jobs? Thanks, Selvakumar Hi Community, I would like to share with you my experience regarding to debugging via Atelier. I'm developing a REST API and would like to attach to a process when I call the API via a REST Client tool, for example Postman. The purpose is to inspect values from HEADER and BODY of the HTTP request during the debugging process. Come on! How am I doing? I am going to demonstrate that by using a class from SAMPLES namespace. 1 - Open Atelier; 2 - Open your REST Service class; 3 - Go to the method related to the URI that you need to debug; I use zf(-2) to spawn a external a Java application in a *nix instance. I would like to kill this process after some conditions met. I would like to leverage $zf("kill ... ") but this requires its the pid of this child process. So is there a way to acquire the pid for the child process when I create it ? If not, how is the suggested way to kill this process? Thanks. Hi all,.". This is probably a very naive question but : Is it possible to create a Windows executable file from a Cache MUMPS (COS) routine, such that the routine can be run directly from Windows ? If so, could some kind soul direct me to a source of information that describes the process. I am using the free Intersystems Cache installation (CachePCkit V2017.1) on Windows 10 for my own use & personal development. Thanks; Working fine in localhost. While connecting to remote server getting the above error. Tried with Web Port 1972 and 80 both. Also there is no log in audit viewer. I am using the free Intersystems Cache installation (CachePCkit V2017.1) on Windows 10 for my own use & personal development. I am writing routines in Studio & running them in the Cache terminal TRM:3672 (TRYCACHE). From a routine, how do I control print position within the terminal screen. I have tried using $X and $Y but this does not work and I cannot find what I need within the Cache terminal documentation. Hope this question is not too simplistic for Members. Any suggestion would be appreciated. Hi, Community! Someday you find yourself having a wonderful class package which can be helpful in several projects. So it is a library package. How to make the classes available for different namespaces in Caché? There are two ways (at least two ways familiar to me): 1. Start the name of the package with %, like %FantasticLib.SuperClass. Wrong way. If you do that the class would be placed in %SYS and would be available in other namespaces. This is wrong because of the two reasons: Hi, Community! Please find the digest of the best articles you posted on DC in 2017 regarding InterSystems Data platform. We had 280 articles in 2017 and split them into 3 categories: posts gathered most of the views, most voted posts and most commented posts. Here we go! TOP 20 Most viewed Hi All, I am new to webservice and UPS. I have tried the sample URL's that UPS have given for testing in PHP codes and it works just perfect for me. But when i try to hit the same URL's in Ensemble. it gives some errors from UPS. If anyone of you guys here has any knowledge about UPS integration or the webservice please help me. it will be much appreciated and helpful. The ensemble code that i am trying with is, Hi, Can you provide a link to a valid license key zip file as the previous key expired December 31st, 2017. Many thanks. I am trying to achieve this in cache objects I am using 2014.1 here is the original code in C# and would like to convert this to cache here is my code first c# and cache follows I use SoapUI 5.4.0 test Cache development web service, the parameters I need to send through SoapUI is as follows: Apart from the database server itself, the standard bundle of the Caché DBMS includes DeepSee, a real-time business intelligence tool. DeepSee is the quickest and the simplest way of adding OLAP functionality to your Caché application. Another standard component is an Audit subsystem with a web interface, which has the options for expanding with your own event types and an API for using in an application code. Below is a small example of the joint use of these subsystems that answers the following questions: who did what and when in an information system? Hi, Hi Everyone, I am trying to reference a field, however, in our production environment, it can be found in the first second or third iteration. My code was only qualifying on the first iteration. I have been attempting to include all iterations, but I have come up short...below is a snippet of what I am attempting to use. My original code simply had GetValueAt("PID:13.4") but this only referenced the first iteration. Thanks for any thoughts! Hi,. Hi, the 2017 filed test key has expired. When can we get the new one?. Hi I am new using atelier and i want to use some of the Intersystem server for me to train so is there any server connections that i can use. Please help me on this. Hi, Community! This post is a digest of the Developer Community postings in December 2017. Most viewed Adventofcode.Com 2017 is live :) 509 SQL or Cache Function? 236 Getting Current Day in Cache 142
https://community.intersystems.com/group/announcements?period=2018&page=41
CC-MAIN-2020-16
refinedweb
976
74.08
. You access the Password Manager from the Firefox menu via "Tools -> Options -> Security / Passwords". The "Saved Passwords" window (Firefox 3) or "Remember Passwords" window (Firefox 2) lists the web sites and user names for your stored passwords and includes a "Show Passwords" button that lets you view your stored" or "Remember ("Exceptions - Saved Passwords" in Firefox 3 or "Don't Remember Passwords" in Firefox 2). If you use Firefox 3 and still see encrypted names and passwords in the file signons3.txt (signons2.txt in Firefox 2.0.0.x) then a possible cause is a wrong or corrupted key3.db file. In Firefox 3.0.2 and 3.0.3 it can also be a problem with the encoding [1][2][3]. If you have updated from Firefox 2 to Firefox 3 and you haven't changed the Master Password then you can try to copy or rename an existing signons2.txt to signons3.txt to see if that works. Firefox 3.5 and later versions use the file signons.sqlite to store the encrypted names and passwords. You can rename signons.sqlite to signons.sqlite.sav to make Firefox 3.5+ versions use the file signons#.txt from a previous Firefox 3 or 2 version. Firefox 3.5 will use an existing signons#.txt if no file signons.sqlite and signons2.txt) in the Profile folder - Firefox. You can also do that if you lost your Master password and the suggestions in the Master password article didn't work. You need to set a new Master password after deleting the file key3.db. 2 uses signons2.txt. Firefox 3.0.x uses signons3.txt. Firefox 3.5 and later versions, including current beta and nightly builds, use signons.sqlite. [4] See Profile folder - Firefox and Profile backup for additional information. You can also use the Password Exporter or FEBE add-ons to back up your passwords. you want a printed copy of the password then look at this forum thread and also read this web page (scroll down to #4). This is the Firefox 3 version of the code from the edmullen's site. You can find the complete file with the Firefox 3 code on: the-edmeister's Firefox Informational Website. The version shown below will run in the Tools > Error Console (paste the code in the Code field and click the Evaluate button) (function(){ /* kb.mozillazine.org */ function twodigs(str) {return (str.length < 2) ? "0" + str : str;} var now = new Date(); var hours = twodigs(now.getHours() + "") ; var minutes = twodigs(now.getMinutes() + "") ; var seconds = twodigs(now.getSeconds() + "") ; var timeValue = " - At " + hours + ":" + minutes + ":" + seconds;(); var today = "On " + days[now.getDay()] + ", " + date + " " + months[now.getMonth()] + " " + now.getFullYear() + timeValue ; var Cc = Components.classes; var Ci = Components.interfaces; pwdmanager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager); var names="",signons = pwd; if (user == ""){ user = "<br>"; } names+="<tr><td>" + host + "<td>" + user + "<td>" + password + "<td>" + submiturl; } catch(e) {} } void(window.open('data:text/html;charset=utf-8, <html><head> <title>Exported Mozilla Passwords</title> <style type="text/css"> body { margin: 1em 3em; background-color: rgb(255, 221, 221); } table {empty-cells: show; background-color: rgb(221, 255, 221);} tr.head {background-color: rgb(204, 204, 255);} td {font-family: "Trebuchet MS", Arial, Verdana, Sans-Serif; font-size: 85%; padding: 1px 2px 1px 2px; } </style> </head><body> <b>MOZILLA PASSWORD INFORMATION</b> <p>Produced by <i>Pasting Code in the "Tools > Error Console: Code field"</i> (by "ernie" - Andrew Poth - Ed Mullen - adapted by dickvl@kb.mozillazine.org to run in the Error Console)<br>'+today+ '</p><p> <table border="1" cellspacing="0"> <tr class="head"> <td><b>Host</b> <td><b>User name</b> <td><b>Password</b> <td><b>Submit URL</b> '+names+'</table> </p></body></html>',"","menubar=yes,resizable=yes,scrollbars=yes,width=1000,height:600")); } })();
http://kb.mozillazine.org/Password_Manager
CC-MAIN-2013-48
refinedweb
637
60.31
Recently I needed to identify which of the rows in a CSV file contained 0 values. This was interesting because normally I tend to look at this problem within columns rather than rows. Pandas provides a neat solution to this which I’ll demonstrate below using this data as an example: import pandas as pd d = {'a': [2,0,2,3,0,5, 9], 'b': [5,0,1,0,11,4,6]} df = pd.DataFrame(d) This data frame should look like this: a b 0 0 0 1 2 1 2 3 0 3 0 11 4 5 4 5 9 6 Now, the final step to subset the data based on the existence of a 0 value within a row is to use the apply function and to look to see if a 0 is in the row values: import pandas as pd zero_rows_df = df[df.apply(lambda row: 0 in row.values, axis=1)] That’s it! You should now have a dataframe containing only the 0 value rows: a b 1 0 0 3 3 0 4 0 11
https://jacksimpson.co/finding-rows-in-dataframe-with-a-0-value-using-pandas/
CC-MAIN-2021-31
refinedweb
183
73.21
The following examples show how to get a value from a pandas Series in three different scenarios. Method 1: Get Value from Pandas Series Using Index The following code shows how to get the value in the third position of a pandas Series using the index value: import pandas as pd #define Series my_series = pd.Series(['A', 'B', 'C', 'D', 'E']) #get third value in Series print(my_series[2]) C By specifying the index value 2, we’re able to extract the value in the third position of the pandas Series. Method 2: Get Value from Pandas Series Using String The following code shows how to get the value that corresponds to a specific string in a pandas Series: import pandas as pd #define Series my_series = pd.Series({'First':'A', 'Second':'B', 'Third':'C'}) #get value that corresponds to 'Second' print(my_series['Second']) B Using this syntax, we’re able to get the value that corresponds to ‘Second’ in the pandas Series. Method 3: Get Value from Pandas Series in DataFrame The following code shows how to get the value in a pandas Series that is a column in a pandas DataFrame import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['Mavs', 'Spurs', 'Rockets', 'Heat', 'Nets'], 'points': [100, 114, 121, 108, 101]}) #view DataFrame print(df) team points 0 Mavs 100 1 Spurs 114 2 Rockets 121 3 Heat 108 4 Nets 101 #get 'Spurs' value from team column df.loc[df.team=='Spurs','team'].values[0] 'Spurs' By using the loc and values functions, we’re able to get the value ‘Spurs’ from the DataFrame. Related: Pandas loc vs. iloc: What’s the Difference? Additional Resources The following tutorials explain how to perform other common operations in pandas: How to Convert Pandas Series to NumPy Array How to Get First Row of Pandas DataFrame How to Get First Column of Pandas DataFrame
https://www.statology.org/pandas-get-value-from-series/
CC-MAIN-2022-40
refinedweb
314
53.24
Question:: - Make the instance globally accessible. - Make sure that there is never more than one instance of that class.. - The second version is simpler to implement and less error prone. In the first variant the private copy constructor is missing on purpose to demonstrate this. In the second variant there is no way to do this error. - Implementation and interface are better separated in the second version. In the first all private members must be declared in the header. This has the advantage that you can rewrite the implementation from scratch and don't even need to recompile anything that uses the singleton. When using the first variant it is very likely that you have to recompile all user code even when only changing slight implementation details. - Implementation details are hidden in both cases. In the first variant using private and in the second variant using unnamed namespaces. Can you please explain me why everybody uses the first variant? I don't see a single advantage over the good old way of doing things in C. Solution:1 According to the party line (E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, Reading, MA, 1995, p. 128), the singleton offers the following advantages over the solution you propose. - You can refine the operations and the representation e.g. through subclassing. - You can change your mind at a later point and have multiple instances. - You can override the singleton's methods polymorphically. - You can configure your application at runtime by initializing the singleton instance with the class you need. Having said that, in most cases I consider the additional complexity excessive and rarely use the pattern in the code I write. But I can see its value when you design an API that others will use. Solution:2 does this help? What is so bad about singletons? Rephrased: A singleton is a glorified global, so just 'implement' it as a global. Solution:3 The construction of static MySingleton singleton; gets called on the first use. (When get_instance() is called.) If it is never called it never calls the constructor. Your method will call the constructor at static construction time. The previous method allows for the order and timing of the constructors being called. You method will order the construction of each singleton according to the compiler static initialisation order. Solution:4 To have functions + static data emulate the singleton pattern would rely on C++'s file scoping and separate-compilation. These are compiler constructs rather than language constructs. The singleton class pattern allows data encapsulation regardless of location with respect to compilation-units; it is correctly encapsulated even if it is defined in a file with other classes and functions. Also it would not in fact emulate the behaviour of the singleton pattern, but merely that of a static object, which is not the same thing. A singleton's lifetime is independent of the life of the process that contains it. The correctly formed singleton is instantiated on first use, whereas static data is instantiated and initialised before main() is started. This may be a problem, if say construction of the object relies on the existence of some other run-time entity. Also the singleton object occupies no memory (other than its static instance pointer) until it is instantiated. It may also be destroyed and re-created at any time, and indeed many times. Note if you modify your singleton to make the constructor protected rather than private, you can subclass it (and thus easily apply reuse singleton pattern), you can't do that with a static object, or an object with all static members, or functions with file scoped static data, or any other way you may try to get around doing it correctly. There is nothing wrong with your suggestion per se, just so long as you are aware that it is not a singleton pattern, and lacks it's flexibility. Solution:5 The problem with just using free functions is that those don't by default get shared persistent behavior, like your singleton class can get with member variables and constants. You could proceed to use static global variables to do the same thing, but for someone trying to figure that out, that makes the scope of what they have to look at to understand those routines' behavior nearly unlimited. With a singleton class, everything is nicely organized into one class for the reader to examine. Solution:6 Personally, I use singletons when I want to have control of when the constructor is executed for the first time. For example; if I have a singleton for my log-system, the code to open a file for writing is put into the singleton constructur, which is is called like; Logger.instance(); in my startup process. If i'd use a namespace I would have that control. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/11/tutorial-singleton-why-use-classes.html
CC-MAIN-2019-04
refinedweb
837
55.64
Categories: Java | Java ME | How To | Code Examples | Games This page was last modified 23:35, 1 February 2008. How to develop a game - Part 1 From Forum Nokia Wiki So you want to develop for your mobile phone? Say hello to Java Micro Edition. JavaME combines a small JVM and a set of Java APIs for developing applications for mobile devices. This article is the first in a series where we are going to approach all the basics for developing an application for mobile phones using JavaME. The final goal of these tutorials is to develop a small Arkanoid clone () and in the process learn all the base libraries, classes and methods available in JavaME: This time, after a quick introduction to the development tools, I will provide a step-by-step guide to creating your first JavaME application, also known as a MIDlet. Development Tools The development environment you use has a big influence on your productivity. After trying out a lot of different IDEs, I narrowed my options to the following two: Both IDEs are completely free and have a strong community backing them up. They allow you to do all the work you need to develop mobile applications. Netbeans is very easy to install and configure and its interface is more intuitive than Eclipse, but it uses a lot of memory and when your project gets bigger it can be very slow. Eclipse is a lot faster and has a smaller memory footprint, it has the same features as Netbeans, but its interface is more awkward to use and it requires more work to configure correctly. So, what's the best for you? If you already have experience with Eclipse, its smaller memory footprint and lightning speed are a big advantage, but if you are a beginner with Java IDEs and mobile programming, Netbeans is a lot easier to start with. Phone SDKs Besides the Java IDE with mobility support you choose, you need to download and install some special software called the phone SDK that allows you to have access to the specific J2ME libraries. Sun has an emulator called Wireless Toolkit (WTK) that provides all the standard libraries. I regularly use this one for my own development because it's very fast, has a lot of extra tools ( Network Monitor, Profiler, SMS Emulator etc...) and can be customized to look and act like several phones. Besides the WTK, it's also a good idea to have some SDKs from the manufacturers of the phones that you wish to support. These SDKs allow you to access any special libraries that those phones might use and often include software that allows you to deploy your applications to the phone. All the big brands of cellular phones have their developer sites where you can download their phone emulators and custom SDKs. Your First Midlet After you installed and configured your Java IDE and phone emulator, it's time to start coding! All the J2ME applications must extend the abstract Midlet class found in the javax.microedition.midlet package, much like creating an applet by extending the java.applet.Applet class. The base entry point is the startApp() method. So lets create our first Midlet named MyMidlet. public class MyMidlet extends MIDlet{ // it's invoked when the application starts and each time is resumed protected void startApp() throws MIDletStateChangeException {} // it's invoked when the Midlet needs to be destroyed protected void destroyApp(boolean uncondicional) throws MIDletStateChangeException {} // it's invoked when the Midlet needs to be paused. (Some phones ignore pauseApp().) protected void pauseApp() {} } If you create this class and run it in the emulator you will have a fantastic blank screen! In order to show some content in your application you need to use the Display class, this class controls what appears on the screen of the Midlet. Each Midlet has one Display and can access it through the Display static method getDisplay(). To present something on the screen you need to set a Displayable object using the setCurrent() method. One class that implements Displayable is the Alert class. This class shows a simple message on the screen. With this information lets change our startApp() method to something more useful. Alert alert; //entry point for the application protected void startApp() throws MIDletStateChangeException { // creates alert alert = new Alert("Hello World"); // shows alert in the screen. Display.getDisplay(this).setCurrent(alert); } If you run your Midlet now, you will see a screen with "Hello World" like the one below: That's a little better but now you still don't have a way to exit your Midlet properly. (You can always press the red button!) In order to have a proper exit, let's add some more lines of code to our startApp() method: // create command comExit = new Command("Exit", Command.EXIT, 1); // add a command to exit the Midlet alert.addCommand(comExit); This shows you the exit command on the screen but if you click on it, it doesn't do anything because you need to add a CommandListener to your Alert in order to react to Command Actions. So let's add some more code: public class MyMidlet extends MIDlet implements CommandListener{ public void startApp(){ [...] // adds a listener to the alert alert.setCommandListener(this); } public void commandAction(Command cmd, Displayable display) { // check what command was selected if (cmd == comExit) { notifyDestroyed(); } } } With this change we finally managed to have a complete functional Midlet. Yeah!! In the next lesson, we are going to look in more detail at the user interface elements like the Alert, Display and CommandListener classes. We are going to use those elements to define the menu interface for our Arkanoid clone. See you soon. Downloads:
http://wiki.forum.nokia.com/index.php/How_to_develop_a_game_-_Part_1
crawl-001
refinedweb
949
59.74
Let’s continue our example in So now we have a working endpoint @. Now we would like to add authentication on this endpoint and return 403 if the request is not authorized. First, if you want to set the authentication globally, you could set it in the settings.py. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Restart the application and try to access the endpoint again. You will get a 403. You will get the correct response only if u have logged in. Similarly, you need to provide the user credential when using the curl command. curl -u <username>:<password> But sometimes, we only want to add the authentication to some specific endpoint. In that case, you don’t need to alter the global config in settings.py. Instead, add the permission_classes in the views.py as follow. <django_root>/custom/views.py from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response from statsd.defaults.django import statsd class CustomGet(APIView): """ A custom endpoint for GET request. """ permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Return a hardcoded response. """ return Response({"success": True, "content": "Hello World!"}) Done =) Reference: Django REST framework – Permissions
https://eureka.ykyuen.info/2015/04/07/django-rest-framework-setting-permissions/
CC-MAIN-2020-40
refinedweb
195
53.68