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 |
|---|---|---|---|---|---|
Use Charts to Visualize Grouped Data
- 3 minutes to read
This topic describes how to use charts to visualize grouped data in a report.
In this tutorial, the report data is grouped against the CategoryID field. A chart is placed in the Group Footer band and is not bound to data. The report’s data source is used to populate the chart with data.
Follow the steps below to make each chart instance display data for its group.
Design Time
Click the chart’s smart tag and select Run Designer.
Add a new series. Click the plus button next to the Series item in the Chart Designer.
Select a series type.
Provide data for the argument and value axes.
Switch to the created series’ Data tab. Drop fields onto the Argument and Value areas.
Filter the chart. Go to the Properties tab. Click the FilterString property’s ellipsis button to invoke the FilterString Editor.
Add a filter condition. On the left side, specify the field by which chart data should be filtered.
On the right side, use a chart parameter to obtain a group value from the report’s group field (CategoryID). Click the right side’s icon until it turns into a question mark and select Add Parameter from the context menu to invoke the Add New Parameter dialog.
Set the Binding property to the report’s group field (CategoryID) and click OK.
Click OK in the FilterString Editor and in the Chart Designer to apply changes.
Switch to Print Preview to see the result.
Runtime
The code sample below illustrates how to filter chart data in code. An XRChart instance named chart is placed in the Group Footer band.
using DevExpress.XtraCharts; // ... // Create a new chart parameter and bind it to the report's group field (CategoryID). Prepend the group field's name with the data member's name. chart.Parameters.Add(new XRControlParameter("controlParameter1", null, "queryProducts.CategoryID")); // Create a chart series. Series series = new Series("Series 1", ViewType.Bar); // Show product names on the Argument axis. series.ArgumentDataMember = "queryProducts.ProductName"; // Show product prices on the Value axis. series.ValueDataMembers.AddRange(new string[] { "queryProducts.UnitPrice" }); // Set up a filter to show products from the specified category only. series.FilterString = "queryProducts.CategoryID = ?controlParameter1"; // Set up a filter to show products from the specified category only. Use the created parameter's name in the filter string. series.FilterCriteria = CriteriaOperator.Parse("queryProducts.CategoryID = ?controlParameter1"); chart.Series.Add(series); | https://docs.devexpress.com/XtraReports/3291/detailed-guide-to-devexpress-reporting/use-report-controls/use-charts/use-charts-to-visualize-grouped-data | CC-MAIN-2022-21 | refinedweb | 407 | 52.15 |
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Support Forum » putting atmega168 and atmega328p projects in different folders/directories
i have two NerdKits, one with the ATmega168 and the other with the ATmega328. i program my kits with my macBook air running 10.8.2. i keep my files in the following paths:
Desktop/gcc4/168/atmega168 project folders, libnerdkits, bootloader168
Desktop/gcc4/328/atmega328 project folders, libnerdkits with io_328p.h, bootloader328p
i came up with this arrangement a couple days ago and now i'm getting a lot of "device type not defined" and "undefined reference to '__heap_end'" errors and also the compiler is telling me that constants like PC4 and PORTC are being referenced before being defined even though i have all the #include <stdio.h> and <avr/io.h> etc statements at the head of the source code.
could it be that the preprocessor/linker/compiler is getting confused by my having multiple copies of the libnerdkits folder?
i'm still having this problem with the warning: device type not defined. it's stopping all my programs that use constants and functions from avr/io.h from compiling.
here's my program:
// initialload.c
// for NerdKits with ATmega168
// mrobbins@mit.edu
//
// modified dec2012 keithmac@maui.net
//
// definitions and includes
#define F_CPU 14745600 //tells delay.h the clock speed
#include <avr/io.h>
#include <avr/pgmspace.h>
#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
// includes not needed
//#include <stdlib.h>
//#include <avr/interrupt.h>
//#include <util/delay.h>
//#include <inttypes.h>
int main() {
// initialize LCD
lcd_init();
// print message to LCD
lcd_goto_position(0,0);
lcd_write_string(PSTR(" Congratulations! "));
lcd_goto_position(1,0);
lcd_write_string(PSTR(" Keith "));
lcd_goto_position(2,0);
lcd_write_string(PSTR(" Your USB NerdKit "));
lcd_goto_position(3,0);
lcd_write_string(PSTR("is alive and works!"));
// set Pxn bit of DDRx register for output from Pxn pin of PORTx register to
// LED anode; LED cathode to GND
DDRC |= (1<<PC4);
// infinite loop to prevent undefined termination of main() and
// demontrate user defined io
while(1) {
// turn on LED
PORTC |= (1<<PC4);
delay_ms(500);
// turn off that LED
PORTC &= ~(1<<PC4);
delay_ms(500);
}
return 0;
}
and here's the Terminal messages i get after i enter the make command:
make -C ../libnerdkits
make[1]: Nothing to be done for `all'.
avr-gcc -o initialload.o initialload.c ../libnerdkits/delay.o ../libnerdkits/lcd.o ../libnerdkits/uart.o
In file included from initialload.c:9:0:
/usr/local/CrossPack-AVR-20121207/lib/gcc/avr/4.6.2/../../../../avr/include/avr/io.h:607:6: warning: #warning "device type not defined" [-Wcpp]
initialload.c: In function 'main':
initialload.c:36:3: error: 'DDRC' undeclared (first use in this function)
initialload.c:36:3: note: each undeclared identifier is reported only once for each function it appears in
initialload.c:36:15: error: 'PC4' undeclared (first use in this function)
initialload.c:43:5: error: 'PORTC' undeclared (first use in this function)
make: *** [initialload.hex] Error 1
what device type is undefined? i assume that once avr/io.h gets the device type defined the undeclared constants (DDRC, PC4 and PORTC) error will be fixed.
please help... k
Keith -
I'm not a Mac guy so I may not be the best help. There may be a few different causes to the problem, so we may need more info. I know the ATmega328 had a problem with the "io.h" files but it should work for your ATmega168. You should post your "makefile" for this project as well...something in there might be wonky. I think you are right about "avr/io.h", once that gets worked out, it should compile.
hi pcbolt. here did download the io_328p.h file for my 328 projects. at first i was thinking that that was causing the problem but now i don't think so. i'm lost. i appreciate any help... k
Looks OK. It's set up to use the ATmega168 (line 1 in make file) so I'm assuming this is the MCU you are programming. The one thing I did notice was you commented out the "include <inttypes.h>". That is about the only difference I can see from a project file I compiled. Your directory structure is similar to what I use as well except I'm using a Windows box. I don't think the compiler is getting confused by your directory structure, but try going back to your original setup and just make incremental changes until you see the errors again.
One other thing to check. If you are programming for the ATmega328, line 1 of the make file should be...
GCCFLAGS=-g -Os -Wall -mmcu=atmega328p
thanks again... i'm stumped, too, but i'm going to try to backtrack like you suggest... i should have kept a log of my downloads, folder creation, file moves, etc but i wasn't expecting anything like this... wish me luck... k
i forgot... thanks for the reminders about the makefile changes and to double check that i haven't mixed up my kits... i did mix up the kits once so i mounted both breadboards to squares of heavy cardboard that're labeled with '168' or '328'... i'm going to strip a copy of initialload.c to just comments and start adding lines of code a few at a time to try to catch where the problem starts... hi ho hi ho, off to work i go... k
after about an hour of trying different versions of initial load all with no compilation due to an assortment of warnings and errors i did some more forum searches and learned a little bit about the directory usr and all the hidden files. in my usr/local directory i have the following items:
k712:local k712$ ls
AVRMacPack CrossPack-AVR bin
AVRMacPack-20080721 CrossPack-AVR-20121207 share
could it be that the multiple versions of macPack and crossPack are causing the problem. how do i rm or uninstall the unneeded directories or files?
It could be a multiple version problem. I wish I knew more about the Mac to help. What is odd is the correct "io.h" file is being called, but the "-mmcu=atmega168" switch isn't being recognized, can't figure out why. Good luck and happy hunting.
There is no need to have different versions of the nerdkit for the 168 and 328. Everything is the same except in your makefile, change the mmcu for gcc and the -p m168 for avrdude for the target you are going to program and go. Get the latest toolchain from ATmel and you don't even have to worry about PB? definitions for the atmega328p, it's fixed.
hi Noter... i think i understand... the makefile tells the preprosser/compiler/linker what to do so if the makefile is correct there should be no confusion which library files to use. here are two of my typical makefiles for my 168 and 328 kits:
did i get it right? both the programs that these makefiles refer to compiled and ran last week before i started rearranging my folders to keep my 168 and 328 projects more organized.
i'm going to put all my projects in a single folder again with only one copy of libnerdkits that includes the io_328p.h file to see if that fixes my problem.
i think the other possible issue is that in my /usr/local directory are AVRMacPack, AVRMacPack-20080721, CrossPack-AVR and CrossPack-AVR-20121207 directories. could the problem be having all these different toolchains available? i'm not sure if i'm saying that right... hopefully you understand what i mean.
any comments or questions are welcome!!! thanks for taking the time to help... k
i just put all my projects back into one folder and i just remembered why i separated them in the first place. there is a different makefile for libnerdkits for the 168 processor vs the 328. the only differences are -mmcu=ATmega168 vs -mmcu=ATmega328p and the inclusion of io_328p.h directives in only the 328p makefile.
do i need to run the libnerdkits 168 makefile before i try to compile a 168 project and the libnerdkits 328 makefile before compiling 328 projects? i thought if i put the two different versions of libnerdkits in different folders and ran the matching makefile in their separate folders i wouldn't have to remake the library each time i changed from a 168 to a 328 project.
could this be the problem?
There's really no difference in the compiled code between the 168 and 328 so either copy of the library object files will work fine There is no need to remake the library when changing mcu's.
I'm not so sure on you crosspack stuff because I'm running Ubuntu and prior to that I was on windows. Don't know that much about macs. But I can tell you that on linux and windows all that matters is where the needed files are found first when going down the list of directories in the PATH variable. Currently I have an old copy of the toolchain somewhere in usr/lib (I think) but I put the latest version in my home directory and added it to the PATH ahead of all the other directories so it is found first and used. I imagine the mac is the same in one way or another.
In my makefiles I've added the makefile itself as a dependent for the gcc compile. This is so when I change the mcu or something like that but not the source program, the program will get a fresh compile anyway. Just a convenience thing so I don't have to remember to edit the c source or clean the directory first after changes to the makefile. For example the initialload makefile will have a line like this:
initialload.hex: initialload.c Makefile
It's so fast to change the make file and compile/download the code that I don't keep different versions of a program around for different chips.
If at some point you start changing mcu clock speeds, baud rates, or pinouts for the ldc, you will have to deal with recompiling the libnerdkits code at that point but until then it will work as is for both the 168 and 328.
i'm learning slowly but surely... from what you've told me i decided to re-download all the source code from nerdkits and start from scratch...
i modified the makefile for initialload as follows: only added a few lines of comments to initialload.c as follows:
// initialload.c
// for NerdKits with ATmega168
// mrobbins@mit.edu
//
// downloaded from nerdkits 19dec12
//
#define F_CPU 14745600
#include <stdio.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>
#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
//;
}
the good news: it compiles and writes to the chip... yay!!!
the bad news: when i run it the LCD flashes and then displays ' is alive! ' on line 0 of the LCD with no display on lines 1-3 and the LED turns on but never turns off
this is not the output of initialload when i first ran it a few months ago
any ideas? thanks in advance... k
k, can you see/use the unmodified initiaload (you did keep a copy :-)?
Once you can run initialload then try to make your modifications ONE LINE AT A TIME!!
Ralph
thanks Ralph... i've been busy with my 'day' job (day in quotes because i work evening and night shifts)... there's lots of overtime this time of year...
i've backed up to the point where i'm going to recheck how i've wired the lcd to the mcu... i think i can get to that later this morning... if the wiring checks out then i'm going to do what you say, i'm going to comment out the code of a copy of my original, unmodified initialload.c, outline step by step which lines of code to uncomment and then after each line of code is added back to initialload.c, compile and document either the compiler errors or if it compiles run and document the lcd/led output... i should have a table of results sometime this weekend... cross your fingers... Merry Christmas... k
well, i'm still stuck... my wiring all checked out... i downloaded a fresh initialload project... i minimally edited the Makefile... the new initialload compiled and downloaded to the kit with no warnings or errors... when i ran the kit the LED flashed on time as expected but this output on the LCD was:
row 0: " is alive! "
row 1,2,3: empty
i then commented out all the code (except for the #define and #include statements) and uncommented:
int main(){
lcd_init();
lcd_goto_position(0,0); // lcd_goto_position() is more flexible for testing/debugging than lcd_line_one()
lcd_write_string((" Congratulations! "));
return 0;
}
cutting to the chase:
given: lcd_goto_position(r,c);
compiled code ignores the value of r, it always writes to row 0
if the value of c causes the string in lcd_write_string() to overflow row 0, the overflow is written to row 2 (not row 1)
if c causes the string to overflow two whole rows, rows 0 and 2 are full and overflow goes to row 1
if c causes the string to overflow three whole rows, rows 0,2,1 are full and overflow is in row 4
if i write to more then one row (no overflow) each write displays on row 0 with its first character missing and it overwrites any previous displays on row 0
does anybody know why my code can no longer access any row but 0 and why the order of the rows has been changed?
Have you tried THIS?? It sounds like you may have the same optimization issues going on.
Rick
thanks Rick... changing '-Os' to '-O0' and cutting '-j .text' from both my project's and the libnerdkits' makefiles, trashing all the .o and .hex files and then recompiling fixed the problem...
when i searched the forums before starting this thread i'm pretty sure i saw the 'ubuntu lcd problems' on the results page but because i'm using a mac osx to write code and download to my kit i didn't look at the page... dumb, dumb, dumb...
thanks again to you all and Merry Christmas... k
No problem, and Merry Christmas to you and yours as well!
i continued an on and off search through the forums the last few days and found this thread:
Microcontroller Programming » LCD library error? Only Line 4 and on line1 ???
on 21Aug12 in the thread (the last entry) thinalrart suggests a change to lcd_goto_position() in libnerdkits/lcd.c that fixed a similar (maybe exactly the same) problem i was having... i'm going to give it a try... not today, it's Christmas day, but soon...
Are you using the latest version of the toolchain? Might take care of your problem.
Atmel AVR Toolchain 3.4.1 for Linux
thanks Noter... you told me about the new toolchain in another thread... i've been running two different threads on this because i originally thought i had two different problems... very confusing...
anyway... i did look at that page and i should have asked you about it... i'm uploading to my nerdkit from a mac osx 10.8.2... is it ok to download and install a Linux toolchain? which version of 3.4.1 should i download? my mac has a core i7 chip so i'm pretty sure it's a 64 bit system...
hard to believe i'm saying that... i remember when 64 bit buses and registers only existed in mainfram systems that took up the middle of an air conditioned room with three 10Mb (10 whole Mb each!!!!) drives in four foot high cabinets lined up against a wall, a punch card reader the size of the xerox machines you see at kinkos and a terminal with a CRT that was 24 inches deep with s 13 inch orange on black display in one corner and if you raised the floor plates all you could see was a rat's nest of cables in a rainbow assortment of colors)...
sorry... i should have given you a garrulous old-man alert... later, k
I don't know much about the mac so can't help a lot but I don't think the linux distribution is compatible with osx. I found this page on CrossPack that looks to have the latest toolchain package for the mac which will definitely be a great improvement over the old version referenced by nerdkits download links.
I remember when the big machine on site was a 36 bit mainframe. I was mostly programming the mini's in those days and the first time ever I did a utility sort on the big box it finished so fast I didn't think it worked, but it did. Wow, 36 bit words, that was real power back in those days.
i downloaded this version of crosspack: CrossPack-AVR-20121128.dmg at the end of Nov and i downloaded CrossPack-AVR-20121207 a couple weeks later... both my nerdkits programmed and run AOK until my lcd stopped working (it would display only two bars no matter which mode my chip was in) and then when i received a new lcd it would only display in rows 0,2,1,3 in that order or if i wrote to all four rows it would only display the row four string in row 0 with the other rows empty... with yours everyone else's help i've now got my second kit and lcd back to running AOK...
i've now got my first kit back from my friend so i'm going to start to 'debug' it, too... maybe i'll even be able to get my original 'broken' lcd running again... that's why i'm still perusing the forums for similar problems... wish me luck and thanks again for all your help...
What was it that got it running ok again? New crosspack? Wiring?
when i changed makefile as follows:
optimization changed from '-Os' to '-O3' on the first line of makefile (line starting with 'GCCFLAGS=')
'-j .text' deleted from line starting with 'avr-objcopy'
actually i like using the -O3 option even though my code is one or two kb longer than with the -Os option...
i still don't know what the -j option does but i'm looking for a fix that allows me to put it back in since the nerdkits people thought it was important enough to put it in in the first place...
who made the 36 bit system... my 64 bit system was a Burroughs (7800 i think)...
The -j option tells avr-objcopy to copy only the .text section from the object file to the hex file. Without it I think all sections are copied. The .text section contains all your program code and the .data section contains the initialization values for variables. I copy both sections in my make file by using two -j options:
avr-objcopy -j .text -j .data -O ihex whatever.o whatever.hex
So with only -j .text your program variables are not initialized at runtime.
Another file I like to have on hand is a memory map which can be created by adding a -map to the the link options:
LINKFLAGS=-Wl,-u,vfprintf -lprintf_flt -Wl,-u,vfscanf -lscanf_flt -lm -Map=whatever.map
I've experienced the optimization bug that affects the lcd position routine but that problem went away when I upgraded to a newer version of the toolchain. Before I upgraded I changed the lcd.c source to use if statements instead of a case statement and that also solved the problem but after the upgrade I put it back to case statements.
That old 36 bit machine was a Dec System 10 made by Digital Equip. Corp. It was primarily a batch processing system but had a couple of hundred terminals wired in for user inquiries/data entry and a herd of programmers hacking away.
aaah, memories...
thank you for the mini makefile tutorial... every bit (byte?) helps... i keep a document in my avrProjects folder with all my notes about makefiles and the dates and changes i've made to my makefiles... it's already come in handy a couple times...
i just got done pasting your note into it so i can start to incorporate your suggestions into my projects... thanks for sharing...
I forgot part of the option for the map file. It has to have the -Wl in front of it to let gcc know it's a linker option.
-Wl,-Map=$@.map
Here's the whole story on make.
Yep, memories. Remember the shelves of reference manuals? And patches took weeks to get. Sure is different now because everything you could ever want is instantly available on the internet.
thanks for getting back to me so quick... i haven't used my new makefiles yet so i'll get the '-Wl,' inserted right away...
i'd forgotten about the manuals but when you mention it i remember the bookshelves full of the biggest three ring binders ever made and they were all overstuffed with hand made tabs sticking out every which way... i was just a user trying not to fumble my stacks of punch cards with FORTRAN code using the hollerith commands to handle string output formatting... you've made my day!!!
thanks for the link to the gnu make manual... it's exactly what i've been looking for... it's amazing how much material has been converted to digital format in the last three decades and the even more amazing amount of new stuff added everyday!!!
now i just have to figure out how to squeeze an extra hour or two of study into my only-a-little-overbooked schedule...
Please log in to post a reply. | http://www.nerdkits.com/forum/thread/2563/ | CC-MAIN-2018-13 | refinedweb | 3,699 | 73.47 |
Neutron/DVR/ServiceNode-HA
Executive summary
The sole objective of this document is to provide details on the Service Node HA for Distributed Virtual Routers. The details about the Distributed Virtual Routers can be obtained from the DVR HowTo Wiki or from the OpenStack Juno Documentation.
DVR L3 Agent Modes
There are three different modes of operation of L3 Agents that it can be configured to. The first mode is "legacy" mode and that is a typical centralized network node mode where all the routers will be created in a Single Node and the router namespaces will have the FIP and SNAT rules configured inside the namespaces. In this mode the l3_agent will not be able to create a DVR router.
The second mode is "dvr" mode and this configuration is for the Compute Node where the VMs reside. The namespaces that you can see in the Compute Node are the 'Router' namespace and the 'FIP namespace'. The router namespaces are distributed across the compute nodes.
The third mode is "dvr_snat" mode which is similar to the "legacy" mode but will also create the distributed routers. This is also called as a Service Node. The Service node will host the "SNAT Namespace" and the "Router namespace".
HA for Service Node
When distributed virtual routers are configured, the routers are distributed across the compute nodes, so even when one of the compute node fails, the VM can still be migrated to the other compute node and the distributed routers will be automatically created. Creating a Compute Cluster is out of scope and will not be discussed here. We are interestded in creating a Service Node HA Cluster.
In Service Node HA Cluster, the HA service is provided only for the SNAT and not for the Routers. That is one shift from how the old network node and HA worked when compared to the distributed virtual routers.
Today we only allow a Distributed Router with a default gateway set to be manually moved from one Service Node to another Service Node. This is because we are only trying to move the SNAT service and not the routing service.
So any HA work that is targeted for the Distributed Virtual Router should be only targeted towards the Service Node and the SNAT namespace.
The L3-HA-VRRP feature was added to neutron as part of the Juno release. L3-HA-VRRP will be leveraged to provide Distributed Virtual Router Service Node HA functionality.
Architecture and Desgin
TBD | https://wiki.openstack.org/wiki/Neutron/DVR/ServiceNode-HA | CC-MAIN-2022-33 | refinedweb | 414 | 61.16 |
Tech Off Thread13 posts
Forum Read Only
This forum has been made read only by the site admins. No new threads or comments can be added.
The best way to effect "net use" from C#?
Conversation locked
This conversation has been locked by the site admins. No new comments can be made.
What's the best way to effect a "net use" from C#? I need to be able to establish named drives, passing the user name and password. AndAlso of course remove said mappings. In other words I'd like to be able to carry out variations on a theme of:
net use q: \\SomeServer\SomeShare foo /user:bar
and
net use /d q:
One way of doing this might be to use System.Diagnostics.Process and redirect the stdout and stderr so I can parse any output to delivery decent structured error messages that my code can act upon. However that seems a little clunky. I'd really rather PInvoke a set of APIs than "shell out". Anyone got any thoughts?
Cheers - tom.
i think this is what you are looking for.
you may also want to look at:
which has a sample zip file with the api calls in a.net class
also your best buddy in windows / .net is
look at:
and the other mpr bits...
Doh. Of course <blush>. Many thanks for the pointer!
To execute shell command from c#, save the commands within a batch file (.bat) extension. You can create a batch file using Notepad application and saving the file like <your-preferred-name.bat> (example: demo123.bat).
After creating the batch file, save the commands within the file like
net use a: \\192.168.1.1\SharedFilder myPassword /user:MyUserName.
A complete followup of "net use" command can be found in or technet.Microsoft.com
Once you are settled with the batch file, invoke it from the C# code:
System.Diagnostics.Process objProcess = new Process();
objProcess.StartInfo.FileName = Server.MapPath("testfiles/netcmd.bat");
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // to hide the command window popping up
objProcess.Start();
objProcess.WaitForExit(); // Gives time for the process to complete operation.
// After code is executed, call the dispose() method
objProcess.Dispose();
and there we go!!!!
for clarification, please feel free to reply to this post.
With thanks,
Arun Prasad.K.R
arun85prasad@live.com
Why suggest a method that the origional poster mentioned he knows, but don't wish to do if have other choice?
You could also use WMI and the classes from the System.Management namespace.
I do not know much about WMI and is there a better way out with System.Management namespaces? These two are relatively new to me, and may be can you show me the way to get there plz?
About bridging the two years of dead interval is that may be, at some point of time, this could help out few new and uninitated by getting them right on track, Just like "dot_tom" showed me the way!!!!
Here's some docs on WMI from a .Net perspective:">
There are a bunch of examples of dealing with shares via WMI out there. Here is one:
Why use the bat file at all? it is a big risk because the password is stored in there!.
Most simple way to do it is:
This way without knowing the sourcecode, they wont know the password. Only thingy tough is that you cannot just change the password..
Necrothread, but can't resist...
Sorry, but strings are stored in plain text inside the executable's data section. Anyone with a hex editor can read them. And tools like ildasm and Reflector make this even easier with .Net. Embedding the string with the password in the executable is not an effective way to secure it. | https://channel9.msdn.com/Forums/TechOff/242590-The-best-way-to-effect-quotnet-usequot-from-C | CC-MAIN-2017-47 | refinedweb | 629 | 76.22 |
Can raise modelling abstraction level by passing an abstract datatype along channel.
sc_signal < bool > mywire; // Rather than a channel conveying just one bit, struct capsule { int ts_int1, ts_int2; bool operator== (struct ts other) { return (ts_int1 == other.ts_int1) && (ts_int2 == other.ts_int2); } ... ... // Also must define read(), write(), update(v) and value_changed() }; sc_signal < struct capsule > myast; // We can send two integers at once.
For many basic types, such as bool, int, sc_int, the required methods are provided in the library, but clearly not for user-defined types.
void mymethod() { .... } SC_METHOD(mymethod) sensitive << myast.pos();
Future topic: TLM: wiring components together with methods instead of shared variables. | http://www.cl.cam.ac.uk/teaching/1011/P35/obj1.2/zhpfbae55f38.html | CC-MAIN-2013-20 | refinedweb | 103 | 57.37 |
Setting Excel header and footer to add information to a spreadsheet is a pretty attractive choice. This is the solution for how to set Excel header and footer in C#, VB.NET. Within this solution, you can either set Excel header and footer in C#, VB.NET at design mode or runtime mode.
Headers and Footers are the lines of text that are displayed below the top margin or above the bottom margin respectively. They can be used to display any kind of useful information on the pages like page number, author name, topic name or date/time etc.
Spire.XLS for .NET allows adding headers and footer to the worksheets and setting them at runtime. At the same time, you can also set headers and footers manually in the pre-designed file for printing and then load it as a template. For example, you can use Microsoft Excel as a GUI tool to set headers and footers easily to reduce your efforts and development time and then upload it by using Spire.XLS for .NET. The image below displays the effect of setting Excel header and footer in C#, VB.NET. You can also freely download Spire.XLS for .NET and have a trial.
The next part is the code for setting Excel header and footer in C#, VB.NET.
using Spire.Xls; namespace HeaderAndFooterForXls { class Program { static void Main(string[] args) { //create your excel document Workbook myworkbk = new Workbook(); //Gets first worksheet Worksheet mysht ="); } } }
Imports Spire.Xls Namespace HeaderAndFooterForXls Class Program Private Shared Sub Main(args As String()) 'create your excel document Dim myworkbk As New Workbook() 'Gets first worksheet Dim mysht As Worksheet =") End Sub End Class End Namespace
As for headers and footers manually in the pre-designed file, please refer how to use Excel template in C#, VB.NET.
Spire.XLS for .NET is a professional Excel component which enables developers/programmers to fast generate, read, write and modify Excel document for .NET. It supports C#, VB.NET, ASP.NET, ASP.NET MVC. | http://www.e-iceblue.com/Knowledgebase/Spire.XLS/Program-Guide/Set-Excel-Header-and-Footer-in-C-VB.NET.html | CC-MAIN-2015-06 | refinedweb | 338 | 60.95 |
Series 2.0 - Change details in RELEASE-NOTES.
Even more changes from Fernando.
Some more changes from Fernando (actually two sets of changes):
- A little bit more bottom-up def motion (notably defS and
COLLECT because of a warning if gatherers are compiled
first)
- Added UNINITIALIZED and DEFAULTED typedefs (unused)
- Added aux and output variable initialization (fragL aux
form now accepts also (var decl init)
- Removed any fragL prolog code initializing vars to
constants and moved to aux decl form.
- Fixed bug in COLLECT. CL: qualifier missing before a
MULTIPLE-VALUE-BIND
- REMOVED LONGSTANDING defS cleanup BUG (inner function in
flet defined before top-level macro def)
- Additional defS and defS-1 simplification (and slet*)
- renamed LETIZE as DESTARRIFY
Forgot to export COLLECT-PRODUCT (caught by Fernando).
o Make when-bind always available
o Add deftype generator for Allegro. I'm not sure this is
correct, but it let's ACL compile series, albeit with
warnings about generator type being defined twice. (Need
to find a better solution.)
o Fernando added an indefinite-extent declaration and uses
it in the one place where it's needed.
o Fernando renamed split-assignment to detangle2 and
corrected some bugs in my version.
Remove the cmu version from scan-range. It was generating bad
initialization code for things like (scan-range :length 10 :type
'single-float).
o Let's try to set the correct package for CLISP depending if we're in
ANSI mode or not. (Not sure this really works.)
o In test 280, we probably really want to use the COMMON-LISP-USER
package instead of just USER. Mostly for CLISP where the USER
package is not a nickname for COMMON-LISP-USER.
o One of Fernando's uses of dynamic-extent was wrong, as Fernando
points out.
o CLISP apparently has a bug in loop such that split-assignment is
broken. Replace that with an equivalent do loop.
Fernando added dynamic-extent declarations wherever needed.
Let's not use fix-types for CMU in optimize-producing. This means the
compiler can't optimize things as well as it could, and I (RLT) want
to see these warnings.
Fix a typo that got in the last few patches: LET should really be
CL:LET. (From Fernando.)
Fernando made these changes: Replace deftest with defok,
defcmumismatch, and defcmukernel if some older versions of CMUCL
produce bad results on these tests. Newer versions of CMUCL pass
these without problems.
Changed all occurrences of defunique to be just defun and added a
comment on where the function is called.
o As discussed with Fernando, the "optional" type is renamed to
null-or.
o Cleaned up and indented some of the comments.
A few more changes from Fernando:
o All functions called from a single site are defined with DEFUNIQUE
for documentation purposes (and eventual inlining via DEFEMBEDDED).
o Fixed the long standing bug that install uninterned everything that
it didn't like. Shadowing import is used now.
There were some other changes that I (RLT) don't understand.
In collect-nth, counter is really a fixnum.
o Some more changes from Fernando. This fixes some bugs that show up
in the test suite. The test suite now passes on CMUCL.
o Fixed up some declarations that used the optional type when, in
fact, it didn't. (Hope I got these all right.)
Two major fixes:
o Bug in collect (missing set of parens)
o Change some defconstants back to defvar. (Tickles CMUCL inf loop).
Here are the changes that Fernando made. I (RLT) don't claim to
understand everything that was changed or why.
1. Removed 1 redundant eval-when
2. Sorted functions so that it can be loaded w/o `undefined function'
warnings.
3. Added inline declarations for all functions called from a single
site.
4. Sorted functions so that inlining will work even if a compiler does
not inline forward references to functions defined in the same
file.
5. Setup eval-when's so that it can be compiled w/o having to load the
source first.
6. Simplified redundant (OR NULL T) to T
7. Simplified redundant #'(lambda (x) (foo x)) to #'foo where foo is a
function.
8. Fixed so it won't complain when LispWorks adds
CLOS::VARIABLE-REBINDING declarations after CLOS macro
transformations (general support provided via the constant
allowed-generic-opts).
9. Added support for MACROLET on LispWorks (necessary because of CLOS
macro transformations).
10. Only declare variables as (OR foo NULL) on implementations that
won't allow to store NIL otherwise (currently, only CMUCL).
11. Added specialization to series declarations (eg: (SERIES FIXNUM)).
12. Do more precise type propagation in PRODUCING forms.
13. Allow `SETF like SETQ' in PRODUCING forms.
14. Added COLLECT-PRODUCT.
15. Extended SETQ-P to take into account multiassignments (not used
yet). This should still be trivially generalized to support PSETQ
and SETF, BTW.
16. Added DEFTYPE for GENERATOR so that LispWorks and CMUCL won't
complain "because it's not a list" (IT IS!!)
17. Replaced PROCLAIMS with DECLAIMS.
18. Replaced DEFVARs with DEFCONSTANTs where appropriate.
19. Removed function namespace pollution by defS-generated code.
Merged 1.32.2.2 (Fernando's changes) with 1.37.
I hope I got this right.
Need to import compiler-let from the extensions package in CMUCL.
o The backquoting of make-sequence added in 1.35 is wrong, I think.
To make it worse, I lost my test cases that caused me to do this.
Stupid!
o Updated a few doc strings. Should really add some more so that
series is a little bit more self-documenting.
The change in 1.17 for scan-range was backwards: The CMUCL version
should get the coercion stuff and the non-CMUCL version shouldn't.
(Hmm, should I remove this dependency on platform? Probably.)
Backed out the changes in INIT-ELEM: they were mostly correct I
think. Just needed to stick a backquote before the make-sequence
stuff so we create the sequences at run-time, not compile. | https://sourceforge.net/p/series/series/ci/3bcc2842f15d11134e6f635dc0abb80893c8a3e8/log/?path= | CC-MAIN-2017-13 | refinedweb | 1,001 | 58.69 |
I'm trying to import a module to connect to my wifi. i'm using a module because i don't want the ssid or password to be tracked on github
But it don't work in my main.py. In repl it works fine, I import ConnectWifi in both main.py and in the repl prompt and :
You'll notice the first line is a print statement from these few lines of code :
Code: Select all
connect to wifi Traceback (most recent call last): File "main.py", line 15, in <module> NameError: name 'ConnectWiFi' isn't defined MicroPython v1.10-331-ge38c68310-dirty on 2019-05-09; ESP32 module with ESP32 Type "help()" for more information. >>> import ConnectWifi >>> ConnectWifi.greetings() Hellooooo ! >>>
I'm trying to check if the import failed or not, it seems to pass but then i can't call it. ConnectWifi.greetings fails and the whole file fails.
Code: Select all
import ConnectWifi try: ConnectWifi except NameError: print("no ConnectWifi") else: print("connect to wifi") ConnectWiFi.greetings()
Am i doing something wrong? | https://forum.micropython.org/viewtopic.php?f=18&t=6468&p=36783 | CC-MAIN-2020-10 | refinedweb | 176 | 74.19 |
A simplified interface for your main function.
Project description
Pymain - Simplified main
Pymain is a decorator and related tools to simplify your main function(s). It is intended to be more simple to use and understand than argparse, while still providing most of the functionality of similar libraries.
Description
The basic idea of pymain is that your main function (though it doesn’t need to be called “main”), and therefore your script or application itself, probably takes parameters and keyword arguments in the form of command line arguments. Since that interface works very similar to calling a python function, pymain translates between those interfaces for you. In addition, so many scripts with entry points include the if __name__ == '__main__': boilerplate, and pymain aims to eliminate that.
Usage
Import and use the @pymain decorator before your main function that has type annotations for the parameters. If you don’t need any short options or aliases, that is all you need to do. Pymain will detect whether the defining module is run as a script (and therefore __name__ == "__main__") or if it is being imported. If it is run as a script, then main will be called and given arguments based on sys.argv. If it is imported, then pymain will not run the function as a main function and it can still be called normally.
Pymain uses the type annotations to determine what types to expect. For short options or aliases, you can add an @alias decorator after the @pymain decorator describing the alias (either a single alias or a dictionary of multiple)
All arguments that are greater than one character in length are long options (e.g. –arg), and arguments that have a single character are short options (e.g. -a). Aliases follow the same rules.
Examples
optional.py:
from pymain import pymain @pymain def main(a: float, b: float, c: str = None): print(a / b) if c is not None: print(c)
Command line:
~ $ python optional.py 4 2 2.0
~ $ python optional.py 9 2 message 4.5 message
keyword.py:
from pymain import pymain @pymain def main(first: int, second: int, *, message: str = None): print(first + second) if message is not None: print(message)
Command line:
~ $ python main.py 4 6 10
~ $ python main.py 1 2 --message "Hello, World!" 3 Hello, World!
alias.py:
from pymain import pymain, alias @pymain @alias({"opt1": "x", "opt2": "y"}) def foo(value: float, *, opt1: float = 1.0, opt2: float = 2.0): print(value + opt1) print(value - opt2)
Command line:
~ $ python alias.py 2 3.0 0.0
~ $ python alias.py 5 -x 1 -y 1 6.0 4.0
~ $ python alias.py 10 --opt1 5 --opt2 2 15.0 8.0
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pymain/ | CC-MAIN-2019-47 | refinedweb | 478 | 66.74 |
., vim.wikia.com/wiki/Open_file_under_cursor).
you can use both:
ctrl+g to specify a line number and jump to it, no command line that i know of...
if you know your way in basic python i guess it could be a breeze to set such plugin
use alt+f3, and f3 to cycle through the results. no sticky highlight yet though ( jon, please... )
Preferences\User File Preferences, add and edit the following:wordSeparators ./\()"'-:,.;<>~!@#$%^&*|+=]{}`~?
btw, read Preferences\Default File Preferences for a complete list of all you can change.
good luck,vim.
These shouldn't be that hard to code a plugin for... I think nick did the second one already...
anyways, when opening a file under cursor... how does that work?
If I have
put cursor under site.css where is it going to get the rest of the path from? the current open file? or project (if any?) ?It shouldn't be hard if u have the full path to it like "c:\Documents and Settings....\site\text.css"I'll have a go at it and see what I can do, but I bet sublimator is gonna woop my ass at writing the plugin haha he's a python beast!
Here is some code that will run any command you want (in your case a ruby or python script) and display the results in a new buffer:
This is a modified version of some of the code from the Mercurial plugin I submitted a while ago.
# Runs a system command from the command line
# Captures and returns both stdout and stderr as an array, in that respective order
def doSystemCommand(commandText):
p = subprocess.Popen(commandText, shell=True, bufsize=1024, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
stdout = p.stdout
stderr = p.stderr
return [stdout.read(),stderr.read()]
def displayResults(Results, view):
if(Results[1] != None and Results[1] != ""):
createWindowWithText(view, "An error or warning occurred:\n\n" + str(Results[1]))
elif(Results[0] != None and Results[0] != ""):
createWindowWithText(view, str(Results[0]))
# Open a new buffer containing the given text
def createWindowWithText(view, textToDisplay):
NewView = sublime.Window.newFile(view.window())
NewView.insert(NewView.size(), textToDisplay)
That will run any command you provide it and capture stdout and stderr. It displays stdout only if theres no output on stderr.
You should be able to take that code and roll a plugin to fit your custom needs.
Very nice work sam
Thanks!
Hi guys
I've recently discovered Sublime and my first impressions are extremely favourable. I love the minimap feature plus the editor looks really cool too.
I've had a look through the various menu options, but something that I use a lot, but can't find (and it doesn't seem to work when I hold down the alt key - although I've tried others as well), is a column select option.
Is this feature available now (ie is it me? ) or is it on the roadmap for future releases?
Cheers,Mick
try alt+ctrl together with up/down arrow keys, is that what you need?
Sort
well, it is a different concept here, because it is not a selection, but rather a multiplication of the cursor. imo, this far stronger, because you can edit all those places instantly, and of course mark the required characters as you like. for example, if you have a rectangular area you want to mark and replace/edit, it will look the same, but if the area is of certain structure, which is not with the same length on each line - here sublime start to shine, e.g. try and edit the following on the editors you have mentioned:
L_acc = L_deposit_l( gbk1[index1][1] );
L_accb = L_deposit_l( gbk2[index2][1] );
L_gbk12 = L_add( L_acc, L_accb );
tmp = extract_l( L_shr( L_gbk12,1 ) );
L_acc = L_mult(tmp, gcode0);
now, try and add _xyz on all functions calls... in sublime you just do the multiple cursor magic at the start of the line, going down 5 lines, now jump with ctrl+left arrow 3 times, insert _xyz - DONE!
L_acc = L_deposit_l_xyz( gbk1[index1][1] );
L_accb = L_deposit_l_xyz( gbk2[index2][1] );
L_gbk12 = L_add_xyz( L_acc, L_accb );
tmp = extract_l_xyz( L_shr( L_gbk12,1 ) );
L_acc = L_mult_xyz(tmp, gcode0);
Thanks very much for the reply, Vim.
The way this works in Sublime is way more powerful than the 'standard' column or region select. I can see that this will prove extremely useful and will save me loads of time.
This works perfectly except for cut/copy/paste scenarios. For example, in the following trivial example, how would I column select the numbers at the end of test and stick them at the end of line, so :
test1 line
test2 line
test3 line
becomes
test line1
test line2
test line3
I guess this question really is, is there a way to column-paste?
true, for me, this is the mostly used plugin. i used it all the time with column related tasks.
yup that + pastecolumn is there too, it's just awesome
Aha perfect, I hadn't spotted those plugins. Thanks guys. | https://forum.sublimetext.com/t/sublime-as-a-replacement-for-my-current-editor/233/9 | CC-MAIN-2016-18 | refinedweb | 836 | 72.87 |
An abstraction for a thread of execution. More...
#include <yarp/os/Thread.h>
An abstraction for a thread of execution.
Definition at line 23 of file Thread.h.
Constructor.
Thread begins in a dormant state. Call Thread::start to get things going.
Definition at line 53 of file Thread.cpp.
Destructor.
Definition at line 61 of file Thread.cpp.
Called just after a new thread starts (or fails to start), this is executed by the same thread that calls start().
Definition at line 102 of file Thread.cpp.
Called just before a new thread starts.
This method is executed by the same thread that calls start().
Definition at line 99 of file Thread.cpp.
Check how many threads are running.
Definition at line 110 of file Thread.cpp.
Get a unique identifier for the thread.
Definition at line 115 of file Thread.cpp.
Get a unique identifier for the calling thread.
Definition at line 119 of file Thread.cpp.
Query the current scheduling policy of the thread, if the OS supports that.
Definition at line 133 of file Thread.cpp.
Query the current priority of the thread, if the OS supports that.
Definition at line 129 of file Thread.cpp.
Returns true if the thread is running (Thread::start has been called successfully and the thread has not stopped).
Definition at line 95 of file Thread.cpp.
Returns true if the thread is stopping (Thread::stop has been called).
Definition at line 90 of file Thread.cpp.
The function returns when the thread execution has completed.
Stops the execution of the thread that calls this function until either the thread to join has finished execution (when it returns from run()) or after seconds seconds.
Definition at line 70 of file Thread.cpp.
Call-back, called while halting the thread (before join).
This callback is executed by the same thread that calls stop(). It should not be called directly. Override this method to do the right thing for your particular Thread::run.
Reimplemented in yarp::os::Terminee, and ZombieHunterThread.
Definition at line 80 of file Thread.c.
Implemented in yarp::dev::FakeMotionControl, yarp::dev::MEIMotionControl, yarp::dev::FakeBot, yarp::dev::JrkerrMotionControl, RunReadWrite, yarp::dev::KinectDeviceDriver::USBThread, yarp::dev::ServerKinect, yarp::dev::ServerInertial, RFModuleThreadedHandler, yarp::dev::ServerSerial, yarp::dev::ServerSoundGrabber, SoundResources, RunTerminator, yarp::dev::UrbtcControl, yarp::os::RosNameSpace, yarp::dev::VirtualAnalogWrapper, yarp::dev::StageControl, ModuleHelper, yarp::os::Terminee, ZombieHunterThread, streamThread, yarp::dev::WxsdlWriter, RFModuleRespondHandler, KinectThread, yarp::os::MpiControlThread, and MessageStackThread.
Set the default stack size for all threads created after this point.
A value of 0 will use a reasonable default.
Definition at line 137 of file Thread.cpp.
Set the stack size for the new thread.
Must be called before Thread::start
Definition at line 106 of file Thread.cpp.
Set the priority and scheduling policy of the thread, if the OS supports that.
Definition at line 124 85 of file Thread.cpp.
Stop the thread.
Thread::isStopping will start returning true. The user-defined Thread::onStop method will be called. Then, this simply sits back and waits. Wait for thread termination so cannot be called from within run().
Definition at line 74 of file Thread.c in streamThread, and yarp::os::MpiControlThread.
Definition at line 107 of file Thread.h.
Release method.
The thread executes this function once when it exits, after the last "run". This is a good place to release resources that were initialized in threadInit() (release memory, and device driver resources).
Reimplemented in streamThread, and yarp::os::MpiControlThread.
Definition at line 116 of file Thread.h.
Reschedule the execution of current thread, allowing other threads to run.
Definition at line 141 of file Thread.cpp. | http://yarp.it/classyarp_1_1os_1_1Thread.html | CC-MAIN-2017-43 | refinedweb | 608 | 61.93 |
Hi,
The coordinate convention for the index in the grid sample is a bit surprising to me. Indeed, it seems to correspond to the standard tensor indexing coordinate but in reverse order.
Here is a code sample to observe what I am saying:
import torch a = torch.rand(1, 1, 4, 3) b = torch.nn.functional.grid_sample(a, torch.tensor([[[[1, -1]]]]).type(torch.FloatTensor), align_corners=True) #b corresponds to top right corner, i.e. j,i coordinates print(a[0, 0, 0, 2], b) c = torch.rand(1, 1, 4, 3, 2) d = torch.nn.functional.grid_sample(c, torch.tensor([[[[[1, 1, -1]]]]]).type(torch.FloatTensor), align_corners=True) #Again, here the convention is k, j, i print(c[0, 0, 0, 2, 1], d)
I was wondering if there were any reasoning behind this convention as it seems counter-intuitive to me.
Thank you for your help,
Samuel | https://discuss.pytorch.org/t/surprising-convention-for-grid-sample-coordinates/79997 | CC-MAIN-2022-40 | refinedweb | 149 | 59.5 |
[
]
Jacques Nadeau commented on DRILL-4455:
---------------------------------------
As someone who worked a lot on the memory layer and accounting stuff, I'm not sure how one
would split it without introducing a level of indirection that would impact performance. The
problem has to do with the ability to transfer data accounting that exists within the memory
buffers and trying to do that while maintaining a single canonical memory representation and
supporting limits. For reference, please review the information at [1] to understand how the
pieces work together.
We have two challenges I see at this point.
- This was originally proposed in November of 15. Note the attached slides in [2], specifically
the last one where all three approaches included the vectors and memory management moving
together in the project (due to the nature of the coupling). Not hearing any disagreement
and then going through the massive amount of work that this patch took to build and then hitting
a -1 6 months later takes a lot of wind out of one's sails.
- The larger problem is I'm not sure who is going to have the interest to try to do this patch
again. We're now ~6 months later with two trees that have moved in their own directions. Rebase
is probably very difficult (or impossible). My sense is that Arrow will continue to create
value and at some point, the Drill community will achieve a consensus that it is valuable
to do this work. In the meantime, I'm not sure anyone's heart is in it right now.
So while it may make sense to ultimately try to come up with a better approach to modularity
in the Arrow library around the first point, I'd like to see some demand from the community
that wants to use Arrow to do that (possibly in the form of patches or approaches proposed).
PS: An interesting question would be: how much development has happened in the "disputed module"
in Drill since this patch (or since my major reworking of it ~12 months ago).
[1]
[2]
> Depend on Apache Arrow for Vector and Memory
> --------------------------------------------
>
> Key: DRILL-4455
> URL:
> Project: Apache Drill
> Issue Type: Bug
> Reporter: Steven Phillips
> Assignee: Steven Phillips
> Fix For: 2.0.0
>
>
> The code for value vectors and memory has been split and contributed to the apache arrow
repository. In order to help this project advance, Drill should depend on the arrow project
instead of internal value vector code.
> This change will require recompiling any external code, such as UDFs and StoragePlugins.
The changes will mainly just involve renaming the classes to the org.apache.arrow namespace.
--
This message was sent by Atlassian JIRA
(v6.3.4#6332) | http://mail-archives.apache.org/mod_mbox/drill-issues/201611.mbox/%3CJIRA.12945704.1456796552000.340665.1479834359038@Atlassian.JIRA%3E | CC-MAIN-2018-30 | refinedweb | 451 | 57.81 |
I wrote in my previous post about the approach we took to the IE9 beta launch: partnering with design agencies and interesting customers to build what we believe are some of the most comprehensive HTML5 reference sites on the web today. Over the course of a couple of blog posts, I wanted to delve into a few of my favorite examples and talk about what I think makes them special, as well as highlight how the designers and developers took advantage of some of the new capabilities of HTML5.
The first experience I want to highlight is Never Mind the Bullets, an interactive comic book set in the Wild West. It comes from Steaw Web Design, a small Paris-based web studio who I met for the first time back in May. Steaw had done some early prototypes with using parallax-style effects with layered images and were keen to see whether they could create a complete experience using that technique. They pulled it off very nicely indeed with the final project, which also takes advantage of the WOFF font format for the comic-style typography and SVG for graphical effects.
You read the comic left to right by simply panning the mouse cursor across to the right side. Each panel of the story is composed out of a series of several transparent or alpha-blended PNG images that are overlaid onto a JPEG background. For example, in the panel above there are separate images for the cowboy, the steam from the train, the traincar, and the passengers. The speech bubbles are created out of an SVG shape with real text rendered using a WOFF display font that is loaded through the @font-face CSS attribute (with fallback solutions for browsers that don’t yet support WOFF).
All these elements are simply positioned using inline styles within a <div> element that represents the panel itself, as shown in this example (edited for brevity and formatting):
<div class="Panel" style="width: 723px; height: 700px;">
<div class="Layers In">
<img class="Layer" style="left:-95px; top:-75px" src="soif-5.jpg"
cp:
<img class="Layer" style="left:-127px; top:-75px" src="soif-4.png"
cp:
<img class="Layer" style="left:-190px; top:-75px" src="soif-3.png"
cp:
<img class="Layer" style="left:-444px; top:-75px" src="soif-2.png"
cp:
</div>
<div class="Layers Out">
<p class="Balloon" cp:
He's come to the west; the land of opportunity.
</p>
<div class="Layer" cp:
<p class="Balloon" cp:
I need a drink.
</p>
</div>
</div>
</div>
The magic of the comic comes from its interactivity, and here Steaw used a clever technique. Each panel element (the cowboy, the traincar etc.) is extended with several custom attributes (prefixed with “cp:”) that contain metadata on how it should be rendered and the depth of field for the parallax effect.
For rendering purposes, the browser itself ignores these custom attributes since they don’t have any defined semantics. But in the $.fn.parallax() function (found in parallax.js), these attributes are read out and used to generate a displacement value that is applied using a callback on the mousemove event, as can be seen below (again, slightly edited):
self.each(function() {
var $this = $(this);
$this.mousemove(function(event) {
var pos = $this.offset();
var mouseX = event.clientX - pos.left;
var mouseY = event.clientY - pos.top;
var containerDemiWidth = $this.width() / 2;
var containerDemiHeight = $this.height() / 2;
var centerX = containerDemiWidth;
var centerY = containerDemiHeight;
var displacementX = Math.min(1, Math.max(-1, (mouseX - centerX) /
(containerDemiWidth - settings.xMargin)));
var displacementY = Math.min(1, Math.max(-1, (mouseY - centerY) /
(containerDemiHeight - settings.yMargin)));
$this.children(".Layers").children(".Layer").each(function() {
var $layer = $(this);
var rect = $layer.data("rect");
var xFactor = $layer.attr(settings.xFactor);
var yFactor = $layer.attr(settings.yFactor);
var x = Math.round(centerX - displacementX * (-xFactor) /
100.0 * (rect.centerX - centerX));
var y = Math.round(centerY - displacementY * (-yFactor) /
100.0 * (rect.centerY - centerY));
$layer.animationMoveTo(x, y);
});
});
});
The resultant effect is very polished and fluid. Open it in Internet Explorer 9, hit F12 to bring up the developer tools and browse around the code – they make heavy use of jQuery but the whole site is a surprisingly small amount of code.
The piece de resistance is that you can customize your own comic strip with the link at the top. Because they’ve used SVG and text for the speech bubbles, it was relatively easy for them to implement this feature, and you can share your own comic strip with others via email, Facebook or Twitter.
Never Mind the Bullets is receiving a good reaction from the community so far:
- It was shortlisted for the FWA Site of the Day award;
- Smashing Magazine featured it in their newsletter;
- The Next Web called it “pretty damn cool”;
- Even John Gruber (not known for his love of Apple competitors) linked to it on Daring Fireball.
Check it out (even if you’re not using Internet Explorer 9) – I’m interested in your thoughts!
Very nicely done.
One tiny question though – the title says "Inside an HTML5 Interactive Experience". Where is the HTML5? I see WOFF (a font format) and SVG (a W3C graphics specification). I see JavaScript, but not making use of any of the new HTML5 APIs. I see good old fashioned HTML 4 in constructs like div class="Panel" (couldn't that be marked up with the HTML section or article elements?)?
So can you mention the HTML5 please?
It does occur to me that you could have added at least one aspect of HTML5 here.
"Each panel element (the cowboy, the traincar etc.) is extended with several custom attributes (prefixed with “cp:”) that contain metadata on how it should be rendered and the depth of field for the parallax effect."
Why not use the data-* attributes that HTML5 provides precisely for this purpose? See the HTML5 spec dev.w3.org/…/elements.html
So it's not HTML5 at all? Just JavaScript and web fonts?
You keep using that word HTML5. I do not think it means what you think it means…
**Where's the HTML5??**
Yes, there's loads of cool CSS3, js, SVG stuff in here, but no explicit mention of anything that's actually HTML5.
C'mon Microsoft. After years of being beaten up by the web development community for lagging so far behind everyone else, with IE9 you've finally got a chance to prove that you 'get' the web. Posts like this show that you've still got some catching up to do.
Hats off to the people who created the sites you mention though, they are truly awesome. And *they* probably understand what HTML5 actually is…
I've just visited "Never mind the Bullets" in Chrome 6, and it recommends I download and install IE9 to see the site better. That's not based on checking the features my browser supports though, it's based on explicitly checking on whether I'm using IE9.
Please can everyone stop using these bad habits of yester-year's browser wars. Design to standards, and use feature-detection (not horrible, dirty, discredited concepts like browser-sniffing), to enable graceful degredation. Something like modernizr.js (see modernizr.com – and no they are nothing to do with me), is ideal for this.
To all designers and developers: please, please let's not go back to the dark days of "This site best viewed in [insert browser-war contender of your choice here]". We're can be much better that that! 🙂
Bruce, of course you're quite right that formally speaking HTML5 is a W3C working draft specification. But as you also know, the term is also used in common parlance to refer to a slightly broader set of technologies that are part of the emerging web, including HTML5 itself, CSS3, SVG, Canvas 2D, WOFF and others.
I don't like the conflation of these terms myself, but it's a reality I think we have to live with. And in fact, you do exactly the same yourself (assuming you're the same Bruce Lawson) with your very good book Introducing HTML5, which includes coverage of Canvas 2D, Web SQL database, Web Workers and Web Sockets- none of which are part of the W3C HTML5 spec as far as I'm aware.
I'd also briefly note that SVG is referenced as a namespace within the HTML5 spec (4.8.15 and 2.8), for what it's worth.
Best wishes,
Tim
Glad you liked the book, Tim! And you're correct: Web Workers, Web Sockets etc are in our book, but not in the W3C spec, but they are all related WHATWG APIs, so that is "a slightly broader set of technologies", and are contained in…/complete.html
Adding graphics specifications like SVG, font specs like WOFF and styling specs like CSS is stretching the bounds of credibility too far, in my opinion – and, from what you said, your opinion too. So we're agreeing.
But I'm still genuinely at a loss to understand why, when you had the opportunity to use some genuine HTML5 features (new semantic tags, data-* attributes) you elected for HTML 4 constructs or just invalid markup.
Tim, it's quite obvious you didn't do any research before writing that last comment. All of those features you just mentioned are in the HTML5 spec.
Also, why do you insist on calling technologies not in the spec "HTML5" when you quite obvious are against the idea? It's not HTML5, and never will be. I'm surprised to find Microsoft employees pushing this misconception to the public. You're just making it worse!
I think that the discussion here in the comments raise an serious point, that being the use of HTML5 as an umbrella term for "emerging web" technologies.
I have concerns that HTML5 will become common place as a reference for SVG, CSS3, GeoLocation and the like, as they are frequently seen in the same context or writings without any clear definitions. We have an opportunity whilst HTML5 is still in draft to make a clear distinction between these technologies/specifications and educate not only those that will be on the frontline using these them, but also those that will be in a position to commission projects using these technologies.
It's possible. Just look at XHTML and CSS, a very clear distinction was made very early on and adopted with little fuss. We are all familiar with those little badges that were very popular a few years back stating my site is valid XHTML and Valid CSS, 2 badges, 2 technologies clearly seen as such. so why not in this instance. (Note: No I'm not advocating lots of little badges…..).
I would hate to see HTML5 become the new Web 3.0, simply through lack of education.
.
Ah, HTML5–the breakfast of champions.
I do like seeing SVG used inline in HTML. Hopefully other uses will follow.
Question: Bruce asked about why you didn't use data-* attributes. I was curious myself about this.
Where is the HTML5/CSS3 support on IE9???
Where is the WPF discussions? where is the Silverlight discussions? WHERE!.
We thought you were cool Tim, but you've sold out to the HTML5 overlords.
Mark, I think we need to find a suitable alternative umbrella term if we don't want HTML5 to be used as a term both for the core specification and the family of modern web technologies. It's going to be tough to persuade a publisher that the "correct" title for a book is "HTML5, CSS3, SVG 1.1, Canvas 2D API, ARIA, WOFF, and Indexed DB for Dummies" 🙂 I'm genuinely interested in this topic – there's no hidden agenda. A few of us toyed with "Web 5.0" for a while, but I don't think that works.
I think a few folk commenting have a slightly different impression of what we were setting out to achieve with these demos. To be clear, the goal wasn't to create the ultimate HTML5 core spec reference site. I'm sure across the 30+ sites we partnered with, you can find some things to pick apart in terms of their usage of HTML – and I quite look forward to that kind of "technical audit" discussion. But while interesting, the point was more to show the kind of quality experience you can now build with browsers that just a few months ago would often have been impossible to accomplish without a plug-in. I personally think that's an exciting development that many web developers people will be delighted in, not least those who are still skeptical of our investment in web standards.
VivaClient, you'll be pleased to hear that I have a couple of Silverlight and WPF articles queued up already. Stay tuned – I haven't met the "overlords" yet…
I'm also curious about the attributes. Why use these non-standard "namespaced" attribute names when you have data-* specifically for that purpose?
And where are the HTML5 tags? Semantics? The dialog element?
Microsoft is to emerging web as Apple is to open source.
@Ricardo – Dialog is no longer in the spec (don't quote on me on this but I seem to remember it was because Microsoft said they wouldn't implement it).
@Tims – We do have other term(s) for 'HTML5' the marketing term. How about 'Open Web Standards', 'Web Standards', 'HTML5 & related technologies' or how about 'Emerging web technologies' (in fact did you say that yourself in a comment – I can't see because of the paginated comments).
More importantly though while HTML5 is used as an umbrella term for marketing types, your audience on this blog is hardly those people. You're talking to developers that are in the trenches, who understand what HTML5 is so I'd expect you to be able to correctly define the technologies here.
Finally, like Bruce & Shelley I'm interested as to why no data-* attributes? | https://blogs.msdn.microsoft.com/tims/2010/10/01/inside-an-html5-interactive-experience-never-mind-the-bullets/ | CC-MAIN-2016-40 | refinedweb | 2,335 | 63.49 |
How to: Create a Product Manifest
To deploy prerequisites for your application, you can create a bootstrapper package. A bootstrapper package contains a single product manifest file but a package manifest for each locale. The package manifest contains localization-specific aspects of your package. This includes strings, end-user license agreements, and the language packs.
For more information about product manifests, see How to: Create a Package Manifest.
To create the product manifest
Create a directory for the bootstrapper package. This example uses C:\package.
In Visual Studio, create a new XML file called product.xml, and save it to the C:\package folder.
Add the following XML to describe the XML namespace and product code for the package. Replace the product code with a unique identifier for the package.
Add XML to specify that the package has a dependency. This example uses a dependency on Microsoft Windows Installer 3.1.
Add XML to list all the files that are in the bootstrapper package. This example uses the package file name CorePackage.msi.
Copy or move the CorePackage.msi file to the C:\package folder.
Add XML to install the package by using bootstrapper commands. The bootstrapper automatically adds the /qn flag to the .msi file, which will install silently. If the file is an .exe, the bootstrapper runs the .exe file by using the shell. The following XML shows no arguments to CorePackage.msi, but you can put command line argument into the Arguments attribute.
Add the following XML to check if this bootstrapper package is installed. Replace the product code with the GUID for the redistributable component.
Add XML to change the bootstrapper behavior depending on if the bootstrapper component is already installed. If the component is installed, the bootstrapper package does not run. The following XML checks if the current user is an administrator because this component requires administrative privileges.
Add XML to set exit codes if the installation is successful and if a reboot is necessary. The following XML demonstrates the Fail and FailReboot exit codes, which indicate that the bootstrapper will not continue installing packages.
Add the following XML to end the section for bootstrapper commands.
Move the C:\package folder to the Visual Studio bootstrapper directory. For Visual Studio 2010, this is the \Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages directory.
The product manifest contains installation instructions for custom prerequisites.
<> | http://msdn.microsoft.com/en-US/library/ee335701(d=printer).aspx | CC-MAIN-2014-23 | refinedweb | 398 | 52.26 |
Red Hat Bugzilla – Bug 729563
F16Alpha install does not have selinux enabled!
Last modified: 2011-08-18 18:25:04 EDT
Description of problem:
Installing F16 Alpha from DVD or net install results
in a system with selinux disabled.
Version-Release number of selected component (if applicable):
FC16 Alpha RC3
How reproducible:
every time
Steps to Reproduce:
1. install Alpha from net or dvd
Actual results:
selinux is disabled
Expected results:
selinux to be enforcing
proposing as alpha blocker so we can discuss whether we should have a criterion for this, and if so, at which stage.
selinux is disabled by /etc/selinux/config , which is part of selinux-policy package, and rpm -V selinux-policy doesn't complain, so it seems selinux disabled actually is the package default - is this a package bug, or is it supposed to be that way and anaconda should override it at install time or smth? CCing Dan for clarification.
oh, seems rpm -V doesn't complain whatever you do to the file. i guess it intentionally ignores config files. i'll poke into the package to see what the default really is.
This might have been caused by the move of /selinux to /sys/fs/, and this might thus be a consequence/duplicate of bug 728576.
FWIW:
[root@localhost ~]# grep selinux anaconda-ks.cfg
selinux --disabled
This is on a freshly installed system, set up with the Alpha RC3 DVD.
Please attach /var/log/anaconda/anaconda.log to this bug report. Thanks.
Created attachment 517619 [details]
anaconda.log from Alpha RC3 DVD installation with enforcing=0
Are you sure that's the right log? I'd expect if that were the case, I'd see enforcing=0 on the command line there at the top. Did you set it at tty2 or something?
Also yes, I'm wondering if comment #3 has it right too. There are a couple places in anaconda where we refer to /selinux. I've got a patch along those lines that I need to test out.
I'm 100% sure it's the correct log. What I'm not sure about right now whether I needed enforcing=0 for the DVD too or only for the live media installs. By the way, this issue can be observed with both, live media and dvd installs.
I'm also 100% sure the installed system had selinux disabled when I first booted it. I then rebooted it into permissive mode (without relabeling) and generated attachment #517580 [details] for bug #728863 which might or might not be connected to this bug.
Anaconda should be using selinux python bindings rather the hard coding paths if possible.
import selinux
if selinux.is_selinux_enabled():
print "You made dan happy"
I didn't need enforcing=0 to install from DVD. for me, installing from DVD with next, next, next, next works, and reproduces this bug. I can provide a log if you're worried about Sandro's.
Right the problem again is hard coding of /selinux. Which Chris is working to fix.
Anyone want to give updates= a try? It worked for me in a brief test.
I thought is_selinux_enabled could return 3 possible values? shouldn't it be
if selinux.is_selinux_enabled() > 0:
print "You made dan happy"
?
Discussed in the 2011-08-10 Fedora 16 go/no-go meeting. Since there are no release criteria stating that SELinux must be enabled, rejected as a blocker. However, it was accepted as an NTH bug for Fedora 16 alpha.
(In reply to comment #12)
> Anyone want to give updates= a try?
> It worked for me in a brief test.
I tried it on a default graphical i686 netinstall and SELinux is enabled by default with no apparent AVC issues..
Just installed F16 Alpha RC4 x86_64 from DVD and this issue seems to be fixed.
anaconda-16.14.6-1.fc16 has been submitted as an update for Fedora 16.. | https://bugzilla.redhat.com/show_bug.cgi?id=729563 | CC-MAIN-2016-36 | refinedweb | 651 | 66.64 |
Red Hat Bugzilla – Bug 1356
Floor Ceil Problem
Last modified: 2016-11-24 07:18:30 EST
The problem was encountered when I was compiling a .c file
that made a reference to the function floor (in math.h).
The error is:
/tmp/cca090901.o(.text+0x2756): undefined reference to
`floor'
I had the same error with ceil yesterday.
Here is a simple program that produces an identical error:
#include <stdio.h>
#include <math.h>
void main() {
printf("%.03f = %ld\n",1.23,(long)ceil(1.23));
}
I have verified this to be a problem on one of the test lab machines.
link in the math library (-lm)
Commit pushed to master at
Issue 1356 - setup should either save cert file or data | https://bugzilla.redhat.com/show_bug.cgi?id=1356 | CC-MAIN-2018-05 | refinedweb | 123 | 68.16 |
.
Cat-A-Moose Part IISeptember 9, 2008.
LoggingJuly 15, 2008
I.
Moose versus Plain PerlJune 11, 2008
Some people have questioned the wisdom of basing future software projects on an Object-Oriented programming technology such as Moose (see previous posts for more details on Moose if you don’t know what it is) rather than doing it the good old-fashioned way in pure, unadulterated Perl.
There are always questions to be considered whenever a new piece of software is introduced into the mix. Is it widely used? It is well written? Does it produce comprehensible and maintainable code? Could someone who has not seen it before pick up where someone else left off in the standard “run over by a bus” scenario? Is it likely to scare the living daylights out of anyone who’s never seen it before? I believe that most of these have been answered on the web by the wider Perl community when it comes to Moose. It seems clear, to me, that something like this is the future of all Perl OO programming, particularly given that it is inspired by work being done for Perl6.
In an attempt to show that Moose produces code which is comprehensible, maintainable and in many ways a big improvement over the pure Perl approach. Here’s an example written both ways: Foo.pm and FooMoose.pm. One thing to notice straight away is that the Moose variant is 49 lines long compared to the 114 lines of the standard version. It allows all the standard handling of getting and setting values to be hidden away. The author can then get on with specifying exactly how the class attributes should be defined.
There’s no doubt that the Moose approach is different, it doesn’t look quite like normal Perl but it is a very perl-ish way of programming. Beyond needing to learn a few basic keywords I don’t think there is much in the code which will scare a Perl programmer who has not previously touched Moose. I’d hope that, if anything, Moose should make it easier for future developers to maintain and extend code written in this way.
Moose on SL5March 3, 2008
I’ve been working through packaging the Moose perl module and its dependencies for SL5. This has now been done and you can now use an LCFG header (currently “develop” only) to include the packages like this:
#include <lcfg/options/perl-moose.h>
I will add the modules for FC6 in next. All the packages which weren’t provided in epel have been built locally and put into the new “world” bucket.
To get the new release tools on the SL5 machine as well you will need this:
!profile.packages mEXTRA(perl-Data-Structure-Util-0.12-1.inf \ perl-YAML-Syck-0.98-1.el5\ perl-UNIVERSAL-require-0.11-1.el5/noarch\ perl-LCFG-Build-PkgSpec-0.0.5-1/noarch\ perl-LCFG-Build-VCS-0.0.5-1/noarch) | http://blog.inf.ed.ac.uk/squinney/tag/moose/ | CC-MAIN-2018-26 | refinedweb | 501 | 70.43 |
Provided by: libguestfs-java_1.32.2-4ubuntu2_amd64
НАЗВА
guestfs-java - How to use libguestfs from Java
КОРОТКИЙ ОПИС
import com.redhat.et.libguestfs.*; GuestFS g = new GuestFS (); g.add_drive ("disk.img", new HashMap<String,Object>() { { put ("readonly", Boolean.TRUE); put ("format", "raw"); } }); g.launch ();
ОПИС
This manual page documents how to call libguestfs from the Java programming language. This page just documents the differences from the C API and gives some examples. If you are not familiar with using libguestfs, you also need to read guestfs(3). CLOSING THE HANDLE The handle is closed when it is reaped by the garbage collector. Because libguestfs handles include a lot of state, it is also possible to close (and hence free) them explicitly by calling the "close" method. ВИНЯТКИ Errors from libguestfs functions are mapped into the "LibGuestFSException" exception. This has a single parameter which is the error message (a "String"). Calling any method on a closed handle raises the same exception. ПОДІЇ // тощо OPTIONAL ARGUMENTS
ПРИКЛАД 1. СТВОРЕННЯ ОБРАЗУ ДИСКА
@EXAMPLE1@
ПРИКЛАД 2. ПЕРЕВІРКА ОБРАЗУ ДИСКА ВІРТУАЛЬНОЇ МАШИНИ
@EXAMPLE2@
ТАКОЖ ПЕРЕГЛЯНЬТЕ
guestfs(3), guestfs-examples(3), guestfs-erlang(3), guestfs-golang(3), guestfs-lua(3), guestfs-ocaml(3), guestfs-perl(3), guestfs-python(3), guestfs-recipes(1), guestfs-ruby(3),,.
АВТОРИ
Richard W.M. Jones ("rjones at redhat dot com")
АВТОРСЬКІ ПРАВА
© Red Hat Inc., 2011–2012. | https://manpages.ubuntu.com/manpages/xenial/uk/man3/guestfs-java.3.html | CC-MAIN-2022-33 | refinedweb | 226 | 69.18 |
Deque
A deque is a data structure containing zero or more items, all of the same type, which may be thought to represent the items lined up in single file with a front and a back. It supports four basic operations:
- Push an element into the front of the deque.
- Push an element into the back of the deque.
- Pop an element from the front of the deque, returning its value in the process.
- Pop an element from the back of the deque, returning its value in the process.
In practice, we might choose to include the following operations as well:
- Construct an empty deque.
- Copy the contents of one deque to another.
- Peek at the front element in the deque, without removing it.
- Peek at the back element in the deque, without removing it.
- Empty an already existing deque.
- Find size of a deque.
- Test if empty.
These peek operations are not really necessary; peek front is the same as pop front followed by push front, if the popped element is copied and then pushed back on; peek back can be defined analogously. And the test if empty operation is really a test of whether the result of the find size operation is zero.
Contents
Terminology
The term deque is a shortened form of double-ended queue. It is said to be double-ended because pushes and pops from both ends are possible; here the term queue is the name of a general class of data structures which allow insertion and removal of elements (but not search). The first element is the one at the front of the deque, and the last is the one at the back of the deque. An element can be described as before another if the former is closer to the front than the latter; the latter is referred to as being after the former. To push means to add an element, and to pop means to remove an element. Note that the front and the back of the deque are fully equivalent; we could interchange the terms front and back throughout our algorithms and they would work exactly as they did before.
Implementation
Array implementation
In an array implementation of a deque, the contents of the deque are stored in consecutive indices in an array. However, we encounter a problem if we want the element in the lowest-indexed position (i.e. 0 or 1) to be constantly at the front: when we pop from the front, we have to shift over all the other elements so that the lowest-indexed position contains the next element to be popped and all elements remain contiguous. The same applies if we want to push at the front; all elements currently in the deque would have to be shifted over to make room for the new element. These operations can both take
time where
is the number of elements currently in the deque. But we need constant time push/pop operations in order to make important algorithms like BFS run in linear time. To solve this, we do not replace the popped element, we merely increment an index into the next element to be popped, and we insert a pushed element at the index just before the current front element. That is, we maintain two indices into the array: one to the front and one to the back. When we push at the front, we add an element to the front and decrement the front index; when we push at the back, we add an element to the back and increment the back index; when we pop from the front, we remove the element from the front and increment the front index; when we pop from the back, we remove the element from the back and decrement the back index. However, consider what happens if, for example, we continually push one element at the front, then pop one from the back, then push another, and pop another, and so on: the size of the deque_front(x) first = (first - 1) mod N A[first] = x function push_back(x) A[last] = x last = (last + 1) mod N function pop_front return_val = A[first] first = (first + 1) mod N return return_val function pop_back(x) last = (last - 1) mod N return A[last] function peek_front return A[first] function peek_back return A[(last-1) mod N] function size return (last-first) mod N function make_empty last = first
Notice that if the deque becomes full and we attempt to push more elements, then the apparent size will wrap to zero and some elements will be overwritten. Also, if we attempt to pop from an empty deque,_front(x) insert x before head of L function push_back(x) insert x after tail of L function pop_front remove head of L, returning its data element function pop_back remove tail of L, returning its data element function peek_front return data element at head of L function peek_back return data element at tail of L function size return size of L function make_empty empty L
As one can easily see, the deque is merely a container over the operations supported by the list itself. (Here we assume that the list maintains its own size; if this is not so then we can add a
size field to the deque object.)
C++ STL deque class
In the C++ STL,
std::deque, found in the
<deque> header, is a template container capable of holding items of any (fixed) type, the type being supplied as a template argument. Hence, for example,
deque<char> is a deque of characters. The container supplies the following member functions (note that
T is the type of the elements of the deque):
void push_front(const T& x): pushes
xinto the front of the deque.
void push_back(const T& x): pushes
xinto the back of the deque.
void pop_front(): pops from the front of the deque.
void pop_back(): pops from the back of the deque.
T& front(): returns the element at the front of the deque
T& back(): returns the element at the back of the deque
size_type size(): returns the number of elements currently in the deque
bool empty(): returns
trueif the deque is empty,
falseotherwise.
void clear(): removes all elements in the deque, leaving it empty.
Additionally, unlike the STL
stack and
queue containers, the
deque container allows random-access iteration over its elements: hence
D[0] is a reference to the element at the front of deque
D, and so on.
The
deque container should be used whenever it is sufficient for the problem at hand; it is quicker and less error-prone to use it than to code your own deque. You are highly unlikely to encounter an application for which the STL
deque is too slow.
Note that the pop operations defined by this container are not identical to our own; they only remove the element and do not return its value. To do both, call
front or
back followed by
pop_front or
pop_back.
The STL
stack and
queue containers, except when this behavior is overridden by the corresponding template argument, are mere containers over STL
deques; since the deque's behavior is a superset of the behaviors of the stack and queue, either can be obtained simply by manipulating a deque with a restricted set of operations. | http://wcipeg.com/wiki/index.php?title=Deque&oldid=194 | CC-MAIN-2020-10 | refinedweb | 1,218 | 62.11 |
extreme alternatives and similar packages
Based on the "ORM and Datamapping" category.
Alternatively, view extreme alternatives based on common mentions on social networks and blogs.
ecto10.0 9.2 extreme VS ectoA toolkit for data mapping and language integrated query.
eredis9.7 0.0 extreme VS eredisErlang Redis client
postgrex9.6 6.8 extreme VS postgrexPostgreSQL driver for Elixir
redix9.5 6.2 extreme VS redixFast, pipelined, resilient Redis driver for Elixir. 🛍
eventstore9.4 7.6 extreme VS eventstoreEvent store using PostgreSQL for persistence
mongodb9.2 6.7 extreme VS mongodbMongoDB driver for Elixir
ecto_enum9.2 0.1 extreme VS ecto_enumEcto extension to support enums in models
amnesia9.2 0.0 extreme VS amnesiaMnesia wrapper for Elixir.
memento9.1 4.1 extreme VS mementoSimple + Powerful interface to the Mnesia Distributed Database 💾
moebius9.0 0.0 extreme VS moebiusA functional query tool for Elixir
mongodb_ecto9.0 0.0 extreme VS mongodb_ectoMongoDB adapter for Ecto
mysql9.0 3.5 extreme VS mysqlMySQL/OTP – MySQL and MariaDB client for Erlang/OTP
rethinkdb9.0 0.0 extreme VS rethinkdbRethinkdb client in pure elixir (JSON protocol)
paper_trail8.9 7.3 extreme VS paper_trailTrack and record all the changes in your database with Ecto. Revert back to anytime in history.
arc_ecto8.8 0.0 extreme VS arc_ectoAn integration with Arc and Ecto.
exredis8.7 0.0 extreme VS exredisRedis commands for Elixir
mariaex8.6 0.0 extreme VS mariaexPure Elixir database driver for MariaDB / MySQL
triplex8.4 2.7 extreme VS triplexDatabase multitenancy for Elixir applications!
ExAudit8.4 4.1 extreme VS ExAuditEcto auditing library that transparently tracks changes and can revert them.
ecto_mnesia8.3 0.0 extreme VS ecto_mnesiaEcto adapter for Mnesia Erlang term database.
shards8.2 1.3 extreme VS shardsPartitioned ETS tables for Erlang and Elixir
xandra8.2 0.0 extreme VS xandraFast, simple, and robust Cassandra driver for Elixir.
riak8.2 0.0 extreme VS riakA Riak client written in Elixir.
Bolt.Sips8.1 1.3 extreme VS Bolt.SipsNeo4j driver for Elixir
timex_ecto7.9 0.0 extreme VS timex_ectoAn adapter for using Timex DateTimes with Ecto
kst7.8 8.0 extreme VS kst💿 KVS: Abstract Chain Database
atlas7.8 0.0 extreme VS atlasObject Relational Mapper for Elixir
instream7.7 8.6 extreme VS instreamInfluxDB driver for Elixir
tds7.7 1.7 extreme VS tdsTDS Driver for Elixir
esqlite7.6 1.2 L3 extreme VS esqliteErlang NIF for sqlite
ecto_psql_extras7.6 4.8 extreme VS ecto_psql_extrasEcto PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
arbor7.6 0.0 extreme VS arborEcto elixir adjacency list and tree traversal. Supports Ecto versions 2 and 3.
inquisitor7.5 0.0 extreme VS inquisitorComposable query builder for Ecto
ecto_fixtures7.4 0.0 extreme VS ecto_fixturesFixtures for Elixir apps
sqlitex7.3 3.4 extreme VS sqlitexAn Elixir wrapper around esqlite. Allows access to sqlite3 databases.
kalecto7.3 0.0 extreme VS kalectoAdapter for the Calendar library in Ecto
mongo7.2 0.0 extreme VS mongoMongoDB driver for Elixir
mongodb_driver7.1 5.9 extreme VS mongodb_driverMongoDB driver for Elixir
boltun7.0 0.0 extreme VS boltunTransforms notifications from the Postgres LISTEN/NOTIFY mechanism into callback execution
redo7.0 0.0 extreme VS redopipelined erlang redis client
tds_ecto7.0 0.0 extreme VS tds_ectoTDS Adapter for Ecto
gremlex6.9 0.0 extreme VS gremlexElixir Client for Gremlin (Apache TinkerPop™)
sqlite_ecto6.9 0.0 extreme VS sqlite_ectoSQLite3 adapter for Ecto
couchdb_connector6.9 0.0 extreme VS couchdb_connectorA couchdb connector for Elixir
neo4j_sips6.8 0.0 extreme VS neo4j_sipsElixir driver for the Neo4j graph database server
sql_dust6.8 2.3 extreme VS sql_dustEasy. Simple. Powerful. Generate (complex) SQL queries using magical Elixir SQL dust.
craterl6.8 0.0 extreme VS craterlErlang client for crate.
github_ecto6.7 0.0 extreme VS github_ectoEcto adapter for GitHub API
ecto_cassandra6.6 0.0 extreme VS ecto_cassandraCassandra Ecto Adapter
triton6.5 0.0 extreme VS tritona Cassandra ORM extreme or a related project?
Popular Comparisons
README
Extreme
Erlang/Elixir TCP client for Event Store.
This version is tested with EventStore 3.9.3 - 4.1.1, Elixir 1.5, 1.6, 1.7 and Erlang/OTP 19.3, 20.3 and 21.0
INSTALL
Add Extreme as a dependency in your
mix.exs file.
def deps do [{:extreme, "~> 0.13.2"}] end
In order to deploy your app using
exrm you should also update your application list to include
:extreme:
def application do [applications: [:extreme]] end
Extreme includes all its dependencies so you don't have to name them separately.
After you are done, run
mix deps.get in your shell to fetch and compile Extreme and its dependencies.
EventStore v4 and later note
Starting from EventStore version 4.0 there are some upgrades to communication protocol. Event number size is changed to 64bits
and there is new messages
IdentifyClient and
ClientIdentified. Since we would like to keep backward compatibility with older v3 protocol,
we introduced new configuration for
:extreme application, where you have to set
:protocol_version equal to
4 if you want to use new protocol, default is
3.
Below is exact line you have to add in you application config file in order to activate new protocol:
config :extreme, :protocol_version, 4
USAGE
The best way to understand how adapter should be used is by investigating
test/extreme_test.exs file,
but we'll try to explain some details in here as well.
Extreme is implemented using GenServer and is OTP compatible. If client is disconnected from server we are not trying to reconnect, instead you should rely on your supervisor. For example:
defmodule MyApp.Supervisor do use Supervisor def start_link do Supervisor.start_link __MODULE__, :ok end @event_store MyApp.EventStore def init(:ok) do event_store_settings = Application.get_env :my_app, :event_store children = [ worker(Extreme, [event_store_settings, [name: @event_store]]), # ... other workers / supervisors ] supervise children, strategy: :one_for_one end end
You can manually start adapter as well (as you can see in test file):
{:ok, server} = Application.get_env(:extreme, :event_store) |> Extreme.start_link
From now on,
server pid is used for further communication. Since we are relying on supervisor to reconnect,
it is wise to name
server as we did in example above.
MODES
Extreme can connect to single ES node or to cluster specified with node IPs and ports.
Example for connecting to single node:
config :extreme, :event_store, db_type: :node, host: "localhost", port: 1113, username: "admin", password: "changeit", reconnect_delay: 2_000, connection_name: :my_app, max_attempts: :infinity
db_type- defaults to :node, thus it can be omitted
host- check EXT IP setting of your EventStore
port- check EXT TCP PORT setting of your EventStore
reconnect_delay- in ms. Defaults to 1_000. If tcp connection fails this is how long it will wait for reconnection.
connection_name- Optional param introduced in EventStore 4. Connection can be identified by this name on ES UI
max_attempts- Defaults to :infinity. Specifies how many times we'll try to connect to EventStore
Example for connecting to cluster:
config :extreme, :event_store, db_type: :cluster, gossip_timeout: 300, mode: :read, nodes: [ %{host: "10.10.10.29", port: 2113}, %{host: "10.10.10.28", port: 2113}, %{host: "10.10.10.30", port: 2113} ], connection_name: :my_app, username: "admin", password: "changeit"
gossip_timeout- in ms. Defaults to 1_000. We are iterating through
nodeslist, asking for cluster member details. This setting represents timeout for gossip response before we are asking next node from
nodeslist for cluster details.
nodes- Mandatory for cluster connection. Represents list of nodes in the cluster as we know it
host- should be EXT IP setting of your EventStore node
port- should be EXT HTTP PORT setting of your EventStore node
mode- Defaults to
:writewhere Master node is prefered over Slave, otherwise prefer Slave over Master
Example of connection to cluster via DNS lookup
config :extreme, :event_store, db_type: :cluster_dns, gossip_timeout: 300, host: "es-cluster.example.com", # accepts char list too, this whould be multy A record host enrty in your nameserver port: 2113, # the external gossip port connection_name: :my_app, username: "admin", password: "changeit", mode: :write, max_attempts: :infinity
When
cluster mode is used, adapter goes thru
nodes list and tries to gossip with node one after another
until it gets response about nodes. Based on nodes information from that response it ranks their statuses and chooses
the best candidate to connect to. For
:write mode (default)
Master node is prefered over
Slave,
but for
:read mode it is opposite. For the way ranking is done, take a look at
lib/cluster_connection.ex:
defp rank_state("Master", :write), do: 1 defp rank_state("Master", _), do: 2 defp rank_state("PreMaster", :write), do: 2 defp rank_state("PreMaster", _), do: 3 defp rank_state("Slave", :write), do: 3 defp rank_state("Slave", _), do: 1
Note that above will work with same procedure with
cluster_dns mode turned on, since internally it will get ip addresses to which the same connection procedure will be used.
Once client is disconnected from EventStore, supervisor should respawn it and connection starts over again.
Communication
EventStore uses ProtoBuf for taking requests and sending responses back.
We are using exprotobuf to deal with them.
List and specification of supported protobuf messages can be found in
include/event_store.proto file.
Instead of wrapping each and every request in elixir function, we are using
execute/2 function that takes server pid and request message:
{:ok, response} = Extreme.execute server, write_events()
where
write_events can be helper function like:
alias Extreme.Msg, as: ExMsg defp write_events(stream \\ "people", events \\ [%PersonCreated{name: "Pera Peric"}, %PersonChangedName{name: "Zika"}]) do proto_events = Enum.map(events, fn event -> ExMsg.NewEvent.new( event_id: Extreme.Tools.gen_uuid(), event_type: to_string(event.__struct__), data_content_type: 0, metadata_content_type: 0, data: :erlang.term_to_binary(event), metadata: "" ) end) ExMsg.WriteEvents.new( event_stream_id: stream, expected_version: -2, events: proto_events, require_master: false ) end
This way you can fine tune your requests, i.e. choose your serialization. We are using erlang serialization in this case
data: :erlang.term_to_binary(event), but you can do whatever suites you.
For more information about protobuf messages EventStore uses,
take a look at their documentation or for common use cases
you can check
test/extreme_test.exs file.
Subscriptions
Extreme.subscribe_to/3 function is used to get notified on new events on particular stream.
This way subscriber, in next example
self, will get message
{:on_event, push_message} when new event is added to stream
people.
def subscribe(server, stream \\ "people"), do: Extreme.subscribe_to(server, self, stream) def handle_info({:on_event, event}, state) do Logger.debug "New event added to stream 'people': #{inspect event}" {:noreply, state} end
Extreme.read_and_stay_subscribed/7 reads all events that follow a specified event number, and subscribes to future events.
defmodule MyApp.StreamSubscriber use GenServer def start_link(extreme, last_processed_event), do: GenServer.start_link __MODULE__, {extreme, last_processed_event} def init({extreme, last_processed_event}) do stream = "people" state = %{ event_store: extreme, stream: stream, last_event: last_processed_event } GenServer.cast self, :subscribe {:ok, state} end def handle_cast(:subscribe, state) do # read only unprocessed events and stay subscribed {:ok, subscription} = Extreme.read_and_stay_subscribed state.event_store, self, state.stream, state.last_event + 1 # we want to monitor when subscription is crashed so we can resubscribe ref = Process.monitor subscription {:noreply, %{state|subscription_ref: ref}} end def handle_info({:DOWN, ref, :process, _pid, _reason}, %{subscription_ref: ref} = state) do GenServer.cast self, :subscribe {:noreply, state} end def handle_info({:on_event, push}, state) do push.event.data |> :erlang.binary_to_term |> process_event event_number = push.link.event_number :ok = update_last_event state.stream, event_number {:noreply, %{state|last_event: event_number}} end def handle_info(:caught_up, state) do Logger.debug "We are up to date!" {:noreply, state} end def handle_info(_msg, state), do: {:noreply, state} defp process_event(event), do: IO.puts("Do something with #{inspect event}") defp update_last_event(_stream, _event_number), do: IO.puts("Persist last processed event_number for stream") end
This way unprocessed events will be sent by Extreme, using
{:on_event, push} message.
After all persisted messages are sent, :caught_up message is sent and then new messages will be sent the same way
as they arrive to stream.
If you subscribe to non existing stream you'll receive message {:extreme, severity, problem, stream} where severity can be either
:error (for subscription on hard deleted stream) or
:warn (for subscription on non existing or soft deleted stream). Problem is explanation of problem (i.e. :stream_hard_deleted). So in your receiver you can either have catch all
handle_info(_message, _state) or you can handle such message:
def handle_info({:extreme, _, problem, stream}=message, state) do Logger.warn "Stream #{stream} issue: #{to_string problem}" {:noreply, state} end
Extreme.Listener
Since it is common on read side of system to read events and denormalize them, there is Extreme.Listener macro that hides noise from listener:
defmodule MyApp.MyListener do use Extreme.Listener import MyApp.MyProcessor # returns last processed event by MyListener on stream_name, -1 if none has been processed so far defp get_last_event(stream_name), do: DB.get_last_event MyListener, stream_name defp process_push(push, stream_name) do #for indexed stream we need to follow push.link.event_number, otherwise push.event.event_number event_number = push.link.event_number DB.in_transaction fn -> Logger.info "Do some processing of event #{inspect push.event.event_type}" :ok = push.event.data |> :erlang.binary_to_term |> process_event(push.event.event_type) DB.ack_event(MyListener, stream_name, event_number) end {:ok, event_number} end # This override is optional defp caught_up, do: Logger.debug("We are up to date. YEEEY!!!") end defmodule MyApp.MyProcessor do def process_event(data, "Elixir.MyApp.Events.PersonCreated") do Logger.debug "Doing something with #Listener, [@event_store, "my_indexed_stream", [name: MyListener]]), # ... other workers / supervisors ] supervise children, strategy: :one_for_one end end
Subscription can be paused:
{:ok, last_event_number} = MyApp.MyListener.pause MyListener
and resumed
:ok = MyApp.MyListener.resume MyListener
Extreme.FanoutListener
It's not uncommon situation to listen live events and propagate them (for example on web sockets). For that situation there is Extreme.FanoutListener macro that hides noise from listener:
defmodule MyApp.MyFanoutListener do use Extreme.FanoutListener import MyApp.MyPusher defp process_push(push) do Logger.info "Forward to web socket event #{inspect push.event.event_type}" :ok = push.event.data |> :erlang.binary_to_term |> process_event(push.event.event_type) end end defmodule MyApp.MyPusher do def process_event(data, "Elixir.MyApp.Events.PersonCreated") do Logger.debug "Transform and push event with data: #FanoutListener, [@event_store, "my_indexed_stream", [name: MyFanoutListener]]), # ... other workers / supervisors ] supervise children, strategy: :one_for_one end end
Persistent subscriptions
The Event Store provides an alternate event subscription model, from version 3.2.0, known as competing consumers. Instead of the client holding the state of the subscription, the server remembers it.
Create a persistent subscription
The first step in using persistent subscriptions is to create a new subscription. This can be done using the Event Store admin website or in your application code, as shown below. You must provide a unique subscription group name and the stream to receive events from.
alias Extreme.Msg, as: ExMsg {:ok, _} = Extreme.execute(server, ExMsg.CreatePersistentSubscription.new( subscription_group_name: "person-subscription", event_stream_id: "people", resolve_link_tos: false, start_from: 0, message_timeout_milliseconds: 10_000, record_statistics: false, live_buffer_size: 500, read_batch_size: 20, buffer_size: 500, max_retry_count: 10, prefer_round_robin: true, checkpoint_after_time: 1_000, checkpoint_max_count: 500, checkpoint_min_count: 1, subscriber_max_count: 1 ))
Connect to a persistent subscription
Extreme.connect_to_persistent_subscription/5 function is used subscribe to an existing persistent subscription. The subscriber, in this example
self, will receive message
{:on_event, push_message} when each new event is added to stream
people.
{:ok, subscription} = Extreme.connect_to_persistent_subscription(server, self(), group, stream, buffer_size)
Receive & acknowledge events
You must acknowledge receipt, and successful processing, of each received event. The Event Store will remember the last acknowledged event. The subscription will resume from this position should the subscriber process terminate and reconnect. This simplifies the client logic - the code you must write.
Extreme.PersistentSubscription.ack/3 function is used to acknowledge receipt of an event.
receive do {:on_event, event, correlation_id} -> Logger.debug "New event added to stream 'people': #{inspect event}" :ok = Extreme.PersistentSubscription.ack(subscription, event, correlation_id) end
You must track the
subscription PID returned from the
Extreme.connect_to_persistent_subscription/5 function as part of the process state when using a
GenServer subscriber.
def handle_info({:on_event, event, correlation_id}, %{subscription: subscription} = state) do Logger.debug "New event added to stream 'people': #{inspect event}" :ok = Extreme.PersistentSubscription.ack(subscription, event, correlation_id) {:noreply, state} end
Events can also be not acknowledged. They can be not acknowledged with a nack_action of :Park, :Retry, :Skip, or :Stop.
def handle_info({:on_event, event, correlation_id}, %{subscription: subscription} = state) do Logger.debug "New event added to stream 'people': #{inspect event}" if needs_to_retry do :ok = Extreme.PersistentSubscription.nack(subscription, event, correlation_id, :Retry) else :ok = Extreme.PersistentSubscription.ack(subscription, event, correlation_id) end {:noreply, state} end
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'add some feature')
- Push to the branch (
git push origin my-new-feature)
- Create new Pull Request
Licensed under The MIT License.
*Note that all licence references and agreements mentioned in the extreme README section above are relevant to that project's source code only. | https://elixir.libhunt.com/extreme-alternatives | CC-MAIN-2021-43 | refinedweb | 2,752 | 51.14 |
Section (3) round
Name
round, roundf, roundl — round to nearest integer, away from zero
Synopsis
#include <math.h>
DESCRIPTION
These functions round
x to the nearest integer, but
round halfway cases away from zero (regardless of the current
rounding direction, see fenv(3)), instead of to the
nearest even integer like rint(3).
For example,
round(0.5) is 1.0, and
round(−0.5)
is −1.0.
RETURN VALUE
These functions return the rounded integer value.
If
x is integral,
+0, −0, NaN, or infinite,
x itself is returned.
ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).
NOTES
POS. | https://manpages.net/detail.php?name=round | CC-MAIN-2022-21 | refinedweb | 106 | 69.07 |
Hung> I have my doubts about Python being the first programming language Hung> to teach. I see all too many newbies running into the problem of Hung> namespaces. How do you explain to them that "from xyz import *" is Hung> a bad thing, if they don't even understand what's going on behind Hung> the scene? Also, how in the world can beginners understand what a Hung> hash table mean? Are we going to tell them something like: "oh Hung> well, think of Python dictionary as a magic black box, you'll Hung> understand it later when you take a course in C/C++"? I think the assumption is that you don't give them everything at once, and you can simply avoid teaching them the "bad" stuff like "from m import *". Regarding dictionaries, I would tell them, "Think of a Python dictionary as a regular dictionary. You look up a 'word' and it gives you the 'definition' of that word." The correspondence is good enough to get them going I think. -- Skip Montanaro (skip at pobox.com) | http://mail.python.org/pipermail/python-list/2001-November/102449.html | CC-MAIN-2013-20 | refinedweb | 179 | 79.3 |
Greetings as get a chance to win a prize! In fact, many of them found our Easter Egg in just a few short hours. More recently, we were able to get even more feedback while devs became true Ionic Jedi Hacksters in our hackathon last week (Stay tuned for results on our Ionic Jedi Hackathon!!!)
Other than the version change, what makes this CLI release special? Let’s take a look at some of the key improvements to the CLI.
Speed + Guidance
The first thing you may notice is how quickly the new CLI installs. This is partly due to eliminating over 90MB of dependencies and thousands of lines of legacy code! Now when you install the CLI, you get a much smaller footprint as well as a faster install time. Going forward, CLI speed and performance will be one of the primary considerations we have.
Another consideration we had was providing more help, guidance, and feedback. A large number of commands now provide interactive prompts when information is needed. The CLI tries to be informative and helpful when problems arise. Command help has also been improved. Just append
--help to any command for a detailed overview of inputs and options. We also provide examples of common use cases. For example, check out the details of
ionic start --help:
Plugins!
We took a different approach to the architecture of the CLI. Instead of providing everything in one global install, we split out non-essential commands and functionality into CLI plugins. This keeps the core small, while still offering valuable, project-specific functionality in plugins.
For the first release of CLI v3, there are four official CLI plugins:
@ionic/cli-plugin-ionic-angular– Ionic Angular project plugin that provides useful build tools and generators.
@ionic/cli-plugin-ionic1– Ionic 1 project plugin that has functionality ported from the old CLI.
@ionic/cli-plugin-cordova– Essential for an Ionic/Cordova app.
@ionic/cli-plugin-proxy– For proxying CLI requests through a firewall.
A common question that came up during the beta test was “Why are the commands different?” With the new CLI, we decided to namespace the Cordova commands (e.g.
ionic build is now
ionic cordova build). We felt this was a necessary change as Ionic developers are beginning to create Ionic apps for desktop, PWAs, and other platforms. To help with the differences, we made you a lovely Cheat Sheet.
Getting Started
Make sure you have Node 6+ and npm 3+.
Install the new CLI globally (after uninstalling the old one):
npm uninstall -g ionic npm install -g ionic@latest
In your Ionic project directory (and assuming you have a standard Ionic project structure), try running a command, such as
ionic info. The CLI attempts to identify your project type and will prompt you to install the respective plugin. If you run
ionic cordova, it will prompt you to install the Cordova plugin. If you run
ionic --help, you’ll see a list of all commands.
You’ll need both the Cordova plugin (
@ionic/cli-plugin-cordova) and the project plugin (
@ionic/cli-plugin-ionic-angular or
@ionic/cli-plugin-ionic1) to continue developing an existing Ionic/Cordova app:
For Ionic Angular:
npm install --save-dev --save-exact @ionic/cli-plugin-ionic-angular@latest npm install --save-dev --save-exact @ionic/cli-plugin-cordova@latest
For Ionic 1:
npm install --save-dev --save-exact @ionic/cli-plugin-ionic1@latest npm install --save-dev --save-exact @ionic/cli-plugin-cordova@latest
The CLI will also occasionally check for updates and prompt you when there’s updates available.
Known Issues
We have a few minor things to improve now that CLI v3 is out.
ionic startstill takes a long time to download dependencies. (#2231)
ionic startdoes not yet support alternatives such as downloading from a Github repo, a zip URL, or an Ionic Creator project. (#2156)
- Using
ionic cordovacommands indent
config.xmlto 4 spaces, which may be alarming for existing apps. We write to
config.xmlfor resource generation and livereload. (#2230)
- For Ionic 1, some gulp hooks are not called. (#1989)
- Uploads from CLI v3 don’t extract properly in Ionic Deploy on Android devices. (#2237)
For a full list of CLI changes, please see CHANGELOG.md. For more documentation, please see README.md.
Questions? Ideas? Feedback? Issues? Please let us know by filing an issue on the Ionic CLI repo.
THANK YOU to all our wonderful Beta testers! Special thanks to those who went the extra mile and contributed issues, comments, and pull requests on Github. ❤️ | https://ionicframework.com/blog/announcing-ionic-cli-v3/ | CC-MAIN-2021-31 | refinedweb | 755 | 56.86 |
Can someone explain why I am getting an invalid syntax error from Python's interpretor while formulating this simple if...else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. "Else" is highlighted by the interpreter. What's wrong?
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48)
[MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax
>>>
Python does not allow empty blocks, unlike many other languages (since it doesn't use braces to indicate a block). The
pass keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0: print('3 greater then 0') else: pass
Or an empty method:
def doNothing(): pass | https://codedump.io/share/Wpgj7tkTu3nN/1/invalid-syntax-on-very-simple-python-if--else-statement | CC-MAIN-2017-51 | refinedweb | 162 | 71.95 |
thriftpy 0.1.6
Pure python implemention of Apache Thrift.
ThriftPy is a pure python implemention of Apache Thrift in a pythonic way.
Documentation:
Installation
Install with pip
$ pip install thriftpy
You may also install cython first to build cython extension locally.
$ pip install cython thriftpy
Code Demo from thriftpy.rpc import make_server pingpong = thriftpy.load("pingpong.thrift") class Dispatcher(object): def ping(self): return "pong" server = make_server(pingpong.PingPong, Dispatcher(), '127.0.0.1', 6000) server.serve()
And a client:
import thriftpy from thriftpy.rpc import make_client pingpong = thriftpy.load("pingpong.thrift") client = make_client(pingpong.PingPong, '127.0.0.1', 6000) client.ping()
See, it’s that easy!
You can refer to ‘examples’ and ‘tests’ directory in source code for more usage examples.
Features
Currently ThriftPy have these features (also advantages over the upstream python lib):
Supports python2.7 to python3.4 and pypy.
Compatible with Apache Thirft. You can use ThriftPy together with the official implemention servers and clients, such as a upstream server with a thriftpy client or the opposite.
Currently implemented protocols and transports:
- binary protocol (python and cython implemention)
- buffered transport
- tornado server and client (with tornado 4.0)
- framed transport
Can directly load thrift file as module, the sdk code will be generated on the fly.
For example, pingpong = thriftpy.load("pingpong.thrift") will load ‘pingpong.thrift’ as ‘pingpong’ module.
Or, when import hook enabled, directly use import pingpong_thrift to import the ‘pingpong.thrift’ file as module.
Pure python, standalone implemention. No longer need to compile & install the ‘thrift’ package. All you need is thrift file.
Easy RPC server/client setup.
Benchmarks
TODOs
Currently ThriftPy is not fully compatible with thrift, I only implemented the features we need in ele.me.
These todos need to be done, but may not be completed by me in near future, so contributions are very welcome!
- other protocol and transport except binary and buffered transport.
- map type const.
- ‘namespace’, ‘extends’, ‘import’, ‘oneway’ etc keywords.
- the ‘.thrift’ file parser will skip a section if it has syntax error. A better warning message should be given.
Contribute
- Fork the repo and make changes.
- Write a test which shows a bug was fixed or the feature works as expected.
- Make sure travis-ci test succeed.
- Send pull request.
- Author: Lx Yu
- Keywords: thrift python thriftpy
- License: MIT
- Categories
- Development Status :: 3 - Alpha
- Intended Audience :: Developers
- License :: OSI Approved :: MIT License
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Programming Language :: Python :: Implementation :: CPython
- Programming Language :: Python :: Implementation :: PyPy
- Topic :: Software Development
- Package Index Owner: lxyu
- DOAP record: thriftpy-0.1.6.xml | https://pypi.python.org/pypi/thriftpy/0.1.6 | CC-MAIN-2016-36 | refinedweb | 438 | 54.08 |
After creating and writing files in java, a user needs to know the concept of java read files. As we know to create a new file, we use createNewFile() method. The output is a Boolean value= true in case the file creation is successful. Otherwise, the program returns the output as false which means the file already exists. The system throws IOException if there is a problem in creation of the file. Similarly, to write a file, the user uses write() method. With the help of this method, the user can write() in the created file.
To read files in java, the use of scanner class comes into play. Scanner class will read the contents of the text file which exists already. In this, the scanner class breaks the input of the file into tokens. As a result, we get the output as the tokens into various types using methods such as nextLine(), hasnextLine() etc
Below is a program to illustrate how we can read files in java using scanner class:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class DeveloperHelps { public static void main(String[] args) { try { File O = new File("filename.txt"); Scanner read = new Scanner(O); while (read.hasNextLine()) { String data = read.nextLine(); System.out.println(data); } read.close(); } catch (FileNotFoundException e) { System.out.println("There is an error while reading the file"); e.printStackTrace(); } } }
The output of this java program using scanner class will be:
There is an error while reading the file
The constructors that can be invoked for java read class are:
FileReader(String file): This constructor opens the file in the read mode and fetches filename in the string. The system throws an exception FileNotFound in case the user cannot find the file, or if the file is missing.
FileReader(File file): This will open the file in the read mode and fetches name of the file in the file instance. The system throws an exception FileNotFound in case the user cannot find the file, or if the file is missing.
In this similar way to Scanner class, the user can also use BufferReader to read the text of the file line by line. In this method, the user can read the text from character-input stream. The user performs the buffer process again and again for better and efficient results in reading characters or arrays. The syntax for BufferReader to read a file is:
BufferReader i= new BufferReader(Reader i, int size);
Here is an example to illustrate the use of BufferReader in java:
package com.javatpoint; import java.io.*; public class DeveloperHelps{ public static void main(String args[])throws Exception{ InputStreamReader x=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(x); System.out.println("Apple is a fruit"); String name=br.readLine(); System.out.println("Cat is an animal"); } }
The output of this program will be:
Apple is a fruit Cat is an animal
Java has launched a new version Java SE 8 in which there’s an introduction to new class for more efficient reading of file. It is java.util.stream.Stream. There is one more way of reading file content in java. We can do it using FileReader class. This class is the best one when the user wants to read character files. When the constructor of the class is invoked, it presumes that default character encoding is appropriate.
The user can also read files in java by reading all the lines of the file in a list. The method ensures that the file will get closed when all the content is read. The bytes of the file are decoded using a particular char set. The output is in the form of DataInputStream class.
After following the processes such as create a file, write a file, read a file, the last method which is followed is delete a file. The user can do this by using delete() method. This method deletes all the contents of the file. | https://www.developerhelps.com/java-read-file/ | CC-MAIN-2021-31 | refinedweb | 664 | 65.32 |
I've ported a low-memory, completely self-contained speech synthesizer available to the ESP8266. No Internet connection or services are used, so you can use this is applications where a web service just isn't possible or desirable.
(note you will also need to handle the I2S or delta-sigma sound output)
Software Automatic Mouth (SAM) was an amazing speech synthesizer available on 8-bit CPUs in the early 80s. There were versions for the Atari 400, Commodore 64, and others. A fan converted it from 6502 assembly to C code and put it online ( ). I took his code, reworked the output so it sent bytes directly to the audio device instead of buffering, and moved what tables I could into PROGMEM.
The quality is not stellar, but still amazing given the small memory footprint. All samples and waveform generation are only 4-bit(!!)) and even with CPU limits of the late 70s/early 80s is spoke in real time. While the ESP8266 has 100x the CPU horsepower of a 1-MHz 6502, it has less free memory than a C64 did, so this low memory usage is critical.
If you have need for a fixed vocabulary for your project, I'd still use the MP3 ESP8266Audio class for much higher quality, but if you don't know what you'll need your ESP8266 to say beforehand this is definitely usable.
Using the code is very simple:
#include <Arduino.h>
#include <ESP8266SAM.h>
#include <AudioOutputI2SDAC.h>
AudioOutputI2SDAC *out = NULL;
void setup()
{
out = new AudioOutputI2SDAC();
out->begin();
}
void loop()
{
ESP8266SAM *sam = new ESP8266SAM;
sam->Say(out, "Can you hear me now?");
delay(500);
sam->Say(out, "I can't hear you!");
delete sam;
} | https://www.esp8266.com/viewtopic.php?p=70512 | CC-MAIN-2019-35 | refinedweb | 283 | 63.39 |
Next, we will learn an important concept – PWM, or Pulse Width Modulation. It is used to switch the LED between on and off fast. Remember the test before we add a time module? The LED blinks too fast, so it seems to be on all the time. That is the principle of the PWM. So what would happen if we change the duration of the LED on and off? What if we make it bright for shorter time, and off for longer?
Let’s give it a try!
Keep the wiring the same, and save a copy of the code in last chapter as pwm_led.py. If you have a display, click File -> Save as in the Python IDLE or just press Ctrl + Shift + S to save a copy.
If you don’t have a screen, you can use the cp command:
Then edit the file:
Now we need to change delay into two variables: on_delay and off_delay, and assign 0.005 to both:
import RPi.GPIO as GPIO import time led_pin = 17 on_delay = 0.005 off_delay = 0.005
Remember to change the two delay in the bottom to on_delay and off_delay too.
Save and run the code. The LED would not blink, right? As the frame perceiving time for human eye is about 0.01 seconds (about 60 frames per second), through setting the two variables to 0.005s, a cycle will be 0.01s (one on + one off), so it seems the LED would not blink – actually it’s that our eyes cannot recognize the frame change.
Let’s write a simple formula to calculate the off_delay time:
Thus once we change the value of on_delay, that of off_delay will be changed accordingly, keeping a whole cycle duration at 0.01s.
For example, modify on_delay to 0.001s, then off-delay will be 0.01-0.001=0.009 s. So that’s what we want it to be: keep the LED on for a shorter time and off longer:
import RPi.GPIO as GPIO import time led_pin = 17 on_delay = 0.001 off_delay = 0.01 - on_delay
Save the code and run it. The LED becomes dimmer, right? Press Ctrl + C to stop it, and change on_delay to 0.009, meaning off_delay will be 0.001 accordingly. Then run it again.
Amazing! The LED becomes brighter now! Have you got it? First, set the cycle duration beyond recognition limitation of the eye, and then adjust the brightness of the LED by changing the pulsing width, i.e., the time of LED on and off, so that is how the PWM works.
The previous experiment is just to help you learn the PWM principle. We would not write such a code usually – too tedious. There is a built-in function in the RPi.GPIO – the GPIO.PWM.
Modify the code like this:
import RPi.GPIO as GPIO import time led_pin = 17 on_delay = 0.5 # Set on_delay to 0.5 which we can see the blink off_delay = on_delay # Set off_delay equals on_delay freq = 100 # Frequency in Hz GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) p = GPIO.PWM(led_pin, freq) # Set up p as PWM at pin "led_pin" and frequency "freq" p.start(0) # Start p at duty cycle 0 while True: p.ChangeDutyCycle(50) # Change Duty Cycle(brightness) to 50, ranges: 0~100 time.sleep(on_delay) p.ChangeDutyCycle(50) # Change Duty Cycle(brightness) to 10, ranges: 0~100 time.sleep(off_delay)
Those lines with the # mark are modified or added.
Here we add a variable freq = 100, which is the frequency, and its unit is Hz. In GPIO.PWM, we use the frequency in the code. The formula to convert cycle to frequency:
Frequency (Hz) = 1(s) / on_off_cycle(s)
Thus the frequency should be set higher than 1/0.01 (on_off_cycle), that is, higher than 100Hz.
But there still has a problem: the LED controlling is reversed – it is off when its cathode is connected to a high voltage at the I/O pin, while it’s on when connected to low level. Therefore, the LED will be brightest if we set the PWM value to 0, and darkest if it’s 100, which is absolutely contrary to common sense. Let’s write a simple function to solve this problem: the LED will be brightest if the value is 100 rather than 0, and vice versa, thus the code makes sense.
def set_led_value(value):
This is a simple example of function statement, define (def) a function named set_led_value, and substitute the parameter with value. This function will run the ChangeDutyCycle, and use 100-value to reverse the old value, so that the code will be easy to understand and make more sense. If you want to change the brightness of the LED, just use set_led_value.
Add the two lines above, and modify the function in while:
import RPi.GPIO as GPIO import time led_pin = 17 on_delay = 0.5 off_delay = on_delay freq = 100 GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) p = GPIO.PWM(led_pin, freq) p.start(0) def set_led_value(value): # Define a function p.ChangeDutyCycle(100-value) while True: set_led_value(50) # use our function to set led value to 50 time.sleep(on_delay) set_led_value(10) # use our function to set led value to 10 time.sleep(off_delay)
Save the code and run it, and the LED will blink between two levels of brightness: 50 and 10 (brighter – dimmer). You can modify the brightness value to try and check the change.
So, what shall we do next? | https://learn.sunfounder.com/7-4-pwm-led/ | CC-MAIN-2021-39 | refinedweb | 919 | 76.52 |
Tag Archives: QML
Free eBook on native BlackBerry 10 app development now available!
Nobody Puts Filtermama in a Corner
Hybrid Apps for BlackBerry 10: Creating a WebView-based QML Component
Live QML Coding is Finally Here!
Improve Your App Startup Time Using Dynamic Loading of Tabs – Now Declaratively!!!
BlackBerry 10 QML Performance Tips [CFA]
How to make Collapsible Items using Cascades and QML
BlackBerry at Qt Developer Days – Santa Clara #QtDD12
Click To Start Your BlackBerry 10 Cascades Apps In No Time Flat With Zygote
Breaking Out of The Box – An Introduction to BlackBerry 10 Mobile Sensing
Console Logging on the BlackBerry 10 Native SDK Beta 3
Calling all Qt ambassadors and Qt superstars!
Qt and Cascades Training in October
Dude, where’s my paint() function? – Custom UI in Cascades
QML/Cascades tip of the day – Property Aliases
This week’s QML/Cascades tip focuses on creating property aliases and why they’ll be your friend when creating custom components in QML.
More Cascades Webcast Sessions!
A second Cascades webcast session will be taking place on Tuesday June 26th.
QML/Cascades tip of the day – Namespaces
Today’s tip is about namespaces in QML and how they can be utilized to avoid name clashes.
QML/Cascades tip of the day: Managing Properties of an Existing Component
A QML-language feature tip for Cascades that demonstrates the ability to add new properties to an already-existing component.
BlackBerry 10 Cascades is here!
Examining the Cascades SDK, its set of native UI elements and capabilities. | http://devblog.blackberry.com/tag/qml/ | CC-MAIN-2015-14 | refinedweb | 253 | 50.97 |
java - please help me with the error in the account creation part in the atm program (i want to solve it immediately tt)
Please write your question in detail here.
(Example) I am making a ●● system with PHP (CakePHP).
■■ The following error message occurred while implementing the function.
Error: No suitable method found for put (String) customer.put (name); ^ ^ Method Map.put (String, Account) is not available (The length of the actual argument list and the formal argument list are different) Method Dictionary.put (String, Account) cannot be used (The length of the actual argument list and the formal argument list are different) Method Hashtable.put (String, Account) is not available (The length of the actual argument list and the formal argument list are different)
What I triedWhat I tried
import java.util.Hashtable; public class Bank { private Hashtable
customer;/* Account list * / private int balance; public Bank () {/ * Initialize account list * / customer = new Hashtable (); } public int open (String name/* account name * /) { int i = 1; if (customer.get (name)! = null) { return -7; } else { customer.put (name); balance = 0; i ++; return 0; } public int close (String name/* account name * /) { if (customer.get (name) == null) { return -7; } else if (balance! = 0) { return -1; } else { customer.remove (name); return 0; } }/* Account cancellation * / public int deposit (String name/* account name * /, int amount/* deposit amount * /) { if (customer.get (name) == null) { return -7; } else if (amount<= 0) { return -3; } balance = balance + amount; return 0; } /* deposit */ public int withdraw (String name/* account name * /, int amount/* withdrawal amount * /) { if (customer.get (name) == null) { return -7; } else if (amount<= 0) { return -3; } else if (balance
I'm a beginner and want to know the solution tomorrow
Please help TT
ATM program
Please provide more detailed information here.
- Answer # 1
- Answer # 2
I declared private Myname and put it in the value in put to solve it!
- Answer # 3
I did private String Myname;to customer.put (name, Myname);and it worked!
Related articles
- java - there is no error when i enter the seek bar code, but please tell me why the app stops
- i get the following error in java code please tell me what is wrong
- java - an error occurred when running with junit assertequals
- java - an error occurs when executing the jar file
- java - i want to get the entire list from the db and display it, but an error occurs when executing the application
- java - | = please tell me the meaning of
- python - please tell me how to solve the value error that occurred when converting csv file data to numpy array
- java - web-app shows error in webxml
- java bigdecimal acceleration error when dividing by 0
- java - i got an error when trying to execute a class that overloaded the constructor
- python - please tell me what to do about the error content "exception in main training loop: index 3 is out of bounds for a
- java - i want to eliminate the springboot error
- java - please tell me how to make a unique key
- i am a beginner in ea creation and am making mql4, but i get an error, so i want to fix the error
- java - i want to get a 404 error when entering a random url in spring boot
- java - i want to display the corresponding argument in the error message when the command argument is not an integer
- java - i get a syntax error on (s), misplaced construct (s) error what should i do? help me
- i'm getting a java compile error "no class, interface or enum", but i think the parentheses are supported
- javascript - about roulette creation error per the error message. The method you are trying to use does not match the number of its arguments.
The HashTable # put method requires two arguments, a key argument and a corresponding value argument.
Even if only the key is passed, an error will occur because you do not know what to associate with.
In the first place, it is recommended to use Map such as HashMap instead of HashTable when developing a new one. | https://www.tutorialfor.com/questions-323165.htm | CC-MAIN-2021-25 | refinedweb | 671 | 53.44 |
Due by 11:59pm on Monday, 9/15
Submission: See Lab 1 for submission instructions. We have provided a hw2.py starter file for the questions below.
Readings: You might find the following references useful: ***"
Two functions intersect at an argument
x if they return equal values.
Implement
intersects, which takes a one-argument functions
f and a value
x.
It returns a function that takes another function
g and returns whether
f and
g intersect at
x.
def intersects(f, x): """Returns a function that returns whether f intersects g at x. >>> at_three = intersects(square, 3) >>> at_three(triple) # triple(3) == square(3) True >>> at_three(increment) False >>> at_one = intersects(identity, 1) >>> at_one(square) True >>> at_one(triple) False """ "*** ***" | https://inst.eecs.berkeley.edu/~cs61a/fa14/hw/released/hw2.html | CC-MAIN-2020-10 | refinedweb | 117 | 58.28 |
Using CPython’s Embeddable Zip File
Steve
On the download page for CPython 3.5.1, you’ll see a wide range of options. Not all of these are well explained, especially for Windows users who have seven (seven!) choices.
Let me restructure the Windows items into a more feature-focused table:
As is fairly common with installers these days, you have the choice to download everything in advance (the “executable installer”), or a downloader that will let you minimize the download size (the “web installer”). The latter allows you to select options before downloading the components, which can reduce the download size to around 8MB. (For those of us with fast, reliable internet access, this sounds irrelevant – for those of us tethering through a 3G mobile phone connection in the middle of nowhere, it’s a really huge saving!)
But what is the third option – the “embeddable zip file”? It looks like a reasonable download size and it doesn’t have any installer, so it seems quite attractive. However, the embeddable zip file is not actually a regular Python installation. It has a specific purpose and a narrow audience: developers who embed Python in their own native applications.
Why embed Python?
For many users, “Python” is the interactive shell that lets you type code and see immediate results. For others, it is an executable that can run .py files. While these are both true, in reality Python is itself a library that is used to interpreter code. Let’s look at the complete source code for python.exe on Windows:
#include "Python.h" #include int wmain(int argc, wchar_t **argv) { return Py_Main(argc, argv); }
That’s it! The entire purpose of python.exe is to call a function from python35.dll. Which means it is really easy to create a different executable that will run exactly what you want:
#include "Python.h" int wmain(int argc, wchar_t **argv) { wchar_t *myargs[3] = { argv[0], L"-m", L"myscript" }; return Py_Main(3, myargs); }
This version will ignore any command line arguments that are passed in, replacing them with an option to always start a particular script. If you give this executable its own name and icon, nobody ever has to know that you used Python at all!
But Python has a much more complete API than this. The official docs are the canonical source of information, but let’s look at a couple of example programs that you may find useful.
Executing a simple Python string
The short program above lets you substitute a different command line, but if you have a string constant you can also execute that. This example is based on the one provided in the docs.
#include "Python.h" int wmain(int argc, wchar_t *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); PyRun_SimpleString("from time import time, ctimen" "print('Today is', ctime(time()))n"); Py_Finalize(); return 0; }
Executing Python directly
Running a string that is predefined or dynamically generated may be useful enough, but the real power of hosting Python comes when you directly interact with the objects. However, this is also when code becomes incredibly complicated.
In almost every situation where it is possible to use Cython or CFFI to generate code for wrapping native objects and values, you should probably use them. However, while they’re great for embedding native code in Python, they aren’t as helpful (at time of writing) for embedding Python into your native code. If you want to allow users to automate your application with a Python script, you’ll need some way of importing the user’s script, and to provide Python functions to call back into your native code.
As an example of hosting Python directly, the program below replicates the one from above but uses direct calls into the Python interpreter rather than a script. (Note that there is no error checking in this sample, and you need a lot of error checking here.)
#include "Python.h" int wmain(int argc, wchar_t *argv[]) { PyObject *time_module, *time_func, *ctime_func; PyObject *time_value, *ctime_value, *text_value; wchar_t *text; Py_ssize_t cch; Py_SetProgramName(argv[0]); Py_Initialize(); // NOTE: Practically every line needs an error check. time_module = PyImport_ImportModule("time"); time_func = PyObject_GetAttrString(time_module, "time"); ctime_func = PyObject_GetAttrString(time_module, "ctime"); time_value = PyObject_CallFunctionObjArgs(time_func, NULL); ctime_value = PyObject_CallFunctionObjArgs(ctime_func, time_value, NULL); text_value = PyUnicode_FromFormat("Today is %S", ctime_value); text = PyUnicode_AsWideCharString(text_value, &cch); wprintf(L"%sn", text); PyMem_Free(text); Py_DECREF(text_value); Py_DECREF(ctime_value); Py_DECREF(time_value); Py_DECREF(ctime_func); Py_DECREF(time_func); Py_DECREF(time_module); Py_Finalize(); return 0; }
In a larger application, you’d probably call Py_Initialize as part of your startup and Py_Finalize when exiting, and then have occasional calls into the Python engine wherever it made sense. This way, you can write parts of your application in Python and interact with them directly, or allow your users to extend it by providing their own Python scripts.
How does the embeddable zip file help?. Header files, documentation, tests and shortcuts are not necessary,
Tools like pynsist will help produce installers for pure Python programs like this, using the embeddable zip file so that you don’t have to worry about whether your users already have Python or not.
Why wouldn’t you just run the regular Python installer as part of your application? Let’s play the “what if two programs did this?” game: program X runs the 3.5.0 installer and then program Y runs the 3.5.1 installer. What version does program X now have? If it ran the installer with a custom install directory, it probably has nothing left at all, but at best it now has 3.5.1.
The regular installer is designed for users, not applications. Programs that are not Python, but use Python, need to handle their own installation to make sure they end up with the correct version in the correct location with all the correct files. The embeddable zip file contains the minimum Python runtime for an application to install by itself.
What about other packages?
The embeddable zip file does not include pip. So how do you install packages? If you didn’t read the last sentence of the previous section, here it is again: the embeddable zip file contains the minimum Python runtime for an application to install by itself.
Using the embeddable zip file implies that you want the minimum required files to run your application, and you have your own installer. So if you need extra files at runtime – such as a Python package – you’ll need to install them with your installer. As mentioned above, for developing an application you should have a full Python installation, that does include pip and can install packages locally. But when distributing your application, you need to take responsibility.
While this seems like more work (and it is more work!), the value is worth it. Do you want your installer to fail because it can’t connect to the internet? Do you want your application to fail because a different version of a library was installed? When you provide a bundle for your users, include everything that it needs (tools like pynsist will help do this automatically).
Where else can I get help?
Though I’m writing about the embeddable distribution on a Microsoft blog, this is actually a CPython feature. The doc page is part of the official Python documentation, and bugs or issues should be filed at the CPython bug tracker. | https://devblogs.microsoft.com/python/cpython-embeddable-zip-file/ | CC-MAIN-2021-43 | refinedweb | 1,226 | 52.8 |
Subject: Re: [OMPI users] OpenMPI 1.3:
From: Jeff Squyres (jsquyres_at_[hidden])
Date: 2009-02-23 10:08:09
On Feb 20, 2009, at 9:53 AM, Olaf Lenz wrote:
> However, I'm using OpenMPI to run a program that we currently develop
> (). The software uses Python as a front-end
> language, which loads the MPI-enabled shared library. When I start
> python with a script using this parallel lib via mpiexec, I get the
> following error:
>
>> mpiexec -n 4 python examples/hello.py
> python: symbol lookup error:
> /people/thnfs/homes/lenzo/software.thop/lib/openmpi/
> mca_paffinity_linux.so:
> undefined symbol: mca_base_param_reg_int
We've talked about similar errors before; I thought that the issue was
caused by the Python front-end calling dlopen() to manually open the
libmpi.so library. Is that the cause in your scenario?
If so, note that it needs to load libmpi.so with RTLD_GLOBAL. For
example:
> When I compile OpenMPI 1.3 using
>
> --enable-shared --enable-static
>
> the problem disappears. Note also, that the same program works when
> I'm
> using OpenMPI 1.2.x (tested 1.2.6 and 1.2.9). I do believe that the
> problem is connected with the problem described here:
Yes, this makes sense, given the way that linkers work. If you don't
dlopen with RTLD_GLOBAL, then libmpi is opened into a private
namespace in the process, and then OMPI's plugins that are
subsequently opened cannot find the symbols that they expect to find
(from libmpi).
If you compile statically, there's no issue because all the libmpi's
symbols are globally available to any plugins that are loaded at run-
time.
(note that I say "libmpi", but I'm really referring to all three of
OMPI's support libraries: libmpi, libopen-rte, libopen-pal)
> PS: It is not obvious on the OpenMPI web site where to report bugs.
> When
> clicking on "Bug Tracking", which seems most obvious, I'm redirected
> to
> the Trac Timeline, and there is no place where I can report bugs or
> anything.
Bummer; I had thought the Big Red Links for "Getting Help/Support"
were obvious. :-( Indeed, the very first line of text on the
page says:
"If)."
--
Jeff Squyres
Cisco Systems | http://www.open-mpi.org/community/lists/users/2009/02/8158.php | CC-MAIN-2015-14 | refinedweb | 369 | 64.91 |
Java Code that creates a random number between 1 and 100 and then asks the user to guess the number and tells if the guess was too high, too low or, the right number. Loops until right number is guessed.
// The "Random_Number_Guesser" class. import java.awt.*; import hsa.Console; public class Random_Number_Guesser { static Console c; public static void main (String[] args) { c = new Console (); int on_off = 1; long number = (Math.round(Math.random() * 100)); int guess; while (on_off == 1) { c.println ("Guess a number between 1 and 101!"); guess = c.readInt (); if (number > guess) { c.println ("Nope, too low."); } if (number < guess) { c.println ("Nope, too high."); } if (number == guess) { c.println ("Congrats, You got it!"); on_off = 0; } } } }
About the Author
Not old enough for one.Lol. | https://www.daniweb.com/programming/software-development/code/216790/random-number-game-i-made | CC-MAIN-2018-47 | refinedweb | 127 | 79.36 |
java.awt.PopupMenu
javax.swing.JPoupMenu
TrayIcon trayIcon = new TrayIcon(someImage, "Tooltip", null););
}
}
});
JPopupMenu.setInvoker()
null
System.exit()
I saw a question about this in the forums awhile back, remarkable your solution looks fairly simple.
leouser
Posted by: leouser on May 04, 2006 at 06:29 AM
Could you post a link to the forum where this problem was discussed and their solution, please?
Posted by: ixmal on May 04, 2006 at 06:56 AM
Ill have to do some digging, but I don't think they came up with a solution. It was more of a "hey why can't we use a JPopupMenu with the TrayIcon" kind of thread. I remember speculating on a possibility, but I like your idea better.
Posted by: leouser on May 04, 2006 at 08:05 AM
It was this thread:
and as I said, no real solutions presented.
Posted by: leouser on May 04, 2006 at 08:08 AM
This is not enough!
The JPopupMenu should be poping up on top of the taskbar, as native popups do.
Posted by: cowwoc on May 05, 2006 at 08:06 AM
Please vote for to fix this problem.
Posted by: cowwoc on May 05, 2006 at 08:12 AM
I tried under Linux and Netbeans 5.0. Works OK but got :
java.lang.ClassCastException: java.awt.TrayIcon cannot be cast to java.awt.Component
Posted by: dags on May 05, 2006 at 10:10 AM
Thanks, dags, I have just got the exception. I think somewhere in the AWT/Swing code all the mouse events are supposed to be sent for Components, but TrayIcon is not a descendant of Component:( I will file a new bug about this.
Posted by: ixmal on May 06, 2006 at 12:56 AM
- When I use PopupMenu with TrayIcon then I cannot use Unicode but I can close popup that don't need click on its menuitems.
- When I use JPopupMenu with TrayIcon then I can use Unicode but I can't close popup, I only close this popup when I click on its menuitems.
Posted by: phubinh13 on October 26, 2006 at 11:43 PM
Posted by: phubinh13 on October 26, 2006 at 11:46 PM
I am using the final release of JDK 1.6.0 and I am still getting the java.lang.ClassCastException: java.awt.TrayIcon cannot be cast to java.awt.Component error. Any luck or workarounds for this? I really prefer to use a Swing Jpopupmenu to a regular menu because I am using a javax.swing.Action framework and i don't see any way to use Actions in regular java.awt.PopupMenu's. Hope there is some workaround!
Posted by: elefkof on December 27, 2006 at 10:24 AM
Hi... I also get the "java.awt.TrayIcon cannot be cast to java.awt.Component" error. Please tell me what to do...
Posted by: geertjan on February 23, 2007 at 10:32 AM
Hello. I can make JPopupWindow above MS-Windows task bar ( SwingUtilities.windowForComponent( JPupupMenu ).window.setAlwaysOnTop( true ) ) , but how to get keyboard focus/input ????
Looking back to normal PopupMenu ... when it is pop up -> it blocks Event Dispatch Thread (EDT) (even if I fire it manually .show() from new Thread , I also tryed install new EventQueue ).
I spent last 10 days to solwe those problems, no success :(((((.
Posted by: kermitas on February 24, 2007 at 03:44 AM
Like kermitas, I can get JPopupMenu to show on top of taskbar, but I cannot make it go away (dismiss) if click on anywhere except on my Java app frame and on JPopupMenu itself.
The java.lang.ClassCastException happens if user invoke the popup again when the it is already visible (but maybe hidden behind other windows).
For popup location, I prefer popping it higher :
popupmenu.setLocation(e.getX(), e.getY()-popupmenu.getPreferredSize().height);
I guess until Sun fixes the 'java.lang.ClassCastException' bug, I will go back to using jeans' TrayIcon ()
Posted by: pk_thoo on March 15, 2007 at 06:55 AM
One more thing, self invoking doesn't work on at least 2 LAF packs : SkinLF and Substance. You'll get StackOverflow error.
Posted by: pk_thoo on March 16, 2007 at 01:30 AM
Hello,
i think i wrote some example on how to fix all that issues, Also my impl. fly over the taskbar.
Take a look at (Forum is german): Swing Based Tray Icon with Java 6
- Jens
Posted by: mac_systems on November 29, 2007 at 08:18 AM
Try this ugly hack to fix a problem with exceptions:
Toolkit.getDefaultToolkit().getSystemEventQueue().push( new PopupFixQueue(jpopup) );
...
public class PopupFixQueue extends EventQueue {
private JPopupMenu popup;
public PopupFixQueue(JPopupMenu popup) {
this.popup = popup;
}
protected void dispatchEvent(AWTEvent event) {
try {
super.dispatchEvent(event);
} catch (Exception ex) {
if (event.getSource() instanceof TrayIcon) {
popup.setVisible(false);
}
}
}
}
Posted by: nick_fedorov on March 18, 2008 at 12:52 AM
@nick_fedorov Thankyou thankyou thankyou thankyou.... This fix worked a charm, and moreover, I can see why it works as well. The best kinds of fix!
Posted by: davyboyhayes on March 31, 2008 at 03:28 PM | http://weblogs.java.net/blog/ixmal/archive/2006/05/using_jpopupmen.html | crawl-002 | refinedweb | 851 | 65.52 |
#include <djv_imaging.h>
This structure provides a function for resampling images.
This callback provides a change to render the source image dynamically.
This callback function is called twice from Imaging::resample function. The first call is to lock a portion of the source image and the second call is to unlock that portion optionally.
Noise reduction method.
Do noise reduction on bitonal image.
Do black compensastion.
trueif the process succeeded.
falseif the process is failed due to some condition. In this case, nothing is returned to outDestImage.
Convert image to grayscale.
Copy an image.
Fill the buffer with white.
Mirror an image horizontally.
Resample the specified image.
Referenced by Celartem::DjVu::ImageRenderer::render().
Resample the specified mask and alphablend against the image already on the specified buffer.
Rotate the image.
Rotate the image 90 degree clockwise or anti-clockwise. | https://www.cuminas.jp/sdk/structCelartem_1_1DjVu_1_1Imaging.html | CC-MAIN-2017-51 | refinedweb | 139 | 55.91 |
Hi, I am rather new to Panda and already encountered an issue that is weird to me.
I’m writing simple 3d Tetris where tetrominoes are moved using
posInterval() but sometimes a random freeze happened. A falling puzzle would suddenly stop and then after 1/2s appear much lower like the game was running in the back and just the screen wasn’t updated. In addition, the issue stopped when I
My question is what could have been the reason for that random freezing?
Hi, I am rather new to Panda and already encountered an issue that is weird to me.
Check out the code from the lesson. If there is no frieze, then the problem is in your code.
OH, freezing happens on this example too, but also setting const fps solves the problem.
Actually intervals are unnecessary to move. Surprisingly, the panda offers unpopular textbook solutions. Intervals have a problem, the time that the panda is trying to calculate to move is not constant for each frame. Object properties are also blocked, for example, you cannot control the Z axis. Use task manager for this purpose.
I changed the code:
from math import pi, sin, cos from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.actor.Actor import Actor class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Disable the camera trackball controls. self.disableMouse() #") # Load and transform the panda actor. self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.setPos(0, 10, 0) self.pandaActor.reparentTo(self.render) # Loop its animation. self.pandaActor.loop("walk") # Run 1 interval self.taskMgr.add(self.pandaPosInterval1, "pandaPosInterval1") #Moving speed self.speed = 1 #Rotational speed self.rotational = 50 def pandaPosInterval1(self, task): if self.pandaActor.getY() <= -10: self.pandaActor.setY(-10)# Stop the increase in error over time. self.taskMgr.add(self.pandaRotation1, "pandaRotation1") return Task.done else: self.pandaActor.setY(self.pandaActor.getY()-self.speed*globalClock.getDt()) return Task.cont def pandaRotation1(self, task): if self.pandaActor.getH() >= 180: self.pandaActor.setH(180)# Stop the increase in error over time. self.taskMgr.add(self.pandaPosInterval2, "pandaPosInterval2") return Task.done else: self.pandaActor.setH(self.pandaActor.getH()+self.rotational*globalClock.getDt()) return Task.cont def pandaPosInterval2(self, task): if self.pandaActor.getY() >= 10: self.pandaActor.setY(10) # Stop the increase in error over time. self.taskMgr.add(self.pandaRotation2, "pandaRotation2") return Task.done else: self.pandaActor.setY(self.pandaActor.getY()+self.speed*globalClock.getDt()) return Task.cont def pandaRotation2(self, task): if self.pandaActor.getH() <= 0: self.pandaActor.setH(0)# Stop the increase in error over time. self.taskMgr.add(self.pandaPosInterval1, "pandaPosInterval1") return Task.done else: self.pandaActor.setH(self.pandaActor.getH()-self.rotational*globalClock.getDt()) return Task.cont #()
Hi @mblasiak, it would be great if you could run PStats and add
want-pstats true in Config.prc. This will pop up the Panda performance dialog. I wonder if your chugs will show up in PStats, and if so, in which categories. You’ll be able to click the coloured labels in order to zoom in further on a particular category.
It would also be great to know more about your system. Are you using Panda3D 1.10? Are you on Windows, Linux, or macOS?
I can add that the intervals have an unknown problem. When I used a laptop and had lessons on C ++,
all examples worked for me, except for intervals. The program, when I tried to launch it, crashed, unfortunately, I don’t remember the details, it was a long time ago.
So:
I’m testing everything on the example of walking panda from tutorial.
Freezes happen on bare tutorial example (program freezes randomly for at least 1/3s then jumps forward like the program would run in the back)
The problem doesn’t show up when I connect example to pstat. As the problem doesn’t appear with pstat, the plots look good to me(nothing exceeds 2ms).
I’m using Linux Mint
Linux 4.15.0-45-generic x86_64)
DISTRIB_DESCRIPTION=Linux Mint 19 Tara
On Huawei MateBook D
NVIDIA GeForce MX150, + Intel UHD Graphics 620
Intel Core i5-8250U
Panda 1.10.0
I attach screen shot just in case:
Using code of serega-kkz freezes still randomly happen.
Hmm, then these are not intervals. Maybe this is your IDE, try to run without an IDE, for example via the command line.
I don’t think this issue has anything to do with intervals or running from the IDE. That would seem rather odd.
As it happens, I have a laptop with almost identical specs to yours. I’ll give it a try on my end.
Running it directly from console doesn’t make difference, I’ve tried it before posting here.
I think the freezing appears only when the interval time is relatively big to the distance and frame rate must be high.
Maybe the moving distance calculated each frame is rounded to zero due to floating point limitations or sth similar, but this way only one object should be effected not whole scene i suppose.
Well, we sort of found out that the intervals are irrelevant. Now the main suspect is a task manager.
Similar problems can cause the same. Overheating of the processor, hard disk operation. I think you need to look at the system resource monitor.
You could try putting a little 1ms sleep in your application:
client-sleep 0.001
But, this will really be equivalent to limiting your framerate. | https://discourse.panda3d.org/t/random-freezeing-with-uncapped-framerate/24391/4 | CC-MAIN-2022-33 | refinedweb | 926 | 53.27 |
When resizing a figure using
fig.set_size_inches, the Qt backend doesn’t take into account the height of the status bar or the toolbar.
For example, the following script plots two figures—both should be 1-inch square, but this is only true of the second figure.
···
import matplotlib as mpl
mpl.use(‘qt4agg’)
import matplotlib.pyplot as plt
fig = plt.figure()
fig.set_size_inches(1, 1, forward=True)
plt.figure(figsize=(1, 1))
plt.show()
#~~~~~
Note that this bug doesn’t appear with
savefig since that doesn’t need to account of toolbar/status bar heights.
I’ve submitted a PR for a fix, but I don’t know how general this is. For example, I couldn’t get the figure to redraw after changing the figure size with
fig.set_figwidth or
fig.set_figheight, so I couldn’t test for that.
Also, I noticed that ‘tkagg’ has problems with this example code, but I didn’t have time to look into that.
-Tony | https://discourse.matplotlib.org/t/resizing-bug-in-qt4-backend/16703 | CC-MAIN-2022-21 | refinedweb | 163 | 69.89 |
Manage your cron jobs with AWS Cloudwatch and Lambda
Project description
Cronyo
The instantly deploy a couple of super-simple, helpful and secure lambda functions to perform HTTP GET/POST requests for you. So if you need to trigger any webhooks on schedule, an AWS account and Cronyo is all you need :)
Key Features:
- Simple command line interface to manage cron jobs (much simpler than aws events put-rules, aws lambda add-permission, aws events put-targets, Cloudformation, or Terraform)
- Pre-built AWS Lambda functions for simple HTTP GET/POST requests, or use your own lambdas.
- Cost Effective (you'll need a TON of cron rules to worry about costs).
- Simple but Secure (HTTP GET/POST include an HMAC signature so you can validate the request is genuine).
- Easy deployment of lambda functions using
cronyo deploy. No need to twiddle with AWS.
- Easily add, delete, enable, disable and export (to yaml) your cron rules.
Background
read the blog post: Simple and Secure Cron using AWS Lambda
Cronyo takes the next step, and provides an automated solution with a CLI.
Roadmap
- import from yaml
- export/import from crontab-esque files
- add other lambdas?
Installation / Quick Start
You will need an AWS account with the
aws cli installed. Then run:
$ pip install cronyo $ cronyo configure $ cronyo deploy # (optional, if you want to use the http POST/GET lambdas)
It will automatically configure two AWS Lambda functions (
cronyo- and
cronyo-
Intro
Examples
cronyo --help- prints a help screen.
cronyo configure- opens your editor so you can edit the config.json file. Use it to update your namespace and signing key.
cronyo preflight- runs preflight checks to make sure you have access to AWS.
cronyo deploy- deploys the code and configs to AWS automatically.
cronyo export- exports all existing cron rules to yaml
cronyo export --prefix- exports all existing cron rules starting with
prefixto yaml
cronyo export --search- exports all existing cron rules matching the search string anywhere in the name
cronyo add '{"url": " --cron "5 4 * * ? *"- sends an HTTP GET request to example.com at 4:05am every day
cronyo disable cronyo-24a0b5504111d9b1d797- disables cron with the name
cronyo-24a0b5504111d9b1d797
cronyo enable cronyo-24a0b5504111d9b1d797- enables cron with the name
cronyo-24a0b5504111d9b1d797
cronyo delete cronyo-24a0b5504111d9b1d797- deletes cron with the name
cronyo-24a0b5504111d9b1d797
cronyo update '{"url": " --cron "5 4 * * ? *" --name myrule- updates an existing rule
Advanced
Names
cronyo creates a name for your cron jobs automatically (unless a custom name is specified). Names are required unique identifiers, and cannot be changed after creation (this is AWS limitation). Names can only contain certain characters.
cronyo comes with a (configurable) namespace --
cronyo by default. You can change the default using
cronyo configure.
cron expressions
cronyo supports
cron or
rate expressions. See the AWS
docs for specific info.
Note that
--cron "<expr>" must be surrounded by quotes, however
--rate won't work with quotes. This is because cron
expressions include characters like
*which mess-up the CLI input.
adding a cron job
cronyo add '{"url": " --cron "5 4 * * ? *"will send an HTTP GET request to example.com at 4:05am every day
cronyo add '{"url": " --rate 5 minuteswill send an HTTP POST request to example.com every 5 minutes
cronyo add '{"url": " "headers": {"User-Agent": "007"}, "cookies": {"biscuit": "oreo"}, "params": {"a": "b"}, "data": {"key": "value"}}' --rate 5 minuteswill send an HTTP POST with custom cookies, headers, URL params and form data.
cronyo add arn:aws:lambda:us-east-1:313623401231:function:cronyo- '{"url": " --rate 5 minuteswill call a lambda function with a specific ARN with given event paramaters every 5 minutes
cronyo add '{"url": " --rate 5 minutes --name my-cron-jobusing
--nameto provide a custom name (see Names above)
cronyo add '{"url": " --rate 5 minutes --description "describe your cron job"using
--descriptionto provide a description for the job.
License
Cronyo is distributed under the MIT license. All 3rd party libraries and components are distributed under their respective license terms.
Copyright (C) 2020 Yoav An. | https://pypi.org/project/cronyo/ | CC-MAIN-2022-21 | refinedweb | 657 | 61.97 |
Inherit Default Object Creation Behavior in the Palette?
Hi,
Is there a way I can inherit the default object creation behavior in the palette?
For instance, if you have the primitives in the separate pallet,
holding Alt + LMB the Cube Icon makes the selected object the child of the new cube.
or holding Shift + LMB the Cube Icon makes the selected object the parent of the new cube.
Currently, what I have in my plug-in is a clickable icon that creates a cube but doesn't take into account the Alt/Shift behaviors.
So, is it possible to inherit the default object creation behavior to the plug-in form?
Thank you for looking at my problem.
Hello,
the C++ API has the function InsertCreateObject() which can be used to insert an object into a document using the modifiers.
Apparently, this function is not available in the Python API.
best wishes,
Sebastian
Thanks for the confirmation. So I guess, I should use the key modifiers manually.
Just wondering, is there a better way to implement this?
This is a working code but just wondering if there is a better way of doing this:
def Command(self, id, msg): # 2000 is the button ID bc = c4d.BaseContainer() shift = False ctrl = False alt = False if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc): if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT: shift = True if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: ctrl = True if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: alt = True if id==2000 and shift == False and alt == False: print "Create Cube" if id==2000 and shift==True: print "Create Cube and make it a child of the selected object" if id==2000 and alt==True: print "Create Cube and make it a parent of the selected object" return True
Thank you for looking at my problem.
Hello,
typically,
c4d.gui.GetInputState()is used to check a specific key e.g.
state = c4d.BaseContainer() res = c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.KEY_ENTER, state)
But if your code works for you, I guess its fine.
best wishes,
Sebastian
Thanks for the response, but I'm confused when you said:
typically, c4d.gui.GetInputState() is used to check a specific key e.g.
Correct me if I'm wrong but I'm already using
c4d.gui.GetInputState()above.
To rephrase the just wondering if there is a better way of doing this: question. I guess, is there a way I can shorten the code? The reason is the whole plugin will have many commands with modifier keys.
@bentraje said in Inherit Default Object Creation Behavior in the Palette?:
The reason is the whole plugin will have many commands with modifier keys.
Hello,
as a I said, c4d.gui.GetInputState() is typically used to check a specific key e.g. the "Enter" key. The qualifier keys are pressed along with this tested key or not.
If you want to reuse your code, you can simply put it in a sub-function that returns a
listor a
dictionarythat describes the current state of the qualifier keys.
best wishes,
Sebastian
RE: as a I said, c4d.gui.GetInputState()
Correct me if I'm wrong but I guess you are trying to distinguish the specific keys and the qualifier keys. In my post above, I didn't know the distinction so I just treat all the keyboard keys as both the specific keys and qualifier keyys.
Can I clarify, if the
c4d.gui.GetInputState()is preferred for the specific keys.
What command should I use for the qualifier keys?
Hello,
I don't think there is a specific command to check for qualifier keys. By themselves, these keys typically don't do anything; so what is typically checked is if another key is pressed and a modifier key is pressed along that key.
best wishes,
Sebastian | https://plugincafe.maxon.net/topic/11889/inherit-default-object-creation-behavior-in-the-palette/8 | CC-MAIN-2019-47 | refinedweb | 635 | 66.64 |
> On 4 Feb 2018, at 2:31 pm, Lanlan Pan <abby...@gmail.com> wrote: > > > > Mark Andrews <ma...@isc.org>于2018年2月3日周六 上午4:11写道: > The problem is that search lists are being applied when “localhost” is being > entered into name lookup APIs and is being matched against localhost.example > which isn’t expected to to a address on the current machine and that the > search list may be auto constructed or come from a untrusted source. > > If only consider about http: > Web browser can also ban this "localhost.example". > CA Single Sign-On might help to solve the "same site" cookie expose problem.
We may as well ban because that can return 127.0.0.1 as well. :-) The first step to fixing this is to record the address that cookies are learnt from and not allow them to be sent to address with a different scope. This would address this issue as has a different address scope to localhost.paypal.com. This however isn’t something for dnsop. > There is also a small risk that hotspots will return something other than a > local address if a address lookup for .localhost is made. > > This is all in the context of processing urls. > > Localhost is the last remanent of the pre hierarchical host scheme. > > The risks are eliminated if the name APIs use local lookup sources in those > contexts. > > Then you have legacy clients. As long as the servers for the namespace on the > public Internet don’t return A or AAAA records for localhost the issue is > addressed there. > > You then have the recursive server where you would like it, by default, > return a answer without contacting the root servers. The only safe way to do > that is to have it serve a empty zone for localhost. As this zone isn’t > linked into the global DNSSEC chain of trust the root zone needed a insecure > delegation for localhost. > > > > -- > Mark Andrews > > On 3 Feb 2018, at 05:25, Bob Harold <rharo...@umich.edu> wrote: > >> >> On Thu, Feb 1, 2018 at 4:26 PM, Ted Lemon <mel...@fugue.com> wrote: >> On Feb 1, 2018, at 2:48 PM, Andrew Sullivan <a...@anvilwalrusden.com> wrote: >>>> As a general principle, when what the RFC says to do is not the right >>>> thing to do, the solution is to update the RFC, not to ignore the problem. >>> >>> I strongly agree with this (as I think or anyway hope you know) >> >> Yes, I will admit I was a bit surprised that you put it that way, although >> as you say, your position is more clear in your formal review of the >> document. >> >> As for why I responded to this and not to the formal review, the answer is >> that the formal review was a bit overwhelming. You made a lot of assertions >> of fact that didn't sound like fact to me—they sounded like strongly-held >> opinion. You are a much more experienced DNS expert than I am, so for me >> to argue you away from those opinions is a tall order—I don't think you've >> really expressed the underlying belief that is the keystone to the whole >> edifice. >> >> The problem I have is that to me it's dead obvious that the name hierarchy >> and the set of names in the DNS are not the same thing. We've had that >> discussion before. We even published a document about it, which hasn't >> quite made its way out of the RFC editor queue yet. It seems to me that it >> is demonstrably the case that these two sets are disjoint. >> >> But you explain your reasoning on the basis that clearly they are the same >> set, and that they are the same set is left unexamined. So if we were to >> succeed in understanding why we disagree on this point, it would be >> necessary to dig down into that. >> >> Having seen you give keynotes at the plenary, I know that you are deeply >> concerned about computer security. The reason that I am in favor of the >> behavior I'm propounding is that I think it closes a small security gap >> through which a truck might some day be driven, to our woe. So to me, the >> need to leave that gap, which I admit is small, open, seems inconsistent >> with what I know of you. >> >> So clearly you value this idea that localhost is a name that exists in the >> DNS, even though it doesn't exist in the DNS. It might be fruitful to >> explore that further. It might also be a waste of time. I don't honestly >> know. But that is, I think, the key to our disagreement. >> >> >> Could someone explain the security problem? If it really is bigger than the >> problems that will be caused by changing resolvers to answer with NXDOMAIN, >> then you might convince me. >> >> -- >> Bob Harold >> >> _______________________________________________ >> DNSOP mailing list >> DNSOP@ietf.org >> > _______________________________________________ > DNSOP mailing list > DNSOP@ietf.org > > -- > 致礼 Best Regards > > 潘蓝兰 Pan Lanlan -- Mark Andrews, ISC 1 Seymour St., Dundas Valley, NSW 2117, Australia PHONE: +61 2 9871 4742 INTERNET: ma...@isc.org _______________________________________________ DNSOP mailing list DNSOP@ietf.org | https://www.mail-archive.com/dnsop@ietf.org/msg16369.html | CC-MAIN-2018-09 | refinedweb | 856 | 71.95 |
> On Thu, 2 Oct 1997, Ian Jackson wrote: > >Processing commands for control@bugs.debian.org: > > > >> reopen 7490 = > >Bug#7490: debmake contains /usr/bin/done !!!! and other namespace pollution > >Bug#5682: Possible namespace collision in debmake > >Bug reopened, originator not changed. > > > >> reopen 5682 = > >Bug#5682: Possible namespace collision in debmake > >Bug is already open, cannot reopen. Christoph Lameter wrote: > These are not bugs. If you want to have a public discussion post to > debian-devel. As developers, we're system integrators, and ensuring that components of the system don't have names that could cause unnecessary confusion or problems falls under that remit. The latest version of debmake doesn't appear to contain /usr/bin/done any more, but problems with the other names I raised in my original bug report still apply. I'm reopening these bugs, and bringing this public discussion to debian-devel as requested. (S) -- Owen `Stribethssonsson' Dunn <owen@greenend.org.uk> `For the Millennium Project, the Government should have abolished Oxford.' (Norman Stone) -- TO UNSUBSCRIBE FROM THIS MAILING LIST: e-mail the word "unsubscribe" to debian-devel-request@lists.debian.org . Trouble? e-mail to templin@bucknell.edu . | https://lists.debian.org/debian-devel/1997/10/msg00738.html | CC-MAIN-2016-07 | refinedweb | 192 | 50.23 |
Stephane Eranian wrote:> Hello,> > I have released another version of the perfmon new code base package.> This version of the kernel patch is relative to 2.6.19-rc6-git10.> > This is a major update because it completes the changes requested > during the code review on LKML. As a consequence, the kernel interface> is NOT backward compatible with previous v2.2 versions. This release has> the v2.3 version number. Backward compatibility with v2.0 is maintained> on Itanium processors.Hi Stephane,I have built the kernel with the new patches and tried things out on x86_64 an x88_64 machine with Fedora Core 4. I attempted use the new libpfm and pfmon to update the source RPMs and I noticed that there were some return values from read() and write() being ignored. When pfmon is being built as an RPM ignoring the read and write return values cause the rpmbuild to fail. Attached is a simple patch that stuffs the return values into dummy variable to avoid the warnings. This patch allows libpfm and pfmon the source RPMs to compile on FC4 and Fedora Core rawhide.-Will--- pfmon-3.2-061127/pfmon/pfmon_util.c.fortify 2006-11-27 05:22:40.000000000 -0500+++ pfmon-3.2-061127/pfmon/pfmon_util.c 2006-11-27 13:38:43.000000000 -0500@@ -1031,6 +1031,7 @@ int fd; size_t max, used; char number[32];+ ssize_t dummy; if (options.opt_is22 == 0) return (size_t)-1;@@ -1042,7 +1043,7 @@ if (fd == -1) return (size_t)-1; memset(number, 0, sizeof(number));- read(fd, number, sizeof(number));+ dummy = read(fd, number, sizeof(number)); close(fd); @@ -1055,7 +1056,7 @@ if (fd == -1) return (size_t)-1; memset(number, 0, sizeof(number));- read(fd, number, sizeof(number));+ dummy = read(fd, number, sizeof(number)); close(fd); max = strtoul(number, NULL, 0);--- pfmon-3.2-061127/pfmon/pfmon_task.c.fortify 2006-11-27 13:39:16.000000000 -0500+++ pfmon-3.2-061127/pfmon/pfmon_task.c 2006-11-27 13:39:57.000000000 -0500@@ -1675,6 +1675,7 @@ int ctrl_fd; int max_fd; int ndesc, msg_type;+ ssize_t dummy; /* * POSIX threads: @@ -1811,7 +1812,7 @@ /* * ack the removal */- write(workers[mycpu].from_worker[1], &msg, sizeof(msg));+ dummy = write(workers[mycpu].from_worker[1], &msg, sizeof(msg)); break; case PFMON_TASK_MSG_QUIT: | http://lkml.org/lkml/2006/11/27/211 | CC-MAIN-2014-15 | refinedweb | 373 | 59.8 |
Hi, I have to implement radio box controls in xamarin forms as shown in the picture above. Since we don't have any control like that in xamarin forms, Can somebody help me how do we implement this into Xamarin.Forms (To target iOS and Android) ?
Thanks
Here is the video of final result with the above plug-in and some tweaking.
Hope it helps you guys decide, finally..
Conclusion: No need to use the AsNUm -XF Controls
Use this extended ListView with some code tweaking.
Catch
Since the ListView control also plays with the visibility property of implemented SelectCell , you guys are not seeing the > un-selected Radio/Check image here. But I guess that can be done quiet easily, some homework for you guys.
-- N Baua
Answers
You can try this:
For example:
Otherwise
@Angelru9 How do I use it in XAML?
Include the namespace in your declaration markup
example:
xmlns:ctrls="clr-namespace:AsNum.XFControls;assembly=AsNum.XFControls"
and call out the implementation as under
<ctrls:RadioGroup
Do not forget to use the following line in Android MainActivity in
OnCreatecall
AsNumAssemblyHelper.HoldAssembly();
Hope it helps.
-- N Baua
@AliRaza.5445 In XAML:
xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
This too it's good idea.
@Angelru9 , I copied your code in my project. Everything is same, code is same. But I get weird errors in BindableRadioGroup.cs file that says: "No overload for OnCheckedChanged" matches delegate EventHandler<EventArgs>.
where this delegate is declared ?
@AliRaza.5445 Take a look here:
If this doesn't work, you should try with
@NBaua ,
using (var stm = this.Asm.GetManifestResourceStream(source)) { var bytes = stm.GetBytes(); return ImageSource.FromStream(() => new MemoryStream(bytes)); }
In the convert method of ResImgConverterBase class, I get an compile time error below this method call: stm.GetBytes();
This error says that: "Steam does not contain a definition for GetBytes() and no extension method GetBytes accepting first argument of type Stream"
Can you help me fix this please ?
Hi @AliRaza.5445,
I don't know what image you're trying to bind from stream here, if this is for On and Off images for radio buttons, Please use the embedded resources. This will save you from coding hazels as well as it is best practice.
Hi @NBaua ,
I changed build action of image to Embedded Resource but problem is still there. Here is below the code for entire class.
`public abstract class ResImgConverterBase : IValueConverter
{
`
Those who are looking for the answer.
use the. You might want to change the
SelectableViewCelland insted of boxview use the images of your choice.
Here is the small video how it looks with default example.
Hope it helps.
Here is the video of final result with the above plug-in and some tweaking.
Hope it helps you guys decide, finally..
Catch
-- N Baua
Hi i am using XFControls for radio group and Can't access selected item in radio group how can i access which radio i selected | https://forums.xamarin.com/discussion/103410/how-to-implement-radiobox-control-in-xamarin-forms-android-ios | CC-MAIN-2020-05 | refinedweb | 495 | 67.15 |
that make web development a lot more convenient. Some other popular alternatives for web development in Python include Django and Flask.
Prerequisites
You need to have basic knowledge of HTML for this tutorial. If you do not have any prior experience with it, do not worry about it, you can still follow this tutorial and understand how Pyramid works, but to develop real world web applications you will have to go back and learn HTML.
Architecture
Before we move on and see the code, let's first understand WSGI and MVC.
WSGI is basically a standard which defines the way in which a Python based web application interacts with a server. It governs the process of sending requests to a server, and receiving responses from a server.
MVC is an architectural pattern which modularizes your application; the model contains the data and business logic of your application, the view displays the relevant information to the user, and the controller is responsible for the interaction between the model and the view.
Google Maps is a perfect example of the MVC architecture. When we use the route-finding feature in Google Maps, the model contains the code for the algorithm which finds the shortest path from location A to location B, the view is the screen that is shown to you containing the map labeled with the route, and the controller contains the code that uses the shortest path found by the model and displays it to the user through the view. You can also view controller, as the code which receives a request from the view (by the user), forwards it to the model to generate a response, and then displays the response from the model back to the user through a view.
Besides WSGI and MVC, there are two more terms that you should be familiar with, which are "routes" and "scripts". Routes allow your website to be divided into different webpages, with each webpage performing a different function.
Let's consider Facebook as an example. If you wish to view your messages, a new webpage with a different view is opened up for that, if you wish to view your own profile, a new webpage is opened for that, but they are all connected to your main website. That's done through routes. Each time you click on a button or link, you are redirected to a new webpage as specified by the routes in our application.
As for scripts, they simply include configuration settings for our application, and help in managing it.
We will learn more about all these terms when we create a basic web application using Pyramid. So, let's begin.
Installation
Whenever we develop a web application that is to be deployed online, it is always considered a good practice to make a virtual environment first. The virtual environment contains all the libraries, or frameworks and all the other dependencies that are necessary for running the web app. This way, when you deploy your app to a server, you can simply re-install all those libraries on the server, for your application to run smoothly.
Let's create a virtual environment before we move forward. Install virtual environment module by running the command below in your terminal:
$ pip install virtualenv
To test that your installation was successful, run the following command:
$ virtualenv --version
If you see a version number printed to the console then the installation was successful (or
virtualenv was already installed on your system).
To create a virtual environment, first navigate to the folder where you wish to create it, and then run the following command:
$ virtualenv myvenv
Note: You can name your virtual environment anything you want. Here we're using "myenv" for demonstration purposes only.
The last step is to activate your virtual environment. On Mac, run the following command in the terminal:
$ source myvenv/bin/activate
On a Windows machine, you can activate the environment with the following command:
'Installation folder'\myvenv\Scripts\activate.bat
Now that you have your virtual environment set up, let's install Pyramid in it. We will use the pip package manager for that:
$ pip install pyramid
Note: When you are done with working with the application and wish to deactivate your virtual environment, run the following command in the terminal:
$ deactivate
Coding Exercise
In this section, we will start off by coding a skeleton app to understand how the Pyramid apps are structured and how they communicate at a basic level. After that, we will see how to create applications with multiple views.
A Simple Example of Python Pyramid
# intro.py # Import necessary functions to run our web app from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response # This function receives a request from the user, and returns a response def intro(request): return Response('Hi, My name is Junaid Khalid') # This function will start a server on our computer (localhost), define the # routes for our application, and also add a view to be shown to the user def main(): with Configurator() as config: config.add_route('intro', '/') config.add_view(intro, route_name='intro') application = config.make_wsgi_app() # 8000 is the port number through which the requests of our app will be served server = make_server('0.0.0.0', 8000, application) server.serve_forever() main()
Note: The
Configurator module is being used to connect a particular view to a specific route. For instance, on Facebook, the "My Profile" view would be different than the "News Feed" view, and they both have different URLs as well. This is exactly what a configurator does; connecting a specific URL/route to a particular view.
Then
make_server methods is used to run our application on a local HTTP server on our machine, with an assigned port number.
The
intro function is used to process the requests received from the user, process them, and return the response to the view. Any processing of the request before sending a response, can be done inside this function.
To run the above application on your workstation, go to the terminal and run the .py file we just created:
$ python3 intro.py
In my case, the filename is intro.py, but yours could be different depending on what you decided to name it.
Then open any web browser on your PC, and go to this address:. You should see a webpage with "Hi, My name is Junaid Khalid" written in a very aesthetically displeasing way. To make it look more pleasant, you can return HTML code as a response as well. For a simple example, let's edit intro function:
def intro(request): return Response('<h2 style="text-align: center; font-family: verdana; color: blue;">Hi, My name is Junaid Khalid.</h2>')
Replace the intro function with the one above, and see the output now. A lot better, right? This was just an example. You can make it a lot better.
Note: When you make any change in the code, the server is not automatically going to log that. You will have to stop the server, and then restart it to see your changes take effect. To do that, open your terminal where the server is running and press
Control+C, this will terminate the server. Then you can restart your server as usual to see the changes.
Separating and Displaying Multiple Views
In this section, we will add a few more views as well as remove our views from the main file (i.e. 'intro.py' file), and put them all in a new separate file ('all_views.py'). This will modularize our code, make it look cleaner, and will also allow us to add new views more easily. So, let's do it.
# all_views.py # Import necessary functions to run our web app from pyramid.compat import escape from pyramid.response import Response from pyramid.view import view_config # view_config functions tells Pyramid which route's view is going to be defined in the function that follows # the name of the function does not matter, you can name it whatever you like @view_config(route_name='intro') def home_page(request): header = '<h2 style="text-align: center;">Home Page</h2>' body = '<br><br><p style="text-align: center; font-family: verdana; color: blue;">Hi, My name is Junaid Khalid.</p>' body += '<p style="text-align: center; font-family: verdana;"> This is my portfolio website.</p>' footer = '<p style="text-align: center; font-family: verdana;">Checkout my <a href="/jobs">previous jobs</a>.</p>' # In the 'a' tag, notice that the href contains '/jobs', this route will be defined in the intro.py file # It is simply telling the view to navigate to that route, and run whatever code is in that view return Response(header + body + footer) @view_config(route_name='jobs') def job_history(request): header = '<h2 style="text-align: center;">Job History</h2>' job1 = '<p style="text-align: center; font-family: verdana;">Jr. Software Developer at XYZ</p>' return Response(header + job1)
Note: At the beginner level, you can write the HTML code by following the strategy used above i.e. declare tags in different variables and simply concatenate them when sending back the response. At some point you'll likely want to use a templating engine, like Jinja to make HTML generation much simpler.
Our application won't run just yet, we need to edit the intro.py file as well.
# intro.py # Import necessary functions to run our web app from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def main(): with Configurator() as config: # In add_route function, the first parameter defines the name of the route # and the second parameter defines the 'route' or the page location config.add_route('intro', '/') config.add_route('jobs', '/jobs') # The scan function scans our project directory for a file named all_views.py # and connects the routes we provided above with their relevant views config.scan('all_views') application = config.make_wsgi_app() # The following lines of code configure and start a server which hosts our # website locally (i.e. on our computer) server = make_server('0.0.0.0', 8000, application) server.serve_forever() main()
As you can see, we have removed the code for our previous view. If we had declared all these views in a single file, the file would have looked a lot more cluttered. Both files look very clean now, and each file now serves a single purpose. Let's see what our web app looks like right now.
Output:
In the image above, we can see our home page. It is located at the route ''. It does not look very aesthetically pleasing, but as stated at the start of the tutorial, this was not our aim anyways. If we want to make it look aesthetic, we can add a lot of styling to it using HTML style attribute, or CSS, or use templates from Bootstrap.
Moving on, you can also see a hyperlink which has been named 'previous jobs'. Clicking that would take you to a new webpage with a different route. We will see the output of that in the next image.
Output:
The above image shows our Jobs page. It is located at the route. We specified this route in our 'intro.py' file. I have only added one job to show as an example.
Conclusion
Pyramid is a Python based Web Development Framework to build web apps with ease. In this tutorial, we learned how to install Pyramid inside a virtual environment and make a basic Web Application using Pyramid which runs on a locally created server on our computer.
If you would like to go into more details, visit Pyramid's documentation - it is quite elaborate and beginner friendly. | https://stackabuse.com/introduction-to-the-python-pyramid-framework/ | CC-MAIN-2020-05 | refinedweb | 1,942 | 62.68 |
The function void clearerr(FILE *stream); clears the error and the eof indicators of given stream. If an Input/Output operation fails either because the end of the file has been reached or because of an error, it causes the internal indicators of the stream to be set. A call to clearerr function clears the state of these indicators.
Function prototype of clearerr
void clearerr(FILE *stream);
- stream : A pointer to a FILE object which identifies a stream.
Return value of clearerr
NONE
C program using clearerr function
The following program shows the use of clearerr function to clear internal error indicators of a stream.
#include <stdio.h> int main(){ FILE *file; char ch; /* Opening an empty text file in read only mode*/ file = fopen("textFile.txt", "r"); /* trying to write on a read only file, It will causes an I/O error */ fputc('A', file); if(ferror(file)) { printf("Error in writing in file\n"); /* Clearing error indicators */ clearerr (file); } /* trying to read from an empty file */ fgetc(file); if(ferror(file)) { printf("Error in reading from file\n"); clearerr (file); } fclose(file); return(0); }
Output
Error in writing in file Error in reading from file | https://www.techcrashcourse.com/2015/08/clearerr-stdio-c-library-function.html | CC-MAIN-2020-16 | refinedweb | 197 | 54.15 |
import "golang.org/x/mobile/app"
Package app lets you write portable all-Go apps for Android and iOS.
There are typically two ways to use Go on Android and iOS. The first is to write a Go library and use `gomobile bind` to generate language bindings for Java and Objective-C. Building a library does not require the app package. The `gomobile bind` command produces output that you can include in an Android Studio or Xcode project. For more on language bindings, see.
The second way is to write an app entirely in Go. The APIs are limited to those that are portable between both Android and iOS, in particular OpenGL, audio, and other Android NDK-like APIs. An all-Go app should use this app package to initialize the app, manage its lifecycle, and receive events.
Apps written entirely in Go have a main function, and can be built with `gomobile build`, which directly produces runnable output for Android and iOS.
The gomobile tool can get installed with go get. For reference, see.
For detailed instructions and documentation, see.
The Go runtime is initialized on Android when NativeActivity onCreate is called, and on iOS when the process starts. In both cases, Go init functions run before the app lifecycle has started.
An app is expected to call the Main function in main.main. When the function exits, the app exits. Inside the func passed to Main, call Filter on every event received, and then switch on its type. Registered filters run when the event is received, not when it is sent, so that filters run in the same goroutine as other code that calls OpenGL.
package main import ( "log" "golang.org/x/mobile/app" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" ) func main() { app.Main(func(a app.App) { for e := range a.Events() { switch e := a.Filter(e).(type) { case lifecycle.Event: // ... case paint.Event: log.Print("Call OpenGL here.") a.Publish() } } }) }
An event is represented by the empty interface type interface{}. Any value can be an event. Commonly used types include Event types defined by the following packages:
- golang.org/x/mobile/event/lifecycle - golang.org/x/mobile/event/mouse - golang.org/x/mobile/event/paint - golang.org/x/mobile/event/size - golang.org/x/mobile/event/touch
For example, touch.Event is the type that represents touch events. Other packages may define their own events, and send them on an app's event channel.
Other packages can also register event filters, e.g. to manage resources in response to lifecycle events. Such packages should call:
app.RegisterFilter(etc)
in an init function inside that package.
Main is called by the main.main function to run the mobile application.
It calls f on the App, in a separate goroutine, as some OS-specific libraries require being on 'the main thread'.
type App interface { // Events returns the events channel. It carries events from the system to // the app. The type of such events include: // - lifecycle.Event // - mouse.Event // - paint.Event // - size.Event // - touch.Event // from the golang.org/x/mobile/event/etc packages. Other packages may // define other event types that are carried on this channel. Events() <-chan interface{} // Send sends an event on the events channel. It does not block. Send(event interface{}) // Publish flushes any pending drawing commands, such as OpenGL calls, and // swaps the back buffer to the screen. Publish() PublishResult // Filter calls each registered event filter function in sequence. Filter(event interface{}) interface{} // RegisterFilter registers a event filter function to be called by Filter. The // function can return a different event, or return nil to consume the event, // but the function can also return its argument unchanged, where its purpose // is to trigger a side effect rather than modify the event. RegisterFilter(f func(interface{}) interface{}) }
App is how a GUI mobile application interacts with the OS.
type PublishResult struct { // BackBufferPreserved is whether the contents of the back buffer was // preserved. If false, the contents are undefined. BackBufferPreserved bool }
PublishResult is the result of an App.Publish call.
Package app imports 10 packages (graph) and is imported by 107 packages. Updated 2020-06-29. Refresh now. Tools for package owners. | https://godoc.org/golang.org/x/mobile/app | CC-MAIN-2020-29 | refinedweb | 702 | 60.11 |
Integrating mstest and coverage reporting in 3rd party Build system with scons
(Tested with VS 2005 only)
I have added mstest.py as new patch, there is a plan to add it to 1.0. But I also added generation of coverage report from mstest run (if coverage was enabled). It does involve running special converter utility and use of external XML python module. So it can not be added in base scons package. I decided to describe steps here.
What will it do?
- Runs mstest
- If you configured coverage in your xxx.testrunconfig scons will convert result to .xml file and then generate short .html report by using .xsl.
Why?
You don't want to use TFS to build your .Net projects, you are using some other build system like CruiseControl, Parabuildetc.
- You want to have Unit Tests and Coverage result presented in your build system
How to do it?
Install: libxml2 and libxslt. It developed by: you can download Windows installer from: You will need both modules libxml2 and libxslt
Download Microsoft.VisualStudio.Coverage.Analysis.dll, coverage.xsl, mstest2xml.exe from this page attachments and put it to your system. Also download , mstest.py. Note: you might need to modify lines: 55, 56, 58,59 to make scons find these files you just downloaded on your system
- Add mstest.py as tool
After you run mstest builder, something like: MsTest("TestResults/unittest.trx","mytests.vsmdi"), and your mytests.vcmdi has coverage enabled, it will generate data.coverage binary file somewhere in In directory TestResults/username_host 2008-04-10 09_01_43/In/host/.
- Then scons will look for that file in TestResults/username_host 2008-04-10 09_01_43/In/host/data.coverage You might need to adjust it
mstest.py will run mstest2xml.exe out covReport xml, where: out location of Out directory, like TestResults/username_host 2008-04-10 09_01_43/Out, covReport full path to data.coverage file and xml location of xml file
- Then mstest builder will convert generated XML file to html by using coverage.xsl. So from 10 Mb xml file you get small html report like this: This is the coverage report
Assembly coverage
If you want to modify mstest2xml.exe, there is .Net code for it, also it depends on Microsoft.VisualStudio.Coverage.Analysis.dll, so add it as reference:
using System; using System.Collections.Generic; using Microsoft.VisualStudio.CodeCoverage; namespace mstest2xml { class Program { static void Main(string[] args) { String CoveragePath = args[0]; // Create a coverage info object from the file CoverageInfoManager.SymPath = CoveragePath; CoverageInfoManager.ExePath = CoveragePath; CoverageInfo ci = CoverageInfoManager.CreateInfoFromFile(args[1]); // Ask for the DataSet // The parameter must be null CoverageDS data = ci.BuildDataSet(null); // Write to XML data.WriteXml(args[2]); } } }
Note: for reference I used next article as source for ideas and instructions: joc'c bLog | http://www.scons.org/wiki/MsTest?action=diff | CC-MAIN-2013-48 | refinedweb | 464 | 52.56 |
From: Jody Hagins (jody-boost-011304_at_[hidden])
Date: 2006-02-01 17:42:27
On Wed, 01 Feb 2006 15:47:46 -0500
David Abrahams <dave_at_[hidden]> wrote:
Sorry for the length, but I thought I should at least try to give you my
opinion in more than "I like it because I like it" terminology.
> > The framework allows for easy test-writing.
>
> Easier than BOOST_ASSERT?
Everything is relative. I think it is as easy to use, and provides more
flexibility. When I start a new test file, I can hit a macro key in vim
and I get my bost-test starter code inserted immediately. From then on,
I just write tests.
There are lots of different "checks" that can be made, and a ton of
extra stuff for those complex cases.
> That's all build system stuff and has nothing to do with the library.
> I do
>
> bjam test
>
> and get the same result.
Yes. I was just saying that because I have said before that I do not
use bjam, except to build boost, and I wanted to emphasize that setting
up the make environment was more complex than using Boost.Test.
> > When I need more tests, I can simply
> > create a new .cpp file with the basic few lines of template, and
> > start inserting my tests.
>
>
> #include <boost/assert.hpp>
>
> int main()
> {
> ...
> BOOST_ASSERT( whatever );
> ...
> BOOST_ASSERT( whatever );
> }
If all your tests can be expressed in BOOST_ASSERT, then you may not
have need for Boost.Test. However, to use the Boost.Tests, it is not
much more work...
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
BOOST_AUTO_UNIT_TEST(test_whatever)
{
...
BOOST_CHECK( whatever );
...
BOOST_CHECK( whatever );
}
I can then separate each related test into an individual test function,
and get reports based on the status of each test. For each related
test, I can just add another function...
BOOST_AUTO_UNIT_TEST(test_whomever)
{
...
BOOST_CHECK( whomever );
...
BOOST_CHECK( whomever );
}
I default to use the linker option. There used to be a header-only
option, but since I never used it I'm not sure if it still exists. If
not, you will have to link against the compiled Boost.Test library.
> > For more complex tests, I use the unit test classes,
>
> What classes, please?
There are many useful features to automatically test collections, sets
of items, templates, etc.
The one I've used most often is test_suite
(boost/libs/test/doc/components/utf/components/test_suite/index.html),
which provides extra flexibility to run and track multiple test cases.
One interesting feature I played with was using the dynamic test suites
to select test suites based upon the results of other tests. This is
really useful for running some distributed tests when some portions may
fail because of reasons external to the test. In these cases, the
suites can configure which tests run based on dynamic constraints.
> > but for almost everything else, the basic stuff is plenty.
>
> I think that might be my point.
Sure, but even with Boost.Test, you get lots of stuff with the "basic"
tests, such as reporting success/failure, and isolating test conditions.
Further, you have the additional features to handle more complex
conditions.
I have lots of tests that were written with BOOST_ASSERT before I
started using BOOST_TEST... there was a long time where I was
aprehensive about diving in, but once I did, I found it very helpful.
If I want simple, I can still get it.
>.
In Boost.Test terminology, you would replace BOOST_ASSERT with
BOOST_REQUIRE. If that's all you need, then you can do a simple
replacement. One immediate advantage is the logging and reporting
features of Boost.Test. It generates nice output, and can generate XML
of the test results as well. If you have to process test output, that
is an immediate advantage.
Beyond that, there are three "levels" CHECK, WARN, and REQUIRE. Output
and error reporting can be tailored for each level. Also, the levels
determine if testing should continue. For some tests, you want to halt
immediately upon failure. For others, you want to do as much as
possible. It is often beneficial to know that test A failed, while
tests B and C passed.
The "tools" come in many varieties. I use the EQUAL tools very
frequently, since when a test fails the log reports that it failed, and
it also reports the value of each item being tested. For example,
BOOST_CHECK_EQUAL(x, y);
will check to make sure that x and y are equal. If they are not, then
the test failure will print (among other stuff), the values of x and y.
This is a dont'care when tests pass, but when they fail, it is extremely
helpful since the failing state is readily available in the failure
reports.
There are also special tools to check for exceptions being thrown/not
thrown. It is trivial to write code that either expects an exception or
must not receive an exception. Writing tests for exceptional conditions
is usually difficult, but the tools in Boost.Test makes it much easier.
One of the things I like is the runtime test checks for macro
definitions and values.
All of those are VERY easy to use. The ones I have a hard time with are
the tools that provide checking for floating point numbers
(BOOST_CHECK_CLOSE and friends). It checks two numbers to see if they
are "close enough" to each other. Unfortunately, I couldn't get it
working how I understood, so I don't use it -- though I'd like to use
it.
I actually think that a big advantage of Boost.Test is the tools that
make specific testing much easier. Unfortunately, the one that just
about everyone gets wrong is testing the closeness of floats. I'm sure
I'm the only one with this problem, because I posted about it a while
back, and the response seemed pretty clear, but I still didn't
understand it.
You ought to skim over the reference documents:
boost/libs/test/doc/components/test_tools/reference/index.html
In addition, there are some nifty tools that allow you to easily write
tests for templatized functions, classes, and metatypes. I've not seen
anything like that, and to duplicate it with BOOST_ASSERT would require
a lot of test code.
> > Thus, after integrating Boost.Test into my process, I find writing
> > and maintaining good tests is not so difficult (I still have to
> > write proxy objects for complex integration testing... someone needs
> > to come up with a good solution for that).
>
> Proxy objects? Oh, I think someone described this to me: a proxy
> object is basically a stub that you use as a stand-in for the real
> thing? There was a guy I met at SD Boston who was all fired up with
> ideas for such a library -- I think he had written one. I encouraged
> him to post about it on the Boost list so the domain experts and
> people who really cared could respond, and he said he would,
> but... well, as in about 75% of such scenarios, he never did.
Right. They are very importat, especially for integration testing. You
create a proxy of the "other" object, and then do all your interaction
testing. You can make the other object behave in any way provided by
the interface so it is a good way to test. You can even make the other
object seem "buggy" to test error handling and such. What I would
really like is something like the expect scripting language for
integration testing.
I like it, but it is a huge PITA to write all those proxies. However,
when you do it, your actual integration testing is trivial. Sunstitute
the proxies with the real thing and run the same tests (this is where
some of the test_suite objects can come in handy as it allows you to
easily replace them and "borrow" tests).
> I don't see why that was hard before Boost.Test. I have absolutely no
> problem writing new tests using BOOST_ASSERT. Having the Boost.Build
> primitives to specify tests is a big help, but as I've said, that's
> independent of any language-level testing facility.
Right. However, with BOOST_ASSERT (or anything similarly simple), you
are limited in what you can do, and it is more difficult to track down
problems.
I could write tests in any manner, and trust me, I've written plenty.
However, in the end I always end up with some complex stuff. As I said,
the trivial tests could be done in any manner you like, but anything
beyond trivial tests are easier done, and failures are easier to
decipher, with Boost.Test. If everything is done with Boost.Test, it is
all integrated, similar, and the report processing is the same, no
matter the complexity of the test.
I didn't write it, and I'm probably not the best defender of its
functionality. However, I have found it to be extremely useful. If all
I had was simple tests, I probably would have never tried it. However,
my needs are more than simple, and it addresses the complex AND the
simple (though I wish it had EVEN MORE to offer, especially w.r.t. proxy
objects... did I say that already).
In fact, since it is used for all my NEWER tests, it is the most used
Boost component (our older tests are still done with assert() or writing
output to stdout/stderr and having scripts interpret the output, and
some are still even interactive -- if we are lucky they are driven by
expect or some other script).
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2006/02/100007.php | CC-MAIN-2022-21 | refinedweb | 1,618 | 73.58 |
Fully understand DART’s asynchrony
Foreword 1: I will update some columns of flutter text tutorials in succession in the next period
Update progress:At least two articles per week;
Update location:The first time is in the official account, and the second day is updated in nuggets and places of thought.
More communication:You can add my wechat 372623326 and follow my micro blog: Code why
I hope you canHelp forward, click to seeGive me more creative power.
Foreword 2: before writing this article, I have been hesitating whether to explain DART’s asynchronous related topics here, because this part of the content is very easy for beginners to be deterred:
1. It’s easy to be confused about the relationship between single thread and asynchronous, although I will try my best to make you understand it in my own way.
2. A large number of asynchronous operation modes (future, await, async, etc.), currently you can’t see the specific application scenarios. (for example, if you have studied promise, await and async in the front end, it may be simpler, but I will assume that you do not have such a foundation.).
However, listen to me: if you have a lot of doubts after this chapter is finished, it doesn’t matter. When you use the relevant knowledge later, looking back, you will suddenly be enlightened.
1、 DART’s asynchronous model
Let’s figure out how dart handles asynchronous operations
1.1. Dart is single threaded
1.1.1. Time consuming operations in the program
Time consuming operations in development:
- In development, we often encounter some time-consuming operations to complete, such as network request, file reading and so on;
- If our main thread has been waiting for these time-consuming operations to complete, it will block, unable to respond to other events, such as the user’s click;
- Obviously, we can’t do this!!
How to deal with time-consuming operations?
- Different languages have different ways to deal with time-consuming operations.
- Treatment 1:Multithreading, such as Java and C + +, is a common practice for us to start a new thread, complete these asynchronous operations in the new thread, and then pass the data obtained to the main thread through the way of inter thread communication.
- Treatment 2:Single thread + event loop, such as JavaScript and dart, is based on single thread plus event loop to complete the processing of time-consuming operations. But how can a single thread perform time-consuming operations?!
1.1.2. Asynchronous operation of single thread
I’ve met many developers who are full of questions about single thread asynchronous operations???
In fact, they do not conflict:
- Because one of our applications is idle most of the time, not unlimited interaction with users.
- For example, waiting for users to click, network request data return, file read-write IO operations, these waiting behaviors will not block our threads;
- This is because similar to network request, file read-write IO, we can all call based on non blocking;
Blocking and non blocking calls
To understand this, we need to know the
Blocking calland
Nonblocking callThe concept.
- Blocking and non blocking concernsThe state of a program waiting for the result of a call (message, return value).
- Blocking call:Before the call result returns, the current thread will be suspended, and the call thread will continue to execute only after getting the call result.
- Non blocking call:After the call is executed, the current thread will not stop executing. It only needs a period of time to check whether there is any result returned.
Let’s use an example in life to simulate:
- You’re hungry at noon. You need to order a take out
Take out actionIt’s our call. Get it
Last order takeoutIt’s the result we have to wait for.
- Blocking call:Order takeout, no longer do anything, is in the silly waiting, your thread stopped any other work.
- Non blocking call:After ordering takeout, continue to do other things: continue to work, play the game, your thread does not continue to perform other things, just need to occasionally see if there is a knock on the door, whether the takeout has been delivered.
Many time-consuming operations in our development can be based on
Nonblocking call:
- For example, the network request itself uses socket communication, while the socket itself provides a select model, which can be used to
Non blocking operation;
- For example, we can use the IO operation provided by the operating system to read and write files
Event based callback mechanism;
These operations will not block our single thread’s continuous execution. Our thread can continue to do other things in the process of waiting: drink a cup of coffee, play a game, etc. when there is a real response, then go to the corresponding processing.
At this time, we may have two questions:
- Question 1:If in multi-core CPU, does single thread not make full use of CPU? I will explain this problem later.
- Question two:How does a single thread handle the results of network communication and IO operations? The answer is the event loop.
1.2. Dart event cycle
1.2.1. What is event cycle
In the single thread model, an event loop is maintained.
What is the event cycle?
- In fact, the event loop is not complicated. It is to put a series of events (including click events, IO events, network events) to be handled in an event queue.
- Take out the event from the event queue and execute the corresponding code block until the event queue is empty.
Let’s write a pseudo code for an event loop:
//Here I use array to simulate queue, first in, first out principle List eventQueue = []; var event; //The event loop is always executing from the moment it starts while (true) { if (eventQueue.length > 0) { //Take out an event event = eventQueue.removeAt(0); //Execute the event event(); } }
When we have some events, such as click event, IO event and network event, they will be added to the
eventLoopWhen the discovery event queue is not empty, the event will be fetched and executed.
- The gear is our event loop, which takes events out of the queue once for execution.
1.2.2. Event cycle code simulation
Let’s take a look at a piece of pseudocode to understand how click events and network request events are executed:
- This is a flutter code. You may not understand a lot of things, but read patiently and you will understand what we are doing.
- A button raisedbutton that executes the onpressed function when a click occurs.
- In the onpressed function, we send a network request, and the callback function in then will be executed after the request is successful.
RaisedButton( child: Text('Click me'), onPressed: () { final myFuture = http.get(''); myFuture.then((response) { if (response.statusCode == 200) { print('Success!'); } }); }, )
How is this code executed in an event loop?
- 1. When the user clicks, the onpressed callback function is put into the event loop, and a network request is sent during the execution.
- 2. After the network request is sent, the event loop will not be blocked, but the onppressed function to be executed is found to have ended and will be discarded.
- 3. After the network request is successful, the callback function passed in then will be executed, which is also an event. This event will be put into the event loop for execution. After execution, the event loop will discard it.
Although there are some differences between the callbacks in onpressed and then, they tell the event loop:I have a piece of code to execute. Help me finish it quickly.
2、 Asynchronous operation of dart
The asynchronous operations in dart mainly use future, async and await.
If you have previous programming experience in ES6 and ES7 of the front end, you can fully understand future as promise. Async, await and ES7 are basically the same.
But without front-end development experience, how can future, async and await understand it?
2.1. Understanding future
I’ve been thinking for a long time about how to explain this future
2.1.1. Synchronous network request
Let’s take an example:
- In this example, I use getnetworkdata to simulate a network request;
- The network request takes 3 seconds, and then returns data;
import "dart:io"; main(List<String> args) { print("main function start"); print(getNetworkData()); print("main function end"); } String getNetworkData() { sleep(Duration(seconds: 3)); return "network data"; }
What is the result of this code running?
- Getnetworkdata blocks the main function
main function start //Wait 3 seconds network data main function end
Obviously, the above code is not the execution effect we want, because the network request blocks the main function, which means that all subsequent codes cannot continue to execute normally.
2.1.2. Asynchronous network request
Let’s improve the code above. The code is as follows:
- The only difference between this code and the previous one is that I use the future object to put the time-consuming operation in the function passed in;
- Later, we will explain some of its specific APIs. For the moment, we know that I have created a future instance;
import "dart:io"; main(List<String> args) { print("main function start"); print(getNetworkData()); print("main function end"); } Future<String> getNetworkData() { return Future<String>(() { sleep(Duration(seconds: 3)); return "network data"; }); }
Let’s take a look at the running results of the code:
- 1. This time, the code is executed in sequence without any blocking;
- 2. Different from the previous direct printing results, this time we printed a future example;
- Conclusion: we isolate a time-consuming operation, which will no longer affect the execution of our main thread.
- Question: how can we get the final result?
main function start Instance of 'Future<String>' main function end
Get the result of future
With future, how to get the requested result: through the callback of. Then:
main(List<String> args) { print("main function start"); //Receive future returned by getnetworkdata with variable var future = getNetworkData(); //When the future instance returns a result, it will automatically call back the function passed in from then //The function is placed in the event loop and executed future.then((value) { print(value); }); print(future); print("main function end"); }
Execution result of the above code:
main function start Instance of 'Future<String>' main function end //Execute the following code after 3S network data
Exception in execution
If there is an exception in the calling process and no result can be obtained, how can the exception information be obtained?
import "dart:io"; main(List<String> args) { print("main function start"); var future = getNetworkData(); future.then((value) { print(value); }). Catchrror ((error) {// catch the exception print(error); }); print(future); print("main function end"); } Future<String> getNetworkData() { return Future<String>(() { sleep(Duration(seconds: 3)); //No more results returned, but an exception occurred // return "network data"; Throw exception ("network request error"); }); }
Execution result of the above code:
main function start Instance of 'Future<String>' main function end //We didn't get the result after 3S, but we caught the exception Exception: network request error
2.1.3. Future use supplement
Supplement 1: summary of the above cases
We learned the use process of some future through a case:
- 1. Create a future (it may be created by us, or it may be obtained by calling an internal API or a third-party API. In short, you need to obtain a future instance, which usually encapsulates some asynchronous operations);
- 2. Through. Then (successful callback function) to monitor the results obtained when the internal execution of future is completed;
- 3. Through. Catchrror (failure or exception callback function), listen for the error information of future internal execution failure or exception;
Supplement 2: two states of future
In fact, in the whole process of future execution, we usually divide it into two states:
Status one:
Incomplete status
- When performing the internal operations of future (in the above case, the specific network request process, we use the delay to simulate), we call this process the unfinished state
Status two:Completed status
- When the operation inside future is completed, it usually returns a value or throws an exception.
- In both cases, we call future the completion state.
Dart official website has the analysis of these two states. The reason why they are posted is that they are different from promise’s three states
Supplement 3: chain call of future
The above code can be improved as follows:
- We can continue to return values in then, and we will get the returned results in the next chained then call callback function
import "dart:io"; main(List<String> args) { print("main function start"); getNetworkData().then((value1) { print(value1); return "content data2"; }).then((value2) { print(value2); return "message data3"; }).then((value3) { print(value3); }); print("main function end"); } Future<String> getNetworkData() { return Future<String>(() { sleep(Duration(seconds: 3)); //No more results returned, but an exception occurred return "network data1"; }); }
The printing results are as follows:
main function start main function end //Get the result in 3S network data1 content data2 message data3
Supplement IV: future other API
Future.value(value)
- Get a completed future directly, which will directly call the callback function of then
main(List<String> args) { print("main function start"); Future. Value ("hahaha"). Then ((value){ print(value); }); print("main function end"); }
The printing results are as follows:
main function start main function end Ha ha ha
Question: why immediately, but
Ha ha haWas it printed at the end?
- This is because then in future will be added to the event queue as a new task. After joining, you must queue for execution
Future.error(object)
- Get a completed future directly, but it is an abnormal future. The future will call the callback function of catchrror directly
main(List<String> args) { print("main function start"); Future. Error (exception ("error message")). Catchrror ((error){ print(error); }); print("main function end"); }
The printing results are as follows:
main function start main function end Exception: error message
Future.delayed (time, callback function)
- When the callback function is delayed for a certain time, the callback of then will be executed after the callback function is executed;
- In the previous case, we can also use it to simulate, but directly learning this API will make you more confused;
main(List<String> args) { print("main function start"); Future.delayed(Duration(seconds: 3), () { Return "information in 3 seconds"; }).then((value) { print(value); }); print("main function end"); }
2.2. await、async
2.2.1. Theoretical concept understanding
If you have a complete understanding of future, there should be no difficulty in learning await and async.
What are await and async?
- They’re keywords in Dart (isn’t that bullshit? Nonsense is also important, in case you use it as variable name, innocent face.)
- They allow us to use
Synchronized code formatTo achieve
Asynchronous calling procedure。
- And, usually, an async function will return a future (don’t worry, you’ll see the code soon).
We already know that future can do not block our thread, let the thread continue to execute, and change its state when completing an operation, and call back then or errorcatch.
How to generate a future?
- 1. You can use the future constructor we learned earlier, or other future APIs we learned later.
- 2. The other is through async.
2.2.2. Case code drill
Talk is cheap. Show me the code.
Let’s change the future asynchronous processing code to the form of await and async.
We know that if we write the code in this way, the code will not execute normally:
- Because future.delayed returns a future object, we cannot treat it as synchronous return data:
"network data"To use
- That is to say, we can’t use this asynchronous code as synchronization!
import "dart:io"; main(List<String> args) { print("main function start"); print(getNetworkData()); print("main function end"); } String getNetworkData() { var result = Future.delayed(Duration(seconds: 3), () { return "network data"; }); Return "requested data:" + result; }
Now I use await to modify the following code:
- You’ll find that I’m
Future.delayedThe function is preceded by an await.
- Once you have this keyword, the operation will wait
Future.delayedAnd wait for its result.
String getNetworkData() { var result = await Future.delayed(Duration(seconds: 3), () { return "network data"; }); Return "requested data:" + result; }
When executing the code after modification, you will see the following error:
- The error is obvious: the await keyword must exist in the async function.
- So we need to
getNetworkDataFunction is defined as async function.
Continue to modify the code as follows:
- It’s also very simple. Just add an async keyword after the () of the function
String getNetworkData() async { var result = await Future.delayed(Duration(seconds: 3), () { return "network data"; }); Return "requested data:" + result; }
Run the code and still report an error (think: your sister ah):
- The error is obvious: functions marked with async must return a future object.
- So we need to continue to modify the code and write the return value as a future.
Continue to modify the code as follows:
Future<String> getNetworkData() async { var result = await Future.delayed(Duration(seconds: 3), () { return "network data"; }); Return "requested data:" + result; }
This code should be the code we want to execute
- We can now use the results returned asynchronously by future like synchronous code;
- Wait for the result to be obtained and then splice it with other data, and then return together;
- When returning, you do not need to wrap a future, just return directly, but the return value will be wrapped in a future by default;
2.3. Reading JSON cases
Here I give a case of reading a local JSON file, converting it into a model object and returning it in the flutter project;
This case serves as a reference for you to learn about future, await and async. I’m not going to talk about it, because I need to use relevant knowledge of flutter;
Later, I will explain it again in the following cases in the process of using it in flutter;
Read the JSON case code (just learn about it)
import 'package:flutter/services.dart' show rootBundle; import 'dart:convert'; import 'dart:async'; main(List<String> args) { getAnchors().then((anchors) { print(anchors); }); } class Anchor { String nickname; String roomName; String imageUrl; Anchor({ this.nickname, this.roomName, this.imageUrl }); Anchor.withMap(Map<String, dynamic> parsedMap) { this.nickname = parsedMap["nickname"]; this.roomName = parsedMap["roomName"]; this.imageUrl = parsedMap["roomSrc"]; } } Future<List<Anchor>> getAnchors() async { //1. Read the JSON file String jsonString = await rootBundle.loadString("assets/yz.json"); //2. Convert to list or map type final jsonResult = json.decode(jsonString); //3. Traverse the list, and turn it into an anchor object and put it in another list List<Anchor> anchors = new List(); for (Map<String, dynamic> map in jsonResult) { anchors.add(Anchor.withMap(map)); } return anchors; }
3、 Asynchronous supplement of dart
3.1. Task execution sequence
3.1.1. Understanding micro task queue
In the previous learning, we know that there is an event loop in dart to execute our code, and there is an event queue in it. The event loop constantly takes events from the event queue for execution.
But if we strictly divide it, there is another queue in dart: Micro task queue.
- The priority of micro task queue is higher than that of event queue;
- In other words
event loopIt’s all priority
Micro task queueTasks in, execute again
Event queueTasks in;
So in the development of flutter, which is put in the event queue and which is put in the micro task queue?
- All external event tasks are in the event queue, such as IO, timer, click, and draw events;
- Micro tasks usually come from dart, and there are very few micro tasks. This is because if there are many micro tasks, the event queue will not be queued and the execution of the task queue will be blocked (for example, when the user clicks and does not respond);
Speaking of this, you may have been a bit messy. How does the code execute in DART’s single thread?
- 1. DART’s entry is the main function, so
Code in main functionWill give priority to implementation;
- 2. After the main function is executed, an event loop will be started, and then the tasks in the queue will be executed;
- 3. First, it will be executed in the order of first in, first out
Micro task queueAll tasks in;
- 4. Secondly, it will be executed in the order of first in, first out
Event queueAll tasks in;
3.1.2. how to create a micro task
In development, we can create a micro task through the schedule micro task under async in dart:
import "dart:async"; main(List<String> args) { scheduleMicrotask(() { print("Hello Microtask"); }); }
In development, if we have a task that we don’t want to queue in event queue, we can create a micro task.
Is the future code added to the event queue or the micro task queue?
There are usually two function executors in future:
- Function body passed in by future constructor
- The function body of then
So what queues do they join?
- The function body passed in by the future constructor is placed in the event queue
- The function bodies of then are divided into three cases:
- Case 1: if future is not finished (there are tasks to be executed), then then they will be added directly to the function body of future;
- Case 2: if the function body of the then is put into the micro task queue after the execution of future, the micro task queue will be executed after the execution of current future;
- Case 3: if the future world chain call means that the next then will not be executed before the execution is completed;
//Future 1 is added to the eventqueue, followed by then 1 Future(() => print("future_1")).then((_) => print("then_1")); //Future has no function executor and then 2 is added to microtaskqueue Future(() => null).then((_) => print("then_2")); //Future, then, and then are added to the eventqueue Future(() => print("future_3")).then((_) => print("then_3_a")).then((_) => print("then_3_b"));
3.1.3. Code execution sequence
We learn one according to the previous rules
Code execution order of poleCase study:
import "dart:async"; main(List<String> args) { print("main start"); Future(() => print("task1")); final future = Future(() => null); Future(() => print("task2")).then((_) { print("task3"); scheduleMicrotask(() => print('task4')); }).then((_) => print("task5")); future.then((_) => print("task6")); scheduleMicrotask(() => print('task7')); Future(() => print('task8')) .then((_) => Future(() => print('task9'))) .then((_) => print('task10')); print("main end"); }
The result of code execution is:
main start main end task7 task1 task6 task2 task3 task5 task4 task8 task9 task10
Code analysis:
- 1. The main function executes first, so
main startand
main endExecute first, no problem;
- 2. Main function execution
In process, some tasks will be added to
EventQueueand
MicrotaskQueueMedium;
- 3. Task 7 passed
scheduleMicrotaskFunction call, so it was first added to the
MicrotaskQueue, will be executed first;
- 4. Then start execution
EventQueue, Task1 added to
EventQueueIs implemented in;
- 5. Pass
final future = Future(() => null);The future then created is added to the micro task, and the micro task is directly executed first, so task6 will be executed;
- 6. Once in a while
EventQueueAdd task2, task3 and task5 to be executed;
- 7. After the print execution of task3, call
scheduleMicrotask, then after the execution of the
EventQueueIt will be executed after task5, so task4 will be executed after task5 (Note:
scheduleMicrotaskAs part of task3, task4 is executed after task5.)
- 8. Task8, task9, task10 added to
EventQueueBe executed;
In fact, the above code execution order may appear in the interview. This kind of complex nesting usually does not appear in our development, and we need to fully understand its execution order;
However, understanding the code execution sequence above will let you
EventQueueand
microtaskQueueHave a deeper understanding.
3.2. Utilization of multi-core CPU
3.2.1. Understanding of isolate
In dart, there is a concept of isolate. What is it?
- We have known that dart is a single thread. This thread has its own memory space that can be accessed and event loops that need to be run;
- We can call this space system an isolate;
- For example, there is a root isolate in flutter, which is responsible for running flutter code, such as UI rendering, user interaction, etc;
In isolate, resource isolation is done very well. Each isolate has its own event loop and queue,
- Isolates do not share any resources and can only communicate by message mechanism, so there is no problem of resource preemption.
However, if there is only one isolate, it means that we can only use one thread forever, which is a waste of resources for multi-core CPU.
If we have a lot of time-consuming calculations in development, we can create an isolate ourselves and complete the desired calculation operations in an independent isolate.
How to create an isolate?
It’s easy to create an isolate. We use
Isolate.spawnYou can create:
import "dart:isolate"; main(List<String> args) { Isolate.spawn(foo, "Hello Isolate"); } void foo(info) { Print ("new isolate: $info"); }
3.2.2. Isolate communication mechanism
But in real development, we will not simply start a new isolate, and we will not care about its running results:
- We need a new isolate to perform the calculation and inform the main isolate of the calculation results (that is, the default open isolate);
- Isolate implements message communication mechanism through SendPort;
- When starting concurrent isolate, we can pass the send pipeline of main isolate to it as a parameter;
- At the end of execution, the pipeline can be used to send messages to main isolate;
import "dart:isolate"; main(List<String> args) async { //1. Create pipe ReceivePort receivePort= ReceivePort(); //2. Create a new isolate Isolate isolate = await Isolate.spawn<SendPort>(foo, receivePort.sendPort); //3. Monitor pipeline messages receivePort.listen((data) { print('Data:$data'); //When not in use, we close the pipe receivePort.close(); //Need to kill isolate isolate?.kill(priority: Isolate.immediate); }); } void foo(SendPort sendPort) { sendPort.send("Hello World"); }
But our above communication has become one-way communication. What if we need two-way communication?
- In fact, two-way communication code will be more troublesome;
- Flutter provides
computeFunction, which encapsulates the creation and bidirectional communication of isolate;
- With it, we can make full use of multi-core CPU, and it is very simple to use;
Note: the following code is not DART’s API, but flutter’s API, so it can only be run in the flutter project
main(List<String> args) async { int result = await compute(powerNum, 5); print(result); } int powerNum(int num) { return num * num; }
Note: all contents start with the official account. After that, Flutter will update other technical articles. TypeScript, React, Node, uniapp, mpvue, data structure and algorithm will also update some of their learning experiences. Welcome everyone’s attention.
| https://developpaper.com/understand-dart-asynchrony-thoroughly/ | CC-MAIN-2021-21 | refinedweb | 4,480 | 50.57 |
Created on 2007-02-15 11:29 by ncoghlan, last changed 2008-01-06 22:29 by admin. This issue is now closed.
This patch hides the iteration variable in list comprehensions.
It adds new tests (modelled on the generator expression tests) and also removes some del statements from the standard library (where code previously cleaned up its own namespace).
The changes to symtable.[ch] are more significant than strictly necessary - I found it necessary to spend some time cleaning up the code in order to understand what was needed for the list comprehension changes. Given that the 2.x and 3.0 compilers have already diverged fairly significantly, I don't believe this will make the process of keeping them in sync any more difficult than it is already.
Assigning to Georg for initial review (as his set comprehensions patch provided a great deal of inspiration for this one).
Speed measurements show a significant speed up over trunk & Python 2.4 for module/class level code:
(Python 2.4)$ python -m timeit -s "seq=range(1000)" "[[x for x in seq] for y in seq]"
10 loops, best of 3: 239 msec per loop
(Python 2.x trunk)$ ./python -m timeit -s "seq=range(1000)" "[[x for x in seq] for y in seq]"
10 loops, best of 3: 193 msec per loop
(Python 3000)$ ./python -m timeit -s "seq=range(1000)" "[[x for x in seq] for y in seq]"
10 loops, best of 3: 176 msec per loop
This is almost certainly due to the variables and the list object becoming function locals.
There is a slowdown inside a function (but we are still faster than Python 2.4):
(Python 2.4)$ python -m timeit -s "seq=range(1000)" -s "def f(): return [[x for x in seq] for y in seq]" "f()"
10 loops, best of 3: 259 msec per loop
(Python 2.x trunk)$ ./python -m timeit -s "seq=range(1000)" -s "def f(): return [[x for x in seq] for y in seq]" "f()"
10 loops, best of 3: 176 msec per loop
(Python 3000)$ ./python -m timeit -s "seq=range(1000)" -s "def f(): return [[x for x in seq] for y in seq]" "f()"
10 loops, best of 3: 185 msec per loop
For reference, the original set comprehensions patch & the py3k list discussion:
Note that the current patch ended up looking a *lot* like the original one (the main difference specific to list comprehensions is that the temporary list is built in the inner scope and then returned rather than being passed in as an argument. Additionally, the code has been unified only for the symtable stage - the AST and compilation stages still use separate code for listcomps and genexps).
It turns out that there are some really curly scoping problems that using a nested function deals with automatically (see the new test_listcomps.py in the patch for examples). Having a more efficient mechanism specifically for 'transient' scopes like this is an interesting idea, but it's far from easy (mainly because the variables in the scope still need to be properly visible in scopes it *contains*).
Adding set comprehensions on top of this patch should be pretty straightforward.
Okay, I looked at the patch, and apart from a refleak in one of the compiler methods I couldn't find anything wrong.
I then manually applied the rest of my set comprehension patch. The result is attached.
Grammar, AST and compilation for comprehensions are now really unified.
It passes the tests for listcomps, genexps and setcomps.
I couldn't check properly for refleaks since e.g. test_genexps leaks in the branch head, as well as some other tests. I'm currently searching for the offending revision(s)...
File Added: new-set-comps.diff
Can't say that slowdown bothers me much, if it's typical.
However I think you need to do a svn up in your workspace and regenerate the patch; I get FAILED message from patch on all the generated files and a few others: graminit.[ch], symtable.[ch], Python-ast.c, symbol.py.
The patch for 'nonlocal' was applied since Georg & I started working on this. It's going to take me a bit of fiddling to update the patch so that the parser/compiler stage play well with each other (I really should have just believed the patch utility when it reported a conflict trying to patch symtable.c).
I've uploaded a new version of the patch that is compatible with the py3k SVN branch as of April 14.
The patch still includes the various cleanups I made to the symbol table processing while working out how to make this change (use sets where appropriate, avoid using the same variable name to refer to completely different things, make a couple of syntax error messages more explicit).
The slowdown should be fixed at the cost of a single function call - the shorter the sequence being iterated over, the greater the percentage slowdown that will be. The speed of generator expressions should actually be (very) marginally increased as they now skip the SETUP_LOOP/POP_BLOCK steps in the same fashion as list comprehensions always have.
File Added: new-comps-updated.diff
Assuming all tests pass in a debug build and you don't see any leaks with "regrtest.py -R 4:3:", just check it in! I've been waiting long enough for this. Speedups are for post 3.0a1.
I applied this and ran regrtest -R. Found no refleaks, and the only tests that failed were compiler and transformer, as expected.
OK, I think Nick can check it in himself, right Nick?
test_compiler and test_transformer are failing due to the fact that the compiler package still needs some TLC to catch up with the Grammar changes.
test_logging, test_tcl and test_structmembers all fail when run with -R 4:3:. However, these failures don't appear to be due to this change. More importantly, no leaks are reported in the new tests that are part of this update (test_listcomps, test_setcomps).
Committed as rev 54835.
The compiler package has been thrown out of Py3k, so there's no reason to leave this open anymore. | http://bugs.python.org/issue1660500 | CC-MAIN-2017-17 | refinedweb | 1,033 | 70.84 |
Hi all.
I am trying to write a template class queue for an "assignment" and I got stuck by what I think is a syntax error.
To be honest, the assignment was MUCH easier than that but after having it completed I thought to be interesting to explore new possibilities... here's why the " " :P
I have two template structures, slist and dlist, that are in fact nodes of single linked lists and double linked lists respectively, that can store data of any given type.
I have a template class, queue, in order to create queues with data organized either in Single or Double linked lists.
I am trying to write two different constructors, one to be run if the object is a queue based on a SLL data structure and one for object built upon the other struct. The reason is that I most likely will need to hande more specifically one or the other case, (e.g. the second pointer of the dll). It would be nice to understand the concept in order to differentiate some other funcion, too, but I bet that this constructor case will give me the start.
Here's what I have so far:
#include <iostream> #include <string.h> using std::cout; using std::endl; using std::cin; template <class D> struct slist { public: D data; slist<D> *next; }; template <class D> struct dlist { public: D data; dlist<D> *next; dlist<D> *prev; }; template <class S> class queue { S *start; string name; public: queue(void); ~queue(void); }; template <class D> queue<slist<D> >::queue(void) { start = new slist<D>; cout << endl << "Constructor slist Test" << endl; return; } template <class D> queue<dlist<D> >::queue(void) { start = new dlist<D>: cout << endl << "Constructor dlist Test" << endl; return; } template <class S> queue<S>::~queue(void) { delete start; cout << endl << "Destructor Test" << endl; return; } int main(void) { queue<slist<int> > ob1; cin.get(); return EXIT_SUCCESS; }
How may I differentiate the constructors?
This code isn't compiling for the following reason, that I don't understand.
error: invalid use of incomplete type ‘class queue<slist<D> >’ error: declaration of ‘class queue<slist<D> >’ error: invalid use of incomplete type ‘class queue<dlist<D> >’ error: declaration of ‘class queue<dlist<D> >’
Thanks in advance for any help, and as usual sorry for my poor english, I Hope I explained myself anyway ^^" | https://www.daniweb.com/programming/software-development/threads/150942/template-specification-constructors | CC-MAIN-2017-17 | refinedweb | 391 | 60.79 |
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hello,
I'm dealing with an instance which has a big database of issues. In order to improve performance, indexing, etc., I would like to archive issues that were last updated the earliest 2 years ago.
After running a simple jql for that: Updated <= startOfMonth(-24) and statusCategory = Done ORDER BY updated DESC , I'm left with more than 700k issues which will have to be archived. (Deleting is not an option sadly as the company wants to have the possibility of reactivating some of the issues if necessary)
Currently I'm looking into a way of doing this with Jira Automation plugin or Scriptrunner, in order to also create an automation rule for future usage and I'm not feeling so lucky just yet. Sadly for scriptrunner I don't have the coding experience and didn't find any script already used by someone.
The other option is exporting all those issues to a separate jira instance which will be used only for archiving, but I would like to leave that as a 2nd option and first focus on the possibility of archiving in the current instance.
Did anyone have an experience with something like this? If yes, how did you deal with it (if you can provide the solution)?
I would appreciate any help if possible.
Thank you!
Hi, you can use the plugin MyGroovy
Use the module
to run the script periodically on a specific JQL
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.archiving.ArchivedIssueService
@StandardModule
ArchivedIssueService a
def authContext = ComponentAccessor.getJiraAuthenticationContext()
//issue = ComponentAccessor.getIssueManager().getIssueObject("TESTISSUE-1234")
def validationResult = a.validateArchiveIssue(authContext.getLoggedInUser(), issue.getKey());
if (validationResult.isValid()) {
a.archiveIssue(validationResult);
}
Thank you for the suggestion, but currently due to the high number of already existing plugins, I wouldn't like to add more to the list and try to deal with the issue with what's currently installed. If nothing else works, I'll probably consider installing it, although it looks like the support version for it is only for server and we're running a Data Center version of JIRA.
Thank you!
We write it for our own needs and use it on Jira DataCenter too (5+mln issues, 4 nodes)and actively share our work with the community. The plugin is open source ()and completely free.
Hello @Adrian Popescu ,
Unfortunately, we currently don't support this type of action on our plugin, as this is a new API on JIRA.
We have already an issue for tracking the development of this feature, but it might take some time for us to implement, as we got higher priority tasks on our backlog at this moment ().
Sorry for not helping that much at this time.
Feel free to reach us in case of any further questions.
Cheers,
Victor - Automation for JIRA
Hello @Victor Seger ,
I understand, that's too bad as I was hoping I'll be able to deal with this more simple when I first started looking into it.
I do have one question though.. Is it possible to run the clone function on schedule with a jql? I was also thinking about the possiblity of cloning the issues (since move is not available) to another project, then delete the old issues and eventually just archive the whole project which will contain all the issues I was interested in archiving.
I ran a test on a test instance with scheduled jql then cloning action to the new project, but it doesn't seem to do anything and I'm being left with "No Actions Performed" status on it.
Any help on this one? It's also a possibility I was thinking about. Most likely not the fastest one, but could also do the trick if possible.
Thank you!
Hi @Adrian Popescu ,
Yes, it is possible. But due to the high number of issues that your JQL query returned, it might be some throttling issues on your rule.
Although, can you please share with me a screenshot of your current rule? That way I will be able to advise you on how to make this work.
Thanks in advance!
Cheers,
Victor - Automation for JIRA
I actually modified it first to test with a lower number of issues. Currently the JQL returns only around 800 issues.
Here's the screenshot. Currently I'm only running it manually for testing.
Thanks for sharing this screenshot of your rule.
Can you please ensure that your rule doesn't have any project restrictions on the "Rule details" page under the "Restrict to Projects" field?
If there are any projects inserted on this field, can you please leave the field blank and see how the rule execution goes?
Cheers,
Victor
My bad, totally forgot about automation rule project restrictions. It should go fine now.
Now time to test how many clones per run it will support and how long it will take.
No problem, @Adrian Popescu !
Thanks for replying!
One thing that is important to do is go to your "Scheduled" trigger, under the "More options" section and select the "Process all issues produced by this trigger in bulk".
So your rule will execute faster, according to my tests here.
Let me know if you got any further questions!
Cheers,
Victor
Wanted to share that we just released issue archiving in Jira Software Data Center 8.1, and a new browse archives page in 8.4. Here's our announcement and blog with all the details, including performance testing results showing a reduction in JQL searches, backlog loading, & re-indexing:
Cheers,
Jess
That's good feedback @Adrian Popescu
With the next release (Jira 8.5) we are delivering an automation cookbook for archiving, with detailed documentation on how to automate this process. Will plan to share that here and with the community once that is live, and would love feedback.
Best,
J. | https://community.atlassian.com/t5/Jira-questions/How-to-archive-a-big-number-of-issues-and-possible-automation/qaq-p/1139323 | CC-MAIN-2019-47 | refinedweb | 992 | 63.39 |
Learn how to build an API backend with Node.js, Express and MongoDB for a React Native app.
Table of contents
What We Will Be Building
In the previous tutorial, we built movie tickets booking app that stored all movie data in javascript files. That is obviously not what you want to do for a real world app. So, this time we’re going to build an API backend for our movie tickets booking app that will store movie data in a MongoDB database and will return it to the app as JSON data.
For your reference, the final code for the app we’re building can be found in this GitHub repo.
Prerequisites
MongoDB
To install MongoDB open Terminal App and execute:
brew install mongodb
Now, let’s create a folder that MongoDB will use to store our database data:
sudo mkdir -p /data/db
And set the correct permissions:
sudo chmod 777 /data/db
Finally, let’s launch MongoDB:
mongod&
Initialize Node.js Project
First, create a new folder:
mkdir MovieTicketsBackend; cd MovieTicketsBackend;
Next, initialize new Node.js project by executing:
npm init
And answering a few questions asked in the terminal. It’s safe to give default answers to all questions.
That will create
package.json file that is used to store your app’s info, scripts, and dependencies.
Install Dependencies
First, install dev dependencies that we’ll going to need during development and to run the app locally:
npm install --save-dev babel babel-cli babel-preset-es2015 babel-preset-stage-0 nodemon
And next, install all of the rest:
npm install --save body-parser express moment mongoose morgan
Create .babelrc File
- Create a new file called
.babelrcwith the following content:
{ "presets": ["es2015", "stage-0"] }
That will allow us to use ES6 features of JavaScript that we have access to when developing React Native apps. In case with React Native ES6 is enabled by default when you do
react-native init project.
Add Scripts
Next, let’s add some scripts to run the app.
- Open
package.jsonfile and find
scriptsobject:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1" },
And update it with the following:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "node_modules/babel-cli/bin/babel.js ./ --source-maps --out-dir dist", "start": "node_modules/nodemon/bin/nodemon.js -- node_modules/babel-cli/bin/babel-node.js server.js", "populate": "node_modules/babel-cli/bin/babel-node.js populate.js" },
We’ll be using nodemon to automatically restart the server when we change anything in the code.
Starting with the Server
Let’s create a script that will run an HTTP server and handle incoming requests.
- Create a new file called
server.jswith the following content:
import express from 'express'; // Initialize http server const app = express(); // Handle / route app.get('/', (req, res) => res.send('Hello World!') ) // Launch the server on port 3000 const server = app.listen(3000, () => { const { address, port } = server.address(); console.log(`Listening at{address}:${port}`); });
For now, it just outputs Hello World when GET request submitted to
/ route.
Let’s launch the server and see how it works.
- Open Terminal App and execute:
npm start
You should see a confirmation that it’s running in your terminal.
Now, let’s open a browser and go to.
That’s great. The serves works. Next, let’s make it serve movie data as JSON object.
Movie Model
We’ll use Mongoose for modeling movie data. It makes writing MongoDB validation, casting and business logic a breeze.
- Create a new folder called
models.
- Create a new file called
movie`.jswithin
modelsfolder with the following content:
import mongoose, { Schema } from 'mongoose'; // Define movie schema var movieSchema = new Schema({ title: { type: String, unique: true, }, poster: String, genre: String, days: Array, times: Array, }); // Export Mongoose model export default mongoose.model('movie', movieSchema);
Populating MongoDB with Movie Data
Next, let’s populate the database with movie data.
- Create a new file called
populate.jswith the following content:
import mongoose from 'mongoose'; import Movie from './models/movie'; const movies = [ { title: 'La La Land', poster: '', genre: 'Drama/Romance', }, { title: 'Paterson', poster: '', genre: 'Drama/Comedy', }, { title: 'Jackie', poster: '', genre: 'Drama/Biography', }, { title: 'Lo and Behold Reveries of the Connected World', poster: '', genre: 'Documentary', }, { title: '10 Cloverfield Lane', poster: '', genre: 'Drama', }, { title: 'Birth of a Nation', poster: '', genre: 'Fantasy/Myster', }, { title: 'De Palma', poster: '', genre: 'Documentary', }, { title: 'Doctor Strange', poster: '', genre: 'Fantasy/Science Fiction', }, { title: 'Eddie the Eagle', poster: '', genre: 'Drama/Sport', }, { title: 'Pride and prejudice and zombies', poster: '', genre: 'Thriller/Action', }, { title: 'Finding Dory', poster: '', genre: 'Comedy/Adventure', }, { title: 'Green Room', poster: '', genre: 'Crime/Thriller', }, { title: 'Kubo and the Two Strings', poster: '', genre: 'Fantasy/Adventure', }, { title: 'In a Valley of Violence', poster: '', genre: 'Drama/Western', }, { title: 'O.J.: Made in America', poster: '', genre: 'Documentary', }, { title: 'Rogue One: A Star Wars Story', poster: '', genre: 'Science Fiction/Action', }, { title: 'Sing Street', poster: '', genre: 'Drama/Romance', }, { title: 'Zoolander 2', poster: '', genre: 'Comedy', }, ]; // Connect to MongoDB mongoose.connect('mongodb://localhost/movies'); // Go through each movie movies.map(data => { // Initialize a model with movie data const movie = new Movie(data); // and save it into the database movie.save(); });
- Open Terminal App and execute:
node_modules/babel-cli/bin/babel-node.js populate.js
Now we have movie data in the database, and the server can get it and serve to the mobile app.
You can use Robomongo to manage your MongoDB databases.
Movies Controller
Let’s create a controller that will be responsible for serving movie data.
- Create a new folder called
controllers.
- Create a new file called
movies`.jswithin
controllersfolder with the following content:
import Movie from '../models/movie'; import moment from 'moment'; // Hardcode the days for the sake of simplicity const days = [ 'Today', 'Tomorrow', moment().add(2, 'days').format('ddd, MMM D') ]; // Same for the times const times = [ '9:00 AM', '11:10 AM', '12:00 PM', '1:50 PM', '4:30 PM', '6:00 PM', '7:10 PM', '9:45 PM' ]; export const index = (req, res, next) => { // Find all movies and return json response Movie.find().lean().exec((err, movies) => res.json( // Iterate through each movie { movies: movies.map(movie => ({ ...movie, days, // and append days times, // and times to each }))} )); };
Set up a Router
Next part is a router, that will be responsible for handling incoming HTTPc requests and directing them to appropriate controllers.
- Create a new file called
router.jswith the following content:
import express, { Router } from 'express'; // Import index action from movies controller import { index } from './controllers/movies'; // Initialize the router const router = Router(); // Handle /movies.json route with index action from movies controller router.route('/movies.json') .get(index); export default router;
Update the Server
Finally, let’s update our server to connect to MongoDB and use the router that we just created.
- Open
server.jsfile and replace it with the following code:
import express from 'express'; import morgan from 'morgan'; import mongoose from 'mongoose'; import router from './router'; // Connect to MongoDB mongoose.connect('mongodb://localhost/movies'); // Initialize http server const app = express(); // Logger that outputs all requests into the console app.use(morgan('combined')); // Use v1 as prefix for all API endpoints app.use('/v1', router); const server = app.listen(3000, () => { const { address, port } = server.address(); console.log(`Listening at{address}:${port}`); });
It should automatically reload if you didn’t close it since we launched it the first time. And if you did, just execute
npm start to launch it.
Get the Data
Open in your browser. And you should see a JSON object with movie data.
What’s Next
In the next tutorial we’ll update our Movie Tickets Booking App to use the API we just built instead of javascript files to get movie data, and to use Redux to store and manage the data.
Wrapping Up
Hopefully, you’ve enjoyed the tutorial and have learned a lot. Subscribe to get notified about new tutorials. And if you have any questions or ideas for new tutorials, just leave a comment below the post.
Pingback: Storing Data From API with Redux in React Native Apps | Rational App Development() | https://rationalappdev.com/api-backend-with-nodejs-express-and-mongodb-for-react-native-apps/ | CC-MAIN-2020-40 | refinedweb | 1,338 | 55.84 |
Differences Between DTDs and Schema
The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.
The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, "terseness in XML markup is of minimal importance," there is no real concern with keeping the syntax brief.
TIP
The documentation provided by the W3C related to the Working Groups and Recommendations can be extremely useful in understanding the design philosophy and goals of a technology. If you are considering development work with a new technology, you should consult the W3C documentation to learn about the appropriate uses for the technology and to keep up with changes in a working draft or updates to a published Recommendation.
However, you might care if you are dealing with a complex Schema. Schema can become long rather quickly. In general, DTDs tend to be shorter, since the syntax is more compactnot necessarily any less convoluted, but usually shorter.
So what are some of the other differences which might be especially important when we are converting a DTD? Let's take a look.
Typing
The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it's such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, "XML Schema. However, if we are following the U.S. ZIP Code format, this is obviously not valid. Using XML Schema, we could actually create a datatype for ZIP codes using regular expressions (simply a pattern that matches a specific set of strings) that would limit the zip element to the standard 5-digit ZIP code. We could also create a datatype to deal with ZIP+4 if we wanted. For example:
<xs:simpleType <xs:restriction <xs:pattern </xs:restriction> </xs:simpleType>
makes use of a regular expression (in the pattern value) to see if the string matches the ZIP+4 format. We'll talk more about both datatypes and regular expressions in Chapter 12, "Representing and Modeling Data."
The ability to get that specific with the datatypes of the content for our elements and attributes is a very powerful aspect of XML Schema.
Occurrence Constraints
Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, "Schema Structure" (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.
The * allows you to specify that an element may occur any number of times, the + signifies that an element may occur one or more times, and ? limits the element occurrence to zero or one. So, let's say we have an element called carton, which can contain egg elements. Table 3.1 shows how we might use the DTD occurrence operators to limit the number of times the elements may appear in an XML document.
Table 3.1 Limiting Element Occurrences in a DTD
As you can see, these options are a little limited. For example, how often do you buy a carton of one egg? And are you aware of any cartons that can hold an infinite number of eggs? What if you wanted to define a carton that could hold exactly a half-dozen eggs? You could do that; the declaration would look like this:
<!ELEMENT carton (egg, egg, egg, egg, egg, egg)>
What if you wanted to be more flexible, and say that carton had a minimum of a half-dozen eggs, but it could store up to a dozen? That could be done in a DTD too, but it's ugly looking:
<!ELEMENT carton (egg, egg, egg, egg, egg, egg, egg?, egg?, egg?, egg?, egg?, egg?)>
That declaration specifies that there are six egg elements which occur once and only once, and then six more egg elements which may occur once, but don't have to. The result is that we must have 6 egg elements in our carton but we can have up to 12.
As you can see, the definitions for accomplishing this level of granularity are really ugly. Schema allow a much cleaner mechanism for occurrence restraints, the minOccurs and maxOccurs attributes, which allow you to specify the minimum and maximum number of occurrences of an element:
<xs:element <xs:complexType> <xs:sequence> <xs:element </xs:sequence> </xs:complexType> </xs:element>
This is a much cleaner mechanism for defining elements which have specific occurrence constraints. If you need this type of control over the elements in your schema, DTDs fall short. This is the up side of verbosity in XML Schema: The added descriptiveness allows Schema to be more human-readable.
Enumerations
An enumeration is simply a list of values. Surfing the Web, you encounter enumerations every time you come across a pull-down menu: The menu presents you with a predefined list of choices. Those choices, or enumerations, can be defined in a DTD for a list of attributes.
So, let's say we had a <shirt> element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:
<!ELEMENT item (shirt)> <!ELEMENT shirt (#PCDATA)> <!ATTLIST shirt size_value (small | medium | large)>
That would allow us to create an XML document that looked like this:
<item> <shirt size="medium">Cotton</shirt> </item>
We can also use a Schema to describe the same thing, an attribute called size that is an enumeration:
<xs:simpleType <xs:restriction <xs:enumeration <xs:enumeration <xs:enumeration </xs:restriction> </xs:simpleType> <xs:element <xs:attribute </xs:element>
But what if we wanted size to be an element? We can't do that with a DTD. DTDs do not provide for enumerations in an element's text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created a simpleType called size_values which we can now use with an element:
<xs:element
That would allow us to use the following XML:
<item> <shirt> <size>medium</size> </shirt> </item>
This kind of flexibility is directly related to datatypes, but it is still one way in which XML Schema can be more flexible than DTDs.
When You Should Use a DTD
Just because the W3C built it does not mean you have to use it. There are times when it will be perfectly reasonable to stick with the DTD you are currently using. Obviously, if your DTD is functional and you don't have any need to extend it, then chances are you might be better off leaving well enough alone. But let's say that you are developing a schema from scratch. When should you use a DTD instead of an XML Schema? Here are a few examples.
When Brevity Matters
We mentioned before that DTDs tend to be more concise than XML Schema. XML in general is not designed for brevity; it is a verbose language, which is part of what helps make it more human-readable. So, if brevity is important, you might want to see if you can accomplish your goals with a DTD instead of a Schema. Need proof? Take a look at an example of a DTD and a Schema, side-by-side, which both define the same thing, a schema for a TV Listing.
The XML Document we are defining the schema for looks like this:
<listing> <show> <title>Frontline</title> <cast>NA</cast> <rating>TV-PG</rating> <description>A PBS news/documentary</description> <date>April 1, 2004</date> <time>10pm EST</time> </show> </listing>
This is a very simple XML document. The root element is the <listing> element, which can contain multiple <show> elements, and the show must contain one each of the title, cast, rating, description, date, and time elements. Here is the DTD which would describe our TV Listing document:
<!ELEMENT listing (show*)> <!ELEMENT show (title, cast, rating, description, date, time)> <!ELEMENT title (#PCDATA)> <!ELEMENT cast (#PCDATA)> <!ELEMENT rating (#PCDATA)> <!ELEMENT description (#PCDATA)> <!ELEMENT date (#PCDATA)> <!ELEMENT time (#PCDATA)>
Because this example does not make use of any complex content models or even attributes, this is as straightforward as DTDs get. Let's take a look at the Schema that describes the exact same document:
<?xml version="1.0" encoding="UTF-8" ?> <schema xmlns=""> <element name="listing"> <complexType> <sequence> <element name="show" maxOccurs="unbounded"> <complexType> <sequence> <element name="title" type="string"/> <element name="cast" type="string"/> <element name="rating" type="string"/> <element name="description" type="string"/> <element name="date" type="string"/> <element name="time" type="string"/> </sequence> </complexType> </element> </sequence> </complexType> </element> </schema>
The Schema takes 22 lines of code to accomplish what the DTD accomplishes in 8 lines. Just comparing the two examples side-by-side shows that Schema are verbose, so if brevity is important to your needs, consider a DTD.
When You Want Users to Be Able to Override Definitions Easily
XML Schema use namespaces. In the previous chapter you saw how XML Schema use namespaces. Schema have one namespace declared for the Schema elements themselves (such as <element>) and another targetNamespace declared for the elements you are defining. With all of these namespaces floating about, it is easy to confuse them, or to create a namespace collision: a situation where there are conflicting references to a namespace. Practically speaking, that means that redefining elements using Schema can be complicated.
When would you want to redefine an element? Well, for example, if we defined an address element in an XML Schema, a user in the U.S. might want to redefine the element to conform to the U.S. address format, which includes a ZIP code:
1023 Easy Street
New York, NY 10002
while a user in the U.K. won't use ZIP codes, but instead would use postal codes:
2312 Kingsbury Way
Southhampton
Lincolnshire
3SW 1N2
With DTDs, redefining or overriding declarations can be pretty easy. It can be done within an external DTD using parameter entities, or it can be done in an internal DTD, contained within the DOCTYPE literal in an XML document. For example, the DOCTYPE declaration used to link an XML document to the DTD can also contain element declarations, attribute declarations, and so on, internally as well. If those internal DTD declarations are in conflict with the declarations in the external DTD, then the internal declarations are used.
Having both an internal DTD (contained in the XML document) and an external DTD (referenced in the document) makes it very easy to manipulate the DTD by extending or overriding the declarations. Of course, XML Schema have methods to import or include other XML Schema; however, doing so is not necessarily trivial, and in fact can be quite complex because of namespace issues that might arise from having two elements with the same name, and keeping track of the various namespaces elements belong to. So if you are using a base schema, but have the need to easily override or extend that schema, a DTD might be a better choice than XML Schema.
When You Have Mostly Text Documents
Everyone talks about the power of XML Schema, especially the power of datatypes. And it is true that datatypes offer a high degree of flexibility and power that was not possible before with DTDs. But not everyone needs that kind of flexibility and power. What if your needs center around large-scale documents which are mostly (if not entirely) text?
Some examples might include manuals, documentation, encyclopedias, and dictionaries. While these might have some elements used for indexing and cross-referencing, the majority of the elements might simply contain large blocks of text.
That's a perfect example of the type of document which might not benefit from an XML Schema. In fact, those types of documents might even benefit from DTD usage, since there are fewer differences between an XML and SGML DTD, and many document solutions were originally built around SGML, making it faster and easier to port an SGML DTD into and XML DTD than into an XML Schema.
If your uses for XML are mostly large blocks of text, then you might want to just stick with DTDs. Unless there is a compelling Schema feature which is essential to your document needs, chances are a DTD will satisfy your schema requirements adequately, and quite possibly more efficiently.
If Your Tools Don't Support Schema
You spend six months researching, designing, and writing the perfect XML Schema. It is a thing of beauty, designed to anticipate your every data need. It is compatible with your database Schema and it describes your XML document perfectly. It allows you to do things you could have never done with a DTD, and even though you don't need that functionality now, your foresight will pay off tenfold in the future. You are proud of your work.
And then you discover from your Web department that the parser it has chosen to use for implementing XML in conjunction with your Web site doesn't support XML Schema.
XML Schema are a fairly new technology. If the tools you rely upon everyday in order to be productive don't support XML Schema, then you might just have to stick to DTDs for a while. That doesn't mean you can't think about XML Schema, or learn how you might use them in the future. But in the meantime, if your software doesn't support XML Schema, it won't do you much good to use them. | http://www.informit.com/articles/article.aspx?p=24614&seqNum=3 | CC-MAIN-2019-09 | refinedweb | 2,372 | 59.53 |
Microsoft Office Tutorials and References
In Depth Information
Note Table 7-1 does not include a column for week number. The table omits it because there
are several techniques for calculating the week number in a year, and different businesses have
different ways to make this calculation. More important, sometimes a week belongs to a year
that is different from the calendar year—the fiscal year, for example—even if only for a few
days of a year. In that case, you also need to define a WeekYear column that must be used for
browsing the weeks in a meaningful way. We preferred not to include a specific week
calculation to keep the Dates table simple and to avoid possible confusion introducing an algorithm
that might be different than that used in your company.
Now you can import this table in PowerPivot as a linked table. The result is shown in Figure 7-9.
FIguRE 7-9 The Dates table imported in PowerPivot as a linked table.
You can see that the month name contains the month number in front of it, so December is
described as 12 – December . It is useful to have the month names automatically sorted. However,
if you want to sort month names but also want to avoid the initial number, please take a look
at the section “Custom Sorting in PivotTables” in Chapter 8, “Mastering PivotTables,” where we
describe how to sort columns of a Dates table in a PivotTable.
You might want to change the data types of some columns in the Dates table. Whenever you
import the Excel table into PowerPivot, columns like Year, MonthNumber, and Day are usually
defined as Whole Number data types. For this reason, when you select one of these columns
in the PivotTable, the selected attribute is placed by default in the Values area of the PivotTable
and is aggregated when you use the Sum function. You might prefer to change the data types
of these columns to Text so that by default they are used to group data in rows.
If you want to test your new Calendar table, you should now import the SalesOrderHeader,
SalesOrderDetail, Customer, and Product tables from the AdventureWorks database into
the same PowerPivot model. Relationships between these tables are automatically detected
during the import. At this point, you need to create a relationship between the OrderDate
field of the SalesOrderHeader table and the Date field of the Calendar table you just imported.
Before starting, in PowerPivot you have to rename the Calendar table to OrderDate so that
it expresses the dates it represents. Then you click the Create Relationship button on the
Design tab of the ribbon and ill in the dialog box, as shown in Figure 7-10.
Search JabSto ::
Custom Search | http://jabsto.com/Tutorial/topic-22/Microsoft-PowerPivot-for-Excel-2010-228.html | CC-MAIN-2018-09 | refinedweb | 461 | 57.91 |
Problem Statement.
Design (state: draft)
The OData protocol already has the constructs necessary to express navigation property URIs in the form of standard <atom:link> elements. For example, the following is the atom representation for an Order Entry which has a navigation property Order_Details expressed as an <atom:link>.
Following this pattern, the URI needed to address the relationship between entities can also be expressed as a link element in the following form:
<link rel=”<relationshipPropertyName>” type=”application/ xml” Title=”< relationshipPropertyName >” ” href=” relatedLinksURI” />
Where:
– relationshipPropertyName is a navigation property name as defined in CSDL associated with the datat service.
– relatedLinksURI is URI which identifies the relationship between the Entry represented by the parent <entry> and another Entry (or group of Entries) as identified by the navigation property
The example below shows an Order entry with a link element (as described above) that represents the orders’ relationship with OrderDetails as a response to the following GET query ””.
For JSON we would use “associationuri” to hold the relationship URI. As shown in the example below the associationuri would be a sibling of the uri property on a navigation property.
In the case of expanded relationships (using data services $expand operator) the associationuri would be placed before the “results” of the expanded related entities. For example the following GET query request “ /Orders(1)?$expand=Order_Details&$format=json” would produce the following server payload: Moustafa
Program Manager, WCF Data Services
This post is part of the transparent design exercise in the Astoria Team. To understand how it works and how your feedback will be used please look at this post.
I like the idea of encoding the relationship information w/o resorting to URI convention. But the suggested use of the rel and title attributes is, I suspect, going to cause trouble for state machine clients.
I’d like to see something like:
<link rel="relationship" href="{uri-to-details}" />
IOW, offer a <link /> that points the user agent to a resource that contains the details you are trying to encode into your REL and TITLE attributes.
This will give the most flexibility, prevent OData from encoding resource-specific information into relation links, and prevent OData from overriding the use of TITLE.
I am just looking at the Data Service Provider toolkit and I notice several things.
1.) You need a huge amount of code to expose the most simple classes like
public Class B
{
public string NoIdProperty {get;set;}
}
public Class A
{
public B MyB { get;set; }
public int MyIDProperty { get; set; }
}
2.) You do really messy things like in GetQueryRootForResourceSet(ResourceSet) function
3.) The whole System.Data.Services.Providers Namespace is as good as undocumented
4.) The whole namespace thing smells like entity framework to me
5.) The whole error reporting/debugging is not even close to real life requirements. I definately need more details that just "Something blew up somewhere".
I really love the idea of a WCF Service that exposes objects and I love the whole basic concept behind data services.
Maybe I am just too stupid, but so far for me it looks the current ADO .NET Data Service implementation will probably never match my expectations.
Maybe you should think about dumping the current implementation and start a rewrite that is focused on exposing objects (not just entity framework) from the scratch. Trying to fix the current code base seems to be a big waste of your and my time. But at least you should do your homework in regards to documentation before thinking about extensions.
Cheers,
Tobias
Tobias,
Answering your points in turn…
1) There is no doubt that the most simple path – the one we originally optimized for – is EF.
However the reflection provider is pretty simple too, and is designed to make it easy for you to take custom classes and expose then as a Data Service.
The first step is to create a ‘Context’ class to represent the model of you Data Service, something like this for example:
public class Context
{
private List<A> _As; // TODO: Initialize some how.
private List<B> _Bs;
public IQueryable<A> As {
return _As.AsQueryable();
}
public IQueryable<B> Bs {
return _Bs.AsQueryable();
}
}
And then on your classes Identify the Key properties using the [DataServiceKeyAttribute] like this:
[DataServiceKeyAttribute(“NoIdProperty”)]
public Class B
{
public string NoIdProperty {get;set;}
}
At this point you can expose your classes as a DataService simply by using
public MyDataService: DataService<Context> {…}
The service will be readonly, but you if your Context class also implements IDataServiceUpdateProvider (like the L2S example we posted on CodeGallery) then you have a readwrite service.
Finally if the reflection provider doesn’t give you enough flexibility then you need to implement a full Data Service Provider, which is admittedly not trivial. But then it is a very advanced API, which we don’t expect many developer to need to implement.
2) See above
3) Both My Blog [] and the OData SDK – DSP toolkit [] cover writing custom providers. I hear your frustration though, it is clear we need more guidance around the reflection provider, we’ll work towards that soon, in the meantime feel free to contact us again if you need help.
4) Namespace is a pretty platform and technology agnostic thing, it is simply a way of avoiding naming conflicts while keeping simple names. The web is built on the same principle. There must be millions of about.html pages out there – simple name – disambiguated by the rest of URL.
5) Have you seen DataService<>.HandleException(..) & DataServiceConfiguration.UseVerboseErrors which you can turn on in your InitializeService method? Both of these simplify tracking down issues in your DataService.
Hopefully my answers to both (1) and (2) cause you to rethink your assessment. I personally have spent a lot of time writing DSPs etc, and can say that there exist a lot of opportuntities to make things even better, and the beautiful thing is that most of the interfaces and APIs are public so you / others don’t necessarily have to wait for Microsoft to take the lead.
Please let me know if you have any more questions
Alex James | https://blogs.msdn.microsoft.com/odatateam/2010/04/05/relationship-links/ | CC-MAIN-2016-30 | refinedweb | 1,016 | 50.77 |
Do you see CSS4 as the end of CSS preprocessors?
The way I think of it, Sass is only as powerful and CSS allows it to be. As CSS get more features and extensibility, Sass can leverage that to be a better abstraction.
We see this happening in JavaScript where ES2015 and better DOM APIs have seen the rise of paradigms like React.
If you look at the progression of the CSS specs, they honestly aren't focusing on increasing the complexity of the language and it's syntax. What they are instead focused on is what you can do with the selectors and properties you have. Think, Flexbox and all the lovely features we've been getting.
Further, there are things that just don't make sense for the browser to ever implement.... Sass (and other processors) do a lot of bundling, merging, splitting, importing, etc. Things that just simply make sense on the server side.
No matter how powerful the low-level OS language Assembly gets, your probably going to prefer to use a language one step up, so you can compile and optimize and handle all sorts of nice things we get from higher-level languages. CSS is the core of what's possible, and Sass is trying to make it powerful and easy from a coders perspective.
Frontend Engineer | Hashnode Alumnus
What's your opinion on Styled Components and "CSS in JS" techniques in general?
Personally I'm fan. Co-location of styles and components is a really great experience, but they don't necessarily exclude using Sass. Using Sass with CSS Modules is 👌
Yeah, before this AMA, I was coding in my
StoreSelector.scss file in a React app. I love styling components individually. Especially I like organizing my SCSS with my JS into Atomic Design elements. :)
Honestly, I challenged myself to use plain CSS in that build platform, and it just started to get really freaking annoying to do BEM. Not having nesting and some basics was :thumbsdown:
Idea Incubator
Are there any major benefits of using Sass over Less ?
A better question is there any benefit of using Less over Sass. As I see it, there's very little. The main reason used to be in-browser implementation, but the upcoming release of Dart Sass will enable that. I honestly don't see any reason to use Less anymore, unless you like the syntax better but it's purely an aesthetic choice at this point. Sass has a bigger community, more robust implementations, and is faster with libSass.
Devlooper
What advices would you give to developers learning Sass for the first time?
Great question!
Sass is often times one of the first languages people learn. One of the great parts, is that if you only know CSS and HTML, you can just start using Sass just like you used CSS, and you can slowly add in features as you learn them. Nesting is usually the first thing people refactor their CSS to do, but there are lots of other features to familiarize yourself with.
If you are familiar with other languages, then there are only a couple unique concepts that you need to learn. Most everything else is pretty freaking boring (in the good way!).
There are a lot of great resources out there for getting started with Sass like
My suggestion is to not over use Sass. Instead focus on writing good CSS and incrementally adopt Sass features a bit at a time as they make your life easier.
Front-end Designer
With native variables coming in, a nesting spec in candidate recommendation and other interesting features pouring into CSS, Do you think there will be a time when Sass will no longer be needed?
Unfortunately, backwards compatibility and the need for very fast parsing on the client has forced the official specs to resort to syntax that is less than ideal. I do think there will be a time in the next few years where people can reasonably get by without Sass, but it's our plan to provide better ergonomics to the upcoming CSS features and compile to more optimal output that CSS provides.
I don't know... maybe!
But, not everything is appropriate to do in the browser. I'd be surprised if we ran out of language-and-syntax improvements that wouldn't be worth the compile time while devving.
Front-End Developer, Free Code Camp student and aspiring Full Stack Developer
What new features/updates can we look forward to in the future?
Sass modules are the big feature of Sass language version 4. I wrote about them in this question
Once we have a module system, we intend to greatly expand on the Sass standard library.
In the near future you can look forward to being able to invoke a mixin whose name is stored in a SassScript variable.
I am the CEO of an Application Hosting Company -
Whet is next on the Sass Roadmap? Are you looking to enhance performance on the framework - or implement any new features to help make the Saas experience better?
I can't speak to new features, but LibSass and Dart Sass have addressed the performance of Sass - they're fast!
What is the correct term to refer to a developer who uses Sass:
To me, it's definitely Sasstronaut.
We even have bands that say it!
I've always liked "Sass Assassin". But honestly, I don't care... just don't be a Sasshole.
Javascript
Are there any major benefits of using Sass over postCSS?
Honestly, we have no beef with the postCSS team, but if you checkout their marketing, they definitely aren't fans of ours!
postCSS is great for prefixing and other last-second optimizations... in fact, I use it with Sass in most of my projects. They can do some stuff we just can't (or don't think we should) do magically with an actual language like Sass.
And yeah, you can use postCSS with enough addons and magical features to make it pretty much look and act like Sass, but the downside is that you've built an entirely non-standard sub-language yourself.
One thing that we really pride ourselves on in the Sass-team is that we really think through every single language feature we add. Natalie, the lead designer of the language, is extremely picky about what goes in. We consider all angles of how a feature would affect our user base now, and with respect to what the W3C is planning in the future. It's a lot more complex than you'd think!
So, I use Sass still, because I want some more powerful language features but I also want to make sure that the next maintainer of the project will have a standard understanding of the code. And, I know how strict we are with ensuring that we do right by our users with stability and predictability.
The big thing that keeps bringing me back to Sass is that it's batteries included. When a codebase is using Sass I immediately know which features are available to me. With postCSS offloading it's features to plugins, I need to know which plugins are being used in a project.
Additionally in a plugin based world there are ongoing costs like handling plugin upgrades, and dealing with plugins that get abandoned.
Batteries included solutions like Sass let me focus on my code.
Coder, Christian
Should browsers support
.scss in future, by-default? Will that be a good option?
No. Sass was designed to be compiled to CSS. It has proven the demand for more powerful syntax and abstractions, but the right thing to do for CSS is to design new language features that can take full advantage of the runtime nature of CSS and the document in scope. A prime example of this is CSS custom properties (CSS Variables) which inherit down the document -- a capability that Sass could never have implemented as a preprocessor and wasn't ever considered when we were designing it.
How are the module features coming along?
The module features got very delayed as Sass has moved away from Ruby first to enable the libSass port and then as the reference implementation is moving to Dart. The initial design phase is complete. It's heavily inspired by Dart's module system in terms of how things are imported and exported from modules.
You'll be able to do things like import a CSS file as a mixin and include it where you want it in the current stylesheet.
A main goal of the module system is to avoid namespace collisions. Sass's global namespace has long forced Sass libraries to do namespacing on their own which was annoying and error prone.
Another big benefit of Sass modules is that they form a scope for the @extend operation -- this means that you won't have to worry about
@extend .last accidently bleeding into a part of your website that you didn't intend.
A lot of the newer features people are experimenting with in CSS are client-side only, and can't be compiled, predicted, or rendered in advance. Do you foresee the need (or popularity) of client-side re-processors in addition to preprocessors? What new features could client-side re-processed Sass include that aren't possible to support in its current form as a preprocessor today?
Fantastic question!
Hell yes this is going to be a thing (sort of). In fact, things like
calc() and CSS variables and browser-based-units (em, etc) are already doing this kind of thing.
I don't think the right mental model is 're-processed' though. I think the right way to think of it is the Javascript execution environment will be deeply intwined and communicating with the current styles and styling rules. Right now, there is communication mostly moderated by the DOM.
CSS => DOM <=> JS... I think the new model will include a full two-way conversation between CSS and JS, including manipulation and response.
For instance, wouldn't it be cool to implement a JS-based constraint system? Imagine if you could say
body { display: constraint-based; } and it would trigger whole new CSS properties and layout behaviours!
CSS optimization is very hard to do outside of the context of a document -- but it's not clear how it would work client side as dynamic changes occur. Like a JIT, you'd need to know when you've violated your optimization assumptions and deoptimize.
In general, I see atomic css as being very fast for browsers to match against, but lacking the ergonomics I crave. I'd like to see tooling bridge this gap, but my sense is that it has to be done at build time with template awareness/rewriting and requiring hints for dynamic changes.
I am the CEO of an Application Hosting Company -
What difficulties did you face when producing the Saas framework? Also what are your thoughts on CSS preprocessors? Thanks.
That first question is pretty tough to answer. Honestly, one of the hardest things to do in an OSS project is keep your effort up and make sure everyone is getting along. It's working for free, in public, with your personal time. There are great benefits, knowing you are helping the world, but the sheer amount of continuous effort is staggering. I mean, Natalie has been coding pretty consistently on the project for EIGHT years now. I only coded a little in the beginning, but she's just kept it up. Maybe taking 6 months here and there to focus on herself. I think Chris has been doing it for 7 years too!
Burn out is all to easy.
Now, the second question... that's easier to answer. I think they're fine. I use autoprefixer in most of my projects. It's cool.
But, I don't use it for hand-constructing a kind of one-off language with a lot of transformers. The fact that Sass is a stable language to build off of is something I think that's a Good Thing(TM).
Also, I do like the idea they have of exposing the tree for manipulation. That's something we've been looking at in the LibSass/Node-Sass project for a while and postCSS is a great example of why that kind of thing is powerful.
What are some of your tips for organizing huge CSS projects?
I'll plug my Sass framework Eyeglass here. It allows you to distribute Sass files and related assets as npm modules. At my work we use this to distribute re-usable parts of our style like our theming system to many applications.
Lots of people like to have a
variables file and
mixins and
partials directories. I'm really not a fan of this approach. Keep related code together and minimize bouncing around from file to file.
To that end, within an application, I suggest organization by product and feature with cross cutting theme or design language shared by all of those.
My team also uses Eyeglass. We distribute all our components as npm packages. Each component has a first class mixin API, and a settings map.
This is a general question for all three of you! :)
What dev tools do you use daily?
Most of my day to day front-end work is React. Webpack, Chrome devtools, Google, and console.log are my most valuable tools :)
Languages: Java 8, ES6, Ruby, SQL.
IDEs: Jetbrains based IDE's... specifically Webstorm and IntelliJ
Frameworks: Create-React, Dropwizard, Rails.
I'm a FullStack Web Developer from PY
Which is the recommended way to use Sass with React? Should I merge my Sass code with the .js code, or should I put my Sass code apart from the .js code? Do you guys know a tutorial, article or something about this? Hampton, please, show me some light about this, you are using React in Rent the Runway, right?
There's no one right way. Do what works for you and your team. Most of my dat to day is still stand-alone compiled CSS and JSX files. On newer projects I like using CSS Modules to import my Sass into React.
This is a great overview
The official "Create-React" app puts a twin CSS file next to the JS file. That's what I do.
Store.js and
Store.scss sit next to each other. And in
Store.scss I wrap everything in
.Store which is the class of the React Component.
Except Sass, which CSS preprocessor would you recommend?
I use several postcss plugins along side Sass in development: autoprefixer, rtlcss, postcss lang optimizer. The ability to work directly with the AST in postcss is very powerful for a certain class of CSS processing -- especially those cases where you rarely, if ever, want to opt-out of the change.
For traditional preprocessors I couldn't imagine using anything other than Sass.
Things like Styled Components are really great too.
I am the CEO of an Application Hosting Company -
Name one word to describe your framework.
Hey there
What's your opinion on beginners learning CSS preprocessors without learning CSS properly? Do you think it'll help them?
I think it's fine. Sass is a fairly thin abstraction over CSS so when you're writing Sass you are writing CSS.
I do think it helps, but I know there's a vibrant discussion within the community on this. In my opinion, it's easy to get stuck in the weeds and lose your momentum when you're first learning CSS. With Sass you can find your stride sooner even if you don't fully grok what's going on under the covers. And then, over time, you can read various mixin definitions and see how they work. I think it's good scaffolding for learning but it really depends on if you're a project based learner or a first-principles based learner.
Coder, Christian
As you mentioned "Sass is only as powerful and CSS allows it to be"..
What are the top 3 CSS features is in your wishlist that Sass can leverage?
Okay, well, I immediately know one.
@extends in the browser. Right now, we have to do all sorts of gross-dark-magic things to make
@extends work in Sass. It's complex and it mostly-works... but it's complex because we don't know the DOM. If we knew the HTML, we could be super efficient about it.
Something with the functionality of
@extends would be trivial in the browser, and then we wouldn't have to do it. We only built it because there were so many good use-cases that it overrode our concerns about complexity and maintainability.
Another thing I really want is a good CSS-JS bridge.
Oh, and I'd love it if nesting was supported. We could still compress our output, but we wouldn't have to repeat selectors over and over in our output!
Front End Web Developer in T Brand Studio, The New York Times
How might Sass evolve to support deeper integration with JavaScript-oriented front end toolkits?
Well, there are two ways to do this. First, there are adding hooks that would allow server-side or compile-time Javascript to hook in. We already have a large number of these implemented in Node-Sass, however, (Michael can correct me if I'm wrong) we still haven't exposed our whole tree in Javascript objects yet for wholesale manipulation. I know we've talked about it, and I know some work has been done on it. Something we definitely would love to support in Node-Sass.
The second way is integrating with browser JS. This is something that Tab Atkins has been working on.. and in fact, functions like
calc() and variables are the first steps in integrating JS and CSS in the browser. This is something I'm personally really excited about. Would allow for some really interesting future developments (alternate layout methods!)
Thank you, Hampton! I put
calc() and variables together based on your earlier answer, and I'm curious to run some experiments with that approach in the future.
I am the CEO of an Application Hosting Company -
What inspired you to create the Saas framework?
How did you get the idea to develop Sass?
A front-end developer told Hampton "Wouldn't it be neat if CSS was like Haml?" and they were wrong but Hampton did it anyway.
A couple years later, I found mixins were a great way to create very bloated CSS and so I worked with Natalie to make them more powerful and built a framework based on it.
Over time, we discovered the actual good use cases for the tool we had made :)
I was working with two really great CSS developers back in 2006-ish when I worked at a company called Unspace in Toronto, Canada (no, I'm not Canadian). They were both brilliant and the tooling they had was shit. They would hand code ONE GIANT CSS file for our projects, and they would scope their selectors by hand-typing over, and over again the root selector... it would look like this:
.parent .child a { ...... } .parent .child a:hover { ...... } .parent .child .under { ...... }
They'd have hundreds of these. And, my god... if we had to change a color, it was find-and-replace-hell.
Anyhow, I went to Rails Conf 2007. At the time Natalie was just graduating high-school and living in Seattle and she had basically taken over development of Haml at this time. So, we asked her mom if we could fly her to Portland to hang out with the Unspace team and attend her first conference. And, amazingly, after some awkward parent-adult phone calls, she was allowed to come.
While there, I had been drawing up some plans for what Sass could be ('Sasstastic' was the original name). That was the original syntax that was inspired primarily by Haml. I remember between some talks, I found a side conference room, and I pitched Natalie and Jeff Hardy (now at Basecamp) about my ideas.
I think at first Natalie was pretty skeptical, but by the time she was flying home, she had taken my original testing commit and was starting to build out the Ruby Sass engine.
Originally, that interpreter was a sub-folder in the Haml project! In fact, I think it lived as part of Haml for a long time.
A couple weeks later, we released a version of Haml (would have to google to know which one) that included the first version of Sass. Whitespace sensitive. Nestied. Simple variables. I think mixins were there too.
It took us until after Less was released to actually break Sass out into it's own project.
Software developer
As a beginner which one is better to learn Sass or Less?
I only have one problem with Less, and it's the way they use classes-as-mixins. It just makes me uncomfortable somehow.
But, that's personal preference. Honestly, they are pretty similar, but Sass is a little more standard, plus I invented it, so obviously I have to say that. :)
Looking back at the history of CSS & Sass, is there a list of new CSS features that you attribute to direct influence from Sass? For example, jQuery is credited with bringing things like
document.querySelector() to JavaScript, after years of Sass how has it shaped CSS as a language?
Honestly, not a ton. I mean, variables are an obvious example. And tons of things that were proposals, but if you look at how CSS is actually expanding as a language, it's generally not expanding as a "language", which has always been Sass' focus. CSS is expanding it's features with new selectors, new attributes, and new ways to integrate with browser-based JS.
We always hope and work with the W3C to help push Sass-like features that should be in the browser. For instance, we <3 Tab Atkin's CSS variables, not because they 'replace' pre-browser rendering, but because they allow users to work with browser-only constructs like 'em' units, etc. Something we just simply can't do until the font is chosen in the actual user's browser.
Sass has inspired CSS Custom properties, the
calc() function. There's a CSS
@apply directive coming which is a barebones
@include without mixin arguments. CSS will soon allow nesting. The ability to nest
@media and
@supports etc came first from Sass. The new CSS color module is inspired by Sass's color functions.
The CSS working group watches what we do here and reacts. That we're able to prove demand with Sass really greases the wheels in those discussions. For many years, the working group held that concepts like variables were just too complicated for CSS developers -- Sass showed them it wasn't. :eyeroll:
When React Native comes, will sass/less die?
Hmmm... I'm not really sure what you mean. React Native is already out. I've been playing with it.
I'm not sure how it's related to Sass and/or it's death.
Software Engineer
What is the difference between SaSS and CSS?
Sass' SCSS syntax is largely a superset of CSS so the difference is whatever you want it to be. Variables? Mixins? Functions? Maps? Pick whichever feature makes your life easier.
Programmer, Entrepreneur, Author
What future awaits Sass regarding features? Anything new planned to come and make our web dev lives easier?
a variety of things, most include time wasting
Are there any projects out there that use Atomic design principles with Sass, webpack, vue/React/any component structure that you'd refer someone to if asked how to implement a maintainable large scale application in a team environment?
I have one at Rent The Runway... but it's not open source. :)
Thanks!
Frontend Developer
Will CSS go SASS only? Meaning that browsers will supports SASS?
Learning the development ropes
What CSS naming convention would you suggest for the most optimal use of Sass?
There's never a one right answer. It depends on your team, your constraints, and your tools. I personally love BEM.
What's about the two language modes .scss and .sass. It feels to me that the former one is far more supported and widely used in contrast to the latter one. What are your thoughts about it and how do you handle current feature releases for both modes?
SCSS is the primary language syntax. We do try to keep support for the original syntax. Sometimes things slip through when we forgot to test on it, but that's usually just new features. No reason to remove it, in our book. It's the same backing code.
front-end developer
What was the most interesting scssy code refactoring you've ever done in a project? Could be just the concept not the actual code. (although that would be awesome!)
A couple years we broke up our monolithic Sass framework into individual components backed of Bower. The design process for how we make those many components fit together easily, and maintain painless theming was fun!
Artist & Technologist
Are there some weird bugs in the Twitter Bootstrap Sass project? I'm getting this horizontal scrolling bar only during specific widths. The row class is causing it. It's unusual.
That's a great question for the Bootstrap team. You can file a bug against them here:
Hey there
Sass is so good that I can't stop myself from using nesting feature. What level of nesting is good according to you?
I like zero amounts of nesting for large projects. But some aspects of state are best managed at the document or module level so for those, I allow 1 level of nesting. This is a great article on this subject.
JS Developer
How do you autoprefix in Sass?
With postCSS.
No, really, that's what I do in my build-stack.
Eventually we want that in Node-Sass as an extension, but for now... I just use
autoprefixer
We also use autoprefixer. It's the right tool for the job :)
Software Engineer. Cupcake lover.
Why SCSS? Just to make the Sass syntax easy or was there some other reason behind it?
Oh, simple. SCSS is CSS compatible. So, if you are at a company, you can add Sass to your build-chain and coworkers who don't want to use it... don't have to!
Also, all of your old code works (as long as it was valid!)
Adoption was slower when you had to 'learn a new syntax'. SCSS made Sass just... CSS++
I use SCSS syntax now (it's the default), but I do really miss the
+myMixin syntax.
I can't speak as to why, but I can say that I would never have used Sass if it weren't for the SCSS syntax. It greatly eased the transition of the 1000s of lines of CSS we had.
Sass is so close to CSS that a new syntax, wildly different syntax, is a cognitive burden. | https://hashnode.com/post/sass-team-cj0j8hjmy0005f5533xzd86xs | CC-MAIN-2021-39 | refinedweb | 4,544 | 73.68 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have a series of points culled from a kinect point cloud (basically only those points relevant to the person, any past a certain depth are ignored)
I am having trouble choosing the appropriate tool in he_mesh to generate a mesh of these point clouds. I have been going through the examples and the references but I cannot seem to find the most appropriate method for achieving this.
If I set things up using the triangulate2d, I lose any depth information, resulting in a flat plane in the shape of the silhouette
I tried triangulate3d, but I get tetrahedra, which don't really feel like they are the right tools for this. I am hoping for a mesh I can use to finagle some awesome things out of. The example with the tetrahedra is... not that.
So, in short, what would be the best way to generate a mesh whose surface is composed of specific points from a Kinect point cloud? I'm not interested in the back of the mesh right now.
This is the code I have so far, minus the he_mesh stuff that would let me explore further.
import org.openkinect.freenect.*; import org.openkinect.processing.*; import java.util.List; //for the hemesh stuff import wblut.hemesh.*; import wblut.core.*; import wblut.geom.*; import wblut.processing.*; import wblut.math.*; ///for the gui control import controlP5.*; // Kinect Library object Kinect kinect; //for the hemesh stuff HE_Mesh firstMesh; WB_Render3D renderMesh; int[] tetrahedra; boolean makeMesh; boolean newMesh; ///for gui controls ControlP5 sliderStuff; ///for control values int dCutoff = 848; // Angle for rotation float a = 0; //to store points from each frame of kinect //WB_Point[] points; //List <WB_Coords> points List <WB_Point> points; // We'll use a lookup table so that we don't have to repeat the math over and over float[] depthLookUp = new float[2048]; void setup() { // Rendering in P3D size(800, 600, P3D); kinect = new Kinect(this); kinect.initDepth(); // Lookup table for all possible depth values (0 - 2047) for (int i = 0; i < depthLookUp.length; i++) { depthLookUp[i] = rawDepthToMeters(i); } //slider to remove points past a certain depth from consideration. sliderStuff = new ControlP5(this); sliderStuff.addSlider("dCutoff").setPosition(10,10).setRange(0,2048); ///only make the mesh once makeMesh = false; newMesh = false; } void draw(){ background(0); text("depth cutoff: " + dCutoff,60,60); pushMatrix(); // Get the raw depth as array of integers int[] depth = kinect.getRawDepth(); translate(width/2, height/2,0); int skip = 8; points = new ArrayList <WB_Point>(); for (int x = 0; x < kinect.width; x += skip) { for (int y = 0; y < kinect.height; y += skip) { int offset = x + y*kinect.width; // Convert kinect data to world xyz coordinate int rawDepth = depth[offset]; if (rawDepth<dCutoff){ PVector v = depthToWorld(x, y, rawDepth); stroke(255); pushMatrix(); // Scale up by 200 float factor = 200; translate(v.x*factor, v.y*factor, factor-v.z*factor); /* used for when points was an array points[x+y*(kinect.width/skip)][0] = v.x; points[x+y*(kinect.width/skip)][1] = v.y; points[x+y*(kinect.width/skip)][2] = v.z; */ points.add (new WB_Point(v.x, v.y, v.z)); // Draw a point point(0, 0); popMatrix(); } } } if (makeMesh & newMesh) { //tried this, have no idea what to do with tetrahedra //WB_Triangulation3D triangulation = WB_Triangulate.triangulate3D(points); //tetrahedra=triangulation.getTetrahedra(); //confirms that there are points being generated println ("there are "+points.size()+" points"); //HE_Mesh thisMesh = new HEC_FromTriangulation().setPoints(points); //this next line results in a Null Pointer Exception, but the previous line works so: ?? firstMesh=new HE_Mesh(new HEC_FromTriangulation().setPoints(points)); firstMesh.smooth(); newMesh = false; //only make the mesh once } if (makeMesh){ pushMatrix(); directionalLight(255, 255, 255, 1, 1, -1); directionalLight(127, 127, 127, -1, -1, 1); /* //translate(-objectRadius,-objectRadius); renderMesh.drawFaces(firstMesh); */ rotateY(mouseX*1.0f/width*TWO_PI); rotateX(mouseY*1.0f/height*TWO_PI); for(int i=0;i<tetrahedra.length;i+=4){ WB_Point center; pushMatrix(); /*draw the mesh stuff al'a your suggestion here popMatrix(); } popMatrix(); } popMatrix(); } void keyPressed(){ if (key == 'r') { if (makeMesh){ makeMesh = false; newMesh = false; } else { makeMesh = true; newMesh = true; } } } // These functions come from: float rawDepthToMeters(int depthValue) { if (depthValue < 2047) { return (float)(1.0 / ((double)(depthValue) * -0.0030711016 + 3.3309495161)); } return 0.0f; }; }
Answers
Hi @gersart,
I realise you posted this question more than a year ago and that you've probably moved on but I feel like it'd be better to provide an answer anyway, hoping it will be useful for future forum users.
I had the same problem you're describing (trying to compute 3D triangulation with Hemesh) and with the precious help of this this forum I could come up with a rather simple solution: using the Triangulate library by Nicolas Clavaud instead.
The library is available here
You can find an example sketch here
For a 3D example sketch you can have a look at the script I posted on this thread (post from may the 3rd, it's in Python but really easy to understand).
Hope that helps.
didn't stop you bumping those other threads that were from 2015
@koogs I'm confused, is it a problem ? I did it because I thought it could be useful for future forum users. I've personally spent a lot of time reading all these questions regarding 3D Delaunay triangulation hoping to find a proper solution. Sharing this workaround is a way for me:
Please tell me what is your opinion/guidelines on "bumping" old threads. | https://forum.processing.org/two/discussion/21320/can-one-use-he-mesh-to-triangulate-a-kinect-point-cloud-if-so-how | CC-MAIN-2019-43 | refinedweb | 921 | 60.45 |
Overview
Task scheduling refers to executing a task on a particular time frame or repeating the task by running a process in a fixed interval. Spring boot provides
@Scheduled and
@EnableScheduling annotations for configuring and scheduling tasks, periodically. Spring allows us to configure the parameters of the @Scheduled annotation by scheduling a task on a fixed rate, with a fixed delay, custom intervals, etc. In this article, we will discuss how to schedule tasks in a Spring boot application.
The thumb rule that needs to be followed to annotate a method with @Scheduled is that the method should not expect any parameters and must have void return type.
Project Setup for enabling scheduling in a Spring boot application
We can create the skeleton of our Spring boot project by using Spring Test Suite(STS), as usual. Creating a scheduler with Spring boot is straight forward. We need to add the
@Scheduled annotation to any method that runs automatically and include
@EnableScheduling to one of our
@Configuration classes. We do not need any additional dependencies to enable scheduling.
To enable scheduling, all we have to do, is annotate our main class:
@SpringBootApplication @EnableScheduling public class DemoScheduleApp { public static void main(String[] args) { SpringApplication.run(DemoScheduleApp.class, args); } }
Scheduling tasks
We can schedule Spring boot tasks by using @Scheduled annotation provided by Spring. But, based on the configuration of `fixedRate` and `fixedDelay` properties, the nature of execution of the tasks changes. Now, let’s configure the parameters of the @Scheduled annotation to schedule the time at which a task will run.
Scheduling a task with a fixed rate
The main job of a scheduler is to schedule the tasks. Spring Boot makes it easy to schedule a task by annotating a method with the @Scheduled annotation. We can schedule a method to be triggered at a fixed time interval by using
fixedRate parameter of the @Scheduled annotation. The fixedRate parameter accepts integers, specified in milliseconds.
This type of scheduling must be triggered when the execution of each task is independent. In the below example, the fixedRate property triggers the scheduled task to run at every at a fixed interval of 5 seconds.
@Scheduled(fixedRate = 5000) public void scheduleTaskFixedRate() { logger.info("Fixed Rate Task : The task execution time is : " + Calendar.getInstance().getTime()); }
Hence, the fixedRate property configures to run a scheduled task at every fixed interval. The fixedRate task is invoked at the fixed interval, even if the previous invocation of the task is not completed.
Scheduling a Task with Fixed Delay
We can schedule a task with a fixed delay between the completion of the last invocation of the task and the start invocation of the next task. This can be done by configuring
fixedDelay parameter of the @Scheduled annotation. In this case, the task always waits for the previous task to get completed. This type of scheduling is used for dependent tasks, where only one instance of the scheduled task runs all the time. For example, let’s schedule a task to run with a fixed delay:
@Scheduled(fixedDelay = 10000) public void scheduleTaskFixedDelay() { logger.info("Fixed Delay Task : The task execution time is", Calendar.getInstance().getTime()); try { TimeUnit.sleep(50000); } catch (InterruptedException ex) { logger.error("Unexpected error {}", ex); throw new IllegalStateException(ex); } }
Here, we have configured a task to run after a fixed delay. In given example, the duration between the end of last execution and the start of next execution is fixed. The task always waits until the previous one is finished. In the above example, the task gets completed at 5 seconds and since we have specified a delay of 10 seconds, the tasks are triggered with a total delay of 15 seconds. Hence, the fixedDelay configuration makes sure to create a delay of n milliseconds between the completion of an execution of task and the start invocation of the next task.
Scheduling a task with Initial Delay
We can configure the `initialDelay` parameter to delay the first execution of a scheduled task with a specified timeframe(specified in milliseconds). We can club this parameter with `fixedRate` and `fixedDelay` according to our requirements. For example, let’s trigger a task that runs every second, by waiting for 2 seconds before it executes for the very first time.
@Scheduled(fixedRate = 1000, initialDelay = 2000) public void scheduleTaskFixedRate() { logger.info("Fixed Rate Task : The task execution time is : " + Calendar.getInstance().getTime()); }
The task will run for the first time after the initialDelay value and the task will continue it’s execution according to the fixedDelay value.
Scheduling a task using Cron
In some cases, we need fine grained control to schedule tasks, in addition to delays and rates. Here is where, cron expressions come handy. The `cron` property gives flexibility to let us define seconds(0-59), minutes(0-59), hours(0-23), day of the month(1-31), month(0-11 or JAN-DEC), day of a week(1-7 or SUN-SAT) and even the year(1970-2099 or empty) that a task is scheduled to run. Is’nt it cool?
All the above mentioned fields(in the same order) except the year field are mandatory. You can even schedule a task to run at year 2099!
Apart from this, each field support special characters to provide detailed control over scheduling. For example, `*` represents all values. `?` represents no specific value and many more.
Hence, a cron expression is a string made up of 6-7 fields that are separated by a white space. The various combinations of the allowed values for the field provides powerful and flexible way to schedule tasks.
Lets go through a few examples.
@Scheduled(cron = "0 0 10 * * ? 2020")
The above cron expression fires at 10 AM, every day of the month, for each month, for the year 2020
@Scheduled(cron = "0 0 8 * * ?")
Fires at 8 AM everyday.
@Scheduled(cron = "0 10 10 * * ? 2021")
Fires at 10:10 AM everyday for the year 2021.
@Scheduled(cron = "0/30 * * * * ?")
Fire every 30 seconds.
@Scheduled("0 0 12 15 * ?")
Fires at every month on the 15th, at noon
Conclusion
In this article, we discussed to use the various functionalities for task scheduling with Spring Boot. The greatest advantage of scheduling tasks using Spring Boot is the ease with which it can be implemented, even by a novice programmer. If we need to require to schedule tasks that need to run quite frequently, it is ideal to configure the fixedRate or fixedDelay property. On the other hand, if we need to schedule tasks with higher execution time, it is ideal to configure the cron property. Apart from this, the cron property provides fine grained control of scheduling tasks, based on our requirements.
Schedulers are mandatory components of popular applications. This is because, most real-time applications are time-critical. | https://programtalk.com/java/how-to-schedule-tasks-with-spring-boot/ | CC-MAIN-2021-04 | refinedweb | 1,131 | 55.44 |
Posted 29 Mar 2013
Link to this post
Posted 01 Apr 2013
Link to this post
Welcome to the Test Studio forums. Using the Extraction and Test as Step features, you can pass a variable between tests. After extracting the variable and before passing it to another test, you can use a coded step to modify the variable. This example converts an extracted variable to all caps:
string myData = GetExtractedValue("varname").ToString();
myData = myData.ToUpperInvariant();
SetExtractedValue("varname", myData);
Posted 02 Apr 2013
Link to this post
Posted 14 Aug 2014
Link to this post
Posted 19 Aug 2015
in reply to
Himanshu
Link to this post
Hello Himanshu, in context to your post which says
>>public class variable
{
public static int a;
}
use it as "variable.a" wherever you want it in any test in the same project but make sure that the test setting the value runs before the test using its value..<<
I have a Query please. Can we assign a value to this variable a which can be used by all other telerik tests just by referring as : "variable.a";
Posted 21 Aug 2015
Link to this post
Posted 23 Aug 2015
in reply to
Boyan Boev
Link to this post
Hi Boyan,
I already had a look at this Utility class.
However I was facing challenges picking up the value of global variable from excel(data driven approach) to be assigned in utility class and the same can be used in other scripts just by referring to the class.variable name.
I am just pasting some part of the class here :
namespace Web_Version_Testing
{
public static class DBConnectionString
{
public static void InitializeConnectionString()
{
string s = Data["server"].ToString();
string d = Data["db"].ToString();}
public string dbconnectionstring = "data source=" + s + ";database=" + d + ";uid=SYSADM;pwd=SYSADM;Persist Security Info=true;";
}}}
I am picking the server and db name fron excel which is binded to this test and then creating the db connection string which I want to use/refer in other tests.
Is this the right way to pursue?
Jippy
Posted | http://www.telerik.com/forums/create-a-variable-to-be-used-across-tests | CC-MAIN-2017-17 | refinedweb | 342 | 58.01 |
Core ML and Vision: Machine Learning in iOS 11 Tutorial
Learn about Core ML and Vision, two cutting-edge iOS 11 frameworks, in this iOS machine learning tutorial!
Version
- Swift 4, iOS 11, Xcode 9.
Build and run your project; you’ll see an image of a city at night, and a button:
Choose another image from the photo library in the Photos app. This starter project’s Info.plist already has a Privacy – Photo Library Usage Description, so you might be prompted to allow usage.
The gap between the image and the button contains a label, where you’ll display the model’s classification of the image’s scene..
Adding a Model to Your Project
After you download GoogLeNetPlaces.mlmodel, drag it from Finder into the Resources group in your project’s Project Navigator:
Select this file, and wait for a moment. An arrow will appear when Xcode has generated the model class:
Click the arrow to see the generated class:
Xcode has generated input and output classes, and the main class
GoogLeNetPlaces, which has a
model property and two
prediction methods.
GoogLeNetPlacesInput has a
sceneImage property of type
CVPixelBuffer. Whazzat!?, we all cry together, but fear not, the Vision framework will take care of converting our familiar image formats into the correct input type. :]
The Vision framework also converts
GoogLeNetPlacesOutput properties into its own
results type, and manages calls to
prediction methods, so out of all this generated code, your code will use only the
model property.
Wrapping the Core ML Model in a Vision Model
Finally, you get to write some code! Open ViewController.swift, and import the two frameworks, just below
import UIKit:
import CoreML import Vision
Next, add the following extension below the
IBActions extension:
// MARK: - Methods extension ViewController { func detectScene(image: CIImage) { answerLabel.text = "detecting scene..." // Load the ML model through its generated class guard let model = try? VNCoreMLModel(for: GoogLeNetPlaces().model) else { fatalError("can't load Places ML model") } } }
Here’s what you’re doing:
First, you display a message so the user knows something is happening.
The designated initializer of
GoogLeNetPlaces throws an error, so you must use
try when creating it.
VNCoreMLModel is simply a container for a Core ML model used with Vision requests.
The standard Vision workflow is to create a model, create one or more requests, and then create and run a request handler. You’ve just created the model, so your next step is to create a request.
Add the following lines to the end of
detectScene(image:):
// Create a Vision request with completion handler let request = VNCoreMLRequest(model: model) { [weak self] request, error in guard let results = request.results as? [VNClassificationObservation], let topResult = results.first else { fatalError("unexpected result type from VNCoreMLRequest") } // Update UI on main queue let article = (self?.vowels.contains(topResult.identifier.first!))! ? "an" : "a" DispatchQueue.main.async { [weak self] in self?.answerLabel.text = "\(Int(topResult.confidence * 100))% it's \(article) \(topResult.identifier)" } }
VNCoreMLRequest is an image analysis request that uses a Core ML model to do the work. Its completion handler receives
request and
error objects.
You check that
request.results is an array of
VNClassificationObservation objects, which is what the Vision framework returns when the Core ML model is a classifier, rather than a predictor or image processor. And
GoogLeNetPlaces is a classifier, because it predicts only one feature: the image’s scene classification.
A
VNClassificationObservation has two properties:
identifier — a
String — and
confidence — a number between 0 and 1 — it’s the probability the classification is correct. When using an object-detection model, you would probably look at only those objects with
confidence greater than some threshold, such as 30%.
You then take the first result, which will have the highest confidence value, and set the indefinite article to “a” or “an”, depending on the identifier’s first letter. Finally, you dispatch back to the main queue to update the label. You’ll soon see the classification work happens off the main queue, because it can be slow.
Now, on to the third step: creating and running the request handler.
Add the following lines to the end of
detectScene(image:):
// Run the Core ML GoogLeNetPlaces classifier on global dispatch queue let handler = VNImageRequestHandler(ciImage: image) DispatchQueue.global(qos: .userInteractive).async { do { try handler.perform([request]) } catch { print(error) } }
VNImageRequestHandler is the standard Vision framework request handler; it isn’t specific to Core ML models. You give it the image that came into
detectScene(image:) as an argument. And then you run the handler by calling its
perform method, passing an array of requests. In this case, you have only one request.
The
perform method throws an error, so you wrap it in a try-catch.
Using the Model to Classify Scenes
Whew, that was a lot of code! But now you simply have to call
detectScene(image:) in two places.
Add the following lines at the end of
viewDidLoad() and at the end of
imagePickerController(_:didFinishPickingMediaWithInfo:):
guard let ciImage = CIImage(image: image) else { fatalError("couldn't convert UIImage to CIImage") } detectScene(image: ciImage)
Now build and run. It shouldn’t take long to see a classification:
Well, yes, there are skyscrapers in the image. There’s also a train.
Tap the button, and select the first image in the photo library: a close-up of some sun-dappled leaves:
Hmmm, maybe if you squint, you can imagine Nemo or Dory swimming around? But at least you know the “a” vs. “an” thing works. ;]
A Look at Apple’s Core ML Sample Apps
This tutorial’s project is similar to the sample project for WWDC 2017 Session 506 Vision Framework: Building on Core ML. The Vision + ML Example app uses the MNIST classifier, which recognizes hand-written numerals — useful for automating postal sorting. It also uses the native Vision framework method
VNDetectRectanglesRequest, and includes Core Image code to correct the perspective of detected rectangles.
You can also download a different sample project from the Core ML documentation page. Inputs to the MarsHabitatPricePredictor model are just numbers, so the code uses the generated
MarsHabitatPricer methods and properties directly, instead of wrapping the model in a Vision model. By changing the parameters one at a time, it’s easy to see the model is simply a linear regression:
137 * solarPanels + 653.50 * greenHouses + 5854 * acres
Where to Go From Here?.
- And thanks to Jimmy Kim (jimmyk1) for this link to Awesome CoreML Models — a collection of machine learning models that work with Core ML: try them out, and contribute your own awesome model!
Last but not least, I really learned a lot from this concise history of AI from Andreessen Horowitz’s Frank Chen: AI and Deep Learning a16z podcast.
I hope you found this tutorial useful. Feel free to join the discussion below! | https://www.raywenderlich.com/577-core-ml-and-vision-machine-learning-in-ios-11-tutorial | CC-MAIN-2019-35 | refinedweb | 1,131 | 54.63 |
09 Mar 2011 Editor's note: Some browsers support SVG animations. These animations were tested in Microsoft Internet Explorer with the Adobe plug-in, Google Chrome, and Mozilla Firefox. The sample animations worked best in Internet Explorer with the Adobe plug-in. Part of the animations worked in Google Chrome. In Download, find the sample SVG files in x-matters42-examples.zip and HTML files that embed the sample SVG files in x-matters42-html-examplefiles.zip.
SVG has been a W3C recommendation for some time now but has been slow to catch on in the wider Web. That might be changing now that Mozilla (Firefox), Apple (Safari), and Opera all support (or are about to support) SVG in their browsers, without plug-ins. The Linux desktops Gnome and KDE also support SVG for use in themes, icons, backgrounds, and games. Until now, the main way to view SVG was to use the Adobe plug-in (see Resources), which I used to test the example code.
What exactly is SVG, and when is it appropriate to use? SVG has been compared to PDF, PostScript, Flash, and HTML, but it has elements of all without duplicating any of them. SVG is complex, which allows it to be many things to many people while remaining a text format (Google can index it) and XML (you can manipulate it with the DOM). At the most basic level, it is an XML language for describing vector graphics -- pictures made by drawing lines (as opposed to bitmap graphics -- pictures made by drawing pixels). But SVG can also contain and manipulate bitmaps, text, even sound files. In addition, it can:
- Describe ways to apply noise and other effects to vector or bitmap images
- Specify elaborate color gradients and patterns
- Provide links to other parts of the Web
- Be scripted and transformed, animated, and styled
- Be interactive in many ways.
I want to follow up on David's earlier XML Matters column on SVG by talking about SVG animation and interactivity, specifically its declarative animation and interactivity.
Note: To view the SVG documents in this article, you need an SVG viewer which you can find in Resources. You can also download a .zip file that includes all associated SVG files.
Declarative programming 101
Declarative programming is more like a description of what you want to happen, without worrying about the details of how to make it happen. Common examples of declarative programming include spreadsheets, SQL, XSLT, and programming languages such as Haskell. Other programming languages that provide a mix of declarative and procedural constructs include Lisp and Python. Several XML dialects are moving to include more declarative features in place of more complex and/or repetitive JavaScript for handling tasks such as forms validation (XForms), data mining (XQuery), transformations (XSLT), event handling (XML Events), and animation (Synchronized Multimedia Integration Language, or SMIL).
SMIL (see Resources) -- a language for mixing video, pictures, music, and text in real time -- has been adopted and extended by SVG. Much of the declarative animation in SVG is borrowed directly from SMIL (without using the SMIL namespace), although some aspects of SMIL were left out because they made no sense in the context of SVG, and others were extended. SMIL is used in RealNetworks' RealPlayer, in Apple's QuickTime, and (as XHTML+SMIL) in Microsoft's Internet Explorer. SMIL is a tool for choreography of these different media formats in response to time and events.
The declarative capability that SVG inherits from SMIL lets you animate graphics (for example) either at predetermined times, or in response to certain events. You can declare five types of animation and use many events to trigger your animations.
It's time to show you some examples.
Drawing a blank
The first example creates a canvas for the rest of the examples in this article. I'm going to drift back to grade school and use sketches of rockets and UFOs, so the background will be a simple sheet of lined notebook paper with three punch holes. This example doesn't use animation. I merely set up a canvas reminiscent of a grade-school notebook, ready for doodles. The paper is quite simple, consisting of a single
svg element containing a short section of definitions: a line pattern and a small circle. Then, in the body (outside the
defs) I draw a rectangle over the whole page, filling it with the line pattern. Then I grab the circle I just defined and draw it in three places. Listing 1 shows the SVG code for the notebook-paper example.
Listing 1. A sheet of notebook paper
<?xml version="1.0" encoding="utf-8"?> <svg xmlns="" xmlns: <defs> <pattern id="single_line" x="0" y="0" width="1" height="32" patternUnits="userSpaceOnUse" viewBox="0 0 1 32"> <line x1="0" y1="32" x2="1" y2="32" stroke="lightblue" stroke- </pattern> <circle id="single_hole" width="28" height="28" cx="14" cy="14" r="14" fill="white" stroke="black" stroke- </defs> <rect x="0" y="0" width="100%" height="100%" fill="url(#single_line)" stroke="none"/> <use xlink: <use xlink: <use xlink: </svg>
To run this example in your browser, download the example code (01_paper.svg in Download). If you have installed an SVG viewer, click to see this example.
Rocket science
The second example adds one
path element to the definitions and uses it once in the body of the
svg (see Listing 2). The path is made up of a move statement (
Mx y) and line-to statements (
Lx y) in absolute coordinates. (Statements using relative coordinates would be lowercase.) The
d attribute contains 1,072 statements (gathered through Wacom tablet), so I've trimmed it for brevity in Listing 2. You can view the full file all its glory in the example code (see 02_rocket_static.svg in Download).
Listing 2. A rocket ship (changes only)
<defs> [...] <path id="rocket" stroke- </defs> [...] <use x="50%" y="50%" xlink:
So far, my doodle is as static as the virtual paper it's sitting on (see Figure 1), but that will change in the next example.
Figure 1. The rocket
To run this example in your browser, download the example code. If you have installed an SVG viewer, click to see graphic.
Blast-off
At last it's time for some motion. The rocket will follow a circle to demonstrate some of the features you can expect from SVG: path following and auto-rotation. This third example demonstrates the first type of declarative animation I'll cover -- the
animateMotion element (see Listing 3).
Listing 3. A rocket ship on the move (changes only)
<defs> [...] <path id="rocket2" transform="rotate(90)" [...]/> <path id="circle" stroke- </defs> [...] <use xlink: <animateMotion rotate="auto" dur="30s" repeatCount="indefinite"> <mpath xlink: </animateMotion> </use>
In the
defs element I've added a
path element that defines a circle for the rocket to move around. I've also added a
rotate transform to the rocket definition so that the rocket will face the right way as it goes around the circle. SVG can turn an image so it always faces the tangent of the line it is following. I chose a circle because my hand-drawn paths made the tangent jump around. Someone with a steadier hand on the tablet might achieve better results. The important thing is that the line the animation follows can be any arbitrary path. Also note that instead of the simpler
circle element, I have created the circle using a
path with elliptical arcs, so the rocket has a path to follow with a beginning and an end.
To run this example in your browser, download the example code (03_rocket_moving.svg in Download). If you have installed an SVG viewer, click to see this animation.
UFO sighting
Okay, so the rocket spinning around gets old after a while. In the fourth example I spice up the scene with a visitor from another world, in a handy-dandy UFO (see Figure 2). This gives me the chance to demonstrate the vanilla
animate element as well as its sibling,
animateColor.
Figure 2. Unidentified flying vectors
Listing 4 shows all the changes that create the UFO.
Listing 4. UFO (changes only)
<defs> [...] <g id="ufo"> <path id="ufo-body" d="M0 50 A100 100 0 0 0 100 50 L100 40 A100 100 0 0 0 0 40 z"/> <circle id="port-1" class="port" cx="25" cy="45" r="6"/> <circle id="port-2" class="port" cx="50" cy="45" r="6"/> <circle id="port-3" class="port" cx="75" cy="45" r="6"/> </g> <path id="back-and-forth" d="M100 50 L700 50 z"/> </defs> <use xlink: <animateMotion dur="50s" repeatCount="indefinite"> <mpath xlink: </animateMotion> <animateColor xlink: <animateColor xlink: <animateColor xlink: </use> [...]
In the
defs, I've added a
ufo formed from simple SVG arcs and circles, in order to avoid another huge block of
path statements from the tablet. I've also added a
path to follow for moving back and forth -- a simple line. The closing
z closes the path so the UFO has something to follow back to its starting point. In the body, I have a more complex
use element than before which contains four different animation elements: an
animateMotion similar to what you've seen with the rocket, then three
animateColor blocks. Interestingly, the
animateColor elements do not apply to the
ufo directly (which would be the default), but instead target the UFO's individual portholes by using
xlink:href attributes. I've also tied the start of each
animateColor to the loading of the UFO's main element.
To run this example in your browser, download the example code (04_ufo.svg in Download). If you have installed an SVG viewer, click to see this animation.
Rockets versus UFOs
The fifth example adds user interaction, still through declarations. SVG supports all of the mouse events you expect but also has support for keyboard events -- even for specific key events, which is what I've chosen to demonstrate here. Each letter of the alphabet triggers a rocket headed for space (see Figure 3). Time to defend your home planet from the UFO invader!
Figure 3. Missile defense
For this example I remove the
transform attribute from the rocket definition, because the rocket will no longer be going in circles, and I remove the definition for the circle. No other changes to the
defs are needed. All the action this time is in the body, with 26 variations on a theme (see Listing 5).
Listing 5. Rockets versus UFOs (changes only)
<use xlink: <set id="showa" attributeName="display" to="inherit" dur="5s" begin="accessKey(a)"/> <animate dur="5s" begin="showa.begin" attributeName="y" from="600" to="-100"/> </use>
Each variation uses the same rocket I defined earlier, but ties it to a different
x coordinate and an alphabetic keyboard event. When the viewer presses a key, it triggers the
set element, which makes the rocket visible at the bottom of the screen. Notice how an ordinary
animate element is tied to the start of the set event. This demonstrates how events can trigger other events. If you want chained events, the second event can be triggered by the end of the set event, rather than the beginning.
To run this example in your browser, download the example code (05_rocket_defense.svg in Download). If you have installed an SVG viewer, click to see this animation. Remember that you need to press a letter key or keys to trigger the rocket motion; depending on your computer's speed, you might experience a slight delay before the rockets appear.
Asteroid invasion
The final example completes your tour of declarative animation scripting in SVG with the
animateTransform element. This example shows five rocks, or groups of rocks, appearing in the center of the page, hurling out toward the viewer and disappearing off the edges (see Figure 4).
Figure 4. Rocks coming right at you
This effect requires the animations both to nest and to influence one another. The
additive="sum" attribute allows the effect of the various transforms to be cumulative. The first inner transform rotates each rock on its own axis, so that the rocks appear to be spinning as they approach the viewer. The second inner transform scales each rock so it grows (simulating the approach). Both of these transforms are applied to the rock's path, which I pull in with the
use element. The outer transform, applied to the entire grouping, moves the rock out toward an edge of the view and off-screen.
Listing 6 shows only one group of animations, but the others are similar, with different points to move offscreen to, and tweaks to their starting time and duration, to mix things up. Most of the line data in Listing 6 is snipped for brevity.
Listing 6. Asteroids! (changes only)
<defs> [...] <path id="rock1" d="M-8 -21 L-9 -21 L-15 -21 [...] /> <path id="rock2" d="M19 -15 L18 -17 L14 -20 L12 [...] /> <path id="rock3" d="M-17 -20 L-18 -20 L-19 -20 [...] /> <path id="rock4" d="M11 -14 L11 -15 L10 -15 [...] /> <path id="rock5" d="M14 -30 L13 -30 L12 -29 [...] /> </defs> [...] <g> <use xlink: <animateTransform additive="sum" attributeName="transform" type="rotate" from="0" to="360" dur="6s" repeatCount="indefinite"/> <animateTransform additive="sum" attributeName="transform" type="scale" from="0.1" to="6.0" dur="6s" repeatCount="indefinite"/> </use> <animateTransform additive="sum" attributeName="transform" type="translate" from="600,400" to="1400,-200" dur="6s" repeatCount="indefinite"/> </g> [...]
To run this example in your browser, download the example code (06_asteroids.svg in Download). If you have installed an SVG viewer, click to see this animation.
Limitations
"Simple things should be declarative. Complex things should be procedural." --Adam Bosworth
Declarative scripting in SVG has its limits. For collision detection and real keyboard navigation, you need to add procedural JavaScript. There was talk of adding a constraint feature to SVG 1.2 but it wasn't adopted, so you need to code constraints procedurally. Adding new objects also requires scripting. Like HTML, SVG adds methods to the DOM interface for more advanced uses. Of course, you can use normal XML DOM methods as well. I think SVG is close to its tipping point, where use of SVG will grow rapidly. At the time of this writing, the latest beta of Firefox doesn't support declarative animation, but the Mozilla team is working on it. The effect once SVG is built into browsers will be huge. New tools to generate or view SVG appear all the time. The future is brighter than a rocket's red glare.
Downloads
Resources
Learn
- Scalable Vector Graphics (SVG) 1.1 Specification: Read the current W3C Recommendation.
- SVG.org: Check out this community Web site for SVG users, developers, and enthusiasts.
- Synchronized Multimedia: Learn more about SMIL at the W3C's Interaction domain.
- SVG Programming: The Graphical Web by Kurt Cagle (Apress, 2002): This is a comprehensive guide to SVG programming.
- "XML Matters: Program with SVG" (developerWorks, April 2005): Read David Mertz's previous XML Matters column, which introduces SVG.
- "Introduction to Scalable Vector Graphics" (developerWorks, March 2004): This tutorial by Nicholas Chase introduces the concepts necessary for building SVG documents, including basic shapes, paths, text, painting models, animation, and scripting.
- "Add interactivity to your SVG" (developerWorks, August 2003): Get a good roundup of SVG interaction techniques with this article by Brian Venn.
- "Interactive, dynamic Scalable Vector Graphics" (developerWorks, June 2003): Find out how to use JavaScript to dynamically control the content and appearance of a floor-plan image rendered using SVG.
- "Bring Scalable Vector Graphics to life with built-in animation elements" (developerWorks, June 2003): Brian Venn shows you how to apply the five flavors of SVG animations to your SVG documents.
- Adobe's SVG Zone: Find many SVG resources.
- XML Matters column: Find other articles by these authors.
Get products and technologies
- Adobe SVG Viewer: Download the viewer that was used to test the examples in this article.
- Batik: Try this Java™ technology-based SVG toolkit from the Apache-XML project.
- Compound XML Document Editor: This standards-based, model-driven editor for mixed-namespace XML documents includes support for SVG and SM. | http://www.ibm.com/developerworks/xml/library/x-matters42/index.html?ca=drs- | CC-MAIN-2014-49 | refinedweb | 2,701 | 63.19 |
Here are my raw notes.
Friday – 1:45pm – Advanced Security Topics
Paul McMillan
Hashing
Common Crpyo Hashes: md5, sha1, sha256
If you’re typing md5 into your code, you’re probably doing it wrong
Message signing – did the message come from who i expect it to come from?
How can we be attacked?
Did this file get corrupted
When doing a basic md5 hash, we check that hash that we have. Where did we get that hash?
If we know that the md5 hash that we have is good, then we’re pretty secure – hard to generate a hash collision (reasonably hard problem).
For message signing, it’s diferent.
H = md5(secret + message)
NO!
An attacker can generate:
md5(secret + message) == md5(secret + message + junk + attacker_message)
maybe your app is strict about format and this will result in an error
If an attacker can, given one message, sign a different message, it’s not good.
Solution: use HMAC
HMAC is essentially: hash(secret + hash(message))
use hmac lib
and salt your secret key.
salt = ‘session_cookie_signing’
hmac.new(salt + secret_key, msg)
If you don’t salt based on the use in each area of your app, then an attacker could take a signed message from one area and use it in another area.
Don’t use MD5! Avoid SHA1. Use SHA256 (for now).
There’s also SHA512, but on 32-bit machines can have serious performance problems. SHA256 is similarly secure.
Encryption
You should not be implementing encryption, in almost all cases.
Why do you need it?
If when protecting data in transit, use SSL/TLS.
Protecting data at rest: use underlying OS. There are already good solutions for this.
Random numbers
Generating a secret key:
import random
secret = ”.join(random.choice(allowed_cars) for i in range(length))
Don’t do that! Default random in python is predictable.
Solution:
from random import SystemRandom()
will use entropy data from various sources.
But… you don’t know how much entropy is actually there. In some cases this can be a real problem. i.e. if you’re running at the start of a virtualized machine, there’s not a lot of entropy yet. It’ll run out of entropy and give you predictable numbers.
Timing attacks
message, sig = ‘|’.split(incoming)
sig2 = hmac.new(salt + secret_key, message)
if sig == sig2:
do_something()
== is the problem because string comparison will short circuit when there isn’t a match.
If you take a lot of message, it’s possible to figure out a long string, one character at a time.
Very small difference but it’s statistically decidable in hundreds-to-millions of messages depending on the app. Over the internet there’s a lot of latency so it’s impractical. But a lot of apps are virtualized – I’m on the same machine as you, can ask you lots of questions really fast.
Solution: use a constant-time compare function.
check same length, then do an operation of every set of characters.
if len(val1) != len(val2):
return False
result = 0
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
Pickle
Loading an untrusted string is equivalent to running eval() on that string!
Use JSON or something, not pickle, for untrusted data.
If you must use pickle, sign and verify it… but use JSON if possible to avoid complexity of signing.
“You would think that…”
No. Always verify your assumptions.
For example….
pip install Django
– I trust the django authors
– i trust the people who run pypi
– i trust the people who wrote pip
– pip verifies the md5 hashes of packages
– packages on pypi can be pgp signed
– pypi uses ssl
So I’m safe right?
Of course not… all of these things require you to trust everyone on the internet.
– pip verifies md5 hash — but it downloaded the hash from the same page it downloaded the package from, and that’s in plain text. if someone can change the code, they can change the hash.
– pgp signed — no tool currently checks pgp
– pypi uses ssl — not really
PyPi –
– untrusted (by default) certificate
– plaintext by default
– easy_install and pip don’t use the SSL
Python doesn’t make it easy to check SSL certs. This is a problem.
You’d think that when you open a HTTPS url you’d get encryption… and you do, but it doesn’t verify the certificate.
Recommendation: use the ‘requests’ library. It *does* do the cert check by default.
Demo
DNS lookup – UDP. Computer will trust the first response it gets back. So on open wifi, easy for someone to spoof your dns and say that pypi.org is whatever they want.
“sudo pip install certifi”
Runs setup.py — so anyone can put code in setup.py and then it’ll run on your computer as root.
PyPI offers everything necessary to make this not possible, but we don’t use it.
How do we help the python community?
– use the requests library
– if you’re using hashes, use hmac.
Q&A
Q: Putting packages on pypi — is there a better way to do this at a release-process level?
A: It’s a hard problem. If you put something in the package that verifies the package is what you expected, that’s no good. If you provide something alongside the package, it’s the same problem. Signed PGP files — it’s great, but noone checks this. We need to make the tools.
Q: How much of this is actually new? How much of this is actually security-specific?
The HMAC stuff, for example, is all “don’t reinvent the wheel”, and security is the context. Are there cases where you have to do something because of a security reason? What about the signing stuff – that’s been seen before too.
A: None of this is new. But as a community we pretend it doesn’t exist. The end result of most conversations about this are “it’s not pypi’s problem, users should be doing something secure.” But that’s not the way to think about this: should make the way that’s obvious the right thing.
Q: But right now it’s more work to do it the right way, so it’s bad engineering on the part of users.
A: Higher-level constructs tend to make code more secure. But have to use
Q: Why didn’t the demo work? Issues with the wifi – security features?
A: Script was set up for WPA2 network, but this is an older network.
Q: Timing attack – constant-time string compare is not the obvious way to do it…
A: Have to think about security implications. Python should have a constant-time compare function.
Q: Constant-time compare function probably has problems because of mallocs. Don’t think it’s possible to really have a constant time compare function.
A: Is possible to get very very close. Not possible in C either but can get close.
Q: Suggestions for downloading packages for doing releases?
A: Most large software projects have a system for finalizing packages. Unusual to install things directly from the cheese shop. Pip team is sprinting on adding auth.
Q: crate.io – what does this actually do to increase security if installers are still the same?
A: Storing sha256 hashes. Storing hashes long-term so you have a history of what files were there. In PyPI things can be changed without you noticing. crate will maintain a history.
Can you reply with me the online database that checks its database for md5 hashes to decrypt them?
Pingback: My experience note-taking at PyCon 2012 « Brian Rue’s Blog
Mole Remover Techniques To Make Use Of
Everything is very open with a precise explanation of
the issues. It was truly informative. Your website is very helpful.
Thanks for sharing!
For latest information you have to visit world-wide-web and on internet I found this
site as a finest web page for latest updates.
Fantastic beat ! I wish to apprentice while you amend your web site,
how can i subscribe for a blog web site? The account helped me a acceptable deal.
I had been a little bit acquainted of this your broadcast offered bright clear idea | https://brianrue.wordpress.com/2012/03/09/pycon-2012-notes-advanced-security-topics/ | CC-MAIN-2015-22 | refinedweb | 1,373 | 76.11 |
I was going into a project to do some general code refactoring (it’s a hobby, you know), and found some tests that were failing. Figured I’d fix those first and then bitch at whoever left failing tests in a project later. One test failure in particular looked a bit odd to me:
1) Error: test: The 'Add to Web' form should pass a URL into the form. (LettucesControllerTest): ActionView::TemplateError: undefined method `rewrite' for "":String On line #1 of layouts/_footer.html.erb 1: <%= link_to 'Privacy Policy', privacy_policy_path %> 2: <%= link_to 'Terms & Conditions', terms_path %> 3: <%= link_to 'Contact Us', site_contact_path %> (eval):15 app/views/layouts/_footer.html.erb:1
…that’s interesting, I thought. What the hell does have to do with anything in that line? Well the functional test looked like this:
setup do login_as :activated_user get :new, :url => '' end
…and the action in the controller looked like this:
# User added lettuces page, scrapes lettuce URL if given for suggested title and images def new @url = params[:url] @lettuce = @url.blank? ? Lettuce.new : Lettuce.from_url(@url) end
Ok, it looks like an external site can pass a
url
param in via the url, to indicate which page this action should reach out to
and scrape for Lettuce content. I removed the @url assignment line from the
action and put a
<%=h @url.class %> and and
<%=h
@url.methods.sort %> into the
new view file and loaded
that in my browser.
Sure enough,
@url is an
ActionController::UrlRewriter, and it has a
#rewrite method, amongst some other things. I’m guessing that Rails routing
is using this somewhere, but I’m not curious to go find out because it will
delay my refactoring mission.
Now, thankfully I didn’t like that there was an instance variable named
@url in the first place, since it was being created only for the purpose of
letting the view use an instance variable instead of accessing #params
directly. However, there was a conditional case in the view for how to handle
a
#blank? url vs a non blank url, so it had to be available to the view
somehow. I refactored to:
def new @lettuce = requested_lettuce_url.blank? ? Lettuce.new : Lettuce.from_url(requested_lettuce_url) end protected helper_method :requested_lettuce_url def requested_lettuce_url params[:url] || '' end
And now:
- The functional tests all pass.
@urldoes not get overwritten, so the routing code will now work.
- The view has access to a
#requested_lettuce_urlmethod (a bit verbose, but
#lettuce_urlcollides with a named route).
- The incoming param stays the same, so any external pages which linked to this
import lettuceview won’t have to change how they link to the page.
Now that the
lettuces_controller is looking good, I can start working on the
meats_controller and see what it has in store. | http://robots.thoughtbot.com/using-url-instance-variable-in-rails | CC-MAIN-2014-42 | refinedweb | 459 | 61.06 |
1. Abide by a specified interface.
2. Are independent of each other.
3. Don’t result in name-conflicts when used in a built application.
4. Installation is independent of main application installation.
1. Is extensible without code modification to main application.
2. Depends only on plug-in interface, not on specific plug-ins.
3. Loads plugins dynamically.
4. May utilizes plug-ins as UI elements or OO Design Pattern such as Strategy or Command.
5. Requires no modification to successfully run in development or run-time environment.
6. Installation is independent of plug-in installation.
The download is available for LabVIEW 2011. If you want it in a previous version, follow the steps in the presentation to implement it yourself.
I'm interested in receiving community feedback, so please comment or ask questions.
In response to questions about displaying plug-ins in a sub-panel and communicating with message queues, I attached a version that does this in the simplest manner I can imagine:
I made a minor but important update to the code and presentation file today (November 2nd 2011).
It now uses the 'Get Exported File Path" function available in the tools pallette under 'File I/O>>Advanced File Functions>>Packed Library' to get the path to the plugin class within the lvlibp.
This will now work even if the plugin has dependencies scattered in various locations on disk. Previously it would output error code 7.
Michael:
Thank you for writing this up. Your step-by-step instructions are really good.
As hard as this sequence of steps is, even harder is the steps needed to build the plugin architecture when the code is already written without that in mind -- i.e., there's one project with the application, a parent class that isn't in its own library, and a bunch of already written child classes that are successfully doing dynamic loading. Making the conversion at that point is more complicated -- something I've tried to do a time or two and always botched. It's really important to have the end design in mind when writing the original code. It is my hope that in the years to come LV gets some better tools for making that transition (that really is a hope, not a backward way of saying anything like that is in the pipeliine; I don't know the roadmap for the packed project library features).
Especially high kudos for documenting so well the "get the class path" portion!
> Step 11 : Create as many plug-ins as you need for now, giving each a new project and built lvlibp.
You don't actually need a separate project for each plugin class. You just need each plugin class to be in a separate .lvlib and to have a different build spec for each one to build independent .lvlibp files. I would in fact recommend using a single project since that makes it easy to pop up on "Build Specifications" and select "Build All" to have them all get created in one go.
> Step 17: Create an installer for the application.
One question that I've been asked in the past is whether there is a way to have the PluginInterface.lvclass be inside the .exe instead of being in a separate .lvlibp. This would make it so there is only one file for the app (the exe) and one file for each plugin (each a .lvlibp). To the best of my knowledge, there is no way to reach this nirvana. Without breaking PluginInterface.lvclass out into its own packed library, each of the child plugins will include a copy of its parent class inside of itself (which has its own set of serious problem issues since the parent class isn't public).
Again, thank you for writing this up.
Michael,
It seems like you are jumping through a lot of strange hoops that could be more easily accomplished if 'Packed Classes' were a feature of the LV language.
If that conceptual idea makes sense to you, do you agree?
~Norm
Michael,
This is excellent! I'll have a few more comments and questions later. For starters, thanks for mentioning the issues with 2010 in Step 9. I experienced the same. And thanks for the highlight of the new VI in Step 14.
Norm,
I like it! I'm assuming Protected VIs would be visible as well as Public VIs. And even though the class data is private, it would be visible as well.
Norm,
That is a great idea - I have several packed libraries where the only content to the lvlib is a single class - the lvlib is only there because I cant pack a class on its own (despite a lvclass being related to a lvlib)
Hi Michael,
Thanks for your wonderful presentation and example code.
I was trying your method to create the packed project library based plugin architecture and faced with following error.
While creating Plugin Overide VI LabVIEW 2011 generates following error:
Error 1035 occurred at Property Node (arg 1) in Apply Configuration For Source Separation.vi->MemberVICreation.lvlib:CLSUIP_Apply New VI Settings.vi->MemberVICreation.lvlib:VIRetooler.lvclass:CLSUIP_CreateNewVI.
Steps follwed: 1. Created interface class and able to build the Interface packed project library. 2. Added the Interface Packed project library in the Plugin project. 3. Created plugin child class. 3. Able to inherit from Interface class present in packed project library. 4. While creating VI for override labview throughs above error.
Kindly help me...
Ruska..., I developed the code in LV2011 and I never ran into the issue you mention above. If you have the service program with NI, you might want to call them or shoot them an email. It could be something wrong with your LabVIEW installation. It sounds like you're following the steps to the letter, so I'm not sure how to help... sorry. One idea: Make sure the project created in step one (interface class) is closed before adding the built packed project library to the plugin project. Perhaps even close and reopen LabVIEW after building it, just to make sure it's no longer in memory. Please let me know if you resolve this, a revision to the presentation or example code may be in order if this turns out to be a common issue.
I'm having hte same problem with the 1035 error. Ideas?
It appears that as soon as I attempt to create the Override VI, error 1035 occurs and then the method I was trying to override in the base class (within the packed project library) shows a broken run arrow.
Here's the workaround: Create a VI for Dynamic Dispatch then turn it into the desired override VI by matching the connector pane and saving it with the same name as the base class method. Obviously there's a LabVIEW bug here that needs to be fixed by NI.
The error code is actually different (and perhaps more insightful) in LabVIEW 2010 :
------------------------------------------------------------------------------------------------------
Error 1012 occurred at Property Node (arg 1) in CLSUIP_ClearBlockDiagram
Possible reason(s):
LabVIEW: Cannot load block diagram.
Property Name: Block Diagram
The block diagram for NULL could not be loaded but is required by this property or method.
--------------------------------------------------------------------------------------------------
Of course it can't load the block diagram, it has been removed because the VI was built into a packed project library. My question for NI: why does auto-creating an override VI require the parent block diagram?
I suppose when I made this demo and presentation, I didn't use 'New>>Override VI'. I must have done the workaround I described above. Good catch guys, and I hope this post has enough visibility that NI gets on it ASAP for bug fix in LabVIEW 2012.
I was able to make the method you described work. Thanks for describing how you created the override VIs; I wouldn't have thought that the New-> override VI would have caused a problem like that.
Hello Everyone,
I reproduced the error described and filed CAR 334314 for further investigation.
Thanks for the work on this!
Hi Michael,
Great document.
You mentioned that step 14 now uses 'Get Exported File Path.vi', but I'm runnig an older version of LabVIEW. What was the code before this VI was there?
Matt, it was messy, it looked like this:
Getting the path correct can be a little tricky. If you're not sure, temporarily add a class method that displays its own VI path, then run it from the dev. environment after building it in a packed project library. This'll show you what the path is to that method within the lvlibp, then you'll know how to correctly form the path to load that plugin in your client application.
This seems like a great leap forward compared to source distributions. My concern is that future changes in LabVIEW will break this capability. Can anyone from NI comment on if this approach will be supported in future versions?
Yes, it can be compared with source distribution, but the only feature which is really missing (and very useful for PlugIn architecture) is Exclude.
Feel differences:
Source Distribution:
and Packed Library:
As result we will get "VIs overhead" in PlugIns...
The other thing that I miss with the packed library approach (as opposed to a LLB based approach that I used to use) is that I cannot use custom extensions.
I otherwords, if I distribute plugins as LLB (and manually face the dependancy pains / lack of namspacing etc) I can build a LLB with a custom estension (e.g. *.psu for power supply unit drivers etc) that can (a) make it easy to find plugins, and (b) I can then add the built files to my project that builds the installer for the main APP and wont have to deal with conflicts etc.
i don't believe that we'll get an exclude for packed libraries. they are modeled after dlls which, by definition, are a self-contained set of files with no external dependencies.
There is bloat to the lvlibp that in some circumstances may be unnecessary. But, the problem with loading source distributions as plugins is that if any of their subVIs are already loaded in memory in the application from a different path than the plugin expects, then they are broken and won't load. This is the 'dependancy pains' shew82 mentioned above. The way around this with source distributions is to check the box in the build spec to 'Apply prefix to all contained items', that way they're guaranteed unique.
Besides this trivial point, the reason I'm not particularly fond of source distributions as plugins, is that they appear as editable LabVIEW files on disk; sometimes many,many files. I feel uneasy having all this stuff exposed to my end user. I've experimented with zipping them and changing the file extension (.plugin), then having my application unzip them during runtime and delete extracted files when shutting down, but this is quite a hassle and prone to error. Packed Project Libraries give a much cleaner look (on disk) to deployed applications, in my opinion.
Just for completeness - in the past, I used LLBs with custom extensions as that means that your end user has to not only have an appropriate install of LabVIEW but also has to actually know that the internal data format of the file in question is a LLB. That certainly reduces some of the risk of source distributions (removing block diagrams etc as part of the build process takes this further still).
Hello LVB,
Right now this is "the" way to create class plugins. We do not intend on breaking this functionality. If something does change to break this it would be considered a bug and we would fix it. We have brainstormed about ways to make this process better for our users. More info is here.
Can this architecture be used to share a single packed project library (shared resource) with multiple LabVIEW applications (EXE)?
JonS, thanks for the prompt confirmation this functionality will remain in the future. This is great news.
Certainly, multiple applications can load plugins from a shared directory. Each application will load its own copy of it in memory. Be aware that if your plugin performs file access or hardware I/O that this scheme doesn't prevent conflicts of those resources, you'd have to work around that the same way you would otherwise with multiple apps (whatever that may be).
What if the intention is to share resources (file handle, hardware IO, ...) across multiple apps? Is there a way to configure the packed project libraries for this operation?
Sharing handles between processes is usually not an option. Almost all the refnums in LabVIEW are application reference (aka project specific) and other handle like objects like most Windows handles are only meaningful on a per process base. Some Windows kernel objects are system wide, but most higher level Windows APIs don't use them or don't expose them.
I love your plugin architecture.
I think that the way you separated it into several projects is the correct way or else I won't be able to compile some of my plugins because LV will say they are busy.
The interface and the plugins shouldn't be located in the same project.
However, I run into some problems implementing your design.
When I run your exe from the example both on my local machine that has LV and on a remote machine that doesn't have LV your exe works just fine.
Yet, when I tried to do the same with my own plugin which is much more complex and uses many vis from other projects my exe run perfectly on my local machine with LV yet the exe failed to run on a machine that had no LV pre-installed (yet it contained the correct runtime) and generated 1003 error.
Basically, what I did is:
1. placed my plugin class inside a lvlib
2. converted the lvlib to lvlibp
3. set the plugin's lvlibp to inherit from the interface lvlibp
4. added the interface lvlibp to the main program
5. searched from the main program's exe the plugin lvlibp as you described
At first, I thought my problem was a static vi reference in the plugin since the static vi is actually a vi from the lvlib and not from the lvlibp.
Thus, I changed my model to search and return the vi from the lvlibp (through a similar search) instead of using a static vi ref that didn't get updated when I converted to lvlibp.
Alas, it didn't help.
Oh, i had another problem with the design: if my main application is using a vi from the interface I must use the vis from the lvlibp or else I'll have to change all the vis once I'm done since the plugins inherit from the lvlibp interface and won't recognize the lvlib interface as valid casting option.
Won't it be better if the interface itself remain as lvlib with the plugins inheriting from it instead of from the lvlibp interface?
P.S. - at the moment I dealing with another question: how do I use functional globals or networked shared variabled with lvlibps. Will the queue be empty clones of the originals?
The reason for the packed libraries is so executables can load them. You only need the run-time engine at that point rather the development environment. This means I can hand a customer a professional looking disk with installer and they have no idea they are running LabVIEW code.
I know what the plugins are for, I just tried to test the exe and it failed on the customer side after it passed on mine.
As a matter of fact there are many more benefits to the plugin architecture with one of them is using less memory and load time resources along a greater separation in the code development.
After some more investigation it appears that a HW driver that I'm using is causing the problem.
Even though I can see that the LVLibP added the dll that a vi from the Hardware Abstraction Layer Project in it uses, once the exe searches for the dll vis it fails with 1003 error.
Once I remove the vi from the HAL the exe works just fine.
P.S. - since it is hard to debug a compiled code from LVLibP, for example, especially since LV crashes a lot when I open debug mode, I started working with NTTrace.
However, just a few seconds result in 10MB of logged events. Is there an easier solution?
Great article and comments!
How would one go about implementing this on an application that has, say, 1000 plugins? Prefereably without spending 5 years on it?
My application - which has those said 1000 plugins - works in the dev environment rather well. I created the classes and established the hierarchy using VIScripting to avoid taking 5 years. Would it be possible (or sane?) to attempt to put together all these libraries and build specs using VIScripting?
Hi,
Update to the exe problem using LVLibP:
After a more thorough investigation the issue was resolved.
There was no problem on the LVLibP side (which works now amazingly and I adore it!).
The problem was a bug in the dll provided to us by Data Translation.
Again, LVLibP works great! I tested every aspect and I use it in a very complicated scenario.
Thanks!
It sounds like your application is better suited for a source distribution and dynamic VI loading. I tend to think of the packed project library as a "DLL for LabVIEW". The packed project library should contain a "set" of VIs that are used together. Given this, do you know of any commercial applications that use 1000 DLL's in the program files folder?
I currently wrap my plugins in an LLB using the OpenG Builder. I do this because I can remove source code and namespace them on the fly at the time I build the LLB. This protects me from crosslinking issue between one LLB of plugins and another LLB of plugins or the EXE itself.
I am considering switching in PPLs but I am concerned about a few things after reviewing your presentation and the comments.
1. Is there a way to group multiple plugins into a single PPL? I currently do this so that I have one LLB containing common plugins and then each dev can create their own custom LLB of their plugins. The EXE can call a plugin out of any of those LLB and be sure that there will not be a conflict. The advantage to me is less files to install and therefore a cleaner footprint on disk. To me, this is more like a DLL since I can have multiple functions within my 'dll' of plugins. Your solution looks more like a lot of DLLs with only one exported function per DLL.
2. I have some shared memory between my plugins and my EXE. This is in the form of a SEQ but could be any other functional global type object. I exclude the VI that wraps this from the plugin LLB so that all plugins are forced to use the one in memory that the EXE provides. Is there a way to achieve something similar with your system without the ability to exclude VIs from the PPL build?
3. How do you handle versioning of your plugins? I need the EXE to log the version of the LLB that a plugin was loaded from. I do this by having a VI in the LLB that includes the version string as a static output. This is incremented in the LLB build process. I would want to have a similar method of storing, auto-updating and reading a version string for each plugin PPL.
4. When I am developing my EXE and plugins, I am able to test the EXE using the source code version of the plugins or the LLB ‘compiled’ version. (when running the EXE, I only can target the compiled version, since I would normally only have the RTE installed for the EXE). It appeared to me that you solution requires the source for the EXE to calls PPL versions of the plugins only and not source. Correct me if I misunderstood. If I am correct, it would seem that editing and debugging your plugins would be difficult as you would have to rebuild and test each time and not have access to traditional debugging tools.
Thanks for any answers you can provide.
-John
John,
Here is my response to the concers you raise:
1. In the example, I only put one method in each PPL for the sake of simplicity. You could put as many methods in there as you'd like; as long as they're defined in the interface class then the main application can call them.
2. Yikes... functional global variables tend to muck up my architecture. I prefer to pass data on a wire if at all possible, or though a tightly managed communications mechanism. If I wanted to share stuff between an application and plugin or from plug-in to plug-in I would create a method in the interface and in the plugins that takes a queue reference (or object reference, or user event reference, etc) as an input, then store that in the plug-in's private class data.
3. You're asking me to give away my secrets! Here's a couple tricks to get version info without having to write your own method in each plugin or do any pre-build actions to update it:
option 1: Load the version of the class within the lvlibp. Pick a method within your plugin class, get the path to it within the lvlibp, open it using OpenVIReference, then use VI Server to get it's containing class ref and the version number of that class.
option 2: No guarantee this will work forever; NI could change this without notice. The lvlibp version is buried within (near the end) of the lvlibp file as text. So it's possible to read the lvlibp as if it's a txt file, then do string parsing to extract its version.
4. The example application does indeed load the built packed project libraries, but it doesn't have to. It could just as easily point to the classes (source code) on disk rather than look for the classes withing the PPLs. I wouldn't use this plugin scheme if it wasn't easy to debug in development environment.
I think LLBs are a fine alternative to PPLs for doing plugins, but I've tried this approach before and banged my head against the wall a lot trying to get build specs correct to prefix files and extract common code. Of course then, I didn't have a straightforward approach using interface classes... so perhaps it's worth revisiting.
Thanks for the comments.
Thanks for the response. I have a few followup questions:
1. regarding packaging multiple plugins in the same PPL, you mention that you could have multiple methods in your plugin class? I am wondering if instead you chould have mupliple classes (all of type plugin) withing the LVLIB thayou then use to create the PPL? My 'plugins' are actually test modules called by my test executive. I would like to have each module be a child of the plugin class but I still want to group several of them into the same PPL.
2. see your point and that is basically how I have done things except in my case this tech datees back quite a ways and uses a variant tree to store system wide data. I could implement this as a named queue or pass the Q ref to the plugin as well. Many optinos here to work around the exclude limitation.
3. In your example you show how to get the version of the class within the PPL. (I think that is what you are doing). Does that get bumped automatically everytime you build the PPL? If not, then option 2 seems like the only way to do what I want. (assuming that version is incremented on build). I have used pre build actions in the past to version web services. That might be the best way to do this for now. I hope that they expose a proper interface to the version information in PPLs in the future.
4. Good to know. I need to give this process a try.
thanks again,
-John
John,
1. Cool idea. A large application might benefit from a grouping strategy like that. It could better organize plugins plus you'd save some build/deploy time by doing them in batches. The main app would just need slightly more complex code for finding & loading the plugins since multiple plugins could be in one lvlibp, but not necessarily every class in the lvlibp is a valid plugin (some could be helper classes).
3. Good point; dependencies may change that don't affect the plugin class version, but a rebuild would increment the lvlibp version. It would indeed be helpful if the PPL palette included a 'Get Version' function!
Best of luck! If you do refactor your test executive or use these ideas in future projects, please post back here to let the community know how it turned out!
Good point LVB...I was able to reduce the number of plugins down to around 15 and still cover our entire product line.
Question Michael:
I got this method to work really well for a class hierarchy that is one level deep, but trying to add another level down generated errors which prevented compilation of the packed library. Here's what I did:
1. Build the interface class and packed library.
2. Build plugin class in new project, inheriting from interface class packed library.
3. Compile plugin class packed library and delete additional copy of the interface class library.
- Everything works great up to here.
4. Start a new project and add the plugin class packed library.
5. Create a class which inherits from the plugin class packed library.
6. Can't compile the 2nd tier packed library because the interface class library is not found.
My application is more or less an options dialog, so each plugin nests a new display into a common front panel (using a strategy similar to...). As such the code to find and load plugins is contained in each plugin UI, which sends the qualified name back to the main app.
Actually I think this sounds rather similar to what jlokanis is doing. Do you have any ideas for extending this framework to multiple levels of hierarchy?
Thanks,
Scott
Michael, this looks fantastic thank you. I was wondering if this works where the plugin is an actor according to the Actor Framework? I will try and figure it out and post back myself, just wondering if is something that has been done already.
AristosQueue,
What you describe above is exactly the situation that I am in and would appreciate any suggestions/advice. How would you suggest going about this transition (especially since you said that in the past you have seen lots of difficulties with this process)?
Right now, we have a newly developed plugin architecture and we did not anticipate these types of challenges with creating successful EXE builds, thus we did not plan for this. However, at the moment, this seems to be about the best option for creating EXE’s that allow for: 1) leveraging the power of the plugin architecture and 2) keeping the build file structure clean and we would like to once again start creating EXE builds.
As you mentioned, I do hope better tools come out soon for managing this, please keep us posted if anything pops up on the horizon.
Amiri
Will this work on the CRIO?
Is it possible to unload a packed project library?
I am having difficulties to update a plugin (copying a new version of the packed library and loading it).
If I am not mistaken if the PPL is loaded once, he will keep this version in memory and work with that one, even if a new one has overwritten the old one.
You can't control when LV unloads anything else from memory; I'd be surprised to learn that PPLs are different. Maybe if you only reference the PPL's contents in a dynamically launched VI that you can stop and restart?
Hi,
I am trying to implement the plugin-architecture using the ppl at run-time. Therefore I have my main-class from which all other classes inherits. Dynamic dispatch has been done and all is ok without ppl. The "To More Specific Class" throws the error "1448". What is the reason why I can't cast my object down to a child element at run-time? Hints?
Best Regards,
Joachim
Hi Joachim,
One possible reason could be the "Dependancy" issue. Do check if you are trying to load the plugin's in source code form (which has the dependancies in LabVIEW vi.lib or instr.lib folder) from the application (in executable form).
In this case, the apllication (executable) does not have the ability to search and load the plugin's (in Source Code from) which has the Dependancies (Sub VI's or Driver VI's used in the Plugin) as against to the LabVIEW IDE.
Hope this helps...
Best regards,
Vijay.
Vijay,
Thanks for your hint. Unfortunately, also after a build I get the same error...
Hi Joachim,
I was trying to recreate your scenario. The error with respect to the dependency issue is 1498. Error 1448, in your case it seems to be "Something to do with the inheritance".
The child class will have the copy of parent data type along with it, when inherited from the parent class. When the plugin (child) or object loaded from the desk and passed to "To More Specific Class.vi" checks for the "Target Class" data Type to the "Reference" data type. I guess there is a miss match in your case.
"Application as well as Plugin must have to use the Interface(Parent Class, *.lvlibp)"
I will give a try to reproduce the error 1448. Can you explain the step by step procedure used in your case?
Best regards,
Vijay.
Vijay,
thanks for your hint - now it works - I've separated the plugin code from the using code into two projects - now it works, because I am only using the classes from the ppl.
Best Regards,
Joachim
Hi Vijay,
one problem still remains: everything is working perfect when using the ppl-Classes with all dependencies via the development environment. When I build an application I get an addition ppl in the data-folder (the "master" ppl is on a network share) and the call of the lv-classes gives me the error 7 --> Get LV Class Default Value.vi<APPEND>.
What is going wrong here?
Best Regards,
Joachim | https://forums.ni.com/t5/LabVIEW-Development-Best/Plug-in-Architecture-using-Packed-Project-Libraries-lvlibp/ta-p/3514395 | CC-MAIN-2019-13 | refinedweb | 5,201 | 71.44 |
Hello,
I have strange problem I use JBOSS 7.1.1 and my app is package in ear. When I run JBOSS on Oracle JDK 1.6.38 and under everything works great but 1.6.39 and above, also JDK 7 it change my logging level to DEBUG.
I know that this is weird but maybe someone had similar problem.
I repeat the problem on 3 computers java version 32 bit vs 64 dosen't matter
Can you explain what you mean by it changes your logging level to DEBUG? Like all you see is debug messages.
--
James R. Perkins
The root logging level which I set to WARN change to DEBUG. After degugging jboss-logging subsystem problem is in
org.apache.log4j.JBossLevelMapping.getPriorityFor(Level)
the code
public static Level getPriorityFor(java.util.logging.Level level) { final Level p; return (p = priorityMap.get(level)) == null ? DEFAULT_LOG4J_LEVEL : p; }
the priorityMap is a IdentityHashMap and contains key "WARN"(and many others) but the input param "level" is also WARN (value from config) but is not the same object(different memory id) as WARN on map. From this code I find that map return null what means that takes DEFAULT_LOG4J_LEVEL which is a DEBUG :-( | https://developer.jboss.org/message/916480?tstart=0 | CC-MAIN-2019-04 | refinedweb | 203 | 58.28 |
1. Go to testcase and click on any .asx link like "56k,100k, 300k". 2. The full-page plugin causes Windows media player to pop up in a helper application. 3. Notice the browser window no longer repaints itself but still shows parts of the last page. It looks bad and is unsable until you click back button. set MOZ_PLUGIN_PATH=C:\Program Files\Windows Media Player npdsplay: 3.0.2.627 WMP 8.00.00.4477 (but also seen on 7.x) Andrei, I think we've had a bug like this before? Was it ever resolved?
This was bugscape 11600 and has been fixed on the branch. I did not pay much attention to this bug on the trunk after at some point it just started work for me. I don't remember if it has been filed on Bugzilla. Anyway, if you see it on the trunk again, we should fix it. Taking.
Reproducable on Win2000. To see it one can just past the .asx url in the url bar. And if you don't have the plugin (npdsplay.dll) in the plugins folder, everything works just fine.
This looks ugly, nominating for beta1.
should we be closing bugscape 11600 ?
sounds like there is a workaround - right? If the user selects the back button and then hits next -- will it render?
I think it will. But first let me try similar approach I used for the branch. If it works, it is going to be not so hard to fix it.
Created attachment 76986 [details] [diff] [review] patch v.1 -- not working yet I am trying to utilize the similar approach which I used to fix bugscape issue 11600. This patch is pretty straightforward and I can see the error condition on both Win2000 and WinXP, so it should be good for both. Strangely enough, the |nsIWebNavigation| service just does not work for me in this patch. I am apparantely overlooking something obvious but cannot immediately see what. Peter, can you please take a look?
Andrei how does |nsIWebNavigation| fail? Does it not navigate or go back or you can't QI to get it?
I get interface, call method, no error returns. It just does not do anything.
Can you use |gotoIndex| or the session history? Adding keywords. This is a regression from the 0.9.4 branch tip.
adding nsbeta1+
Interesting finding (thanks, Radha!): "The goback() operation is succeeding. And the load of the previous page starts. But the load is cancelled by the load of ":\docume~1\radha~1.met\locals~1\temp\wmpc4e.htm/" at the following stack trace. I think this is the actual file downloaded by the media player. It looks like someone in another thread is posting an event to load this page, thereby the previous page is nevercompletely rendered."
Created attachment 78252 [details] stack trace mentioned by Radha in the previous comment
Note: This does not depend on full-screen mode of the player nor the browser.
*** Bug 136439 has been marked as a duplicate of this bug. ***
Updating title to avoid confusion.
Could someone summarize the purpose and role npdsplay.dll plays and why removing it shouldn't break something else?
Media Player is an application to play various media formats and it can be hooked in other applications and processes. npdsplay.dll is supposed to launch Media Player as a plugin, which means that all the gui, controls etc of the player should appear inside the browser window either embedded in other page content (if we have <embed> tag) or full-page (like in our case). Another mechanism of playing media out of the web using Media Player is employing it as a helper application when it takes over completely and launches its own window with control in it. This should normally happen if we don't have a plugin but the OS has some application registered to handle this given mimetype. In our test case Media Player tries to starts as a plugin but cannot finish for some reason, aborts and starts as a helper application instead, leaving incomplete page uncleaned. This is the actual bug. If we remove npdsplay.dll it will not attempt to start as a plugin and launch helper app at once, thus the problem does not occur.
...but without nsdsplay.dll, imbedded WMP content cannot play at all. So, is the bug in the .dll or the plug-in code?
I think our bug is that we display wrong page after plugin failure.
Well, it's not plug-in failure that shows the bug, just simply lauching the plug-in causes it. I cannot access the page while the player has launched and is playing the correct content.
I do not fully understand what you are saying. What I mean, the plugin fails to play the content, specifically opening the stream fails, after which the dll decides to launch Media Player as a helper application. The page stays in its intermediate state, which I beleive is our bug.
By the way, the posted patch works just fine when I make a local test case with bogus .asx file.
I see the bug with valid content. It doesn't have to be "bogus" for the paint bug to appear.
Content might be valid but plugin may still fail. As I said, it gets error code when trying to open a stream via NPAPI. This could be a bug too, but the plugin itself seems to handle this situation well. Can you please make your point?
I'm just trying to clarify the comments here -- you're referring to "failure" and "bogus content" when I can reporduce with valid content. The terminology, the summary are incorrect. The bug shows itself in imbedded (not just full-page as the summary states) and with valid content (as opposed to "bogus" content as you claim).
1. plugin does fail to play content, helper application does not 2. my comment about 'bogus' content was just a description of what I did to see the patch working 3. can you show the bug in embedded case? I did not see it. 4. please suggest the correct terminology and your version of summary.
topembed+ since it is something we need for an embedding customer, assuming we can fix this on our side and it is our bug.
OK, I admit it, I could have been on crack. I've been trying to reproduce the bug in embedded mode and can't.
I was able to reproduce this one quite easily using the build from today - 20020415. Try this (this one uses media player): 1. Go to 2. In the drop down list, where it says select a channel, select John Lennon 3. When the resulting page finally loads, select 'Play All' from one of the music choice. Windows Media player will launch, grab the plug-in and move it over the browser window -- it's awful Now, minimize both windows (browser and plug-in), restore the browser window and go to another page, to force a repaint. Restore the plug-in window and move over the browser window, The painting problem will not occur.
After seeing this problem with 1.0RC1, I found this bug, and Bug #85722 (which appears to be a dup of this one).
*** Bug 114746 has been marked as a duplicate of this bug. ***
*** Bug 143801 has been marked as a duplicate of this bug. ***
I found a generic way to cause the similar symptom. Very likely it is related. 1. load a full-page plugin, say, Flash: 2. remove/rename npswf32.dll while it is running (this is possible at least on XP) 3. hit reload button, the page becomes non-repaintable
*** Bug 129538 has been marked as a duplicate of this bug. ***
removing adt1.0.0, this bug does not have a FIX yet and it not ready to be nominated for checkin to the 1.0 branch. btw, I am seeing the URL in comment #12. Looking at this temporary file created by WMP, it looks like the plugin is trying to use Javascript and do the right thing by trying to tell us to go back to the previous page: <html><script language='javascript'>window.history.go(-2);</script></html> However, what I see is that the we can not load this file because we can't find it because of the last '/'. We add that -- it does not come from the plugin. The format of the URL that the plugin passes us is like in comment #12.
mass move PL RTM
Comment on attachment 76986 [details] [diff] [review] patch v.1 -- not working yet This patch is not relevant. The problem is that WMP gives us the URL which is formatted not exactly how Necko expects. Thanks to darin for pointing this out.
Created attachment 86122 [details] [diff] [review] patch v.2 This is a simple prototype which illustrates a possible approach to fix the bug. And it really does. Maybe this patch is even good enough to get in :) Please review.
Comment on attachment 86122 [details] [diff] [review] patch v.2 > char* absURIStr; >- NS_MakeAbsoluteURI(&absURIStr, aURL, uri); we cannot continue if NS_MakeAbsoluteURI() fails so I would change this code rv = NS_MakeAbsoluteURI(&absURIStr, aURL, uri); NS_ENSURE_SUCCESS(rv, rv); >+ // let's fix possible back slashes as necko cannot handle this >+ // while some plugins may use them, see bug 133286 and start scan if there is '\'char for (char * p = strchr(absURIStr); *p; p++) { >+ for (char * p = absURIStr; *p; p++) { and there could be a problem with japanese charset as I found it in with that we have to use isleadbyte // We need to call isleadbyte because // Japanese windows can have 0x5C in the sencond byte // of a Japanese character, for example 0x8F 0x5C is // one Japanese character if(isleadbyte(*p) && *(p+1)) ++p; else if (*p == '\\') *p = '/'; other then that, we need this patch, r=serge.
Created attachment 86282 [details] [diff] [review] patch v.3 Thank you, serge, for suggestion. I think it can be made even more effective. Please review.
Created attachment 86283 [details] possible addition to the fix Now I am wondering if we need this too.
Maybe I'm missing something here, but what about when target=NULL and we don't go through layout but rather |nsPluginHostImpl::NewPluginURLStream|? Since nsIURI doesn't do this fixup, I wonder if we will be breaking anything here?
Moving the patch to |MakeNew4xStreamInternal|, perhaps?
Created attachment 86291 [details] [diff] [review] patch v.4 Like this... In fact, with this patch, there is no need to make separate identical changes to both |nsIPluginInstanceOwner| objects, and it covers pretty much every path we can take from the plugin to the browser.
well, I just tested geturl works just fine on:\publish\bugzilla\115308\readme.txt
Comment on attachment 86291 [details] [diff] [review] patch v.4 r=peterl
how about postURL from the local file c:\temp\bla\bla.bla does it work with the patch?
The patch fixes the url to post to, not the data we are going to post. So if Mozilla ever supports posting to file:// type url we should test it.
Comment on attachment 86291 [details] [diff] [review] patch v.4 >Index: ns4xPlugin.cpp >+ // let's fix possible back slashes in the url as necko cannot handle >+ // this while some plugins may use them, see bug 133286 >+ // but don't touch anything if following local language 'lead byte' >+ char * relURL = PL_strdup(relativeURL); nit: backslashes are uncommon right? so how about deferring this strdup until after we know for certain that the string contains backslashes? >+ if (!relURL) >+ return NPERR_GENERIC_ERROR; >+ >+ char *p = relURL; >+ while (p = PL_strchr(p, '\\')) { >+ if (!isleadbyte(*(p - 1)) || (p == relURL)) >+ *p = '/'; >+ >+ p++; >+ } major: what if the first character in relURL is a backslash? looks to me like the call to isleadbyte would address invalid memory. you could just move the (p == relURL) test in front of the isleadbyte call to avoid this problem.
Although the patch does fix the problem, looks like this is not we really want to do. Backslashes can be legitimate parts of the url string, so changing them we are going to break cases with querry strings or passwords. Another wrong thing with this particular plugin, as serge pointed out, is that it uses 'file://' as a uri scheme, note only two slashes. Changing it to three also seems to fix the problem and is probably the correct way to do that.
Created attachment 86477 [details] [diff] [review] patch v.5 Very basic thing, we might benefit if we fix it in Necko. This patch does not limit existing Windows url authoring code to the presence of forward slashes after the scheme.
Comment on attachment 86477 [details] [diff] [review] patch v.5 >Index: nsURLParsers.cpp > const char *p = nsnull; > if (specLen > 2) { > // looks like there is an authority section >- p = (const char *) memchr(spec + 2, '/', specLen - 2); > #if defined(XP_PC) > // if the authority looks like a drive number then we > // really want to treat it as part of the path >- if (((p && (p - (spec + 2) == 2)) || (specLen == 4)) && >- (spec[3] == ':' || spec[3] == '|') && >+ if ((spec[3] == ':' || spec[3] == '|') && > (nsCRT::IsAsciiAlpha(spec[2]))) { > pos = 1; > break; > } > #endif >+ p = (const char *) memchr(spec + 2, '/', specLen - 2); > } a few problems... |spec| is not necessarily null terminated. so, if specLen == 3, then spec[3] would address invalid memory. another problem... suppose spec = "//f:4000/bar" in this case "f" is probably a hostname and not a drive letter. that's why the old code checked for '/' before checking for the existance of a drive letter. how about this check: if ((specLen > 3) && (spec[3] == ':' || spec[3] == '|') && nsCRT::IsAsciiAlpha(spec[2]) && ((specLen == 4) || (spec[4] == '/') || (spec[4] == '\\'))) { pos = 1; break; }
Created attachment 86487 [details] [diff] [review] patch v.6 darin, if you agree that we can go ahead and fix this problem in Necko and given you probably know better than anybody else how to test this code, do you think I should reassign this to you? It is fine with me either way.
yeah, i can take it from here... i have a set of testcases that i'll need to run to verify that this doesn't regress anything.
*** Bug 149471 has been marked as a duplicate of this bug. ***
*** Bug 148149 has been marked as a duplicate of this bug. ***
what are the chances this is gonna be resolved by 06.14? pls add eta.
patch is ready... i just need to run some verification tests on it... i'm hoping to do so tomorrow.
this patch passes all of our URL parsing tests.
Comment on attachment 86487 [details] [diff] [review] patch v.6 sr=darin
Comment on attachment 86487 [details] [diff] [review] patch v.6 r=dougt
fixed-on-trunk
shrir - can you pls verify this one on the trunk tomorrow? thanks!
first thing tomorrow...sure.
wonderful, works great now. tested this test url and other testcases as well to be sure. verifi on 0620trunk.
wfm me also on 6/20 trunk with
marking VERIFIED per previous two comments.
please checkin to the 1.0.1 branch. once there, remove the "mozilla1.0.1+" keyword and add the "fixed1.0.1" keyword.
adt1.0.1 (on ADT's behalf) approval for checkin to the 1.0 branch, pending drivers' approval. pls check this in asap, then replace Mozilla1.0.1+ with the "fixed1.0.1" keyword.
fixed1.0.1
*** Bug 151717 has been marked as a duplicate of this bug. ***
verified fixd on 0723 brnch. | https://bugzilla.mozilla.org/show_bug.cgi?id=133286 | CC-MAIN-2017-17 | refinedweb | 2,588 | 75.2 |
Like.
How does the kernel initialize its CSPRNG?
The kernel has an "entropy pool," a place where unpredictable input observed by the kernel is mixed and stored. That pool serves as a seed to the internal CSPRNG, and until some threshold of estimated entropy is reached initially, it is considered uninitialized.
Let’s now see how the kernel initializes its entropy pool.
After the kernel takes control on power-on, it starts filling its entropy pool by mixing interrupt timing and other unpredictable input.
The kernel gives control to systemd.
Next, systemd starts and initializes itself.
Systemd, optionally, loads kernel modules which will improve the kernel's entropy gathering process on a virtual machine (e.g., virtio-rng).
Systemd loads the rngd.service which will gather additional input entropy obtained via a random generator exposed by hardware (e.g., the x86 RDRAND instruction or similar) and jitter entropy1; this entropy is fed back into the kernel to initialize its entropy pool, typically in a matter of milliseconds.
After the last step, the kernel has its entropy pool initialized, and any systemd services started can take advantage of the kernel’s random generator.
Note that the virtio-rng kernel module loading in step (3), is an optional step which improves entropy gathering in a virtual machine by using the host's random generator to initialize the guest systems in KVM. The rngd.service loading at the final step (4) is what ensures that the kernel entropy pools are initialized on every scenario, and furthermore it continues mixing additional data in the kernel pool during system runtime.
How does the kernel provide access to its CSPRNG?
The Linux kernel, as shipped with Red Hat Enterprise Linux after 7.4, provides the following interfaces for accessing the CSPRNG:
getrandom(): A system call which provides random data from the kernel CSPRNG. It will block only when the CSPRNG is not yet initialized.
/dev/random: a file which if read from, will output data from the kernel CSPRNG. Reading from this file is blocked until the kernel estimates that enough random events have been accumulated since the last use (many details are omitted for clarity).
/dev/urandom: a file which if read from, will provide data from the kernel CSPRNG. Reading from /dev/urandom will never block.
AT_RANDOM: a location in process’ memory containing 16-bytes of random data; these are accessible via getauxval() and are always available.
The recommended kernel interface for Red Hat Enterprise Linux 7 is getrandom(); in the following paragraphs we will discuss the weaknesses and strengths of each interface which will make our statement above apparent.
/dev/random
This interface is described in the random(4) manpage as: "/dev/random is suitable for applications that need high-quality randomness, and can afford indeterminate delays." The interface was designed to work even when the cryptographic primitives it depended on were broken in a catastrophic way.
In practice, because that interface depends on proven primitives like the stream cipher ChaCha20 (in the past it was SHA256), that did not prove to be a reasonable risk, and in practice its dependence on conservative randomness estimation which blocks indefinitely made it unsuitable for applications. Putting its threat model in contrast with existing applications, if the
/dev/random threat model applies, the majority of the protocols and algorithms that take advantage of the random generator are already untrustworthy as they depend on the same primitives.
As such, due to its unpredictable semantics, we do not recommend the use of that interface in any scenario.
/dev/urandom
The device /dev/urandom provides access to the same random generator, however it will never block, nor apply any restrictions to the amount of new random events that must be mixed in the kernel entropy pool in order to provide any output. That is quite natural given that the cryptographic primitives used by the Linux kernel random generator, when initialized, can provide enormous amounts (practically unlimited) of output prior to being considered insecure in an informational-theory sense.
Unfortunately /dev/urandom has a quite important flaw. If used early on in the boot process when the random number generator of the kernel is not fully initialized, it will still output data. The "unpredictability" or "randomness" of that data is system-specific.
AT_RANDOM
That interface provides 16-bytes of randomness to each process, following the same rules and having the same limitations as /dev/urandom above, i.e., its value may be derived from an uninitialized entropy pool. Its value remains constant for the lifetime of the process, and is shared with potential children processes after fork(). It can be accessed by using the getauxval() glibc call.
Due to the limitations above, we do not recommend the use of that interface in any scenario.
getrandom()
The getrandom() interface provides non-blocking access to kernel CSPRNG, after the kernel's entropy pool is initialized. When the entropy pool is not initialized the function blocks, making this interface suitable not only for the typical user-space application, but also for applications requiring random data early, during the system's boot process.
Another advantage of this interface is that it does not require a file descriptor to operate. That not only simplifies code using the random generator, but also makes applications more resilient when operating in chroot() environments, because it does not require the presence of a device file.
Which CSPRNG interface should I use in my application?
In order to access a CSPRNG in an application, the use of the kernel’s getrandom() interface is recommended only when no cryptographic library is used. When an application is already using one of our core crypto libraries, we recommend using that library’s provided interfaces. The core crypto libraries provide a CSPRNG which uses getrandom() internally for seeding, and are designed to be efficient, high throughput, and easier to use. The table below summarizes these interfaces; please review the library’s documentation when using these interfaces.
How to use getrandom() in an application safely?
The getrandom() function was introduced to Red Hat Enterprise Linux in 7.4, and is a low-level interface. It is not suitable to be used directly by applications expecting a safe high-level interface, may return less data than requested when reading more than 256-bytes, and this system call is not wrapped by glibc on versions prior to Red Hat Enterprise Linux 8 Beta.
For portable code, that means that it should be accessed via the syscall() interface, and callers should fallback to a different interface (e.g.,
/dev/urandom) if the ENOSYS error code is returned. An illustration of (safe) usage of this system call, is given below.
#include <sys/syscall.h> #include <errno.h> #define _sys = _sys_getrandom(p, left, flags); if (ret == -1) { if (errno != EINTR) return ret; } if (ret > 0) { left -= ret; p += ret; } } return buflen; }
Don’t leave randomness to chance
Which interface to use, and the limitations of each, can be confusing. I hope this post is useful in helping you to choose the right interface for your use case.
Entropy gathered by measuring timing variance of operations on the local cpu.. | https://www.redhat.com/ko/blog/understanding-red-hat-enterprise-linux-random-number-generator-interface | CC-MAIN-2020-45 | refinedweb | 1,189 | 52.19 |
Community
Participate
Working Groups
Report message to a moderator
Menus
It seems that adding an ampersand (&) to the menu texts does not make the following letter act as a shortcut to open the menu together with the alt key (I'm talking windows here
Instead it seems that Alt plus the first letter of the menu text puts the focus on the menu bar, repeatedly pressing the same letter switches between main menu entries with the same letter. Pressing the down arrow opens the menu and then pressing the first letter of a submenu entry either executes that entry (if it is the only one starting with that letter) or again switches between entries with the same starting letter.
While this works, it is counter intuitive to most other applications.
--> What do I need to do in order for scout to (a) user and (b) show keyboard short cuts on menus and submenus? Especially shortcut letters that are not the first letter of a menu?
Navigating between views
I seem to be unable to navigate from one view to another using the keyboard? Is there I default keybinding to do this that I am unaware of? If not, how can I set this up?
Alternatively (or additionally): How do I assign a key binding with which I can set the focus to a certain view?
FormField short cuts
Is there a way to define shortcuts to jump to certain form fields? In other applications I've done this using the ampersand (&) in the label name which shows the corresponding letter underlined, pressing ALT plus that letter will set the focus to that field.
Using the ampersand in the name of a field does show the underline (though only after pressing ALT once) but using that letter does not seem to have any effect. How do I change this?
@Order(10.0)
public class MyKeyStroke extends AbstractKeyStroke {
@Override
protected String getConfiguredKeyStroke() {
return "F3";
}
@Override
protected void execAction() throws ProcessingException {
getXYField().requestFocus();
}
}
follow-up question: In the outline tree, when I move to another entry in the tree, the corresponding page is shown, stealing the focus from the outline tree. This makes it impossible to move through the outline tree using the keyboard. Is there any way to fix this?
follow-up question: I have one page that contains a form directly in a view. If I place the cursor into a FormField of that form, using ALT+<letter> no longer works to access the main menu. Can this be changed somehow?
Back to the top | http://www.eclipse.org/forums/index.php/t/489253/ | CC-MAIN-2014-52 | refinedweb | 424 | 68.3 |
This article was previously published on Rensu Theart's blog.
Recently I started to learn NativeScript in order to develop an app for a friend. Previously I've worked with the Android SDK and have also done some extensive development using Unity. But this new app had to be cross-platform (i.e. iOS and Android), and have a native feel, which makes Unity not well suited for this. So after playing around with Ionic and NativeScript a bit, I really liked the native performance and the low level power NativeScript allows.
Another great thing about NativeScript is it allows 100% code reuse, unlike any other native API. Furthermore, I feel like Angular 2 and TypeScript are the future of both web and app development, so I decided to learn the Angular version of NativeScript. But that's enough background, now onto the topic of this post's title: How to do you implement the ability to drag and drop UI elements in NativeScript - and while you’re at it, restrict the movement within a bounding box.
The whole process of detecting touch screen input on UI elements is conveniently wrapped for us in NativeScript's Gestures API. In NativeScript all UI elements inherits from the View class, which has on and off methods that allow you to subscribe or unsubscribe to all the events and gestures that the UI element detects. You can then pass the type of gesture you want to detect as well as the callback function for that gesture to these methods.
View
on
off
Alternatively, you can use the magic of Angular 2 and simply connect your TypeScript functions to the event described in your XML where you defined the UI element. I feel this is much easier to follow in the code for the Angular implementation so that is what we will do below.
You can read more detail here, including which gestures can be detected (most everything you can imagine to need in your application is included in the API).
The name of the gesture we will need to detect dragging and dropping events is called "Panning". In the NativeScript docs it is described as "Action: Press your finger down and immediately start moving it around. Pans are executed more slowly and allow for more precision and the screen stops responding as soon as the finger is lifted off it."
From the NativeScript docs, the usage is as follows:
For the TypeScript side:
onPan(args: PanGestureEventData) {
console.log("Pan delta: [" + args.deltaX + ", " + args.deltaY + "] state: " + args.state);
}
For the XML side:
<Label text="Pan here" (pan)="onPan($event)"></Label>
So there is really not much to it. In the XML, where you define the element, you simply add the (pan) event and give it your callback function in your TypeScript component. You pass the PanGestureEventData data to the function with the $event parameter. In your function you then have access to several event properties. The three main ones we care about are the deltaX, deltaY (which refers to the amount of device-independent pixels that were panned in the last update) and state (i.e. finger down, up or pressed, etc.) properties.
(pan)
PanGestureEventData
$event
deltaX
deltaY
state
Ok, now lets create a simple app that uses this to move a picture around.
I'm taking inspiration from this stack overflow page, which uses vanilla JavaScript instead of Angular.
I'm taking inspiration from this stack overflow page, which uses vanilla JavaScript instead of Angular.
For a base project template to demonstrate this, let's use the NativeScript angular tutorial template. Type the following in the command prompt (obviously you would have needed to set up NativeScript first. Instructions can be found here):
tns create DragDrop --template nativescript-template-ng-tutorial
In the app.component.ts file under the template XML code add the following code:
<ActionBar title="Drag and Drop">
<GridLayout width="100%" height="400" backgroundColor="gray">
<Image #dragImage</Image>
</GridLayout>
Note here that we are giving the Image the local template variable of #dragImage, which we will refer to later. Also notice that we attach the callback function onPan (which we will create shortly), to the NativeScript event (pan). Therefore, when the image is being panned (user drags their finger over the image), the onPan function will be called.
#dragImage
onPan
Also, add the following imports at the top of the file which we will need later:
import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { PanGestureEventData } from "ui/gestures";
import { Image } from "ui/image";
Define the following variables at the top of the class:
@ViewChild("dragImage") dragImage: ElementRef;
dragImageItem: Image;
prevDeltaX: number;
prevDeltaY: number;
The only complicated piece of code above is where we are retrieving the UI Image element using Angular's @ViewChild decorator with our template variable dragImage which we defined in the XML code. However, before we can use this image we will have to store it in a Image variable, which we define next. Then there are two delta movement variables we will need to perform the translation.
dragImage
Image
Good practice is to initialize variables in the ngOnInit function instead of in the constructor, which we inherit from the OnInit class. So let AppComponent implement OnInit as follows:
ngOnInit
OnInit
export class AppComponent implements OnInit
Then add the following function to the class (under the variable declarations):
public ngOnInit() {
this.dragImageItem = <Image>this.dragImage.nativeElement;
this.dragImageItem.translateX = 0;
this.dragImageItem.translateY = 0;
this.dragImageItem.scaleX = 1;
this.dragImageItem.scaleY = 1
}
Next we implement the onPan function, which is where everything comes together.;
}
else if (args.state === 3) // up
{
}
}
In this function we first check which state the panning gesture is in. When the user initially touches the UI element, we reset the panning variables. And while the user is panning, the Image's translateX and translateY properties are updated with only panning change of the last frame. These translate properties works the same as the CSS animation properties, and therefore it refers to the translation from the origin. That is why we are cumulatively changing these properties. The position of the image will now be updated according to the panning gesture.
If we run the code we get the effect shown here:
Now let's take this a step further and add some collision detection. This can be very useful for many applications, such as collecting items in a game or not allowing the user to move an image outside a defined area, which is what we will do. In order to demonstrate how to combine collision detection with the panning of UI elements, we will elaborate on what we have so far.
To start, add the local template variable #container to the GridLayout. For this example we will also ensure that the image starts in the top-left corner, by adding the horizontalAlignment and verticalAlignment properties.
#container
horizontalAlignment
verticalAlignment
<GridLayout #container
<Image #dragImage</Image>
</GridLayout>
We will also need to add the following imports on top of our app.component.ts file.
import { GridLayout } from "ui/layouts/grid-layout";
import { AnimationCurve } from "ui/enums";
And similar to before, since we now would like to know where the edges of the bounding box (GridLayout) is, we also need to retrieve the GridLayout from our XML.
GridLayout
@ViewChild("container") container: ElementRef;
itemContainer: GridLayout;
And, again, we add the following line to our ngOnInit function.
this.itemContainer = <GridLayout>this.container.nativeElement;
Now back to our onPan function. We will use the code we had before but now expand it to restrict the movements of the image to only within the bounding container.;
// calculate the conversion from DP to pixels
let convFactor = this.dragImageItem.width / this.dragImageItem.getMeasuredWidth();
let edgeX = (this.itemContainer.getMeasuredWidth() - this.dragImageItem.getMeasuredWidth()) * convFactor;
let edgeY = (this.itemContainer.getMeasuredHeight() - this.dragImageItem.getMeasuredHeight()) * convFactor;
// X border
if (this.dragImageItem.translateX < 0) {
this.dragImageItem.translateX = 0;
}
else if (this.dragImageItem.translateX > edgeX) {
this.dragImageItem.translateX = edgeX;
}
// Y border
if (this.dragImageItem.translateY < 0) {
this.dragImageItem.translateY = 0;
}
else if (this.dragImageItem.translateY > edgeY) {
this.dragImageItem.translateY = edgeY;
}
}
else if (args.state === 3) // up
{
this.dragImageItem.animate({
translate: { x: 0, y: 0 },
duration: 1000,
curve: AnimationCurve.cubicBezier(0.1, 0.1, 0.1, 1)
});
}
}
A few notes for explanation. There is a challenge we have of two different coordinate systems being used, with no direct way of converting between the two. The PanGestureEventData's deltaX and deltaY variables use the device-independent pixels (dp), which is the same as is returned by the UI element's View.width variable. However, for the GridLayout, since no fixed width is defined, this variable returns “100%”, which is not very useful in terms of dp translation variable comparisons. The same problem would occur for elements defined with the star (*) layout properties. So since the container does not return the desired width when we call View.width, we need to use a trick. Now there is clearly a few ways you could do this, such as retrieving the Page's width, but much easier is to define the Image with a known width in dp (in this case 100), and then to use the function getMeasuredWidth() which returns the width in pixels on the screen, and then with simple division a conversion factor can be calculated. We can then multiply the width and height in pixels with this conversion factor, and we get the width of the container in dp.
getMeasuredWidth()
Now that we know where the edges of the container are, we simply use four if-statements to ensure that the image cannot move outside this border. And then just as a nice effect, whenever the user lifts up his finger the image automatically slides back to the origin position with an animation.
Here is an example of what all of this looks like in practice:
In this post we learned how to drag and drop an image using NativeScript. This same principle can be applied to any of NativeScript's UI elements with very simple adaptions to the code. We also learned how to convert the width of UI elements from onscreen pixels to device-independent pixels. This allowed as to implement a basic collision detection system. And lastly we implemented some basic animations to make the UI element slide back to the origin position.
Thanks for reading, please leave some feedback!
(expect a newsletter every 4-8 weeks) | https://www.nativescript.org/blog/drag-and-drop-ui-elements-with-basic-collision-detection | CC-MAIN-2018-34 | refinedweb | 1,730 | 54.02 |
Read what i wrote, i did not say anything about viewport. I did not selectd that objects in viewport, i selected them in the tree.
Blender Tutorials
I’m testing it, it already works fine.
The developer of it shared a build for testing. You can find it in the following link, among other info about it.
Try to press delete while your mouse cursor is in the outliner.
Yes, you are correct there, it does not delete. I certainly must have moved the cursor to the viewport after selecting them all in outliner.
See
You just have to move the cursor some pixels to the left into the viewport.
Edit: nevertheless is annoying and a substantial fault in interaction model.
OK…so that’s where I (and Scott) were having our issues.
If the cursor is over the outliner you cannot delete an object…unless you use the context menu.
I hope to get a Nvidia 2080 TI in a few months.
So this is cool:
I also hear they are targeting a 3 month cycle for new releases.
That’s correct.
One thing that was freaking me out until I discovered what I was doing wrong.
When doing operations you can tap x,y,z to constrain along an axis. What I was doing wrong was thinking I had to keep the x/y/z held down. The screen would start flashing and jumping around.
A simple tap of the key was all I needed.
A feature that ought to be in both c4d and in blender–but is in neither–is a drop to floor command.
I rely so much on that plugin in c4d…and will be looking for equivalent for Blender.
As it is I enter half the z height into the z location…to get precise seating.
Run this script:
import bpy context = bpy.context for obj in context.selected_objects: mx = obj.matrix_world minz = min((mx @ v.co)[2] for v in obj.data.vertices) mx.translation.z -= minz
Their decision to use the spacebar to start and stop the animation play head is pretty stupid i think, it should be used for toggling the last used tool so you can switch between them… Cinema 4D even though it speciality is motion graphics has for a long time got this right. Blender on the other hand isn’t really as specialised in this area in the same way but has a core key allocated to something which isn’t a continual muscle memory triggered process.
OK…that script works. Now I need to figure out how to make it permanently accessible in the interface.
Scott…c4d uses spacebar for playback as does AE …and other animation apps.
Listen…you are only going to drive yourself – and the rest of us nuts – by critiquing every little thing. There are 10 million Blender users and it is well liked software.
How about you decide if you want to give it a try. If you do decide to jump in…then you have to LEARN. A big part of learning is to not fight everything.
Those are the options that you can choose for your spacebar. (in the preferences)
Tools or search might be more useful to you? Unfortunately the option you want is not there.
There are ways, yeah. I’m too lazy right now, but if I do it I’ll let you know.
The whole navigation is so much better now with the industry standards… and the lower contextual help bar is a great idea.
But to be fair, there are still weird design choices in the UI with some stuff duplicated and scattered a bit everywhere, menus with the same name but different contents etc…
For instance in the property panel, why do you need to get you first “in your face” the data you change the least (scene globals etc…) while you have to scroll down to the very bottom on a tiny icon to find the stuff you need the most… ?
For instance, why not have the render and output settings in say… the render menu (in the top bar)? Call me crazy I know !
In fact, the whole block of “contexts” (scene, world, etc…) should be found in the top menus to free up space and allow for bigger thumbnails for the actual properties that change often. | https://forums.cgsociety.org/t/blender-tutorials/2053089?page=4 | CC-MAIN-2019-35 | refinedweb | 727 | 81.83 |
Heap
Establish the heap property for a given root.Controller: CodeCogs
Interface
C++
MaxHeapify
The function maxHeapify accepts a heap, defined by a pointer to its data and a total node count. It performs the heapify operation on the given root different to the actual root of the heap which resides in position 0 of the data array. A heap is a very important data structure in computing. It can be described as a nearly-complete binary tree. In more simple terms, a heap is a pyramidal data structure which grows downwards from a root node. Each level in the heap has to be complete before the next level begins. Each element in the heap has zero, one or two children. The (max) heap property is that a given node has a value which is greater than or equal to the values held by its children. Heaps are useful because they are very efficiently represented as an array. In the array representation, the following equations are necessary to calculate the indices of the left and right children:
Note
- the root node index starts at 1 rather than 0
Parameters
Authors
- James Warren (July 2005)
Source Code
Source code is available when you buy a Commercial licence.
Not a member, then Register with CodeCogs. Already a Member, then Login.
HeapSort
Heap sort permutes an array of values to lie in ascending numerical order. The code for heap sort is fairly compact, making it a good all round choice. The complexity of heap sort is: Computing/Sort/bucket ). The algorithm is also non-recursive, so can never cause a stack overflow in the case of large data arrays. Heap sort is beaten by Computing/Sort/quick in terms of speed, however, with large data sets the recursive nature of quick sort can become a limiting factor. Heap sort works by firstly transforming the array of values into a max-heap using the <em> maxHeapify </em> function. The maximum values are then read out from the top of the heap one at a time, shrinking the heap by one iteratively. A index moves from the end of the array backwards. Here the maximum values are stored, creating the ascending sorted list.
Example 1
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <codecogs/computing/sort/heap.h> int main() { double vals[25]; int n=25; for (int i=0; i<n; i++) vals[i]=((double) n*rand())/RAND_MAX; printf("\nArray to be sorted:\n"); for (int i=0; i<n; i++) printf("%3.0f ", vals[i]); Computing::Sort::heapSort(vals, n); printf("\nSorted array:\n"); for (int i=0; i<n; i++) printf("%3.0f ", vals[i]); printf("\n"); return 0; }Output:
Array to be sorted: 23 6 6 13 11 10 13 4 9 4 17 14 7 5 16 7 21 7 17 17 23 6 16 9 18 Sorted array: 4 4 5 6 6 6 7 7 7 9 9 10 11 13 13 14 16 16 17 17 17 18 21 23 23
Parameters
Authors
- James Warren (July 2005)
Source Code
Source code is available when you buy a Commercial licence.
Not a member, then Register with CodeCogs. Already a Member, then Login. | https://www.codecogs.com/library/computing/sort/heap.php | CC-MAIN-2020-16 | refinedweb | 536 | 63.7 |
Hi there, I'm having issues with my program. Only one part of the driver program is having issues. For that reason, I've only attached a small section of the code. I was wonder if anyone would be kind enough to explain why I keep having the errors:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range
here is the code:
Code :
import java.util.Scanner; public class characterTest { public static void main(String [] args) { Scanner input = new Scanner(System.in); String str; System.out.println("Enter string"); str = input.next(); int i, count3 = 0; for (i = 1; i <= str.length(); i++) { if (Character.isUpperCase(str.charAt(i))) count3++; } System.out.println("your upper char: " +count3); } }
Thank you for any advice! | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/8131-issue-character-isuppercase-class-printingthethread.html | CC-MAIN-2014-35 | refinedweb | 125 | 54.18 |
Problem
I had a Python script that used Caffe2. It worked fine on one computer. On another computer with same setup, it would fail at the
import caffe2.python line with this error:
WARNING:root:This caffe2 python run does not have GPU support. Will run in CPU only mode. WARNING:root:Debug message: dlopen: cannot load any more object with static TLS CRITICAL:root:Cannot load caffe2.python. Error: dlopen: cannot load any more object with static TLS
As I mentioned above, the GPU support warning is a red herring cause this Caffe2 Python was built with GPU support. The real error is the dlopen.
Solution
The only solution from Googling that gave a clue was this. As suggested there, I placed the
import caffe2.python line at the top above all other imports. The error disappeared.
Tried with: Ubuntu 14.04
Advertisements | https://codeyarns.com/2017/06/09/dlopen-cannot-load-any-more-object-with-static-tls/ | CC-MAIN-2019-26 | refinedweb | 144 | 69.48 |
In this article I will explain how to use Fault Message in BizTalk. When a web service is called, the service might encounter exception (System exception or User defined exception).
The service then serializes the exception and sends across the client as a Fault Message.
My client here is BizTalk and since it is a solicit response port; this kind of scenario is handled by orchestration.
There is an option in send port which will specify whether to allow the fault to travel to orchestration or not.
If we do not enable this option, then the fault message received by the send port is not allowed to go to the orchestration as a Message instead it is treated as any other transmission error in the send port
and the orchestration gets a XlangSoapException object back. If there is an exception handling block for this type or its base type, the exception is handled in orchestration accordingly.
If we enable the “Propagate fault message” option, then the send port is not suspended instead sends the serialized Fault message to the Orchestration. These are the steps on how to handle that fault message in Orchestration.
I am using the standard fault message schema in my example below. You also can have a custom fault message in the service, in which case the custom fault message schema will also be created along, when we create the proxy of the service in
the BizTalk project.
First, add a new Fault Message to the operation that is involved either by right clicking on the operation from the port surface or from the Orchestration View as shown below.
Here, I am creating a Fault Message with the default name Fault_1
Select the Message type as BTS.soap_envelope_1_1.Fault(You can also select any other custom fault message that the service will send). If your service confines to Soap1.2 then select fault1_2 Messagetype.
Now, add an exception handling block to the scope enclosing the send shape, in the drop down of the exception object type select the fault message that we created and I have named the exception object name as SoapFault, as shown below.
In the exception handling block, you can handle the exception using the exception object SoapFault(which is actually a biztalk message not a .Net object). I my example, I have extracted the fault string and logged it.
strfaultmessage = xpath(SoapFault, "string(/*[local-name()='Fault' and namespace-uri()='']/*[local-name()='faultstring' and namespace-uri()=''])");
In this way, you can handle a fault message. You can add multiple fault message provided the fault type is different to an operation and handle the fault in the same way. If the biztalk port receive a fault type which is not handled then it is handled by the default fault type.
Happy Biztalking!!
Written by
Shashidharan Krishnan
Reviewed by
Shailesh Agre
Microsoft India GTSC
Can we have the Sample Code for this example.
Thanks
Nice….it was helpful while i was struggling to catch the same exception
Port1.Helloworld.Fault_1 is not displaying to select in Exception Object Type…..What could be the reason..?Please suggest
Thanks for the post. | https://blogs.msdn.microsoft.com/biztalknotes/2013/02/12/how-to-handle-fault-message-in-biztalk-server/ | CC-MAIN-2018-13 | refinedweb | 524 | 60.95 |
I am in the process of learning basic Python. I am currently attempting to create a simple calculator program that only has addition and subtraction. I have one issue though. I am not sure how I would add text to my Python label upon button press. Right now, upon pressing the '1' button, my program will change the display label to the text "1". However, I want my program to add text, not set it.
For example, if I press 'button 1' 5 times, it currently will reset the label text 5 times and will result with a single 1. I want it to add the number to the label upon press, not replace.
Current Result after pressing button 5 times: 1
Requested result after pressing button 5 times: 11111
Here is my current code for the program. If anything is unclear, just ask; thanks.
from tkinter import *
window = Tk()
# Creating main label
display = Label(window, text="")
display.grid(row=0, columnspan=3)
def add_one():
display.config(text='1')
# Creating all number buttons
one = Button(window, text="1", height=10, width=10, command=add_one)
two = Button(window, text="2", height=10, width=10)
three = Button(window, text="3", height=10, width=10)
four = Button(window, text="4", height=10, width=10)
five = Button(window, text="5", height=10, width=10)
six = Button(window, text="6", height=10, width=10)
seven = Button(window, text="7", height=10, width=10)
eight = Button(window, text="8", height=10, width=10)
nine = Button(window, text="9", height=10, width=10)
zero = Button(window, text="0", height=10, width=10)
# Placing all number buttons
one.grid(row=1, column=0)
two.grid(row=1, column=1)
three.grid(row=1, column=2)
four.grid(row=2, column=0)
five.grid(row=2, column=1)
six.grid(row=2, column=2)
seven.grid(row=3, column=0)
eight.grid(row=3, column=1)
nine.grid(row=3, column=2)
# Creating all other buttons
add = Button(window, text="+", height=10, width=10)
subtract = Button(window, text="-", height=10, width=10)
equal = Button(window, text="=", height=10, width=10)
# Placing all other buttons
add.grid(row=4, column=0)
subtract.grid(row=4, column=1)
equal.grid(row=4, column=2)
window.mainloop()
You should use a StringVar for this. And your callback needs to get the current contents of the StringVar, modify it, and use the modified string to set the new value of the StringVar. Like this:
import tkinter as tk window = tk.Tk() # Creating main label display_text = tk.StringVar() display = tk.Label(window, textvariable=display_text) display.grid(row=0, columnspan=3) def add_one(): s = display_text.get() s += '1' display_text.set(s) one = tk.Button(window, text="1", height=10, width=10, command=add_one) one.grid(row=1, column=0) window.mainloop()
BTW, you should try to make your program a little more compact by using
for loops to create and lay out your buttons, in accordance with the DRY principle.
Also, it's not a good idea to use
from tkinter import *. It imports over 130 names into your namespace, making it easy to create name collisions if you accidentally use a Tkinter name for one of your own variables or functions. | https://codedump.io/share/ql7QFCbocnt5/1/how-would-i-modifyadd-text-to-a-tkinterlabel | CC-MAIN-2017-13 | refinedweb | 537 | 60.92 |
40. Empty model tests
This example is for Django's SVN release, which can be significantly different from previous releases. Get old examples here: 0.96, 0.95.
These test that things behave sensibly for the rare corner-case of a model with no fields.
Model source code
from django.db import models class Empty(models.Model): pass
Sample API usage
This sample code assumes the above model has been saved in a file mysite/models.py.
>>> from mysite.models import Empty >>> m = Empty() >>> m.id >>> m.save() >>> m2 = Empty() >>> m2.save() >>> len(Empty.objects.all()) 2 >>> m.id is not None True >>> existing = Empty(m.id) >>> existing.save() | http://www.djangoproject.com/documentation/models/empty/ | crawl-002 | refinedweb | 109 | 62.44 |
![if gte IE 9]><![endif]><![if gte IE 9]><![endif]><![if gte IE 9]><![endif]><![if gte IE 9]><![endif]>
Hello,
i tried to enter in a low power mode from a interrupt subrutine, but i can`t return. I read in the datasheet about that, but i don´t know what i'm doing wrong. In this code, i want to blink a LED on p1.0 while timer 1 is running and variable "i" is less than 10. When i = 10, i enter to a low power mode (PM2) on the ISR of timer 1, and i try to wake up clearing a bit on port 2 using its ISR. But i can´t return. Any help? Thank you!
#include "ioCC2530.h"/************************************************/void contador_on(void);void contador_off(void);/**************************************************/unsigned char i=0;void main(void){ unsigned long y,x=0; P1 &=~0x01; P1DIR |= 0x01; P1 |= 0x01; PICTL |= 0x08; // Interrupción por flanco de bajada en puerto 2 P2IEN |= 0x01; // Interrupcion habilitada en el p2.0 IEN2 |= 0x02; // Habilitadas las interrupciones para puerto 2 IEN0 |= 0x80; // Habilitadas las interupciones (máscara general off)*/ contador_on(); for(;;){ for(y=0;y<20000;y++) // Toggle a LED on p1.0 P1 &=~0x01; asm("NOP"); // OTRAS ACCIONES for(y=0;y<20000;y++) P1 |= 0x01; }}void contador_on(void) // Inicialize and activation of timer 1{ T1CNTL |= 0x00; // Reset del contador mediante escritura registro T1CTL |= 0x0C; // Tick frecuency / 128 T1CTL |= 0x01; // Se activa el contador del timer TIMIF |= 0x40; // Máscara OFF de interrupción por overflow de timer 1 IEN1 |= 0x02; // Habilitadas las interrupciones para timer 1 IEN0 |= 0x80; // Habilitadas las interupciones (máscara general off)}void contador_off(void) // Stop the timer 1{ T1CTL &=~ 0x0F; // Se desactiva el contador del timer T1CNTL |= 0x00; // Reset del contador mediante escritura registro TIMIF &=~ 0x40; // Máscara ON de interrupción por overflow de timer 1 IEN1 &=~ 0x02; // Deshabilitadas las interrupciones para timer 1}#pragma vector = 0x33 // 0x33 -> vector interrupcion para puerto 2 en evento pin entrada__interrupt __root void P2_ISR(void) { P2IFG &=~ 0x01; // Puesta a cero del flag de interrupc P2IFG.bit0 IRCON2 &=~ 0x01; // Puesta a cero del flag de interrupc IRCON2.P2IF //contador_off(); IRCON &=~ 0x02; // Puesta a cero del flag de interrupc IRCON.T1IF if (i >= 10){ SLEEPCMD &=~ 0x03; contador_on(); P1 |= 0x01; } i=0; // Reinicio contador para desactivación}#pragma vector = 0x4B // 0x4B -> vector interrupcion para timer 1 por desbordamiento__interrupt __root void timer1_ISR(void) { IRCON &=~ 0x02; // Puesta a cero del flag de interrupc T1STAT &=~ 0x20; // Puesta a cero del flag de overflow del timer 1 i++; if(i >= 10){ contador_off(); P1 &=~0x01; SLEEPCMD |= 0x02; PCON = 0x01; asm("NOP"); asm("NOP"); asm("NOP"); }}
You can't wake up from PM2 from Timer1. The reason for this is that the system clock will stop in PM2 in order to save power, and timer 1 will stop counting. The only peripherals that are active in PM2 are the sleep timer and GPIO, which means that the only interrupts that can wake you up from PM2 are the sleep timer interrupts and GPIO interrupts. So to use PM2 in your application, you should use the sleep timer for timing the LED blink.
In reply to hec:
hello Hec,
first of all, thank you very much for your quick answer, buy maybe i didn´t explain very well. i try to enter from the timer 1, here i activate the low power mode, and it doesn´t wake up until the p2.0 is cleared (using the ISR of port 2). I can´t return using this GPIO ISR and IAR send me a warning message saying : " idata and xdata is filled 100%". Any idea? Really thankful!
In reply to David Medina:
Hi,
Sorry about the misunderstanding. I tried your code and saw the behavior that you report. The reason for this is that you cannot wake up on an interrupt which does not have higher priority than the interrupt in which you went to sleep. When you try to do so, the chip will lock up, including the debug interface, and the lock-up of the debug interface casued the warning messages that you see.
In order to wake up correctly, you either have to go to sleep from outside any ISR, or to set a higher priority for the interrupt that will wake you than for the ISR from which you go to sleep. Unfortunately, Timer 1 and Port 2 are in the same interrupt priority group, so it is not possible to set different priority for these two. This means that you must either change one of the interrupt sources or redesign the program so that you go to power mode from the main loop, not directly from an ISR. You can for instance set a flag in the ISR that tells the main program that it is time to go to sleep.
Hello Hec,
thank you very much for your help. i tried to wake up outside the ISR before and it's true it's work, but i couldn't understand why not in ISR. this info will be very helpful for my project. i think i will do some changes on my code to run this propertly. Again, thanks for your help. | http://e2e.ti.com/support/wireless_connectivity/f/155/t/59987 | CC-MAIN-2015-06 | refinedweb | 858 | 65.86 |
On Fri, 2006-07-14 at 10:49 -0600, Eric W. Biederman wrote:> - if (current->fsuid == inode->i_uid)> + if ((current->fsuid == inode->i_uid) &&> + (current->nsproxy->user_ns == inode->i_sb->user_ns))> mode >>= 6; I really don't think assigning a user namespace to a superblock is theright way to go. Seems to me like the _view_ into the filesystem iswhat you want to modify. That would seem to me to mean that each'struct namespace' (filesystem namespace) or vfsmount would be assigneda corresponding user namespace, *not* the superblock.-- Dave-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/7/14/146 | CC-MAIN-2015-22 | refinedweb | 115 | 55.03 |
Hello,
I am using an NXP P89LPC922 with Eclipse and SDCC. I need some
mathematical functions and so I want so include <math.h> but Eclipse is
saying: unresolved inclusion. I tried to find something about that in
the documentation of SDCC but there is not much written. Can anyone help
me on how to get mathematical functions to work with the LPC922?
Thanks in advance.
This has nothing to do with the SDCC compiler. Simply include math.h
like...
#include <math.h>
and thats it.
Thanks,
first include math.h was not working but I found the folder what its
placed. | https://embdev.net/topic/228805 | CC-MAIN-2017-13 | refinedweb | 102 | 79.36 |
Basic problem, please help.
I'm in a java class and my teacher's is horrible. Heavy accent, poorly explains things and goes very fast. Everything I've learned I've learned from the book and online. I've come into a jam here and our project is due Monday.
I have all the program written and it works just peachy, but I don't know how to create worker classes. I know I know, that's bad. I've looked every where. I have it all in the implementation class as of now. But, the only thing that can be in the impl class are input and output methods, no calculation methods. Please help me...
Here is the file:
Any suggestions or explainations would help a lot. I'm not asking for anyone to do my work, just some insight. I only need one worker class for all the calculations. I'll continue to work on my own, this is just a back up plan, thanks all.
Here's the source code if you don't want to download it...
//Steve Hofstetter. CIS 234 Assignment #1
import javax.swing.JOptionPane;
public class VendingMachineImpl
{
public static void main(String[] args)
{
String name,
inputString;
int totalChange,
quarters,
dimes,
nickels,
cost;
//get their name
name = JOptionPane.showInputDialog("What is your name?");
//get cost of time
inputString = JOptionPane.showInputDialog("How much does " + "your item cost? Example: 45 for 45 cents.");
//convert cost to an integer
cost = Integer.parseInt(inputString);
//control whether or not it is greater than 25 and a multiple of 5
if
(cost < 25 || ((cost % 5) != 0))
JOptionPane.showMessageDialog(null, "Your item needs to cost more than 25 cents and be a multiple of 5!!! Make a new selection.");
//if everything is okay, program continues
else {
//calclate change
totalChange = 100 - cost;
//how many quarters
quarters = totalChange / 25;
//how many dimes
dimes = (totalChange % 25) /10;
//how many nickels
nickels = (totalChange % 25 % 10) / 5;
//print name, cost and change
JOptionPane.showMessageDialog(null, "Hello " + name + ". You bought an item for $0." + cost + " with a dollar. Your change is $0." + totalChange);
//print what change consists of
JOptionPane.showMessageDialog(null, "Your $0." + totalChange + " change consists of " + quarters + " quarters and " + dimes + " dimes and " + nickels + " nickels and 0 pennies.");
System.exit(0);
}
}
}
You could make a class that takes an int in the constructor (the amount of change) and checks that it's a multiple of 5. Then, you could give it a method that returns an array of ints with length 3, where ints[0] is the number of nickels, ints[1] is the number of dimes, etc. That would be a worker class. The impl class would then format and print the result array of ints. | https://www.java.net/node/655772 | CC-MAIN-2015-22 | refinedweb | 450 | 77.23 |
Debugging from GDB using pyOCD!
We are pleased to release a python library which allows to drive the Debug Access Port of Cortex-M microcontrollers over CMSIS-DAP!
What can be achieved with pyOCD?
- Debugging using GDB, as a gdbserver
Currently, the library works on Windows (using pyWinUSB as backend) and on Linux (using pyUSB as backend).
Quick overview
Use python to control your mbed platform
from pyOCD.board import MbedBoard board = MbedBoard.chooseBoard() target = board.target flash = board.flash target.resume() target.halt() print "pc: 0x%X" % target.readCoreRegister("pc") pc: 0xA64 target.step() print "pc: 0x%X" % target.readCoreRegister("pc") pc: 0xA30 flash.flashBinary("binaries/l1_lpc1768.bin") print "pc: 0x%X" % target.readCoreRegister("pc") pc: 0x10000000 target.reset() target.halt() print "pc: 0x%X" % target.readCoreRegister("pc") pc: 0xAAC board.uninit()
Use GDB to debug your mbed projects
Before using GDB, a .elf file has to be generated with a GCC toolchain.
- Python code to start a GDB server on port 3333
from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard board = MbedBoard.chooseBoard() # start gdbserver on port 3333 gdb = GDBServer(board, 3333)
- Debug the target from GDB:
arm-none-eabi-gdb l1_lpc1768.elf <gdb> target remote localhost:3333 <gdb> load <gdb> continue
All the source code is available on our git repository under workspace_tools/debugger
You can quickly get started with pyOCD by reading the README. It provides all the information that you need to know concerning the dependencies, installation and how to use the library. There are even some sample programs to get started even quicker!
Conclusion
pyOCD provides a simple and efficient solution to debug mbed platforms over CMSIS-DAP.
We expect quite soon the support of all the mbed platforms in OpenOCD as well. There is even a fork of OpenOCD adding CMSIS-DAP support: cmsis-dap support in OpenOCD
Have fun with pyOCD!
9 comments on Debugging from GDB using pyOCD!:
You need to log in to post a discussion
@Samuel Thanks for amazing works!! Many people asked me about CMSIS-DAP with gdb at Maker Faire Shenzhen. If I knew this, I could say "YES!!".
Why not supprting OS X? Is this because technical difficulties of HID handling on OS X? | https://os.mbed.com/blog/entry/Debugging-from-GDB-using-pyOCD/?compage=1#c7307 | CC-MAIN-2021-49 | refinedweb | 370 | 61.73 |
Pretty print Qt classes in Googletest
I am attempting to dump Qt classes in the Googletest framework.
The basics of how to pretty print custom classes in Googletest is "here":
I've tried an example with QSize, but have been unable to pretty print it so far.
My code attempt:
@
QT_BEGIN_NAMESPACE
void PrintTo (const QSize& size, ::std::ostream* stream)
{
const QString dump = QString("[Size w:") % QString::number(size.width()) %
QString(" h:") % QString::number(size.height()) %
QChar(']');
*stream << dump.toStdString();
}
QT_END_NAMESPACE
@
However, my output is this:
@....\tpeb\test\tpeb_test_graphiccomponents.cpp(475): error: Value of: preferredSize.toSize()
Actual: 8-byte object <80-00 00-00 80-00 00-00>
Expected: QPixmap(pixmapName).size()
Which is: 8-byte object <18-00 00-00 18-00 00-00>@
Any ideas?
Hi everyone,
I have a similar problem. I try to print a QString, for which I implemented a PrintTo method
@void PrintTo(const QString& str, ::std::ostream* os)
{
*os << "QString(" << str.toStdString() << ")";
}@
But I also still get the default output of google test
[----------] 1 test from One
[ RUN ] One.Two
../UnitTests/tests/printtotest.cpp:21: Failure
Value of: second
Actual: { 2-byte object <57-00>, 2-byte object <6F-00>, 2-byte object <72-00>, 2-byte object <6C-00>, 2-byte object <64-00> }
Expected: first
Which is: { 2-byte object <68-00>, 2-byte object <65-00>, 2-byte object <6C-00>, 2-byte object <6C-00>, 2-byte object <6F-00> }
[ FAILED ] One.Two (0 ms)
Does anyone have an idea why we cannot get this to work although in the "googletest documentation": this is described as the way to go?
Since that posting, I made it work, although I don't remember exactly how I did that, unfortunately.
One hint I found in my code is that the PrintTo must not be declared/defined within a namespace. It's possible that this was my original problem.
Hi Asperamanca,
thank you for your answer. In my code, the PrintTo function is not defined inside a namespace. Could you maybe post a part of your code that is already working? That would be a great help for me. Thanks!
I would have posted them right away had I seen something interesting. But here you go:
Example for pretty printing of QString
Header:
@void PrintTo(const QString& dumpObject, ::std::ostream* os);@
Cpp:
@void PrintTo(const QString& dumpObject, std::ostream* os)
{
*os << dumpObject.toStdString();
}@
Nothing else really. No defines, no namespaces before that code. Just including the header file in the cpp file.
Hm, that is the same way I did it, but it doesn't seem to work for me. Maybe it's a compiler specific issue? I use clang on MacOS and Qt 5.3.0
Windows and MSVC 2010. In my case, I do have the PrintTo in a separate library. Although I feel having them in the same project should actually make it easier, not harder.
Funny thing is, it works with a QDateTime object, like this:
@void PrintTo(const QDateTime& dumpObject, std::ostream* os)
{
*os << dumpObject.toString().toStdString();
}@ | https://forum.qt.io/topic/39624/pretty-print-qt-classes-in-googletest | CC-MAIN-2017-51 | refinedweb | 509 | 66.54 |
This tutorial is part of the 2020 Call for Code Global Challenge. It’s also part of the Data analysis using Python learning path.
Python overview
You might think that Python is only for developers and people with computer science degrees. However, Python is great for beginners, even those with little coding experience because it’s free, open source, and runs on any platform. The Python packages documentation is great, and after an introductory course, you have a good foundation to build on.
Python is a general purpose and high-level programming language that is used for more than working with data. For example, it’s good for developing desktop GUI applications, websites, and web applications. However, this tutorial focuses on the data and only goes through getting started with data.
Unstructured versus structured data
Data is broadly classified into unstructured and structured data. Unstructured data refers to data that is mostly free form with information that does not have consistent data types. Hand-written notes by doctors and movie reviews collected from blogs are two examples of unstructured data. On the other hand, structured data is information that is available in an organized format so that it is easily readable. Examples of structured data are tables with variables as columns and records as rows or key-value pairs in a noSQL database.
Introduction to pandas
pandas is an open source Python Library that provides high-performance data manipulation and analysis. With the combination of Python and pandas, you can accomplish five typical steps in the processing and analysis of data, regardless of the origin of data: load, prepare, manipulate, model, and analyze.
There are many options when working with the data using pandas. The following list shows some of the things that can be done using pandas.
- Cleaning data by removing or replacing missing values
- Converting data formats
- Sorting rows
- Deleting or adding rows and columns
- Merging or joining DataFrames
- Summarizing data by pivoting or reshaping
- Creating visualizations
This list is far from complete. See the pandas documentation for more of what you can do.
This tutorial walks you though some of the most interesting features of pandas using structured data that contains information about the boroughs in London. You can download the data used in the tutorial from data.gov.uk.
Getting started with Jupyter Notebooks
Instead of writing code in a text file and then running the code with a Python command in the terminal, you can do all of your data analysis in one place. Code, output, tables, and charts can all be edited and viewed in one window in any web browser with Jupyter Notebooks. As the name suggests, this is a notebook to keep all of your ideas and data explorations in one place. In this tutorial, you use IBM Watson Studio to run a notebook. For this, you need a free IBM Cloud account. The following steps show you how sign up and get started. When you have the notebook up and running, you can go through the notebook.
Prerequisites
To complete this tutorial, you need:
- An IBM Cloud account
- Watson Studio
Steps
Set up
Click Create Resource at the top of the Resources page. You’ll see the resources under the hamburger menu at the upper left.
Select the Lite plan, and click Create.
Go back to the Resources list, click your Watson Studio service, and then click Get Started.
You should now be in Watson Studio.
Click either Create a project or New project.
- Select Create an empty project.
- Give the project a name.
- Choose an existing Object Storage service instance or create a new one. This is used to store the notebooks and data. Note: Don’t forget to click refresh when returning to the Project page.
- Click Create.
Load and run a notebook
Click Add to project, then click Notebook to add a new notebook.
-
- Choose new notebook From File.
- Select the downloaded notebook.
- Select the default runtime.
- Click Create Notebook. The notebook loads.
- Run the notebook. In the open notebook, click Run to run the cells one at a time.
Notebook overview
The following list shows some of the capabilities within pandas that are covered in this tutorial.
- Data exploration (loading data, Series, and DataFrames)
- Data transformation (cleaning data, selecting data, merging data, and grouping data)
- Data visualization
The notebook associated with this tutorial displays more elaborate functions of pandas.
Data exploration
As long as the data is formatted consistently and has multiple records with numbers, text, or dates, you can typically read the data with pandas. For example, a comma-separated text file that is saved from a table in Excel can be loaded into a notebook with the following command.
import pandas as pd df = pd.read_csv('data.csv')
You can load other formats of data files such as HTML, JSON, or Apache Parquet a similar way.
Series and DataFrames
A
Series is a one-dimensional labeled array that can contain data of any type (for example, integer, string, float, or Python objects).
s = pd.Series([1, 3, 5, np.nan, 6, 8]) s
A DataFrame is a two-dimensional data structure. The data consists of rows and columns that you can create in various ways. For example, you can load a file or use a NumPy array and a date for the index. NumPy is a Python library for working with multidimensional arrays and matrices with a large collection of mathematical functions to operate on these arrays.
The following code is an example of a DataFrame
df1 with dates as the index, a 6×4 array of random numbers as values, and column names A, B, C, and D.
dates = pd.date_range('20200101', periods=6) numbers = np.random.randn(6, 4) df1 = pd.DataFrame(numbers, index=dates, columns=['A', 'B', 'C', 'D']) df1
Running the previous code generates an output similar to the following image. The notebook shows a few more ways of creating a DataFrame.
Selecting data
To select data, you access a single row or groups of rows and columns with labels using
.loc[]. (This only works for the column that was set to the index.) Or, you select data by a position with
.iloc[].
boroughs = df.copy() boroughs = boroughs.set_index(['Code']) boroughs.loc['E09000001', 'Inland_Area_(Hectares)']
boroughs.iloc[0]
boroughs.iloc[:,1]
Selecting rows based on a certain condition can be done with boolean indexing. This uses the actual values of the data in the DataFrame as opposed to the row and column labels or index positions. You can combine different columns using
&,
|, and
== operators.
Data transformation
Cleaning data
When exploring data, there are always transformations needed to get it in the format that you need for your analysis, visualization, or model. The best way to learn is to find a data set and try to answer questions with the data. Some things to check when cleaning data are:
- Is the data tidy, such as each variable forms a column, each observation forms a row, and each type of observational unit forms a table?
- Are all columns in the right data format?
- Are there missing values?
- Are there unrealistic outliers?
The following code shows how to add and drop a column that might not be required from the data set using pandas.
boroughs['new'] = 1 boroughs.head()
boroughs = boroughs.drop(columns='new') boroughs.head()
Merging data
pandas has several different options to combine or merge data. The documentation covers these examples. In this notebook, you create two new DataFrames to explore how to merge data. Then, you use
append() to combine these DataFrames.
data = {'city': ['London','Manchester','Birmingham','Leeds','Glasgow'], 'population': [9787426, 2553379, 2440986, 1777934,1209143], 'area': [1737.9, 630.3, 598.9, 487.8, 368.5 ]} cities = pd.DataFrame(data) data2 = {'city': ['Liverpool','Southampton'], 'population': [864122, 855569], 'area': [199.6, 192.0]} cities2 = pd.DataFrame(data2) cities = cities.append(cities2) cities
Grouping data
Grouping data is a quick way to calculate values for classes in your DataFrame.
boroughs.groupby(['Inner/Outer']).mean()
When you have multiple categorical variables, you can create a nested index.
boroughs.groupby(['Inner/Outer','Political control']).sum().head(8)
Data visualization
Visualization in pandas uses the Matplotlib library. This plotting library uses an object-oriented API to embed plots into applications. Some of the examples are line plot, histograms, scatter plot, image plot, and 3D plot. In this tutorial, we use matplotlib.pyplot, which is a collection of command-style functions that make matplotlib work like MATLAB.
The following example shows a visualization of the employment rate through a histogram. You can change the number of bins to get the wanted output on your histogram.
%matplotlib inline import matplotlib.pyplot as plt boroughs = boroughs.reset_index() boroughs['Employment_rate_(%)_(2015)'].plot.hist(bins=10);
Conclusion
This tutorial walked you through the steps to get IBM Cloud, Watson Studio, and a Jupyter Notebook installed. It gave you an overview of the ways of analyzing data using pandas and a notebook that you can run to try it yourself. The tutorial is part of the Data analysis using Python learning path. To continue, look at the next step Introduction to geospatial data using Python. | https://developer.ibm.com/languages/python/tutorials/data-analysis-in-python-using-pandas/ | CC-MAIN-2020-50 | refinedweb | 1,524 | 57.57 |
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0) Gecko/20100101 Firefox/4.0 Build Identifier: I must say I am utterly puzzled by the way and coexist right now, with newer top-level pages using /en-US/ prefixes and most of the reference docs using /en/ prefixes. Anyway, I'm arguing the language prefix for the English documentation should be /en/ rather than /en-US/. I don't think there is any intent to offer a /en-GB/ or some other English localization, or to strictly enforce American English spelling and choice of words. Furthermore, this change from "en" to "en-US" is inconsistent with what is done for other languages. For instance, there is no, only. This might puzzle tech-savvy users (which abound on developer.mozilla.org). Finally, this change partly breaks the Accept-Language detection, as described in Bug 647796. I suspect this might get wontfixed. But still, this "en-US" is the wrong way to go. ;) Reproducible: Always
"en" is DekiWiki's English locale namespace, while "en-US" is django's English locale namespace. Yeah, it's complicated; we're moving away from DekiWiki and towards django. It'll be confusing until we're done. :( I can see how "en" might be preferred, but "en-US" is becoming the standard across Mozilla WebDev sites (support.mozilla.com, addons.mozilla.org, drumbeat.org, etc.) We'll keep bug 647796 for fixing 'en' language detection but wontfix this one. Sorry. :( | https://bugzilla.mozilla.org/show_bug.cgi?id=647801 | CC-MAIN-2017-51 | refinedweb | 249 | 57.87 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Critical
- Resolution: Fixed
- Affects Version/s: None
- Fix Version/s: 2.8.0, 2.7.3, 3.0.0-alpha1
-
- Labels:None
- Hadoop Flags:Reviewed
Description
Right now, during upgrades datanode is processing all the storage dirs sequentially. Assume it takes ~20 mins to process a single storage dir then datanode which has ~10 disks will take around 3hours to come up.
BlockPoolSliceStorage.java
for (int idx = 0; idx < getNumStorageDirs(); idx++) { doTransition(datanode, getStorageDir(idx), nsInfo, startOpt); assert getCTime() == nsInfo.getCTime() : "Data-node and name-node CTimes must be the same."; }
It would save lots of time during major upgrades if datanode process all storagedirs/disks parallelly.
Can we make datanode to process all storage dirs parallelly?
Issue Links
- blocks
-
- depends upon
-
- duplicates
-
- is related to
-
- relates to
-
Activity
- All
- Work Log
- History
- Activity
- Transitions
doTransition is doing either upgrade or rollback on each directory. If transition on each directory is not related each other and the code is thread safe, there should not be any issue doing them in parallel.
Aaron T. Myers, Suresh Srinivas, Colin P. McCabe - do you foresee any issue with above approach? If not, we would like to pick it up and contribute. I see it is very good improvement addition to upgrades.
I am not sure if there was a strong reason behind to do in sequential. But in my quick look, it make sense to do in parallel. Vinay had prepared an initial patch on this and take a look if you can like that and works for you. Vinayakumar B, could you post you patch here as initial pass.
And also Let's look at ATM, Suresh, Colin comments what they will suggest on this further.
Attaching the initial patch for this as mentioned.
This patch is almost similar to what I have in mind. Patch looks good to me. +1 (non-binding)
Minor comment:
Do we need to have an extra lock object or should we simply depend on list like syncronized(succeedDirs)?
Do we need to have an extra lock object or should we simply depend on list like syncronized(succeedDirs)?
Oh Yes, Earlier I was trying to do in another way using direct threads. Missed it while moving to executor service.
Will update in next patch.
Hi Vinayakumar B, Raju Bairishetti, Amareshwari Sriramadasu.
I think it's a great idea to do the upgrade of each storage directory in parallel. Although these upgrades are usually quick, sometimes they aren't. For example, if there is a slow disk, we don't want to slow down the whole process. Another reason is that when upgrades are slow, it's almost always because we are I/O-bound. So it just makes sense to do all the directories (i.e. hard drives) in parallel.
There are a few cases where we will need to change certain log messages to include the storage directory path, to avoid confusion when doing things in parallel. Keep in mind the log messages will appear in parallel, so we won't be able to rely on the log message ordering to tell us which storage directory the message pertains to.
private StorageDirectory loadStorageDirectory(DataNode datanode, NamespaceInfo nsInfo, File dataDir, StartupOption startOpt) throws IOException { ... LOG.info("Formatting ...");
The "Formatting..." log message must include the directory being formatted.
private void linkAllBlocks(DataNode datanode, File fromDir, File toDir) throws IOException { ... LOG.info( hardLink.linkStats.report() ); }
Here is another case where the existing LOG is not enough to tell us which storage directory is being processed.
245 try { 246 IOException ioe = ioExceptionFuture.get(); ... 259 } catch (InterruptedException e) { 260 LOG.error("InterruptedExeption while analyzing" + " blockpool " 261 + nsInfo.getBlockPoolID()); 262 }
If the thread gets an InterruptedException while waiting for a Future, you are simply logging a message and giving up on waiting for that Future. That's not right. I think this would be easier to get right by using Guava's Uninterruptibles#getUninterruptibly. You also should handle CancellationException.
Thanks, guys.
Any concerns about overloading the controller?
Just realized that, parallelism should be added at the datanode level in DataStorage#addStorageLocations(). Not in the BlockPoolSliceStorage.
BlockPoolSliceStorage#loadBpStorageDirectories() called sequentially for each datadir during startup in DataStorage#addStorageLocations()
And during startup, If any one of the blockpool storage directories failed to load/upgrade also, datanode continues to start with other directories available. Only if all directories are failed to load then only it will fail.
Updated the patch, please review.
Any concerns about overloading the controller?
In general, the upgrade workload is creating a bunch of hardlinks, often one per block file. This is not a large amount of I/O in terms of bandwidth. Normally it completes in a second or two. The only cases we have seen problems are where write caching is turned off on the hard disks, forcing a lot of non-sequential I/O to update the inode entries. I would also argue that it is Linux's responsibility to manage sending commands to the disk controller and backing off (putting the user mode process to sleep) if there are too many in flight. So I don't see any concerns here about overloading the disk controller.
Just realized that, parallelism should be added at the datanode level in DataStorage#addStorageLocations(). Not in the BlockPoolSliceStorage.
OK, so your idea is that that will allow us to parallelize upgrades between different block pools. Fair enough.
And during startup, If any one of the blockpool storage directories failed to load/upgrade also, datanode continues to start with other directories available. Only if all directories are failed to load then only it will fail.
I don't think this is true. The DN will not start up if more than dfs.datanode.failed.volumes.tolerated volumes have failed, as per this code:
/** * An FSDataset has a directory where it loads its data files. */ FsDatasetImpl(DataNode datanode, DataStorage storage, Configuration conf ) throws IOException { ... if (volsFailed > volFailuresTolerated) { throw new DiskErrorException("Too many failed volumes - " + "current valid volumes: " + storage.getNumStorageDirs() + ", volumes configured: " + volsConfigured + ", volumes failed: " + volsFailed + ", volume failures tolerated: " + volFailuresTolerated); }
Updated the patch, please review.
ok
OK, so your idea is that that will allow us to parallelize upgrades between different block pools. Fair enough.
Not exactly. DataStorage#addStorageLocations(..) is called per blockpool only. And two different blockpools initialization is synchronized in Datanode.java itself.
synchronized (this) { storage.recoverTransitionRead(this, nsInfo, dataDirs, startOpt); }
My change was because for the same blockpool, each directory is being loaded separately in . DataStorage#addStorageLocations(..).
List<File> bpDataDirs = new ArrayList<File>(); bpDataDirs.add(BlockPoolSliceStorage.getBpRoot(bpid, new File(root, STORAGE_DIR_CURRENT))); ... ... bpStorage.recoverTransitionRead(datanode, nsInfo, bpDataDirs, startOpt);
So in BlockPoolSliceStorage#loadBpStorageDirectories(... Collection<File> dataDirs, ...), dataDirs will have only one directory during startup. So adding parallelism there will not change anything.
I don't think this is true. The DN will not start up if more than dfs.datanode.failed.volumes.tolerated volumes have failed, as per this code:
Yes!! You are right. I just checked only DataStorage#addStorageLocations(..), had totally forgot about dfs.datanode.failed.volumes.tolerated.
Vinayakumar B I Agree, Making changes in BlockPoolSliceStorage won't help us in improving the performance as HDFS-7035 makes the data dir/disk processing atomic.
My bad, initially I was looking into the 2.6.0 branch. Changes in BlockPoolSliceStorage would have been helpful only 2.6.0 branch. Lots of refactoring happened as part of HDFS-7035. It was merged to 2.7.0 branch.
Some minor comments:
Typo mistake in the logs: exception instead of exeption
LOG.error("Unexpected exeption while loading storage directories"
LOG.error("InterruptedExeption while loading storage directories"
Can we shutdown the ExecutorService once the work is done?
Vinayakumar B Have you done any performance benchmarking with this approach? If yes, Could you please post the results here?
Vinayakumar B Have you done any performance benchmarking with this approach? If yes, Could you please post the results here?
Nope. I dont have any results.
Raju Bairishetti, would you mind testing with this patch with your loads?
We are using the 2.6 branch in our cluster. I am benchmarking against the 2.6 branch with a different patch which has changes in BlockPoolSliceStorage class. I don't think those performance metrics will be applicable for this patch.
I think overall functionalitywise, both does same. So, performance results against earlier patch also fine IMO.
Attaching a patch which works with 2.6.0 branch and adding results.
We are seeing a a huge diff in upgrade times of datanode on various clusters.
Sequential processing of volumes in prod clusters
Note: Assuming disk is good if we don't see any errors in dmesg output.
performance metrics with the patch:
Sequential processing of volumes in prod clusters
|Cluster || number of blocks/links|| Upgrade time || Disk health||
|testCluster1 |296472 |20 mins | good |
....
Posted these metrics as we are seeing huge difference in processing times of volumes across clusters. These metrics are not related to patch as the above benchmarking was done without patch.
performance metrics with the patch:
||Node ||Number of blocks or links ||Single volume time total time for processing all volumes ||Processing mechanism||
|node1 |1.326278 million |75 secs |75 secs | parallel |
|node2 |1.325818 million |60 secs |342 secs |sequential
Datanode is expecting higher heap memory(Xmx) to process volumes in parallel.
Vinayakumar B Can we introduce a new config which will tell how many number of volumes can be processed in parallel (i.e. thread pool size)? If the config value is one then it processes all the volumes in sequential.
Thanks Raju Bairishetti for posting the metrics.
Good to see the improvements.
Will post a updated patch soon with the configuration for the num of parallel threads
Updated the patch with configuration
Please review
Thanks Vinayakumar B for the quick response and with the patch.
Can we shutdown the ExecutorService once the work is done?
Vinayakumar B Can we handle this case if you feel it is correct?
One more minor ask: Do we need to validate the config value which is provided by user? Like the config value is valid or not.
int numParallelThreads = datanode.getConf().getInt( + DFSConfigKeys.DFS_DATANODE_PARALLEL_VOLUME_LOAD_THREADS_NUM_KEY, + dataDirs.size());
I feel we should not honor the config value if it is more than number of volumes on the datanode. Can we calculate the num of threads by checking the minimum number between user provided value and number of total volumes (i.e. min(userProvidedValue, dataDirs.size()))? Usually users keep single config value across all datanodes but number of disks on datanodes can be vary. In such cases we may end up spawning more threads than necessary.
Go with number of total volumes if provided value is more?
Amareshwari Sriramadasu yes, we should go with the number of total volumes if provided value is more. Can we use -1 value to start the thread pool with number of volumes in the datanode?
Attached the patch, for using the max dataDirs size threads and Min 1.
+1(non-binding) for the latest patch.
Fixed checkstyle and whitespace warnings.
Please review.
Attached the patch with checkstyle,whitespace and test failure fixes
Attached patch with some more test fixes
Fixed TestReplication which fails intermittently, not exactly related to this Jira.
TestHDFSCLI failed due to collision with hadoop-common precommit job.
TestDataNodeRollingUpgrade passes locally.
Attaching a patch with one more additional change.
finding datanodeUUID by checking all storages, before processing in parallel.
This is required for formatting new dir added and datanode restarted.
Vinayakumar B Seeing check style issue and test failures. Looks good to me otherwise. +1 (non-binding)
Rebased the patch.
All above tests are passing locally.
We've seen in production that the upgrades take ~3hours for 24 disks.
I think it makes sense to simply run a thread for each disk instead of having a new configuration, unless it is possible to parallelize the hard links for individual disks.
thanks Haohui Mai
I will update accordingly
Haohui Mai Thanks for reviewing and comments.
Haohui Mai Datanode may *require more memory* to process all volumes/disks in parallel. I feel, It would be nice to have a configuration in which we can tell how many disks a datanode can process in parallel. If we configure the value to 1 then it falls back to sequential mode(i.e. processing one disk at a time). We can control datanode heap memory by processing few number of disks in parallel.
At INMOBI, We have deployed HDFS-8578-branch-2.6.0.patch in production. We had seen improvements in datanode upgrade time. We have tuned the memory &gc settings to avoid OOM errors.
Datanode may require more memory to process all volumes/disks in parallel.
That doesn't sound right to me. Can you identify why it requires more memory if the tasks of each threads are to create hardlinks for blocks? Note that in the current implementation the lists of blocks have been pre-calculated.
Haohui Mai sure, I will give a try. I had seen OOM errors with 2.6 release when it processed 6 disks in parallel.
Updated the patch
1. Removed the new Configuration for num of parallel threads, using no of disks.
2. fixed TestDataNodeHotSwapVolumes#testReplicatingAfterRemoveVolume() failure. Though its not related to patch, it was failing frequently in jenkins runs for this patch.
Oh, great, there is already an inprogress patch....
private void format(StorageDirectory sd, NamespaceInfo nsInfo, String datanodeUuid) throws IOException { sd.clearDirectory(); // create directory this.layoutVersion = HdfsServerConstants.DATANODE_LAYOUT_VERSION; this.clusterID = nsInfo.getClusterID(); this.namespaceID = nsInfo.getNamespaceID(); this.cTime = 0; this.datanodeUuid = datanodeUuid; if (sd.getStorageUuid() == null) { // Assign a new Storage UUID. sd.setStorageUuid(DatanodeStorage.generateUuid()); } writeProperties(sd); }
Thanks....
There will be only one DataStorage instance per DN. And Values assigned in DataStorage.format() will be same for all directories, because these are not read from disk. layoutVersion is from the code, and other values from NamespaceInfo from namenode. Out of DataStorage's properties in VERSION file below, except storageID(which is not a field of DataStorage), others will be same for all directories after format/upgrade. Below are the properties from Datastorage's VERSION file.
storageID=DS-8a5170b7-a105-45cd-b9b2-9d01c160e11f clusterID=testClusterID cTime=0 datanodeUuid=35e3d456-c507-47c8-aaf9-54e77ce49ce0 storageType=DATA_NODE layoutVersion=-56
So I dont think handling synchronization for properties of DataStorage is required.
Only thing is, have to read datanodeUuid, which will be used later, before going in parallel.
Hope I have cleared the confusion?
-Thanks
Could we assign these values earlier at the time you load properties from all the StorageDirectories for getting datanodeUuid? This could make things more clear.
Use multiple threads to write a shared field without locking is not a good choice although we do not have any problem right now. It implies that the method is thread safe so later people may add some dangerous code in the method...
Thanks.
Attached updated patch
could we assign these values earlier at the time you load properties from all the StorageDirectories for getting datanodeUuid? This could make things more clear.
All properties are loaded while reading from VERSION file.
// Load the VERSION file to know the datanodeUUID readProperties(sd);
Use multiple threads to write a shared field without locking is not a good choice although we do not have any problem right now. It implies that the method is thread safe so later people may add some dangerous code in the method...
Thats a good suggestion, thanks Duo Zhang. Made DataStorage#setFieldsFromProperties(..) synchronized.
If I read the patch correctly the parallelism will be the total number of storage directories:
int numParallelThreads = dataDirs.size();
With 12 disks and 3 namespaces that would mean 36 parallel threads right?
Perhaps it would be better to make this configurable. It can default to 0, meaning as parallel as possible, or any other explicit value set (up to # storage directories, although the newFixedThreadPool with more threads than running would simply not run more in parallel anyway). That way cluster admins can choose to either dial this all the way up, hammer the disks and pagecache and get it over with as soon as possible, or perhaps tune it down a bit in case they choose to keep the NM up and executing tasks in the meantime.
I can imagine that 12 parallel threads (1 per disk in the above example) might turn out to be a reasonable compromise for some use cases.
Wrt. catching InterruptedException, even though the newer patches do distinguish between ExecutionException | CancellationException and others, it is still good form to leave the interrupt status intact by re-interupting the current thread before returning:
Thread.currentThread().interrupt();
Or in this case perhaps yield and break out of the for loop, because the interrupt indicated that the thread should clean up and wrap up asap.
Thanks Joep Rottinghuis for review.
With 12 disks and 3 namespaces that would mean 36 parallel threads right?
Parallelism is within blockpool/namespace. Not all blockpools will be in parallel. Datanode#initStorage() have the synchronization.
synchronized (this) { storage.recoverTransitionRead(this, nsInfo, dataDirs, startOpt); }
Perhaps it would be better to make this configurable. It can default to 0, meaning as parallel as possible,
Earlier versions patch of patch had configurable value. But it was changed to # of storage dirs on suggestion of Haohui Mai.
I can imagine that 12 parallel threads (1 per disk in the above example) might turn out to be a reasonable compromise for some use cases.
Yes, this is what happens.
Wrt. catching InterruptedException, even though the newer patches do distinguish between ExecutionException | CancellationException and others, it is still good form to leave the interrupt status intact by re-interupting the current thread before returning:
Or in this case perhaps yield and break out of the for loop, because the interrupt indicated that the thread should clean up and wrap up asap.
Yes, Will upload updated patch to re-interrupt thread.
Its would be good to wait till all the threads finish instead of leaving fs in bad state.
Patch with re-interrupt.
Please review.
With 12 disks and 3 namespaces that would mean 36 parallel threads right? had seen OOM errors with 2.6 release when it processed 6 disks in parallel.
Raju Bairishetti Vinayakumar B Do you have a better sense of how much the memory footprint of the data node increases due to this parallelism?
The only other case that I see where we do a full scan of the storage directories for hard-linking is during the DataStorage#prepareVolume code path. This has already been parallelized in the DataNode#refreshVolumes method. The number of parallel threads in this case is 1 per changed storage location * 12 (default but configurable) hard-link worker threads.
I am attempting to revert one of our test clusters back to a 256x256 layout and will test this patch out on this cluster. Without parallelism datanodes on this cluster were each taking 1.5hrs to upgrade. missed hard-link workers in my earlier comment. So effective threads would be 12*12=144. As said no parallelism across namespace.
One big spot where I see the memory footprint potentially increasing is in DataStorage#linkBlocksHelper. We build a list of LinkArgs called idBasedLayoutSingleLinks. This has 1 LinkArgs object per hard-link that we will need to create. Now with the parallelism we will have potentially 12 * 3 = 36 of these lists in memory at the same time. In other words, 1 LinkArgs object in memory for every hard-link we have to create on the data node.
Vinayakumar B Woops, sorry I missed the part about no parallelism across namespaces. So 12 of these lists in memory.
One big spot where I see the memory footprint potentially increasing is in DataStorage#linkBlocksHelper
I think you are right. Each list contains LinkArgs entry for all block files and meta files inside each volume. this will be precreated even before starting any hardlink workers for each volume. Each LinkArgs have 2 File objects.
In the above one of the test results, for 1.326278 blocks, There will be 1.326278*2 links required.
So total 1.326278(blocks)*2(blockfile+metafile) LinkArgs instances will be created at same time.
One possible solution to limit memory growth is to rewrite DataStorage#linkBlocks and DataStorage#linkBlocksHelper to use a producer/consumer type model with a bounded queue. For example, you could use a LinkedBlockingQueue with a fixed capacity. The logic roughly in the DataStorage#linkBlocksHelper method would be the producer that adds LinkArgs objects to the queue. The logic in the linkWorkers ExecutorService would simply do what it does now, except it would pull LinkArgs objects out of the queue.
Vinayakumar B Do you want to take a crack at this? If you don't have time in the next day or so let me know and I will take a look.
Attaching the patches for trunk and branch-2.7 for the BlockingQueue approach to solve OOM error.
Had to change the way duplicate entries are handled.
Earlier, duplicates were processed on the list itself.
Now after creating all links, FileAlreadyExistException will be thrown during link creation. based on this, duplicates list will be formed.
Once all link workers are finished, duplicate entries will be processed against the already linked files.
Please review.
Fixed findbugs and checkstyles
Allen Wittenauer, yetus is not actually running in docker.
JAVA_HOME: /home/jenkins/tools/java/jdk1.7.0_79 does not exist. Dockermode: attempting to switch to another. Running in Jenkins mode Processing: HDFS-8578
... except that message only shows up when running under Docker.
I mean. Its falling back to jenkins mode due to Java missing in image.
You're misinterpreting the output entirely.
a. The first message means the value of JAVA_HOME that was inherited from pre-Docker doesn't work in Docker. Since Yetus is running under Docker and wasn't told to use anything different, it's going to find a new one to use instead.
b. Oh, --jenkins was passed, so let's turn on all the specific bits that are enabled when running under Jenkins regardless of whether this is Docker or not.
You'll note:
apache-yetus-201a378/shelldocs/ apache-yetus-201a378/shelldocs/shelldocs.py apache-yetus-201a378/yetus-project/ apache-yetus-201a378/yetus-project/pom.xml Running in Jenkins mode Processing: HDFS-8578 HDFS-8578 patch is being downloaded at Tue Dec 8 10:29:37 UTC 2015 from
... that Yetus tell you it is running in Jenkins mode immediately after untarring too. Jenkins and Docker are not exclusive modes to each other.
There are two different problems:
- data dirs are processed sequentially;
- OOM if all data dirs are processed in parallel.?
> ... Also, #2 need more discussion. ...
Datanode's memory should be large enough to hold all the blocks, otherwise, it won't run. So I think using BlockingQueue with a fixed capacity may not be the best way to solve the problem. We should be able to reduce the memory footprint in the data structures.?
Yes, we can take solving OOM problem in separate jira, just not to hurry.
I will update the patch for #1, along with configuration for numParallelThreads.
Updated patch as suggested by Tsz Wo Nicholas Sze.
- Introduced config dfs.datanode.parallel.volumes.load.threads.num which defaults to # of data dirs configured.
I agree with Tsz Wo Nicholas Sze let's fix the OOM part in a follow up jira. It wound up being more complicated then I originally thought. I also agree that we should make the number of parallel storage dir threads configurable so that users have some way to control the memory footprint of the upgrade.
Thanks Vinayakumar B for the new patch.
I think we have to keep addStorageLocations synchronized since addStorageLocations involves a lot of code. It is very hard to keep synchronization correct if addStorageLocations is not synchronized. In case that there is a synchronization bug, the datanode memory state may be inconsistent and result in data loss. So we should be very careful here.
It would be great if we can process (including load, upgrade, recover) all the directories in parallel. However, it is hard to get everything correct. Let's focus on only upgrade since it is our problem today.
I played around the code. It seems that it is relatively easy to run upgrade in parallel since the hardlink related code are mostly static. I will base on Vinay's patch to work on a patch.
h8578_20151210.patch: execute hardlink tasks in parallel.
The patch is big due to a lot of method header changes. The change actually is simple and safe since the hard link code are almost static. There is no synchronization issues.
I think its a good idea to run all linkBlocks in parallel.
But I do believe patch will not work.
Because, during bpStorage.recoverTransitionRead, linkBlocks will be made async, but while returning, immediately, rename of current-previous happens, also it logs as upgrade completed, even before all links are created and actual upgrade is over.
In my v15 patch, synchronization was removed on addStorageLocations because, getDatanodeUuid() was also synchronized, and threads were getting blocked because of this.
But now, since datanodeUuId is updated only once, we can remove synchronization on this. and can make it volatile.
Will update the patch shortly.
Attaching the updated patch,
restoring the synchronization on addStorageLocations(), but made datanodeUuid as volatile and removed synchronizarion on get/setters.
Good catch! It needs more refactoring to make it work. Will wait for your patch.
Even if addStorageLocations is synchronized, the code inside call() does not have the lock. I think it is hard to make sure the code moved into call() is synchronized correctly.
Synchronization on DataStorage will affect only for this part of the code, which basically does the formatting/loading version file in datanode level. Since data loaded from version file will be same accross all VERSION file, it should not matter.
File root = dataDir.getFile(); try { if (!containsStorageDir(root)) { // It first ensures the datanode level format is completed. StorageDirectory sd = loadStorageDirectory(datanode, nsInfo, root, startOpt); addStorageDir(sd); } else { LOG.info("Storage directory " + dataDir + " has already been used."); } } catch (IOException e) { LOG.warn("Failed to add Storage directory " + dataDir, e); return null; }
Earlier, getDatanodeUuid() was called, which was getting blocked, so only I had removed synchronization on addStorageLocations().
Still I believe there should not be any problem with synchronization.
Only thing is, since I have restored synchronizarion on addStorageLocations(), synchronization on DataStorage#setFieldsFromProperties(..) is removed in latest patch. Still since all values are same values, there should not be any problem with this.
One possible synchronization bug in the patch:
- call -> containsStorageDir -> iterate storageDirs
- call -> addStorageDir -> storageDirs.add(sd)
Another potential dead lock problem:
- call -> loadStorageDirectory -> doTransition -> cannot enter createStorageID since it is synchronized.
- synchronized addStorageLocations but waiting for call.
I believe there are many similar problems which need to be studied carefully.
Because, during bpStorage.recoverTransitionRead, linkBlocks will be made async, but while returning, immediately, rename of current-previous happens, also it logs as upgrade completed, even before all links are created and actual upgrade is over.
It seem that we can move rename in call(). Here is a patch.
h8578_20151211.patch
One possible synchronization bug in the patch:
Storage.storegeDirs was made synchronized lists, so this was not a problem.
Another potential dead lock problem:
Ooops.. Yup, this is a problem. Actually createStorageID doesn't need synchronization.
Checked other parts as well for synchronization issues in DataStorage. I dont think any more exists.
Uploading updated patch.
h8578_20151211b.patch: fixes unit tests.
> Storage.storegeDirs was made synchronized lists, so this was not a problem.
Synchronized lists does not synchronize list iteration.
Tsz Wo Nicholas Sze, thanks for taking this up and for simple way of parallel upgrade.
I have checked the latest patch.
In case of normal "start-dfs.sh -upgrade", I observe below log.
2015-12-12 22:34:09,126 WARN common.Storage (BlockPoolSliceStorage.java:loadBpStorageDirectories(225)) - Failed to analyze storage directories for block pool BP-1461195821-127.0.0.1-1449939842938 java.io.IOException: Data-node and name-node CTimes must be the same. at org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceStorage.loadStorageDirectory(BlockPoolSliceStorage.java:184) at org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceStorage.loadBpStorageDirectories(BlockPoolSliceStorage.java:221) at org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceStorage.recoverTransitionRead(BlockPoolSliceStorage.java:249) at org.apache.hadoop.hdfs.server.datanode.DataStorage.addStorageLocations(DataStorage.java:442) at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:526) at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:1523) at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:1484) at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:320) at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:228) at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:829) at java.lang.Thread.run(Thread.java:745)
Still I see that storagedir was added to successVolumes, that means, exceptions will be ignored..?
It is a bug – it checks CTime too early. Also, upgrade does not need to check it. Will upload a new patch.
h8578_20151212.patch: fixes the bug and cleans up the code.
> ... thanks for taking this up and for simple way of parallel upgrade.
No, thank you! It is based on your patch.
h8578_20151213.patch: Fixes an error message.
There are a lot of test failures in the previous report. However, if we click the link , there are only two tests failed.
Allen Wittenauer, do you know why?
> 458m 22s
From:
Build timed out (after 300 minutes). Marking the build as aborted.
The test run took too long. Jenkins thinks it is killing it before it completes and therefore grabs partial output. But because it is wrapped in a docker container, Yetus still finishes. There's a chance of potentially merging the output of multiple runs, but I'd have to do a lot more research on that.
One other thing: testreport on Jenkins will only show the last JDK executed, not all of them. So in this case, JDK8 errors are only visible via what Yetus reports back.
The failed tests in the previous build do not seem related to the patch.
Allen Wittenauer, thanks a lot for explaining it. I also appreciate you effort on improving Jenkins!
For h8578_20151213.patch
1. I think executor service should be shutdown once the loading is over.
SubmissionService(int numThreads) { super(Executors.newFixedThreadPool(numThreads)); this.numThreads = numThreads; }
2. I think there is some change in behavior, in case of any upgrade failure for any one of the disk.
final int taskCount = service.getCount(); LOG.info("loadBlockPoolSliceStorage: processing " + service); for(int i = 0; i < taskCount; i++) { success.add(service.takeResult()); }
In above part of the code after patch, if any disk fails to upgrade, entire upgrade will fail, even though other upgrades in-progress.. But earlier, only that disk was excluded and upgrade of other disks were continued. Need to handle exceptions here and continue with other disks.
Nit:
3. One checkstyle comment, line length > 80 also can be corrected.
Other changes looks fine.
+1 once addressed.
Hi Tsz Wo Nicholas Sze, thanks for the updated patch! One comment so far:
I think that we can get rid of the SubmissionService class and directly use an ExecutorService instead. You can use the shutdown and awaitTermination methods to wait for all of the doUpgrade tasks to complete. This way we will not need an extra class or to keep track of the number of tasks submitted.
You might need to pass one more list of futures into the methods so that when the callables are submitted we can keep track of the futures to fill the success list at the end. I am not totally convinced that we need this yet though.
Tsz Wo Nicholas Sze
Also, we might want to break this into a few subtasks. I could see there being the following separate patches:.
3. Add the new ExecutorService to parallelize scan in hard-linking (i.e. doUpgrade). This patch would finally add the executor service and make the scan run in parallel.
What do you think? Let me know if I am missing something here. It took me a little bit to wrap my head around the patch again. Splitting it up might help get some more eyes on the patch and have it committed sooner.
Vinayakumar B and Chris Trezzo, thanks for the comments. Will update the patch..
Sure, let's do a code refactoring before changing to processing all storage/data dirs in parallel. Filed
HDFS-9654.
h8578_20160117.patch: addresses the review comments from Vinayakumar B and Chris Trezzo.
Notes that the patch includes the refactoring code posted in
HDFS-9654. Will remove refactoring code once HDFS-9654 has been committed.
HDFS-9654 is now committed (thanks Vinayakumar B and Chris Trezzo for reviewing it.) The refactoring idea is great. Here is a much smaller patch:
h8578_20160128.patch
patch looks great.
Simple nits.
1. typo,doUgrade. I think it was missed in
HDFS-9654.
2. Fix possible checkstyles. Looks very trivial.
3. Can skip to print this when no upgrade tasks?
+ LOG.info("loadBlockPoolSliceStorage: " + tasks.size() + " upgrade tasks"); + for(UpgradeTask t : tasks) { + try { + success.add(t.future.get()); + } catch (ExecutionException e) { + LOG.warn("Failed to add storage directory " + t.dataDir + + " for block pool " + bpid, e); + } catch (InterruptedException e) { + throw DFSUtilClient.toInterruptedIOException("Task interrupted", e); + } + } +
Thank Vinay. Here is a new patch addressing your comment.
h8578_20160128b.patch
+1. Latest patch looks excellent
Chris Trezzo, do you want to take a look?
Looking through the patch now.
Tsz Wo Nicholas Sze Vinayakumar B
One major issue I see with this patch is that we change the order of execution for some of the operations. For example, in DataStorage#loadStorageDirectory the hard-linking of directories now happens after the following:
// 3. Update successfully loaded storage. setServiceLayoutVersion(getServiceLayoutVersion()); writeProperties(sd);
This would present issues in the scenario where the data node fails after the above step, but before hard-linking actually occurs.
> ... we change the order of execution for some of the operations. ...
Chris Trezzo, thanks for the comment. I agree we should not change the order of execution of loading a directory. I think it is preserved by the patch. For DataStorage, doTransition is changed to return a boolean and it returns true when upgrade as shown below.
//DataStorage.loadStorageDirectory if (doTransition(sd, nsInfo, startOpt, callables, datanode.getConf())){ return sd; } // 3. Update successfully loaded storage. setServiceLayoutVersion(getServiceLayoutVersion()); writeProperties(sd); return sd;
//DataStorage.doTransition // do upgrade if (this.layoutVersion > HdfsServerConstants.DATANODE_LAYOUT_VERSION) { if (federationSupported) { // If the existing on-disk layout version supports federation, // simply update the properties. upgradeProperties(sd); } else { doUpgradePreFederation(sd, nsInfo, callables, conf); } return true; // doUgrade already has written properties }
h8578_20160216.patch: sync'ed with trunk.
The failed tests do not seem related.
+1, Latest patch looks good to me.
Vinayakumar B, thanks for reviewing the patch!
Chris Trezzo, do you want to take a look at the latest patch?
Thanks Tsz Wo Nicholas Sze! I now see that the boolean ensures that properties are only written in the case where they have not already been written.
One small nit that might make it clearer with respect to the boolean:
In DataStorage.loadStorageDirectory, maybe pull the write properties into the if statement like so:
//DataStorage.loadStorageDirectory if (!doTransition(sd, nsInfo, startOpt, callables, datanode.getConf())){ // 3. Update successfully loaded storage. setServiceLayoutVersion(getServiceLayoutVersion()); writeProperties(sd); } return sd;
Outside of this small nit, the patch looks good to me. +1.
Thanks Tsz Wo Nicholas Sze and Vinayakumar B for all the work.
h8578_20160218.patch: addresses Chris' comment.
FAILURE: Integrated in Hadoop-trunk-Commit #9343 (See)
HDFS-8578. On upgrade, Datanode should process all storage/data dirs in (szetszwo: rev 66289a3bf403f307844ea0b6ceed35b603d12c0b)
- hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
- hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
- hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
- hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java
I have committed this. Thanks Vinayakumar B for working on this and thanks Chris Trezzo for reviewing the patches!
I have committed this. Thanks Vinayakumar B for working on this.
No. Thank You, for making this simple.
This is causing compilation to fail on branch-2.7.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project hadoop-hdfs: Compilation failure: Compilation failure: [ERROR] /Users/vvasudev/Workspace/apache/committer-rw/hadoop/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java:[57,30] cannot find symbol [ERROR] symbol: class DFSUtilClient [ERROR] location: package org.apache.hadoop.hdfs [ERROR] /Users/vvasudev/Workspace/apache/committer-rw/hadoop/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java:[444,17] cannot find symbol [ERROR] symbol: variable DFSUtilClient [ERROR] location: class org.apache.hadoop.hdfs.server.datanode.DataStorage [ERROR] /Users/vvasudev/Workspace/apache/committer-rw/hadoop/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java:[493,17] cannot find symbol [ERROR] symbol: variable DFSUtilClient [ERROR] location: class org.apache.hadoop.hdfs.server.datanode.DataStorage [ERROR] -> [Help 1]
It looks like DFSUtilClient.java is missing in branch-2.7
HWxxxxx:hadoop vvasudev$ git branch YARN-2139 YARN-3926 branch-2 * branch-2.7 branch-2.8 trunk HWxxxxx:hadoop vvasudev$ git pull Already up-to-date. HWxxxxx:hadoop vvasudev$ find . -name DFSUtilClient.java HWxxxxx:hadoop vvasudev$
Thanks Varun Vasudev, I will fix it soon.
Attaching Committed addendum patch to fix compilation for reference
Fixed the compilation in branch-2.7
Thanks Varun Vasudev for reporting compilation problem and thanks Vinayakumar B for the quick fix.
Tsz Wo Nicholas Sze Vinayakumar B This patch also needs to go into branch-2.8 (which was already cut when this was committed). Same for
HDFS-9654 and HDFS-9730.
Woops. Nevermind. I see the commits there now. Sorry about that
No problem. Thanks for checking.
Closing the JIRA as part of 2.7.3 release.
I am not seeing any critical section code in the code flow. Please clarify me if I am missing anything.
Is there any critical section code which is forcing us to process volumes in sequential? | https://issues.apache.org/jira/browse/HDFS-8578 | CC-MAIN-2017-13 | refinedweb | 6,387 | 59.9 |
I am getting myself deeper into trouble on a program I am working on. I strated out with only four errors and am now up to twelve (I am currently learning and working with six languages-c++,html,javascript,PHP,SQL,and c#). I think my languages are running together!
This program is from a textbook, but is NOT homeework, I am trying to write this as practice for what we are learning on classes and constructors. This asks you to write a program using a class to determine if input is a palindrome. Similar posts have been in here, but not using a class. I will be going to a tutorial next week on this, but I would like to continue to work through it in the meantime. Can someonre help me back onto track.
#include <string> #include <iostream> using namespace std; //create class class PString : public string { public: PString(const string &aString); bool isPalindrome() const; }; //constructor PString::PString( const string &aString ) : string( aString ) { } //funct to check pal bool PString::isPalindrome() const {string upperCase (string str) { for (int i = 0; i < str.size(); i++) if(islower(str[i])) str[i] = toupper(str[i]); return str; } bool checkPalindrome(string str) { int n = str.size(); for (int i=0; i<str.size()/2;i++) if (str[i] !=str[n-1-i]) return false; return true; } int main() { string str; cout << "This program is a palindrome-testing program. Enter a string to test:\n"; cin >> str; // Create a PString object that will check strings PString s(str); // Check string and print output if (s.isPalindrome()) { cout << s << " is a palindrome"; } else { cout << s << " is not a palindrome"; } cout << endl; system("pause"); return 0; } | https://www.daniweb.com/programming/software-development/threads/356401/getting-deeper-into-trouble | CC-MAIN-2017-09 | refinedweb | 281 | 71.55 |
driver enables such hotkey facilities of various Panasonic laptops as changing LCD brightness, controlling mixer volumes, entering sleep or suspended state and so on. On the following models it is reported to work: Let's note (or Toughbook, outside Japan) CF-R1N, CF- R2A and CF-R3. It may also work on other models as well. The driver consists of three functionalities. The first is to detect hotkey events and take corresponding actions, which include changing LCD luminance and speaker mute state. The second role is to notify occurrences of the event by way of devctl(4) and eventually to devd(8). The third and last is to provide a way to adjust LCD brightness and sound mute state via sysctl(8). Hot driver. Fn+F4 Toggle muting the speaker. Fn+F5 Turn the mixer volume down. Fn+F6 Turn the mixer volume up. Fn+F7 Enter suspend-to-RAM state. Fn+F9 Show battery status. Fn+F10 Enter suspend-to-disk state. Actions are automatically taken within the driver for Fn+F1, Fn+F2 and Fn+F4. For the other events such as mixer control and showing battery status, devd(8) should take the role as described below. devd(8) Events When notified to devd(8), the hotkey event provides the following information: system "ACPI" subsystem "Panasonic" type The source of the event in ACPI namespace. The value depends on the model but typically "\_SB_.HKEY". notify Event code (see below). Event codes to be generated are assigned as follows: 0x81-0x86, 0x89 Fn+F<n> pressed. 0x81 corresponds to Fn+F1, 0x82 corresponds to Fn+F2, and so on. 0x01-0x07, 0x09, 0x1a Fn+F<n> released. 0x01 corresponds to Fn+F1, 0x02 corresponds to Fn+F2, and so on.
SYSCTL VARIABLES
The following MIBs are available: hw.acpi.panasonic.lcd_brightness_max The maximum level of brightness. The value is read only and automatically set according to hardware model. hw.acpi.panasonic.lcd_brightness_min The minimum level of brightness. The value is read only and automatically set according to hardware model. hw.acpi.panasonic.lcd_brightness Current brightness level of the LCD (read-write). The value ranges from hw.acpi.panasonic.lcd_brightness_min to hw.acpi.panasonic.lcd_brightness_max. hw.acpi.panasonic.sound_mute A read-write boolean flag to control whether to mute the speaker. The value 1 means to mute and 0 not.>. | http://manpages.ubuntu.com/manpages/precise/man4/acpi_panasonic.4freebsd.html | CC-MAIN-2013-20 | refinedweb | 391 | 52.26 |
Hi all,
I've been working with activating conda env from python script and probably by mistake modified the way my interpreter starts. I ended up with a bash script generated from python script and calling it by subprocess.Popen(...)
Now to the problem, every time I'm in debugging mode and calling console in Pycharm, I have doubled interpreter start which slows down a lot the process.
One thing I remeber had to do with conda itself that asked me to copy some lines to my ~/.bashrc however I don't remember what exactly though. Can anyone help me please??
import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 6.3.1
self
Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51)
[GCC 7.2.0] on linux
Out[2]: <__main__.Controller at 0x7f7854037da0>
also, it seems that debugging itself is super slow when working with big arrays (like TIFF image 30MB converted to array by mpimg.pil_to_array). is there a way to somehow accelerate it?
Hi,
Does unchecking Use IPython if available option under Settings/Preferences | Build, Execution, Deployment | Console help?
Please attach a screenshot of your Run/Debug Configuration and a screenshot showing this problem in PyCharm.
It kinda worked, thanks. I think the problem was partly because of the heavy files I operated with | https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001714659-double-call-of-python-interpreter-when-debugging | CC-MAIN-2019-22 | refinedweb | 260 | 69.18 |
Sugar Prices in China Fall After Government Auction (Update2)
July 19 (Bloomberg) -- Sugar prices in China, the world's second-largest
consumer of the sweetener, fell for a third day to an all-time low after
a state auction attracted less interest from local buyers, raising
concerns of an oversupply.
The government failed to sell 92,000 metric tons of refined sugar at an
auction yesterday. A second attempt today fetched prices that average
4.1 percent less than the previous, sale organizer China Merchandise
Reserve Management Center said in a statement on its Web site.
``This is the first time such an auction failed'' on its first attempt,
said Huang Yongjin, sugar analyst at Shenzhen- based Top Win Futures Co.
China aims to sell an extra 552,000 tons by Sept. 12, he said. ``Buyers
all expect sugar prices to be depressed further by more auctions
ahead,'' Huang said.
China, trying to cool rising consumer prices, wants to lower sugar
prices that almost doubled in the past year. It auctioned 386,000 tons
from government inventories in the first six months and has said it will
import supplies from Cuba.
White, or refined, sugar futures for delivery in March ended trading
down 16 yuan at 4,001 yuan ($500) a ton on the Zhengzhou Commodity
Exchange. Earlier the futures touched a record low of 3,975 yuan. They
have declined 16 percent since they began trading on Jan. 6.
Prices at the auction today averaged 4,378 yuan a ton, compared with an
average of 4,567 yuan a ton at the previous auction last month. The
Chinese government has held eight auctions of sugar from state reserves
this year.
Inflation
Consumer prices in China rose 1.5 percent in June, the fastest pace
since January, a government report yesterday showed. China's central
bank may raise its benchmark interest rate by the end of September to
curb economic growth.
Only India consumes more sugar than China.
Global sugar production is poised to rise 0.2 percent in the year
through September, erasing an anticipated shortfall, according to F.O.
Licht. Consumption growth may be limited to 1.1 percent, partly because
of increased use of sugar substitutes, especially in Mexico and China,
the Ratzeburg, Germany-based company said last week.
To contact the reporters on this story:
Feiwen Rong in Singapore at Frong2@bloomberg.net
Last Updated: July 19, 2006 04:18 EDT | http://cubadata.blogspot.com/2006/08/sugar-prices-in-china-fall-after.html | crawl-002 | refinedweb | 405 | 64.3 |
Get the highlights in your inbox every week.
Build web apps to automate sysadmin tasks | Opensource.com
Build web apps to automate sysadmin tasks
There are lots of ways to save time as a sysadmin. Here's one way to build a web app using open source tools to automate a chunk of your daily routine away.
Subscribe now
System administrators (sysadmins) waste thousands of hours each year on repetitive tasks. Fortunately, web apps, built using open source tools, can automate a significant portion of that pain away.
For example, it takes only about a day to build a web app using Python and JavaScript to reclaim some of that time. Here is the core structure that any web application must have:
- A backend to persist data
- A web server to host and route traffic
- An HTML user interface
- Interactive JavaScript code to make it more functional
- CSS layout and styling to make it pretty
The scenario: Simplify employee offboarding
Imagine you're a sysadmin at a company with a thousand employees. If the average employee leaves after three years, you have to offboard an employee every single day. That's a significant time sink!
There's a lot to do when an employee leaves: remove their user account from LDAP, revoke GitHub permissions, take them off payroll, update the org chart, redirect their email, revoke their keycard, etc.
As a sysadmin, your job is to automate your job away, so you've already written some offboarding scripts to run the IT side of this automatically. But HR still has to call you and ask you to run each of your scripts, and that's an interruption you can do without.
You decide to dedicate one full day to automating away this problem, saving you hundreds of hours in the long run. (There is another option, which I'll present at the end of this article.)
The app will be a simple portal you can give to HR. When HR enters the departing user's email address, the app runs your offboarding scripts in the background.
Its frontend is built in JavaScript, and the backend is a Python app that uses Flask. It's hosted using Nginx on an AWS EC2 instance (or it could be in your corporate network or private cloud). Let's look at each of these elements in turn, starting with the Python (Flask) app.
Start with the backend
The backend allows you to make an HTTP POST request to a particular URL, passing in the departing employee's email address. The app runs your scripts for that employee and returns success or failure for each script. It uses Flask, a Python web framework that's ideal for lightweight backends like this.
To install Flask, create a Python Virtual Environment, then use pip to install it:
~/offboarding$ virtualenv ~/venv/offboarding
~/offboarding$ source ~/venv/offboarding/bin/activate
(offboarding) ~/offboarding$ pip3 install flask
Collecting flask
Downloading
...
Handle a request with Flask
Create HTTP endpoints in Flask by decorating functions with @app.route(<url>, ...), and access the request data using the request variable. Here's a Flask endpoint that reads the employee's email address:
#!/usr/bin/env python3
from flask import Flask, request
app = Flask(__name__)
@app.route('/offboard', methods=['POST'])
def offboard():
employee_email = request.json.get('employeeEmail')
print("Running offboarding for employee {} ...".format(employee_email))
return 'It worked!'
if __name__ == "__main__":
app.run(threaded=True)
It responds to the HTTP request with status 200 and the text "It worked!" in the body. To check that it works, run the script; this runs the Flask development server, which is good enough for testing and light use (despite the warning).
(offboarding) ~/offboarding$ ./offboarding.py
* Serving Flask app "offboarding" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on (Press CTRL+C to quit)
Here's a curl command that makes a request:
~$ curl -X POST \
-d '{"employeeEmail": "shaun@anvil.works"}' \
-H "Content-Type: application/json" \
It worked!
The final line is the response from the server: it's working! Here's what the server prints:
Running offboarding for employee shaun@anvil.works ...
127.0.0.1 - - [05/Sep/2019 13:10:55] "POST /offboard HTTP/1.1" 200 -
It's up and running! You have an endpoint that can take in your data. Expand this to make it run the pre-existing offboarding scripts.
Run the scripts with Python
To keep things simple, put the scripts in a single folder and iterate over the folder, running anything you find. That way, you don't need to modify the code and restart the server to add new scripts to your offboarding process; you can just copy them into the folder (or create symlinks).
Here's how the Flask app looks when it's been modified to do that (the comments in the code point out some best practices):
#!/usr/bin/env python3
from flask import Flask, request
import subprocess
from pathlib import Path
import os
app = Flask(__name__)
# Set the (relative) path to the scripts directory
# so we can easily use a different one.
SCRIPTS_DIR = 'scripts'
@app.route('/offboard', methods=['POST'])
def offboard():
employee_email = request.json.get('employeeEmail')
print("Running offboarding for employee {} ...".format(employee_email))
statuses = {}
for script in os.listdir(SCRIPTS_DIR):
# The pathlib.Path object is a really elegant way to construct paths
# in a way that works cross-platform (IMO!)
path = Path(SCRIPTS_DIR) / script
print(' Running {}'.format(path))
# This is where we call out to the script and store the exit code.
statuses[script] = subprocess.run([str(path), employee_email]).returncode
return statuses
if __name__ == "__main__":
# Running the Flask server in threaded mode allows multiple
# users to connect at once. For a consumer-facing app,
# we would not use the Flask development server, but we expect low traffic!
app.run(threaded=True)
Put a few executables in the scripts/ directory. Here are some shell commands to do that:
mkdir -p scripts/
cat > scripts/remove_from_ldap.py <<EOF
#!/usr/bin/env python3
print('Removing user from LDAP...')
EOF
cat > scripts/revoke_github_permisisons.py <<EOF
#!/usr/bin/env python3
import sys
sys.exit(1)
EOF
cat > scripts/update_org_chart.sh <<EOF
#!/bin/sh
echo "Updating org chart for $1..."
EOF
chmod +x scripts/*
Now, restart the server, and run the curl request again. The response is a JSON object showing the exit codes of the scripts. It looks like revoke_github_permissions.py failed on this run:
~$ curl -X POST \
-d '{"employeeEmail": "shaun@anvil.works"}' \
-H "Content-Type: application/json" \
{"remove_from_ldap.py":0,"revoke_github_permissions.py":1,"update_org_chart.sh":0}
Here's the server output; this time it informs us when each script starts running:
Running offboarding for employee shaun@anvil.works ...
Running scripts/remove_from_ldap.py
Running scripts/revoke_github_permissions.py
Running scripts/update_org_chart.sh
127.0.0.1 - - [05/Sep/2019 13:30:55] "POST /offboard HTTP/1.1" 200 -
Now you can run your scripts remotely by making an HTTP request.
Add authentication and access control
So far, the app doesn't do any access control, which means anyone can trigger offboarding for any user. It's easy to see how this could be abused, so you need to add some access control.
In an ideal world, you would authenticate all users against your corporate identity system. But authenticating a Flask app against, for example, Office 365, would take a much longer tutorial. So use "HTTP Basic" username-and-password authentication.
First, install the Flask-HTTPAuth library:
(offboarding) ~/offboarding$ pip3 install Flask-HTTPAuth
Collecting Flask-HTTPAuth
Downloading …
Now require a username and password to submit the form by adding this code to the top of offboarding.py:
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {
"hr": generate_password_hash("secretpassword"),
}
@auth.verify_password
def verify_password(username, password):
if username in users:
return check_password_hash(users.get(username), password)
return False
@app.route('/offboard', methods=['POST'])
@auth.login_required
def offboard():
# ... as before …
Specify a username and password for the request to succeed:
~$ curl -X POST \
-d '{"employeeEmail": "shaun@anvil.works"}' \
-H "Content-Type: application/json" \
Unauthorized Access
ubuntu@ip-172-31-17-9:~$ curl -X POST -u hr:secretpassowrd \
-d '{"employeeEmail": "shaun@anvil.works"}' \
-H "Content-Type: application/json" \
{"remove_from_ldap.py":0,"revoke_github_permisisons.py":1,"update_org_chart.sh":0}
If the HR department were happy using curl, you'd pretty much be done. But they probably don't speak code, so put a frontend on it. To do this, you must set up a web server.
Set up a web server
You need a web server to present static content to the user. "Static content," refers to the code and data that ends up being used by the user's web browser—this includes HTML, JavaScript, and CSS as well as icons and images.
Unless you want to leave your workstation on all day and carefully avoid tugging the power cable out with your feet, you should host your app on your company's network, private cloud, or another secure remote machine. This example will use an AWS EC2 cloud server.
Install Nginx on your remote machine following the installation instructions:
sudo apt-get update
sudo apt-get install nginx
It's already serving anything put into /var/www/html, so you can just drop your static content into there.
Configure Nginx to talk to Flask
Configure it to be aware of the Flask app. Nginx lets you configure rules about how to host content when the URL matches a certain path. Write a rule that matches the exact path /offboard and forwards the request to Flask:
# Inside the default server {} block in /etc/nginx/sites-enabled/default...
location = /offboard {
proxy_pass;
}
Now restart Nginx.
Imagine your EC2 instance is at 3.8.49.253. When you go to in your browser, you see the "Welcome to Nginx!" page, and if you make a curl request against, you get the same results as before. Your app is now online!
There are a couple more things left to do:
- Buy a domain and set up a DNS record ( is not pretty!).
- Set up SSL so that the traffic is encrypted. If you're doing this online, Let's Encrypt is a great free service.
You can figure out these steps on your own; how they work depends strongly on your networking configuration.
Write the frontend to trigger your scripts
It's time to write the frontend HR will use to access the app and start the scripts.
HTML for an input box and button
The frontend will display a text box that HR can use to enter the departing user's email address and a button to submit it to the Flask app. Here's the HTML for that:
<body>
<input type="email" id="email-box" placeholder="Enter employee email" />
<input type="button" id="send-button" onclick="makeRequest()" value="Run" />
<div id="status"></div>
</body>
The empty <div> stores the result of the latest run.
Save that to /var/www/html/offboarding/index.html and navigate to. Here's what you get:
It's not very pretty—yet—but it's structurally correct.
JavaScript and jQuery for making the request
See onclick="makeRequest()" in the HTML for the button? It needs a function called makeRequest for the button to call when it's clicked. This function sends the data to the backend and processes the response.
To write it, first add a <script> tag to your HTML file to import jQuery, a really useful JavaScript library that will extract the email address from your page and send the request:
<head>
<script src=""></script>
</head>
...
To make an HTTP POST request using jQuery:
This request is made asynchronously, meaning the user can still interact with the app while they're waiting for a response. The $.ajax returns a promise, which runs the function you pass to its .done() method if the request is successful, and it runs the function you pass to its .fail() method if the request fails. Each of these methods returns a promise, so you can chain them like:
$.ajax(...).done(do_x).fail(do_y)
The backend returns the scripts' exit codes when the request is successful, so write a function to display the exit code against each script name in a table:
function(data) {
// The process has finished, we can display the statuses.
var scriptStatuses = data;
$('#status').html(
'<table style="width: 100%;" id="status-table"></table>'
);
for (script in scriptStatuses) {
$('#status-table').append(
'<tr><td>' + script + '</td><td>' + scriptStatuses[script] + '</td></tr>'
);
}
}
The $('#status').html() gets the HTML Document Object Model (DOM) element with ID status and replaces the HTML with the string you pass in.
On failure, trigger an alert with the HTTP status code and response body so the HR staff can quote it to alert you if the app breaks in production. The full script looks like this:
var makeRequest = function makeRequest() {
// Make an asynchronous request to the back-end
var jqxhr = $.ajax({
type: "POST",
url: "/offboard",
data: JSON.stringify({"employeeEmail": $('#email-box')[0].value}),
contentType: "application/json"
}).done(function(data) {
// The process has finished, we can display the statuses.
console.log(data);
var scriptStatuses = data;
$('#status').html(
'<table style="width: 100%;" id="status-table"></table>'
);
for (script in scriptStatuses) {
$('#status-table').append('<tr><td>' + script + '</td><td>' + scriptStatuses[script] + '</td></tr>');
}
})
.fail(function(data, textStatus) {
alert( "error: " + data['statusText']+ " " + data['responseText']);
})
}
Save this script as /var/www/html/offboarding/js/offboarding.js and include it in your HTML file:
<head>
<script src=""></script>
<script src="js/offboarding.js"></script>
</head>
...
Now when you enter an employee email address and hit Run, the scripts will run and provide their exit codes in the table:
It's still ugly, though! It's time to fix that.
Make it look good
Bootstrap is a good way to style your app in a neutral way. Bootstrap is a CSS library (and more) that offers a grid system to make CSS-based layouts really easy. It gives your app a super clean look and feel, too.
Layout and styling with Bootstrap
Restructure your HTML so things will end up in the right places in Bootstrap's row and column structure: columns go inside rows, which go inside containers. Elements are designated as columns, rows, and containers using the col, row, and container CSS classes, and the card class gives the row a border that makes it look self-contained.
The input boxes are put inside a <form> and the text box gets a <label>. Here's the final HTML for the frontend:
<head>
<link href="" rel="stylesheet" />
<link href="" rel="stylesheet" />
<script src=""></script>
<script src=""></script>
<script src="js/offboarding.js"></script>
</head>
<body>
<div class="container" style="padding-top: 40px">
<div class="row card" style="padding: 20px 0">
<div id="email-input" class="col">
<form>
<div class="form-group">
<label for="email-box">Employee Email</label>
<input type="email" class="form-control" id="email-box" placeholder="Enter employee email" />
</div>
<input type="button" class="btn btn-primary" id="send-button" onclick="makeRequest()" value="Run" />
</form>
<div id="status"></div>
</div>
</div>
</div>
</body>
Here's how the app looks now—it's a huge improvement.
Add status icons
One more thing: the app reports the status with 0 for success and 1 for failure, which often confuses people who aren't familiar with Unix. It would be easier for most people to understand if it used something like a checkmark icon for success and an "X" icon for failure.
Use the FontAwesome library to get checkmark and X icons. Just link to the library from the HTML <head>, just as you did with Bootstrap. Then modify the loop in the JavaScript to check the exit status and display a green check if the status is 0 and a red X if the status is anything else:
for (script in scriptStatuses) {
var fa_icon = scriptStatuses[script] ? 'fa-times' : 'fa-check';
var icon_color = scriptStatuses[script] ? 'red' : 'green';
$('#status-table').append(
'<tr><td>' + script + '</td><td><i class="fa ' + fa_icon + '" style="color: ' + icon_color + '"></i></td></tr>'
);
}
Test it out. Enter an email address, hit Run, and…
Beautiful! It works!
Another option
What a productive day! You built an app that automates an important part of your job. The only downside is you have to maintain a cloud instance, frontend JavaScript, and backend Python code.
But what if you don't have all day to spend automating things or don't want to maintain them forever? A sysadmin has to keep all the many plates spinning, deal with urgent requests, and fight an ever-growing backlog of top-priority tickets. But you might be able to sneak 30 minutes of process improvement on a Friday afternoon. What can you achieve in that time?
If this were the mid-'90s, you could build something in Visual Basic in 30 minutes. But you're trying to build a web app, not a desktop app. Luckily, there is help at hand: You can use Anvil, a service built on open source software to write your app in nothing but Python — this time in 30 minutes:
Full disclosure: Anvil is a commercial service - although everything we do in this article you can do for free! You can find a step-by-step guide to building this project on the Anvil blog.
No matter which path you take going forward—doing it on your own or using a tool like Anvil, we hope you continue to automate all the things. What kind of processes are you automating? Leave a comment to inspire your fellow sysadmins.
1 Comment, Register or Log in to post a comment.
It’s hard to find good quality writing like yours these days. Very good article, keep writing | https://opensource.com/article/19/9/web-apps-sysadmins | CC-MAIN-2021-25 | refinedweb | 2,957 | 65.01 |
Per Kreipke wrote:
>Very simple summary of thread so far:
>
>a. what Stefano, Michael, Gianugo, Ulrich agree on is that handling #1-4
>
>b. it'd be extremely hard to edit #6 (the output): reversing the
>transformations, then decomposing it into its constituent pieces using the
>'reverse pipeline' discussed in this thread. How it even work when the same
>document is available in PDF, WML, HTML, XML, on different devices, etc? As
>stated by others: does it even have meaning to edit a transformed document
>because it implies that the author is crossing concerns (e.g.
>presentation/content)?
>
There is a difference between the browsable web site and the atomic
content unit that this website contains. We cannot reverse the
transformations that Cocoon made to generate a particular web page in
order to retrieve the atomic content unit that make it up, so we have to
concentrate on using WebDAV on loading and saving those units. Let's
make an example where I can show how we can address this topic fairly easy:
We have a intranet web page of a company here; on the right side, there
are several current news articles, each just showing the news title and
a one line summary, while the news title is a link to a page showing the
whole article. On the center, we see the full-blown detailed news
article. Loading and saving this whole web page directly via WebDAV does
not make sense, as we cannot propagate changes back into the appropriate
places correctly.
Instead of editing the full page, I logon to the site. As a consequence,
the web page is now being rendered with a additional links next to each
atomic content unit. On the right side, next to each news article
summary, and on the center, next to the title of the full-blown news
article, there are links called "edit", each referring to a seperate
WebDAV-URI from where this atomic content unit can be loaded and saved
to in a format which is suitable for editing, eg OO or Word. I click on
the link, with the protocol being registered to the editing application.
For OO and WebDAV, this would be "vnd.sun.star.webdav://". As a
consequence, OO opens, loads the content and presents it in an end-user
compatible way. We modify the content to our needs and simply save it back.
As Cocoon allows transforming XML content to a multitude of formats
(PDF, RTF, PS), stacking WebDAV support ON Cocoon gives many interesting
opportunities. Speaking in Cocoon terms, we could add Serializers for OO
(my favourite) to deliver OO files and write a Generator (Deserializer)
to retrieve back the content, to allow the following:
1.) We can load and save contents, allowing additional steps like
workflow operations to be interwoven.
2.) We can browse and load dynamic virtual contents; any application
that might benefit from concepts like virtual harddisks (eg. Explorer
namespace extension) can now do so in a server-based manner easily.
>Observations/Questions:
>
>i. is 'web folders' access to #1-6 necessary (e.g. does it need to be
>browsable)? We could just use WebDAV to do resource locking, searching,
>versioning, etc without browsing.
>
I am against leaving browsability behind; a solution should be able to
cope with WebDAV completely.
>ii. corollary: perhaps not all methods of WebDAV need to be supported.
>
>iii. WebDAV access to #1-4 (sitemap) would be interesting and would require
>integration with Cocoon. I can't wait to see a Cocoon aware IDE based on
>this.
>
>iv. WebDAV access to #5 (content) shouldn't require access through Cocoon,
>it could integrate directly to the XML content (dbXML, etc). This is the
>'atomic' stuff Stefano, et al mentioned (I think). Con: it would require a
>separate URL space independent of the sitemap controlled space.
>
Again, I think WebDAV access through Cocoon is more than worth the effort.
Best regards,
Michael Hartle,
Hartle & Klug GbR
---------------------------------------------------------------------
To unsubscribe, e-mail: cocoon-dev-unsubscribe@xml.apache.org
For additional commands, email: cocoon-dev-help@xml.apache.org | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200111.mbox/%3C3BE2E327.9090700@hartle-klug.com%3E | CC-MAIN-2016-22 | refinedweb | 678 | 61.16 |
Generic 3D primitive description class.
See TBuffer3DTypes for producer classes....
TVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const TBuffer3D & buffer, Bool_t * addChildren = 0)
If you use the first (simple) case a viewer using logical/physical pairs SetSectionsValid(TBuffer3D::kBoundingBox);.
Definition at line 17 of file TBuffer3D.h.
#include <TBuffer3D.h>
Definition at line 43 of file TBuffer3D.h.
Definition at line 49 of file TBuffer3D.h.
Destructor.
Construct from supplied shape type and raw sizes
Definition at line 222 of file TBuffer3D.cxx.
Destructor.
Definition at line 235 of file TBuffer3D.cxx.
Clear any sections marked valid.
Definition at line 286 of file TBuffer3D.cxx.
Decrement CS level.
Definition at line 512 of file TBuffer3D.cxx.
Return CS level.
Definition at line 496 of file TBuffer3D.cxx.
Definition at line 68 of file TBuffer3D.h.
Increment CS level.
Definition at line 504 of file TBuffer3D.cxx.
Initialise buffer.
Definition at line 245 of file TBuffer3D.cxx.
Definition at line 80 of file TBuffer3D.h.
Definition at line 82 of file TBuffer3D.h.
Definition at line 81 of file TBuffer3D.h.
Definition at line 67 of file TBuffer3D.h.
Set fBBVertex in kBoundingBox section to a axis aligned (local) BB using supplied origin and box half lengths.
Definition at line 320 of file TBuffer3D.cxx.
Set kRaw tessellation section of buffer with supplied sizes.
Set fLocalMaster in section kCore to identity
Definition at line 296 of file TBuffer3D.cxx.
Set kRaw tessellation section of buffer with supplied sizes.
Definition at line 359 of file TBuffer3D.cxx.
Definition at line 65 of file TBuffer3D.h.
Definition at line 85 of file TBuffer3D.h.
Definition at line 107 of file TBuffer3D.h.
Definition at line 88 of file TBuffer3D.h.
Definition at line 39 of file TBuffer3D.h.
Definition at line 87 of file TBuffer3D.h.
Definition at line 90 of file TBuffer3D.h.
Definition at line 92 of file TBuffer3D.h.
Definition at line 22 of file TBuffer3D.h.
Definition at line 24 of file TBuffer3D.h.
Definition at line 23 of file TBuffer3D.h.
Definition at line 118 of file TBuffer3D.h.
Definition at line 112 of file TBuffer3D.h.
Definition at line 26 of file TBuffer3D.h.
Definition at line 114 of file TBuffer3D.h.
Definition at line 28 of file TBuffer3D.h.
Definition at line 91 of file TBuffer3D.h.
Definition at line 30 of file TBuffer3D.h.
Definition at line 113 of file TBuffer3D.h.
Definition at line 27 of file TBuffer3D.h.
Definition at line 89 of file TBuffer3D.h.
Definition at line 20 of file TBuffer3D.h. | https://root.cern.ch/doc/v622/classTBuffer3D.html | CC-MAIN-2021-21 | refinedweb | 435 | 55.1 |
I'm traveling tomorrow to Europe and am only taking my iPad and camera. I'm planning on using an SD card reader to upload my photos/videos to my iPad, then use Dropbox on the iPad to copy my daily shots to my Dropbox account.
I'm thinking that I'll have an AppleScript on my home computer's /Dropbox/europe/ folder to look for newly added data and then auto import that into iPhoto.
What's the best way to handle this?
I got it working with a couple of test images but when iPhoto sees photos that it's already imported it asks me if I want to import in the duplicates or skip them. I'd like to skip them or write the AppleScript in a way that handles this.
I'm also fine with copying the photos out of the Dropbox folder into a separate folder elsewhere and not using iPhoto.
I'm just trying to theft proof my data in case my iPad gets stolen or if my Dropbox goes goofy and deletes the photos. Maybe copy newly added data to a designated directory outside of the Dropbox folder? How can I do this?
Any suggestions?
I'm running 10.6.8
Camelot Jun 1, 2012 8:49 AM
Re: How can I handle iPhoto's "import duplicates" prompt when using AppleScript folder actions in response to alternapop
The nature of your question implies that you're unfamiliar with Folder Actions...
I'd like to skip them or write the AppleScript in a way that handles this.
By their very nature, Folder Actions are passed a list of newly-added files. Your Folder Action script should look something like:
on adding folder items to my_folder after receiving the_files
-- your code goes here
end adding folder items to
where, in this case, the_files is a list of the newly-added files. It won't include pre-existing files, so all you need to do is iterate through the_files and you're set. Something like:
on adding folder items to my_folder after receiving the_files
tell application "iPhoto"
repeat with each_photo in the_files
try
import each_photo to album "Europe 2012"
end try
end repeat
end tell
end adding folder items to
The only caveat here that I can think of is the fact it's a DropBox folder, so there might be some odd latency in the files appearing in the directory, but I don't use Dropbox to know.
Note that in the above I import each photo independently, via a repeat loop. This might not be necessary, and you might be able to pass the entire the_files variable to the import command to have all the images imported in one go - I haven't tried that, though.
alternapop Jun 1, 2012 1:57 PM
Re: How can I handle iPhoto's "import duplicates" prompt when using AppleScript folder actions in response to alternapop
I was using Automator to create the Folder Action and your reply helped me realize that I had one extra unnecessary step in my Automator action.
I had a Finder action first and then a Photo action when I only needed the second one.
Thanks! | https://discussions.apple.com/thread/3995338 | CC-MAIN-2015-14 | refinedweb | 533 | 64.04 |
<marcos> Hi, I was wondering if someone could give me some advice. In the widget spec, we want to define and "auto update" mechanism for updating widget packages over the air....
<marcos> the proposal looks like this <widget version="1.0 beta" id="htt://widgets.org/mywidget/"> <update uri=""> </widget> Where, at runtime, %version% is replaced by the UA for the value of the version attribute.
<marcos> The question I have is, would it be better to to define%version% as an entity reference?
<marcos> i.e., &version; ?
<marcos> does it matter?
<Philip> Where the entity reference is not defined in the widget XML file itself, and comes from the environment outside the parser instead?
<marcos> yeah
<Philip> If so, that sounds like it'd be a bit of a pain for anyone using normal XML tools to process or generate those files
<marcos> yeah, true
<marcos> that would suck
<marcos> I'll stick with %version%
<Philip> Rather than %-substitution, you could use (a subset of) URI templates instead
<Philip> i.e. basically just use {version} instead
<marcos> ok, that could work too
<marcos> is there anything written about that?
<Philip>
<Philip> Oh
<Philip>
<marcos> great, I'll check those out.
<Philip> That might be a silly idea, but at least the syntax seems less likely to conflict with the usual existence of % in URIs
<hsivonen> marcos: entity references are trouble
<MikeSmith> fwiw, I agree with hsivonen .. named entity references are one of the ugliest legacies inherited from SGML.. wish we could kill them off entirely
<marcos> hsivonen, yeah. I see that now...
<marcos> MikeSmith, understood.
<Philip> (but sandboxing saved the day)
<Philip> (Uh, I think they might have meant to write file:// in that example)
<jmb> Philip: have you a link to that?
<Philip> jmb:
<jmb> ta
<Philip> (It seems they're ignoring the issue of the web security model (i.e. enforcing same-originality etc), and only trying to prevent web pages interfering with the user's own computer)
<hsivonen> what's the observing etiquette and schedule? is it poor form to request observer status on another WG on the same days the HTML WG meets (since that would mean either skipping some HTML stuff or not actually observing most of the time)?
<DanC> you're welcome to request observer status all over the place, hsivonen . TPAC scheduling is overconstrained, and creative compromises are expected
<DanC> it's quite common to request to observe several meetings at once
<hsivonen> DanC: OK. thanks.
<smedero> DanC: So I requested observer status through the survey form - but should I be following up with the chairs of the respective working groups directly?
<DanC> the norm is that the ball is now in the chairs' court, smedero . You should follow up only if you think a special case is worth making
<DanC> most chairs just send a bulk "sure, fine, come and observe" message to all requesters, I think
<DanC> I suppose some don't get around to it at all
<smedero> that's what I assumed... I just wanted to make sure I didn't drop the ball on that.
<ChrisWilson> grr
<scribe> scribe: Gregory_Rosmaita
<scribe> scribeNick: oedipus
<ChrisWilson> in light of DSinger's only being here for the first 10 minutes or so, I'll suggest we start with a/v accessibility discussion
<ChrisWilson> anything to add to the agenda?
<Laura> tp://lists.w3.org/Archives/Public/public-html/2008Aug/thread.html#msg697
<Laura>
<Laura> I started a page in the Wiki for Multimedia Accessibilty <Audio> <Video>
<Laura>
<DanC> copy of use cases:
<Laura> Considerations:
<Laura> Multimedia presentations (rich media) usually involve both motion and the spoken word. This can present accessibility barriers to those who suffer either visual or audio impairments.
<Laura> The visual components of a multimedia presentation can't be directly accessed by visual impaired users. Likewise, users who are deaf or hard of hearing will not be able to directly access auditory information.
<Laura> Some users may simply not have the equipment, software or connection speed necessary to access multimedia files.
.
<Laura> Recommendation:
.
<Laura> Example: and look at the source code: there are params for the video, the caption, JW FLV also supports descriptive audio, and even little extras like the watermark. HTML 5 should have a similar approach in native support of any media asset
<Laura> Captions, transcripts, text descriptions, and audio descriptions are different from one another.
.
<Laura> The embedded model ensures that the linkage is there, and if the author chooses to also provide an in-the-clear linkage to one or more of these support pieces than this is a win.
<Laura> Some kind of mechanism is needed...attributes on <video> could do it. Likewise for attributes on <audio>.
DanC: had trouble following thread - longdesc diversion; use cases help me a lot
JG: tried to get conversation on
higher level - not how to do, but ability to express
captions
... will look at use cases, as well
... Lachlan's point about user being part of rendering surface -- sometimes yes, sometimes no~~~~~~; ~~~~ssed as
... media queries: adaptability of content; competing approaches expressed on list
CW: need to do further reading on
topic before discussing on call (audio & video
thread)
... tons of posts on topic
CS: trying to discharge action items for PF
<ChrisWilson> any further discussion on this, or shall we move on?
HS: prefer discussion more focused - went off topic with longdesc and such
GJR: perhaps some wiki work is needed
HS: media query proposal good idea, but syntax needs work -- idea of querying user's indicated capabilities
<Laura> notes to Dan that I am having trouble hearing. Some static on my end of the call.
CW: interesting idea - privacy implications?
<Lachy> I'm here now, IRC only
HS: privacy problem in any case if person doesn't want to reveal disability to access video stream with certain properties
<Zakim> oedipus, you wanted to ask role of CC/PP
GJR: i am working on a CC/PP
profile for assistive technologies
... one possible approach to ensuring that content negotiation done correctly
... will set up ESW wiki page for issue
<Lachy> ChrisWilson, no, I think i've said all I need to say on the mailing list
<hsivonen> clarification on the privacy point: a user who selects a media stream meant for people with a given disability end up revealing that (s)he may have that disability
CS: privacy issues about AT concerns?
<ChrisWilson> @Lachy ok thanks.
<hsivonen> but with MQ being able to query stuff all the time, the disability may be revealed without the user noticing that a selection mechanism ran
GJR: whatever is going to raise privacy concerns -- interested in CC/PP as well as XQuery
CS: use of CSS
<Zakim> hsivonen, you wanted to ask about CC/PP & XQuery
GJR: gathering participants to revive CSS-Reader
<DanC> (hmm... "need" is a strong word)
HS: CSS media selectors sufficient?
<DanC> "exposing an accessible _what_"?
<hsivonen> DanC, tree
<DanC> thanks
<DanC> HS: isn't the trend away from the AT accessing the DOM directly to the UA exposing an accessible tree?
<DanC> GR: ATs need to support XML vocabularies/applications
<DanC> HS: seems sufficient to convert to HTML server-side
GJR: HS' idea is a non-starter -- if people need to use an xml-derived language, they should be able to do so without having forced on them as text/html which is less robust
HS: underlying assumption of HTML5 work is HTML5 is common ground - arbitrary XML vocab mapped to semantics AT understands introducing new layer of interaction - new middleware between AT and markup - why not make that ground HTML
GJR: HTML5 does not exist as a specification - one class of readers to disclaimers might change are AT vendors -- they are going to wait until there is sufficient market penetration
<DanC> (the "just use HTML as the AT solution for specialized vocabularies" sounds familiar... that was the outcome in the HTML 2 timeframe for SGML accessiblity.)
GJR: one reason why at vendors putting eggs in ARIA basket
<hsivonen> ARIA is in flux as well
CW: adding features to HTML5 via ARIA aren't distant future-sollutions, but will be added over time
GJR: incremental adaptation without standards and coordination will not happen from AT side
CW: why for features added to HTML5 but not ARIA features added to current HTML implementations
<hsivonen> XQuery for AT capabilities doesn't exist as a REC today, either, right?
CW: agree that need standards and coordination here - have to have that on AT side, as well -- not sure why precludes one sollution or another
GJR: i don't think it precludes one solution or another, but i don't think we should proscribe one solution over another
DS: point of ARIA not to supersede native semantics of ML language; ATs will adapt to HTML5 and ARIA, but ARIA goes beyond the scope of HTML WG
CS: browser devs will do same things doing now - mapping HTML semantics to appropriate accessibility API so ARIA can be used anywhere
DS: not certain why conflict at all between HTML5 and ARIA?
CS: synchronization
CS: if supports ARIA
... some vendors will do for older browsers
DS: only if AT supports it -- values and attributes into the DOM what UA should do
CS: also important for UA to map to OS
DS: if UA can do that, we are ok
GJR: point simply was that ARIA
for more than HTML5
... therefore needs to be janus-like
<Lachy> xquery is overkill, something like media queries would be syntactically better, but media queries itself is not suitable
HS: in end, need to have
something AT understands -- AT understands stuff in DOM or uses
API that AT understands
... arbitrary XML vocabularies are not accessible - mapping to ARIA or HTML5 if UA knows about ARIA or HTML5
<DanC> (hmm... since the HTML 2 timeframe, I wonder what ebooks do... do they use HTML vocabulary for accessibility, I wonder?)
GJR: the solution is going to be middle-ware --
CW: mapping components from known to more simplistic
DS: HTML is going to be more
sparse language than GUI frameworks natively supported on
desktops;
... ARIA goes beyond what HTML5 does or plans to do -- why map to something that is known to be less rich when have option to map to something more rich just for the sake of a vocabulary (in this case HTML5)
HS: HTML5 and ARIA being implemented so UA understands DOM and communicates to AT; just pointing out that arbitrary XML vocabularies
<DanC> (the first ebook standard I find uses XHTML + namespaces. <html xmlns="" xmlns: )
GJR: available now is ARIA; what is being developed are expert handlers that build upon the ARIA model to provide meaningful read/write access to XML dialects in specialized knowledge domain
DS: CWilson right -- drifting away; don't need to introduce arbitrary XML into conversation; use of script, plus CSS plus markup to make
widgets
GJR: ARIA not for HTML5 per se, broader
DS: violent agreement
<ChrisWilson> overdue action items
<ChrisWilson> action-34?
<trackbot> ACTION-34 -- Lachlan Hunt to prepare "Web Developer's Guide to HTML5" for publication in some way, as discussed on 2007-11-28 phone conference -- due 2008-09-04 -- OPEN
<trackbot>
CW: action 34 - pretty old action on lachy
LH: have to put off again; been extremely busy
DC: approximate date?
LH: no set date just yet
CW: postpone discussion for TPAC?
LH: would be better
<scribe> ACTION: ChrisW - put "web developer's guide to html5" publication on agenda for TPAC face2face meetings [recorded in]
<trackbot> Sorry, couldn't find user - ChrisW
<ChrisWilson> reset due date, will discuss moving forward at TPAC
<DanC> don't make a new action, pls
CW: 21 october due date - face2face is 23rd and 24th
<ChrisWilson> action-66?
<trackbot> ACTION-66 -- Joshue O Connor to joshue to collate information on what spec status is with respect to table@summary, research background on rationale for retaining table@summary as a valid attribute -- due 2008-08-29 -- OPEN
<trackbot>
<ChrisWilson> action-74?
<trackbot> ACTION-74 -- Michael(tm) Smith to raise on the list for discussion the issue of XSLT output=html (non)compliance in HTML5 -- due 2008-08-28 -- OPEN
<trackbot>
<DanC> yes
<DanC> (RRSAgent's action list is less relevant than trackers)
CW: status list from last week?
DC: raised for discussion
<smedero> issue-54 has been discussed over the last week
CW: can close it
<DanC> close action-74
<trackbot> ACTION-74 Raise on the list for discussion the issue of XSLT output=html (non)compliance in HTML5 closed
<Julian> pointer?
<ChrisWilson> action-75?
<trackbot> ACTION-75 -- Michael(tm) Smith to raise question to group about Yes, leave @profile out, No, re-add it -- and cite Hixie's summary of the discussion -- due 2008-08-28 -- OPEN
<trackbot>
<ChrisWilson> julian, were you asking for ptr to email to group on XSLT issue?
<Julian> yes
CW: action 75 - not done by MikeSmith - want to do a poll on that -- leave open for now
<Laura> What is the next step for @headers Action 72?
<ChrisWilson> Will look in a minute.
<DanC> re action-74, there are lots of msgs, e.g.
<smedero> julian, I groked that from the tracker agenda but you can view the issue itself to see there has been discussion:
<Julian> likely
CW: action 74 - XSLT output=html
<ChrisWilson> action-29?
<trackbot> ACTION-29 -- Dan Connolly to follow up on the idea of a free-software-compatible license for a note on HTML authoring -- due 2008-09-11 -- OPEN
<trackbot>
CW: action 75 still open; action
29 status
... Dan?
DanC: some promising internal discussion, but don't know specifics yet - hoping to report today
GJR: discussed at HTC?
DanC: don't expect so
<DanC> (life is getting a little too meta when there's a question about what's the next step on an action; an action is supposed to _be_ a next step)
CW: move to?
DanC: give same due date as lachy
CW: done
... covers all of the overdue issues, i believe
<DanC> (ah... re my licensing action, there's an internal thingy due 2008-10-08 ; so I'll set my due date near that...)
CW: Laura asked about action
72
... Lachy, set deadline for TPAC for web dev doc
<Laura> Approx a thousand headers messages to date on list on action 72:
<Laura>
<Laura> @headers has been an issue since May 1, 2007 with about 39 threads.
<Laura>
<Laura> Latest @headers discussion thread, September 2008:
<Laura>
CW: next steps on action 72 - action on CW about headers and header functionality; still need to shift through all info; either declare consensus or post a poll; collect issues into 1 email to send to list -- hope to get to it very soon
<ChrisWilson> @Laura - yes, I need to collate and distill, then ask a question to the group. Still assigned to me.
<Laura> Thank you.
<smedero> TPAC agenda:
CW: MikeS sent out email on TPAC
agenda - only 1 response received so far
... my take on TPAC similar to MikeSmith's -- first steps are looking through spec and ascertaining where spec is stable enough to generate test cases and creating test suite
... figuring out where we are in terms of stability more interesting in short term
... any suggestions for additions to TPAC meetings, plese send to list
LH: too much time on tutorial slotted (3 hours)
CW: going to end up spending a lot more of our time figuring out what portions of tech are ready for test cases; easier for us to expand into test case writing area than contract schedule - take what time is needed
LH: ok
HS: face2face time better for discussion than writing tests
CW: absolutely
... comment to MikeS was time spent at last TPAC doing tutorial on how to build test cases useful - can see us spending that time, but this time with follow up -- identifying where we can write test cases - what is solid and what is not
... don't want to spend a lot of time with everyone coding - not point of TPAC meeting
<Lachy> DanC, I don't have any ideas yet, but I'll think about it and mail the list
CW: value in using test suite for getting handle on how stable spec is, which is what i really want to get out of f2f
<DanC> (I wish I'd made more progress on tests to date... sometimes I wonder where all the time went.)
<ChrisWilson> any other items for discussion today?
CW: additional items for discussion?
DanC: next week (18 september)
<ChrisWilson> move to adjourn?
<Julian> publication of spec?
CW: at Web 2.0 conference in New
York - scheduled to be doing something at this time slot - have
to check MikeS' availability
... have to move tuesday call too
<DanC> I'm out-of-office 25 Sep and 2 Oct
DanC: not available 25 september and 2 october
<ChrisWilson> adjourned
<ChrisWilson> Thanks again to oedipus for scribing
This is scribe.perl Revision: 1.133 of Date: 2008/01/18 18:48:51 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/interested/interested in/ Succeeded: s/lest/less/ Found Scribe: Gregory_Rosmaita Found ScribeNick: oedipus Default Present: +1.425.646.aaaa, smedero, +1.408.398.aabb, ChrisWilson, DanC, Julian, +1.218.349.aadd, Gregory_Rosmaita, hsivonen, Cynthia_Shelly Present: ChrisWilson Cynthia_Shelly DanC Gregory_Rosmaita Julian Lachlan_Hunt Laura_Carlson hsivonen smedero Doug_Schepers Regrets: Mike_Smith SteveF Joshue WARNING: No date found! Assuming today. (Hint: Specify the W3C IRC log URL, and the date will be determined from that.) Or specify the date like this: <dbooth> Date: 12 Sep 2002 Guessing minutes URL: People with action items: - chrisw developer guide put s web] | http://www.w3.org/2008/09/11-html-wg-minutes.html | CC-MAIN-2014-52 | refinedweb | 2,942 | 54.36 |
Duplicate cursors with transparent image
By
chachew, in AutoIt GUI Help and Support
Recommended Posts
Similar Content
- By TheDcoder
ProxAllium
ProxAllium is a GUI frontend to Tor, it aims to make the usage of Tor easier by directly exposing its SOCK5 proxy which can be used to access the Tor network. The GUI is designed to be simple and user-friendly and it has a few other features... namely:
Fully portable - doesn't write outside its own directory Integrated with Tor via the controller interface and properly communicates with it Minimize to tray Option to start with Windows Interface to configure bridges if Tor is censored in your region Many customization options are available via the config.ini file Screenshots:
The code is made with pure AutoIt, is fully open source and you are free to adapt it to your needs
The GitHub repository hosts all the releases and code. As a bonus it has a somewhat sparsely documented Tor UDF which can be used to control Tor, the code also demonstrates the proper usage of my Process UDF which might be interesting if you want to deal with processes.
As some of my friends know, I no longer use Windows as my main operating system. I switched to Linux a few months back as my primary operating system and haven't looked back since. Unfortunately that meant I could no longer use my own program due to it being Windows only... after a few months of playing around with C and making a basic program, I have decided to rewrite all of ProxAllium into C and make it cross-platform. Sadly this means that the AutoIt version of ProxAllium will not receive any major updates now.
Let me know if this is something you guys would use, I used it daily with my IRC client to connect via Tor (to protect my I.P). I hope you enjoy using my program!
- remin
I do have one autoit script file with multiple functions.
p.e.
#include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <String.au3> #include <GuiButton.au3> #include <Constants.au3> #include <EditConstants.au3> #include <Misc.au3> #include <MsgBoxConstants.au3> #include <HotString.au3> Func ACase() $Form4=GUICreate("ACase", 100, 195, 290, 142) etc etc GUISetState(@SW_SHOW, $Form4) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE SUB_Write2ini(....) ;I write a few things in an ini file Case $a Case $b etc EndSwitch WEnd EndFunc Func BCase() $Form5=GUICreate("BCase", 100, 195, 290, 142) etc etc GUISetState(@SW_SHOW, $Form5) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE SUB_Write2ini(....) ;I write a few things in an ini file Case $a Case $b etc EndSwitch WEnd EndFunc When I activate the 1st function (ACase), using a shortcut and the 2nd function (BCase) (with a different shortcut) and I click on a button in whatever of these 2 Gui's, I can't use the other Gui anymore. It doesn't do the right thing as if autoit only remembers the Gui I first used.
What did I wrong? How can I let autoit know which GUI is active and to connect to the function of that Gui?
Hope I made myself clear.
- By Sven-Seyfert
- By WoodGrain
Hi guys,
I've written a script that will move my mouse to a location on the screen whenever my remote access software becomes active, the problem I have is that as soon as the remote access software becomes active it appears to capture the mouse and keyboard so nothing happens when I use MouseMove().
Is there any way around this?
Thanks! | https://www.autoitscript.com/forum/topic/161708-duplicate-cursors-with-transparent-image/?tab=comments | CC-MAIN-2019-04 | refinedweb | 597 | 69.72 |
Mouseposition [SOLVED]
On 14/06/2015 at 13:56, xxxxxxxx wrote:
Hello again,
I am trying to get the Mouseposition in the Viewport when I run a Script. Is this possible without making a Tool-Plugin? I tried this code and it does not return anything.
import c4d from c4d import gui def main() : bc = c4d.BaseContainer() c4d.gui.GetInputState(c4d.BFM_INPUT_MOUSE,c4d.BFM_INPUT_X,bc) mouse_x = bc[c4d.BFM_INPUT_X] print mouse_x if __name__=='__main__': main()
On 14/06/2015 at 14:02, xxxxxxxx wrote:
Sorry....I was sitting on this for hours now....and a minute after posting I found the solution:
mouse_x=bc.GetInt32(c4d.BFM_INPUT_X)
But I have another Issued with mouse coordinates...now I get the Coordinates of the mouse in the complete C4D-Window. But I need the coordinates of the mouse inside the viewport. Do you have a solution?
What I need is the Pixel-Vallue of the left uper corner of the Viewport in my Layout.
On 15/06/2015 at 03:31, xxxxxxxx wrote:
Hello,
a script might not be the right place to do such user interaction. A script is meant to include some commands that are executed and then the script is finished.
If you want user interaction with the viewport you might want to create a SceneHookData plugin (only in C++) or a ToolData plugin to create proper tools.
Getting the correct coordinates you might need to use functions like Screen2Local(). Such functions are available in GUI related classes like GeDialog and GeUserArea but also EditorWindow. You can get the EditorWindow from the BaseDraw using GetEditorWindow() and the BaseDraw from the document using GetBaseDraw().
Best wishes,
Sebastian
On 15/06/2015 at 04:03, xxxxxxxx wrote:
Thanks Sebastian. That worked for me. But instead I used Global2Local() which gives the Coordinates relative to the C4D Window. | https://plugincafe.maxon.net/topic/8824/11660_mouseposition-solved | CC-MAIN-2020-40 | refinedweb | 306 | 67.35 |
The natural logarithm of a number can be calculated by using different modules in Python. The numpy module provides the
log() method in order to calculate the natural logarithm. Also, the Pytyhon
math library provides the
log() method in order to calculate natural logarithm too.
Calculate Natural Logarithm with math.log()
The math module is provided by the Python framework by default. The log() method of the math module can be used to calculate the natural logarithm of the specified number. In order to use the math.log() method the math module should be imported.
import math math.log(1) # 0.0 math.log(10) # 2.302585092994046 math.log(100) # 4.605170185988092
We can also import the math module log() method directly and call this method without module definition like below.
from math import log log(1) # 0.0 log(10) # 2.302585092994046 log(100) # 4.605170185988092
Calculate Natural Logarithm with numpy.log()
As a popular mathematical module, the
numpy provides the
log() method in order to calculate the natural log of the specified number. The numpy is a 3rd party module and not provided by Python by default so it should be installed with pip like below.
$ pip install numy
Now we can use the numpy.log() method like below.
import numpy numpy.log(1) # 0.0 numpy.log(10) # 2.302585092994046 numpy.log(100) # 4.605170185988092
The NumPy module definition can be shortened as “np” and the log() method can be used like below.
import numpy as np np.log(1) # 0.0 np.log(10) # 2.302585092994046 np.log(100) # 4.605170185988092 | https://pythontect.com/how-to-calculate-the-natural-logarithm-ln-in-python/ | CC-MAIN-2022-21 | refinedweb | 265 | 68.87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.