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
On Wed, 4 Oct 2006, Daryl Tester wrote: > Chris Foote wrote: > >> The voice peering project I'm working on has an embedded interpreter >> running in a seperate thread in 'screen' sessions (using code.interact() ) > > Reminding me of code.interact() brings up painful memories. :-) It's the > second time where I've coded up something only to find out there was an > equivalent method in the standard library (at the time of the quilter > talk, my REPL was implemented using exec and eval, but I wasn't happy > with it. Then I found HTTPREPL which pointed me in the appropriate > direction). It annoys me, because when learning a language I make sure > I go over the library in detail so I don't reinvent any unneccessary > wheels. hehehe... It's so easy to reinvent the wheel with Python anyway, so it doesn't surprise me that everyone's written similar things :-) HTTPREPL is very cool.. I stumbled onto it a couple of months back: >> It's a shame that it's not usable outside of reloading a module: >> >>>>> class C(object): >> ... def method(self): >> ... return '1st method version' >> ... >>>>> c = C() >>>>> c.method() >> '1st method version' >>>>> >>>>> def newmethod(self): >> ... return '2nd method version' >> ... >>>>> C.method = newmethod >>>>> >>>>> c.method() >> '2nd method version' >>>>> >> >> i.e. existing object uses new version of method. > > I'd expect this, because the class that the instance refers > to is being patched. Unfortunately the copy module doesn't > appear to touch classes, but a possible workaround is to > subclass C with the new method, then assign that to C. > > e.g. - > >>>> class C(object): > ... def method(self): > ... return '1st method version' > ... >>>> c = C() >>>> c.method() > '1st method version' >>>> class C1(C): > ... def method(self): > ... return '2nd method version' > ... >>>> C = C1 >>>> c.method() > '1st method version' >>>> c1 = C() >>>> c1.method() > '2nd method version' Cool - I didn't think of that :-) > If a module is used there is no need to subclass the original > class, as the new class is defined in what is effectively a > new namespace (same name, but any existing instances hold > references to the old namespace). Very neat stuff. -- Chris Foote <chris at inetd.com.au> Inetd Pty Ltd T/A HostExpress Web: Blog: Phone: (08) 8410 4566
https://mail.python.org/pipermail/sapug/2006-October/000125.html
CC-MAIN-2014-15
refinedweb
371
75.71
Original article posted at <- performance-best-practices-and-lessons-8ef4035ddea6.html> React is one of the most widely used and popular libraries that has seen great adoption from developers in comparison to other libraries. It supports many out-of-the-box techniques to minimize the number of costly DOM operations required to update the UI. Though it automatically handles many of the heavy lifting under the hood, that does not mean everything is done efficiently. We might be writing inefficient code that is making React do unnecessary things and slowing things down significantly. If you are like us at Botsplash, who likes to develop applications at rapid speed with great quality, you are likely to see few or no performance issues. However, there are times, it is inevitable to self reflect and audit the performance plan. Let’s look at few lessons learned that will help to get the best out of React and improve the application’s performance. 1. Check for redundant component renderings The render method inside a React component is called automatically when its parent component’s render is called or setState function is called inside the component. Every time the render method is called, the JSX inside it is evaluated along with its state and props. There are cases when the component’s state and props haven’t changed but is still forced to re-render. Let’s take the following component for instance. This is a really simple component which has an input and a button to set the new message. There is child component that takes in the message as prop and displays it. I’ve also added a variable called childComponentRenderCount to keep track of the render count for the child component. The problem arises when you start typing the new message in the text box. As you can see, the render count keeps increasing on every keystroke. The main component with the text input needs to be updated but there is no need for the child component to update. It only needs to update when the submit button is clicked. This becomes a problem in the real world application where the component is complicated and the child component also becomes nested and large. It is therefore good to identify such unwanted renderings and cut down the unwanted work React has to do. One way is to implement shouldComponentUpdate lifecycle hook to cut down unnecessary renderings of the child component. ... // inside ChildComponent shouldComponentUpdate(nextProps) { return this.props.message !== nextProps.message; } ... The lifecycle hook shouldComponentUpdate returns true by default and hence the component is updated every time. But we can use it to add our own logic to control when we want to re-render the component. We only want to re-render the Child component when the message prop changes. Let’s look at the difference with shouldComponentUpdate implemented. You can also use PureComponent which always shallowly compares the change in the props and state and re-renders the component only when the change is detected. We do not need to implement shouldComponentUpdate with PureComponent. Using PureComponent is exactly the same like writing React.Component the following way. class MyComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } ... } PureComponent should only be used when the component has simple props and state as complex data structures could produce false-negatives as it only shallowly compares the objects. There are couple of ways we can identify these unwanted renderings in existing application. If you are using React v15, there is an excellent tool called react-addons-perf. It shows exactly how many times a component rendered unnecessarily and how much time it wasted on it. You can also use the Performance tab in Chrome DevTools or the React Profiler that is available from React v16.5. By looking at the results, we can implement shouldComponentUpdate to remove those renderings. 2. Prevent function binding or new object as props inside render While passing objects and functions as props to child components, it might seem convenient to just declare these inline or inside the render function like the following code. However, this is a bad practice. Since all the props above are declared inline, every time the render function is called, new objects (for propA and propB) and a new function (for actionA) is created even though the values they hold are same. This is also true when using bind inside the render function. (Using ES6 arrow function automatically binds the function) Creating new object and function every time on render causes even bigger issue when we have implemented shouldComponentUpdate to shallowly compare the props or used PureComponent as discussed in previous point. Since new reference of the actionA is passed as prop every time, the shallow compare of the props fail leading to re-rendering of the component. The above component can be re-written as: We have now assigned arrow function to actionA and also declared propA and propB at the time when the component is created. Note: If you prefer to use bind over the arrow function, you should bind it early inside the constructor ... constructor(props) { super(props); this.handleActionA = this.actionA.bind(this); } ... There might be cases when we need to create arrow functions inside the render method when using list of items. One possible solution is to create a new component and pass down the id and the function as props as mentioned here. You can also opt to use memoize function from lodash without having to create a new React Component. 3. Index as key We require keys whenever we are dynamically rendering list of items in loop. Keys are required by React to identify which items have changed, are added, or are removed. These keys need to be unique for each element and sometimes we do end up using index as key for the element. ... {items.map((item, index) => <Item key={index} /> )} ... Now this code is absolutely fine in most cases until we need to update, sort or filter the list. In that case, the key for each item also changes and this can cause the application to behave strange. If you look at the ReactJS documentation on Reconciliation, it says: Component instances are updated and reused based on their key. If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways. If you have a list of 1000 elements and you have used index as key, when you remove the first element, the indexes for all the subsequent items are updated and since React compares the DOM based on the key, it thinks all the items have been updated and thus causes performance degradation. It is hence, advised to use unique, stable and predictable key. You can use item.id in above case given that it has a unique id. If not, you can use libraries like shortid to generate an id for you. You should also prevent using functions like Math.random to generate keys. You should proceed to use index as key only when you are certain that the list doesn’t update in any sort of form. 4. Production build and code splitting When working with React application, there are lots of tools that are only used while development. There might be tools to display different warning and errors that assist us in debugging issues. These packages come at a cost and increases the bundle size of our application. When used in the production environment, it will significantly slow down our application. Thus, while deploying the React application to the production, you should make sure you are using the build that is generated specifically to be used in production environment. If you are using create-react-app, you can simply generate it using npm run build or yarn run build command. If you are using webpack you can also set flag ( webpack --mode=production) to instruct it to generate production build. This way, the bundle size will be significantly lower since development-only codes are removed. The code will also be uglified and minified with create-react-app though you might need to setup plugins for webpack if you aren’t using create-react-app. In addition to it, there are other different ways to reduce size of the production build. **Code Splitting ** Using a single production build is okay for small to medium sized application but as the application grows, so does the production build size. Sometimes, due to large production build, the application might take long time to load. In that case, we can make use of webpack’s code splitting feature. If we have code like this: import someLibrary from './someLibrary'; someLibrary.someFunction(); We can split the “someLibrary” file to separate bundle and only load it when it is required by the application. import('./someLibrary').then(someLibrary => { someLibrary.someFunction(); }); This can reduce the initial bundle size and initial page load time significantly when used correctly. This is however only supported in webpack. Also, the dynamic import() syntax is still not supported in ECMAScript. You will need to use babel-plugin-syntax-dynamic- import to support the syntax. React also supports React.lazy which allows us to render a dynamic import as a regular component. const OtherComponent = React.lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <OtherComponent /> </div> ); } The OtherComponent is bundled into separate bundle and loaded only when MyComponent is loaded. This makes it very easy to implement code-splitting based on route. We can easily create separate bundles for routes that have large components and load it when that route is active. Suspense in the above example is another component provided by React which gives us the control to display fallback content while the component is being loaded. The above example has been taken from React’s code-splitting documentation. You can find more detailed information here. 5. Clearing timers and event listeners Timers and event listeners might not be React specific but I’ve decided to include it here anyway since we use timers and event listeners frequently in our applications and can cause memory leaks and performance impacts when not handled properly. The component above has setInterval to change the value of countdown every 60 second and also has an event listener for scroll attached when the component is mounted. Now suppose that this page is rendered by react-router and you change the route to mount different component. The event and timer will still continue to exist in the memory. If there are multiple of such timers and event listeners, it will significantly impact the page’s performance over the time if the page hasn’t been refreshed. Even worse, if the App component is mounted again, new timer is started and a new event is attached on top of the existing. This is the reason you always need to clear these intervals and event listeners before the component unmounts. setInterval returns an integer which needs to be passed to clearInterval function to kill the timer. Similarly, we need to pass the same callback function that was used in addEventListener to remove the event listener. Conclusion So these are few of the ways you can speed up your application. There still are several other ways like SSR or ServiceWorkers which you can implement but that really depends on the level of optimization you are looking for. Having said that, you need to correctly identify where and why your application is slowing down first before you start to implement the solutions. As I mentioned earlier, Chrome DevTools or the React Profiler are great ways to visualize and benchmark your application..
https://sumeetbajra.github.io/blog/react-application-performance-best-practices-and-lessons-8ef4035ddea6/
CC-MAIN-2019-35
refinedweb
1,956
54.02
07 November 2010 22:30 [Source: ICIS news] RIO DE JANEIRO (ICIS)--Pemex Petroquimica is proceeding with plans to expand its styrene monomer (SM) capacity in ?xml:namespace> The project, which has been on hold for several years, will raise SM capacity to 250,000 tonnes/year from 150,000 tonnes/year, said Carlos Pani, sub-director for commercial operations. Start-up is scheduled for the end of 2013, he added. The project was delayed as a result of budget allocation decisions by the central government, Pani explained. Engineering work is under way for the project, which could be implemented with a joint venture partner, he told ICIS on the sidelines of the Latin American Petrochemical Association (APLA) annual meeting. One potential partner is Mexican polystyrene (PS) producer Resirene, he suggested. “We’re still in very preliminary conversations,” he remarked. APLA lasts through Tuesday. For more on styrene
http://www.icis.com/Articles/2010/11/07/9408029/apla-10-mexicos-pemex-revives-styrene-expansion-project.html
CC-MAIN-2015-06
refinedweb
148
55.95
The typical program of Hello World in c is somewhat like //HelloWorld.c #include <stdio.h> main() { printf("hello,world\n"); } To compile in linuc, we use cc HelloWorld.c and to run ./a.out The output of the program is hello, world Now in Page 6, chapter1, we have two exercises Exercise1-1 : Run the "hello, world" program on your system. Experiment with leaving out parts of the program, to see what error messages you get. Lets do it, First, we comment the line #include <stdio.h> like //#include <stdio.h> we get a compile time error like HelloWorld.c:5: warning: incompatible implicit declaration of built-in function ‘printf’ hence we conclude that the printf function comes from the library <stdio.h>, which is responsible for standard input/output. Secondly, we comment the function main() like //main(), we get a compiler error like HelloWorld.c:4: error: expected identifier or ‘(’ before ‘{’ token which implies that every program must have a main function, hence that. Also the return type of the main funtion is interger, hence if we specify it as void, we get the compiler error like HelloWorld.c:6: warning: ‘return’ with a value, in function returning void HelloWorld.c:4: warning: return type of ‘main’ is not ‘int’ But if we specify the return type as int, it compiles successfully. *the environment used during the exercise was Linux and the compiler is gcc. Please post more information if you feel. Thanks Print | posted on Wednesday, March 03, 2010 8:17 AM | Filed Under [ C Programming ]
http://geekswithblogs.net/prasenjitdas/archive/2010/03/03/deeper-into-hello-world.aspx
crawl-003
refinedweb
259
67.25
Assertions are statements to ensure that a particular condition or state holds true at a certain point in the execution of a program. These checks are usually only performed in debug builds, which means that you must ensure that the expressions in the assertions are side-effect free. Because assertions are only validated in debug builds, you can abuse them to make your code more readable without impacting performance and without having to write a comment. Every time you write a line in which you assume a particular machine state that is not clearly implied by the code immediately preceding the new line, write an assertion. Let’s look at a real world example derived from Kyua’s code. Consider the following extremely-simplified function which implements the help command: def help_command(args): if len(args) == 0: show_general_help() else: show_command_help(args[0]) With this code alone, try to answer these questions: “What happens if args, which apparently is a subset of the arguments to the program, has more than 1 item? Are the additional arguments ignored and thus we have a bug in the code, or has the args vector been pre-sanitized by the caller to not have extra arguments?" Well, you can’t answer this question because there is nothing in the code to tell you what the case is. If I now show you the caller to the function, you can get an idea of what the expectation is: def main(args): commands = {} commands['help'] = cli.Command(min_args=0, max_args=1, hook=help_command) ... cli.dispatch(commands, args) Aha! There happens to be an auxiliary library that processes the command line and dispatches calls to the various subcommands based on a declarative interface. This declarative interface specifies what the maximum number of arguments to the command can be, so our function above for help_command was correct: it was handling all possible lengths of the input args vector. But that’s just too much work to figure out a relative simple piece of code. A piece of code needs to be self-explanatory with as little external context as possible. We can do this with assertions. The first thing you can do is state the precondition to the function as an assertion: def help_command(args): assert len(args) <= 1 if len(args) == 0: show_general_help() else: show_command_help(args[0]) This does the trick: now, without any external context, you can tell that the args vector is supposed to be empty or have a single element, and the code below clearly handles both cases. However, I argue that this is still suboptimal. What is the complementary condition of len(args) == 0? Easy: len(args) > 0. Then, if that’s the case, how can the else path be looking at the first argument only and not the rest? Didn’t someone overlook the rest of the arguments, possibly implying that the input data is not fully validated? This would be a legitimate question if the function was much longer than it is and reading it all was hard. Therefore, we would do this instead: def help_command(args): if len(args) == 0: show_general_help() else: assert len(args) == 1 show_command_help(args[0]) Or this: def help_command(args): if len(args) == 0: show_general_help() elif len(args) == 1: show_command_help(args[0]) else: assert False, 'args not properly sanitized by caller' Both of these alternatives clearly enumerate all branches of a conditional, which makes the function easier to reason about. We will get to this in a future post. Before concluding, let’s outline some cases in which you should really be writing assertions: - Preconditions and postconditions. - Assumptions about state that has been validated elsewhere in the code, possibly far away from the current code. - Complementary conditions in conditionals where not all possible values of a type are being inspected. - Unreachable code paths.
https://jmmv.dev/2013/07/readability-abuse-assertions.html
CC-MAIN-2022-27
refinedweb
636
50.67
Overview: In this project you will learn to use a basic functionality of chipKIT board in MPLAB X IDE, which is to read an analog value and output the corresponding digital reading for it. A potentiometer is a three-terminal resistor with a sliding contact that forms an adjustable voltage divider. Using a potentiometer measuring instrument, you could measure the electric potential. In this example we use the potentiometer in the chipKIT Basic IO shield. Find the same project using MPIDE here. Hardware Used: To do the analog read project, you require the following hardware devices. - chipKIT Uno 32 - chipKIT Basic IO shield - PICkit® 3 In-Circuit Debugger/Programmer - USB cable - 6 pin header to connect chipKIT board and PICkit® 3 Reference: The reference guide for each board, schematics and other resources are available on their individual homepages: - chipKIT Uno32 homepage at: - chipKIT Basic I/O Shield homepage: Procedure: - Connect the hardware devices. The PICkit® 3 should be connected to the chipKIT Uno32 board through a suitable header and use the USB cable to connect the PICkit® 3 to your PC. - Place the IO shield on top of the Uno32 board with a bit of a firm press. A0-potentiometer of the IO shield will be used as peripheral for Uno32 board, in this excercise. - Once the hardware setup is made and the device drivers are updated for PICkit® 3 on your computer, launch MPLAB X (Start>All Programs>Microchip>MPLAB X IDE>MPLAB X IDE vx.xx on Window® Machines ). - Create a new project through File>New Project. In the pop up new project window, select Standalone Project under Projects and click Next. Under Family scroll and select 32-bit MCUs (PIC32). Note the processor number from the chipKIT board’s reference manual and enter it under the Device option. Click Next. - Select PICkit3 in the Hardware Tools, click Next. Select XC32 (v1.20) under Compiler Toolchains, click Next. Give a project name to create the project. - In the Project tab on the left side of the MPLAB X IDE, right click on Source Files > New > C Main File.. and give a file name for main source code. Once the dot c file opens, select all the codes in the file and replace it with the codes below. #include <plib.h> #include <xc.h> #pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF #pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_1 #define SYS_FREQ (80000000L) unsigned int channel4; // conversion result as read from result buffer unsigned int offset; // buffer offset to point to the base of the idle buffer int main(void) { // Configure the device for maximum performance but do not change the PBDIV // Given the options, this function will change the flash wait states and // enable prefetch cache but will not change the PBDIV. The PBDIV value // is already set via the pragma FPBDIV option above.. SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE); // configure and enable the ADC CloseADC10(); // ensure the ADC is off before setting the configuration // define setup parameters for OpenADC10 // Turn module on | ouput in integer | trigger mode auto | enable autosample #define PARAM1 ADC_MODULE_ON | ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON // define setup parameters for OpenADC10 // ADC ref external | disable offset test | disable scan mode | perform 2 samples | use dual buffers | use alternate mode #define PARAM2 ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_OFF | ADC_SAMPLES_PER_INT_9 | ADC_ALT_BUF_OFF | ADC_ALT_INPUT_OFF // define setup parameters for OpenADC10 // use ADC internal clock | set sample time #define PARAM3 ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_15 // define setup parameters for OpenADC10 // do not assign channels to scan #define PARAM4 SKIP_SCAN_ALL // define setup parameters for OpenADC10 // set AN2 as analog inputs #define PARAM5 ENABLE_AN2_ANA // use ground as neg ref for A | use AN2 for input A // configure to sample AN2 SetChanADC10( ADC_CH0_NEG_SAMPLEA_NVREF | ADC_CH0_POS_SAMPLEA_AN2); // configure to sample AN2 OpenADC10( PARAM1, PARAM2, PARAM3, PARAM4, PARAM5 ); // configure ADC using parameter define above EnableADC10(); // Enable the ADC while ( ! mAD1GetIntFlag() ) { } // wait for the first conversion to complete so there will be vaild data in ADC result registers // the result of the conversion is available in channel4. while (1) { channel4 = ReadADC10(0); // read the result of channel 4 conversion from the idle buffer } return 0; } - To read the potentiometer value, access the watch window from Window > Debugging > Watches or you can use the shortcut key Alt+Shift+2. In the watch window panel that opens on the MPLAB X IDE, enter the new watch as channel4, in the blank <Enter new watch> area as shown below in the figure. - In the program editor window, put a breakpoint by clicking on the line number after the code line channel4 = ReadADC10(0); // read the result of channel 4 conversion from the idle bufferThat is on the line with the closing braces of the while loop. This should create a red box in the number line as shown in the figure below, - Click on Debug Project icon shown below, - Once the program halts its execution at the line with the breakpoint, click on Watches output window, right click on the expand button under Value column and select Display value column as > Decimal. The value that appear in this column for channel4 variable corresponds to the potentiometer reading which is read in the range of 0 to 1023. A value 0 corresponds to 0 volts and a value 1023 corresponds to 3.3 volts. - Now, click on Continue button from the top pane and observe the value of channel4 to change and reflect the potentiometer reading as described before. - If you would like to change the potentiometer knob and see a different value, then, change the potentiometer knob and click on the Reset button on the top pane. This will initialize the variables back to zero. Clicking on the Play button on the top pane, will get your changed potentiometer value on the Watches window. Below is a screenshot showing the potentiometer value for 3.3 volts being read in the Watch window. VN:F [1.9.22_1171] VN:F [1.9.22_1171]
http://chipkit.net/tag/breakpoint-mplab/
CC-MAIN-2017-34
refinedweb
982
56.39
VARIABLES: We can print variables by simply using the {{ VARIABLE_NAME }} syntax. If you want to print just an element of an array, you can use {{ ARRAY_NAME[‘KEY’] }}, and if you want to print a property of an object, you can use {{ ARRAY_NAME[‘KEY’] }} . Refer the following for an example; FILTERS: From time to time, you would want to change the style of a string a little bit, without writing specific code for it. For example, you may want to capitalize some text. For doing so, you can make usage of one of the Jinja’s filters, such as {{ VARIABLE_NAME | capitalize }}. CONDITIONALS: One thing that can often be proven useful in a template engine is the possibility of printing different strings, depending on the content (or existence) of string. Take a cue from this example to add an interesting element to your static web page: <body> <h1>Hello World!</h1> <p>This page was created on {{ ansible_date_time.date }}.</p> {% if ansible_eth0.active == True %} <p>eth0 address {{ ansible_eth0.ipv4.address }}.</p> {% endif %} </body> </html> In the above, it is clear that the capability to print the main IPv4 address is added for the eth0, if the connection is active. With conditionals, tests can also be used. So, to obtain the same result, the following can also be written: <body> <h1>Hello World!</h1> <p>This page was created on {{ ansible_date_time.date }}.</p> {% if ansible_eth0.active is equalto True %} <p>eth0 address {{ ansible_eth0.ipv4.address }}.</p> {% endif %} </body> </html> CYCLES: The jinja2 template system gives you the option of creating sycles . Let us add a feature to our page that will print the main IPv4 network address for each device, instead of only eth0. Refer the following code for the same: <body> <h1>Hello World!</h1> <p>This page was created on {{ ansible_date_time.date }}.</p> <p>This machine can be reached on the following IP addresses</p> <ul> {% for address in ansible_all_ipv4_addresses %} <li>{{ address }}</li> {% endfor %} </ul> </body> </html> As you can see, the syntax for cycles will seem familiar if you already know Python. But this information on Jinja2 templating was not a substitute for the official documentation. In fact, Jinja2 templates are much more powerful than we have explored here. To know more about Ansible and the application of the same, head on ‘Learning Ansible 2.7 – Third Edition.’ By Fabio Alessandro Locati, who is a senior consultant at Red Hat, a public speaker, an author, and an open source contributor. Let him take you through the fundamentals and practical aspects of Ansible by introducing you to topics that include playbooks, modules, BSD, Windows support, etc. You can definitely look forward to be equipped with the Ansible skills that are required to automate complex tasks for your organization.
https://linuxhint.com/jinja2_templates_ansible/
CC-MAIN-2019-39
refinedweb
457
64.3
Magic Mirror in the story “Snow White and the Seven Dwarfs” had one cool feature. The Queen in the story could call Mirror just by saying “Mirror” and then ask it questions. MagicMirror project helps you develop a Mirror quite close to the one in the fable but how cool it would be to have the same feature? Hotword Detection on SUSI MagicMirror Module helps us achieve that. The hotword detection on SUSI MagicMirror Module was accomplished with the help of Snowboy Hotword Detection Library. Snowboy is a cross platform hotword detection library. We are using the same library for Android, iOS as well as in MagicMirror Module (nodejs). Snowboy can be added to a Javascript/Typescript project with Node Package Manager (npm) by: $ npm install --save snowboy For detecting hotword, we need to record audio continuously from the Microphone. To accomplish the task of recording, we have another npm package node-record-lpcm16. It used SoX binary to record audio. First we need to install SoX using Linux (Debian based distributions) $ sudo apt-get install sox libsox-fmt-all Then, you can install node-record-lpcm16 package using npm using $ npm install node-record-lpcm16 Then, we need to import it in the needed file using import * as record from "node-record-lpcm16"; You may then create a new microphone stream using, const mic = record.start({ threshold: 0, sampleRate: 16000, verbose: true, }); The mic constant here is a NodeJS Readable Stream. So, we can read the incoming data from the Microphone and process it. We can now process this stream using Detector class of Snowboy. We declare a child class extending Snowboy Hotword Decoder to suit our needs. import { Detector, Models } from "snowboy"; export class HotwordDetector extends Detector { 1 constructor(models: Models) { super({ resource: `${process.env.CWD}/resources/common.res`, models: models, audioGain: 2.0, }); this.setUp(); } // other methods } First, we create a Snowboy Detector by calling the parent constructor with resource file as common.res and a Snowboy model as argument. Snowboy model is a file which tells the detector which Hotword to listen for. Currently, the module supports hotword Susi but it can be extended to support other hotwords like Mirror too. You can train the hotword for SUSI for your voice and get the latest model file at . You may then replace the susi.pmdl file in resources folder with our own susi.pmdl file for a better experience. Now, we need to delegate the callback methods of Detector class to know about the current state of detector and take an action on its basis. This is done in the setUp() method. private setUp(): void { this.on("silence", () => { // handle silent state }); this.on("sound", () => { // handle sound detected state }); this.on("error", (error) => { // handle error }); this.on("hotword", (index, hotword) => { // hotword detected }); } If you go into the implementation of Detector class of Snowboy, it extends from NodeJS.WritableStream. So, we can pipe our microphone input read stream to Detector class and it handles all the states. This can be done using mic.pipe(detector as any); So, now all the input from Microphone will be processed by Snowboy detector class and we can know when the user has spoken the word “SUSI”. We can start speech recognition and do other changes in User Interface based on the different states. After this, we can simply say “Susi” followed by our query to ask SUSI on the MagicMirror. A video implementation of the same can be seen here: Resources: - MagicMirror Project Website: - SUSI Magic Mirror Repository: - Snowboy NodeJS official example code: - Documentation for Snowboy usage and tutorial: - Snowboy nodejs implementation:
https://blog.fossasia.org/hotword-detection-on-susi-magicmirror-with-snowboy/
CC-MAIN-2022-21
refinedweb
601
56.35
The information published in this post is now out-of-date. —IEBlog Editor, 20 August 2012 I hopefully got your attention with the title of my If you want to try out the latest IE browser, I strongly encourage you to download and run the latest release candidate for XPSP2 Service Pack 2. You can download it here. Scott Stearns Test Manager, IE I have doubts about whether IE has a bug that select object can not be covered with div object or other objects Glad to hear that IE is not being ignored, but IE is still losing respect in general. I think you guys should release a "Version 7" to give the general public the impression that progress is being made and IE is not outdated. Several browsers have had more recent (and well publicized) releases since the last major IE release. I think the “new” IE is going to get lost in SP2, as far as perception goes. Release a version 7, for all your supported OSs, sometime after SP2 and rejuvenate the buzz…stop the attrition. No. If it’s not good enough for you guys to slap with a RTM label, it’s not good enough for me to download and run on my machine. No offense. 🙂 It is nice to see this blog, Scott. Probably you’ll be bombarded with such kind of messages but anyway: when do you think this one will be fixed –? It has been reported and registered a year ago and still do the same in SP2 RC2. Just curious. Well said up there, that IE is losing respect in the real world.. the fact that people are taking Firefox seriously still urks me, but they have some valid points.. MUCH more configurability, tabbed browsing, etc.. And then I found MyIE2 (a wrapper for IE –) – which has tabbed browsing – which is key for these MSDN blogs for example – I have a "group" I open, that opens all the blogs I normally check – and opens them "tabbed" so I don’t have a zillion windows open. I can work my way through that "group" all within one container – much more ideal than individual browsers (for most cases). Point is, once I started looking around at browsers (I haven’t done that since the Browser Wars) – the things that are making the difference are the fru-fru usability things. And as a developer (for a long time and of all Microsoft languages) – let me say, that the heat you guys get for security flaws is bull. You guys are between a rock and a hard place. I work for a company where I write intranet apps and users are NEVER happy with the functionality. They want web apps that work like windows apps – and that’s only possible with powerful scripting and objects (like activex and applets).. but at the same time, Internet developers say you shouldn’t even ALLOW these things because they are too risky. You can’t win. Anyhow.. sucks to be you, but keep up the good work!! 🙂. sorry for the double post… Firefox… gotta love it! IE is a good idea but not the final ideal ,maybe smartclient is "I realize that statement will cause some people to chuckle based on current press on security issues and perceived lack of innovation, but that is my job." It’s strange that someone’s job in the IE team is to cause us to chuckle instead of innovating in web browsing, but looking at IE state of the art, I think I understand… Scott, with all due respect when your browser properly supports web standards like firefox, etc then those of us who where long time fans of IE may return to using it. I loved IE at V3.0. V4.0 was a poor user experience. I loved V5.0 again. V6.0 and since have been OK, but nothing special. I certainly don’t love V6.0 – and I’m astonished that anyone loves V6.0 – the Courtney Love in a world of Kirsten Dunst’s. "If you want to try out the latest IE browser, I strongly encourage you to download and run the latest release candidate for XPSP2 Service Pack 2." I strongly advise you to get over this boneheaded idiocy and release a new version of the browser that I can use in Win2K and 2K3. Just because IE’s (legitimately) a part of the OS does not justify this asinine approach to releasing updates. As a web developer, I’m doing everything in my power to get people to switch away from Internet Explorer. This is because, when developing websites,. If a new version of Internet Explorer was available that didn’t screw up so damn much, not only would it make my life much easier, but I’d stop switching people away from it. The features of other browsers are just the "honey" that web developers use to get people to switchaway from IE. Right now, the only thing keeping many web developers from dropping Internet Explorer support completely is its market share. It’s the new Netscape 4. *Please* fix IE. Top of the list: 1. CSS 2 bugs ("peekaboo", "guillotine", "3px jog", etc). 2. CSS 2 tables. 3. CSS 2 generated content. 4. CSS 2 selectors. 5. PNG alpha channel. CSS 2 is over six years old, and Microsoft have had employees in the CSS working group the whole time. PNG is almost eight years old and Microsoft promised PNG support for Internet Explorer 4.0. Given that Microsoft are the world’s biggest software company, it looks very much like standards are deliberately being sabotaged. Is it any wonder web developers are starting to get royally pissed off with Microsoft? Sorry but your browser is not standard compliant, I’m Web developer to and that’s why I use (and I love) Firefox. Edit : Another CSS 2 bug, "hover" is not supported by IE ! A good start would be setting up Bugzilla, to get tot know precisely what bugs are around. Gotta say that after using and switching to FireFox, IE really looks like a dog in comparison. Loads about 4 times slower than FireFox and it’s supposed to be part of the OS?! After using tabbed browsing I don’t think I could ever go back. Speed of page loading is insane, makes IE look like it’s running on a 386 or something. Plus, all this and then you have a huge amount of good, quality plugins and themes none of which seem to detriment the speed of the core browser like toolbars do to IE. Aside from the user benefits I mentioned above the standards support is simply great, it allows the web to be made the way it should be. Why can’t IE be made to support STANDARDS? They are there for a reason. Kev IE sux man. It’s not W3C compliant, it let pass too much pop-ups, too big security hole … how can you say that honestly ? Moreover, There is a lot of more efficient browsers … Oh yeah, forgot to mention I am running XPSP2 and the changes to IE are barely noticeable. Pop-up blocking thats no-where near as flexible as FireFox’s just isn’t going to cut it. You Firefox people need to relax. As a web developer, I won’t TOUCH anything that has Netscape-ish/anti-microsoft crap. Mainly because choosing a product because it’s "good", is more important that choosing a product because it’s "not the company’s product" I have ZERO issues with CSS compliance – and what do you mean "hover" isn’t supported? Do you mean: .MyLinks:Hover { color: red; text-decoration: underline; } I use that every day, I don’t get it? About the only thing I agree on is that Firefox and MyIE have better usuability. IE has become the plain-Jane of browsers but for W3C and CSS compliance and for things like activex support, I’ll accept no substitute. i love IE too because of the security aspect, coupled with outlook drebin test that and you will see : input:hover { background-color: red; } IE doesn’t work that well for me even though I should have used it to check for w3 compabilities. I remember i run ie in solaris once, but now I’m using other *nixes that is not supported… Don’t think solaris is supported anymore either.. why make ie just for windows? drebin: as you can read it here IE have :" Full CSS Level 1 Support" What about CSS2 ? Maybe it’s time to implement some aspect of the CSS2 even if it’s still a candidate recommendation ? What do you thing about that ? "I have ZERO issues with CSS compliance – and what do you mean "hover" isn’t supported? Do you mean:" You may be kidding ! IE6 CSS support is pretty outdated and partial, now try this in IE, which is a basic and perfectly standard CSS declaration: tr:hover {background-color:yellow} <a href="" title="Get Firefox – The Browser, Reloaded."><img src=" /firefox/buttons/header.png" width="305" height="150" border="0" alt="Get Firefox"></a> How much of the old NCSA Mosaic code is there in IE today? Will IE 7.0 be in managed code? There is a huge community of Bloggers and Channel9’ers out there ready and willing to help create the Browser of our dreams. Brant Gurganus : you are right. Drebin, did you miss my list above? Internet Explorer doesn’t support CSS tables, CSS 2 selectors, or generated content. Also, as others have noted, the :hover pseudo-class is only implemented for the a element type. Whole chunks of the CSS 2 specification, which Microsoft are partly responsible for, being completely unusable because Internet Explorer doesn’t support them. I like IE, I would like to see the security problems fixed and tabbed browsing. About security, just see this recommendation of the US-CERT : solutions: _Disable Active scripting and ActiveX_ (sorry Dride but how can i use ActiveX with IE if there are security exploit ?!? ) […] _Use a different web browser_ I’m agree with Jim, IE must do a lot of improvements to be a true browser ! As others have already mentioned, the current problems with IE are countless. Here are some of them in a short list: – IE is by far the slowest browser (compared to Firefox, Opera, et al.) – it has many security problems that only the more computer-oriented people can protect themselves from – it has also many other, not necessarily security-related bugs – it is not standards compliant – the patching of these problems is too slow (MS should have invested the 70 and then some billions to security-related development instead of lining the pockets of investors) Why doesn’t somebody just come out and admit that IE has deliberately been allowed to slip to relieve preassures and allegations of anti-trust and monolopoly against MS, and that IE isn’t going to make any leap forwar again until its believed Mozilla has a significant enough foothold. The freezing of IE can only be explained as a business decision. For those who harp on and on waving a finger saying "IE is not standards compliant"… if the IE dev team had of carried on at the pace that took them to version 5.5 the same people would have been harping on about monopolistic practices. Understand this truth…. there will be no significant advance of Internet Explorer until Mozilla (or alternative) is fealt to have a secure hold within the "marketplace", and ideally after various flavours of browser are more closely integrated into KDE and Gnome…. remember MS took a lot of heat over browser integration into the operating system, and over the death of Netscape. I like to participate in arguments to either further validate my beliefs or to learn new things. Today, I have learned new things. I can see the usefulness of the hover for a <tr> (and it never dawned on me that that should be possible) and after doing some research, there is a lot of cool stuff in CSS2 that I didn’t even know about!! I wonder what Microsoft’s stance is on this – if there is a release that’s planned to support CSS2? Looking back, it’s almost like in the old days, IE was ahead of it’s time and supported CSS1, but things that looked good in IE looked bad in Netscape.. whereas now, it’s the other way around and they feel behind the curve. And to be honest, with this security issue – there already IS a solution, for Internet sites, the browser disallows things like activex.. and for Intranet – it allows more. Why is that not enough? Hello Microsoft, If you want the security problems fixed and tabbed browsing capability then turn to. Install Mozilla package or FireFox which is a very quick state-of-art standalone browser. It can tabbed browsing too. And install Linux OS. Microsoft Windows is far too expensive and overly vulnerable to viruses and attacks. Only OpenSource developers can make the software right ! Begin eg. with "Mandrake 10 Official". What a brilliant system it is. Isn’t it ? So I will never go back to Microsoft Windows or IE anymore. I can’t afford to waste money or time with it. Good bye. // moma About IE 6 having full CSS 1 support, that is not true, background-attachment:fixed; is not supported for all elements other than body. Drebin, > I like to participate in arguments to either further validate my beliefs or to learn new things. That’s an admirable attitude. > after doing some research, there is a lot of cool stuff in CSS2 that I didn’t even know about!! Sadly, that’s very commonplace. The thing is, no CSS tutorials will teach things like display: table as long as the most popular web browser doesn’t support it. So people are unaware of these parts of CSS. And because they are unaware, they think Internet Explorer does everything just fine. If people were more aware of the features of CSS that the other browsers support but Internet Explorer doesn’t, I think you’d be hearing a lot more complaints about how Internet Explorer is holding things up for the web. Hmm… Why can’t people debate maturely? I just see immature kiddies here calling other people’s software "shit" with no reason without telling the cons of the program they are "protecting". Don’t argue. Now I have to find the holes from your statements, cerbere. You seem to act by these lines laready said: "Mainly because choosing a product because it’s "good", is more important that choosing a product because it’s "not the company’s product"". So: " "make Internet Explorer the best way for browsing the web." … how can you said that ?" By just saying it. That’s cheering up and a wish. "I’m sorry to inform you that your browser is NOT standards compliant. So how can it be the best way for browsing the web ?". "I’m using Mozilla Firefox – you can download and try it at :" Thanks for the link. "It’s GPL guys, do you know what does it mean ?" I don’t. Teach me. In a non-fanatical way, thank you. "Some features from this PERFECT browser (yes i said perfect, because you insinuate that IE is a good browser):" Nothing is perfect. Thus Firefox isn’t either. Simple. No need to use CAPITAL letters for that. You only make yourself sound silly. 🙂 "_Popup Blocking_ : Mozilla Firefox : YES / your shit: NO" Indeed, using underlines is a fine to get people focus on something. Though, used many times, make you sound silly again. Weeee! ^_^ And I see you begin very unfair here. You first time use the whole name, Mozilla Firefox… but then why do you call Microsoft Internet Wxplorer by the name "your shit"? It’s not its name, you know that. No one learns from this, you just start arques and slow down world wide technological improvement. And everyone will blame you for that. That wouldn’t be so fun, would it? "_Space Installation require on Windows_ : mozilla Firefox: 4.7MB / your shit: it depend if you install security patch, do you know what I mean ?" Not to mention your numerous grammar errors in your sentences (which clearly show you are taken over by your fanatical feelings), here’s how you probably should’ve put your text: – Fix the first sentence. – Mozilla is a name, thus it needs to start with a capital letter. – The file space needed is invalid wince you do not tell us the version number. – Again the "your shit" problem. Learn to use correct product names. – Oh, you are really going to make me trust with all those typographical mistakes. 😛 – Give us the options, thank you. What is the full download size if you download it, what is the less space needed and did you note that it is up to some point integrated with Windows, so you can’t really say exactly how much you are installing and how much of the browser you have already… – Security fixes? You’d rather have a completely new version of the browser up for download each time there is one? For example, many of those mass spreading of a virus events wouldn’t have happened if people wouldl’ve used Windows Update. "_New Theme : Mozilla Firefox : YES / your shit : maybe you will implement this functionnality.. one day.." – I you meant the plural form… – "Your shit" problem again… – Are you that desperate to get custom themes to IE? Wow, nice to see you care about IE’s development. 🙂 (I personally have never liked any custom themes in any programs, though.) "Try to respect to the standards : Mozilla Firefox: YES / your shit : AH AH AH AH !" Okay, now I’m certain that you are a grammar illiterate ignorant trouble maker. "well i think it could be a good idea to take a look at – you will find 114 extensions made by the GPL Community." Hm… I didn’t quite get it, what do you want to tell us by this statement? "Conclusion : Use Firefox, it’s so more simple." I am using Firefox, but simplicity is just an opinion of a person. That’s not general. "hum .. did I precise that it’s GPL, stupid?" Yes, you did. In the beginning of your speech. Gee, I never knew you had that bad memory… Oh, and calling someone stupid (not intelligent) without knowing that for a fact just makes you youself look stupid, sorry to say. Indeed, you sound like an immature 12-year old. Learn how to debate. Otherwise, thanks for the laughs. 🙂 Oh, silly me, forgot to comment myself. Hehe. Well, guys, I hope IE’s development would get some more resources. I do understand that all of you are focusing on Longhorn, maybe even on Windows eXPerienced Reloaded, but maybe you could compile somekind of an IE 6.5 in the SP2. I’d be glad to wait for XPSP2 for anther few weeks if you did that. I’m eagerly waiting for the revise in Longhorn. 🙂 LEAULE !! ahum sorry. You’re funny. Left already? 🙂 I don’t believe you had enough time to read everything I wrote…? Joonas, first, sorry for all grammar mistakes, my english is not very good. If you thing that i cant debate on IE, i’m sorry but what can i say when i read : "make Internet Explorer the best way for browsing the web". What can we say ? ok IE is the best. where is the debate here ? If you thing i’m sounding like a 12-year old, what can we say about this blog ? is this a commercial presentation or a real space to debate ? The true thing is that i’m thinking like Guy Murphy. IE was let behind. the good question is why ? Microsoft people can maybe give us a clue. Second, i’m sorry but for security reasons, using IE in commercial/professionnal environment is totally silly. Just see my link : even US-CERT disencourage using IE. third, I’m using OpenSource all days. And i’m so happy with that. It’s so easy to participate to the developpement of some stuff. Why not IE ? because it’s close. I’m not clausing to IE because of it’s a Microsoft product, that’s not the reason. I’m refusing to use IE because there’s a problem because IE is not improve like Guy said. So how can we trust IE is a good product is nothing is done to improve it ?? " Left already? :-)" Not yet :/ "I don’t believe you had enough time to read everything I wrote…" of course not many time, just in order to reply. "Anyway, let’s get to Firefox’s problems. I hope these will get fixed too:" "- Some rare random crashing." on GNU/LINUX Debian — — never see that. "- Doesn’t process Java Script correctly." can’t said. "- Page formatting on various sites." can’t said "- Pop-up blocker a bit "too active"." I’s better than have no blocker with IE. And you can desactive, at any moment the blicker, just click the blue button at the left botton of firefox. "I don’t remember having any formatting problems with IE… Funny, isn’t it?" Does IE can format page with CSS 2 ? well the answer has already be done: no. IE is not so usefull as Firefox. And there’s a lot of many others browser, that i’m missing. The problems with IE are numerous, the main one is that MS made the decision to bundle it into the OS. Go back to college and ask your OS professor if the browser is really important to the OS. Then even worse after you used IE to illegally destroy Netscape, it was abandoned. Or at that is how it appears to most people who make money doing web development. I too used to be an IE user but since I have switched to Firefox I will not look back. And I usually try to convert any IE users that I can find. I am glad though that it appears that MS has gotten it’s head out of it’s ass and is going to start working on IE again. What is sad is that I have read that IE will never be stand-alone again. That means for me that I will in fact never run the damn thing. Bundling a browser into an OS is just a bad idea. It shows that people who make decisions at MS do not understand what an OS really is… for that matter the connection between IIS and the OS is just about as bad. It is almost like MS must have hired the dumbest developers that they could find. Which once again makes me sad. MS has got more money than God and yet has been unable to "on it’s own" come up with a good secure product. It has only been in recent months that enough devestating bugs (ie press) have hit MS that there has been any attention paid to security at all. And yes I know supposedly Gates started the whole security thing a while ago and we are just now seeing the fruits of this work. We will see. Good luck to the IE team. Unbundle your product from the OS and get a clue. Dear Joonas, Sure, the Gecko engine (used in Mozilla browser, Firefox, etc.) is not perfect, but it is by far better than IE, and used as a reference when benchmarking web browsers… I’m glad you’re happy running IE. In fact, I still wonder why so many web designers/developers keep complaining about this brilliant piece of software… Oh silly me, it may be because of the infamous lack of CSS2 support ? Not to mention some CSS1 bugs (such as fixed background, as mentioned earlier) : just have a look on alistapart.com and how many IE hacks are needed to have it working almost correctly. It’s awful how developers have to trick the CSS engine with… comments !? Or maybe it is just the repetitive security problems involving Microsoft’s master piece ? Let’s play a game, search "Internet Explorer" on Cert.org : that’s about 1609 results to me. And compare this to "firefox" : that’s about 1 result today. And this result involves a Microsoft Windows related problem. I may be a little too confident, but my guess is that this will be quickly fixed. Love it if you want. After all, some people still use Netscape 4 too. 🙂 As a web develolper, I’d love to see an updated IE6 that better supports CSS2 (and 1, for that matter). Sadly, I doubt that will ever come to be. I only use IE to test compatibility for all the people un-educated enough to keep using it. I educate my clients, and they usually love Firefox. Firefox is my browser of choice for development (you’ve got to try the developer tools plugin, it’s fantastic:) and for surfing. I hope that Microsoft and the IE team can hear past the immature noise here and gets the message that there’s a huge demand for standards compliance above all other concerns. Joonas: "- Some rare random crashing." I’ll agree this needs to be worked on. "- Doesn’t process Java Script correctly." Show me an example of how Firefox violates a JavaScript standard. (If it actually does, I’ll gladly submit a bug) "- Page formatting on various sites." HA, no. View source, I guarantee the problem is in the web developer. "- Pop-up blocker a bit "too active"." Actually I have many more problems with Google Toolbar’s excessive popup blocking than I have ever had with Firefox. "I don’t remember having any formatting problems with IE… Funny, isn’t it?" Well, you obviously haven’t been viewing (or developing) standards compliant code. (You know, those W3C standards MS participated in?). IE vs. Firefox: . " Not being standards compiant means that IE does not conform to the W3C standards for CSS (There are other standards too, but CSS is the most wanted and beneficial standard to start with). CSS when properly used enables a website author to make sure that their website will display correctly on any platform that supports the internet standards – note platform here means anything from a smartphone through to PC’s, not just operating systems. CSS enables true seperation of content and design thus providing much better accessibility options as well as dedicated designs for different devices that are all defined from a central document. IE’s lack of and buggy support for all of CSS1 and virtually non-existent support of CSS2 means that web developers have to continually downgrade their websites to work with and around IE. Apart from a few old versions of browsers that are still around pretty much any current browser not based on the IE engine supports and complies to the W3C standards so you can see why there is so much anger from web developers towards IE. So to re-iterate a few of the points for CSS when used correctly: – Better cross-platform support for devices including printers – Specific designs for each device to take best advantage of available resources – Better accessibility for disabled users – Better content/style seperation which leads to better document indexing and automated analysis – Website look-and-feel can be updated from one file Again, they are just a few of the benefits to having websites comply to the standards. I say websites there as in the end it’s truly up to the web developers to take advantage of CSS but developers aren’t going to use these benefits if the dominant browser doesn’t support the standards and makes it 10x harder if they do try to use them. I could also go on about how IE is in the position it is due to being built as part of the OS but I think thats best left to a different discussion. My point is the sooner IE coforms the sooner everyone benefits. Kev travis: I couldn’t agree with you more, when developing pages you should be able to make total crossbrowser compatability by using standards, which the Gecko engine totally lives up to, whereas IE often freezez, and installs stuff behind my back… Browser – and web developing, has become a much easier task since I became a firefox user. > – Some rare random crashing. Possible, do you have any URLs where Mozilla or Mozilla Firefox crashes? > – Doesn’t process Java Script correctly. Standard compliant Java Script ("ECMA Script") using the DOM or some proprietary JScript? URL? > – Page formatting on various sites. Are the HTML or XHTML valid? If not, then there is no "right" or "wron" page rendering. URL? ((X)HTML Validator) (CSS Validator) > – Pop-up blocker a bit "too active". It is hard to block only the right pop-ups, but there are great improvements in work (you will see them in Firefox 1.0RC1) > I don’t remember having any formatting problems > with IE… Funny, isn’t it? Thats because almost every webdesigner has to create websites, that are compatible with the market leader, but there are some sites, that use the full power of XHTML/CSS2 and IE will not be able to display them properly.. –Thomas How can you love MSIE when there is Mozilla Firefox for virtually every operating system? I have serious doubts that if windows development was shut down that people would volunteer their time to develop IE in the same way that is being done on Beos I’m a FireFox hound and have encourage family and friends to switch from using IE. Everyone I’ve switched has enjoyed their FireFox experience despite not being "techies". As a web developer, I want good browsers on the market and in the hands of consumers. IE was ahead of the curve but, as one poster put it, it’s now the new Netscape 4. Newer browsers are faster, simpler and lack the security holes of IE. The standards support issue is also huge since a site’s code can be so much cleaner and effecient when separating style from content. IE can do this to a certain point but then the hacks come in where CSS support differs from other browsers (CSS hack chart:). I want IE to be a good browser so I can code pages that work across browsers and platforms without over coding or hacks. If , as some say, a browser is just a browser, then why not get over ourselves and let the user’s experience online be consistent throughout? I’ve tried to stay objective, but comparing my experiences with MSHTML and Gecko over the past 5 years or so, I just can’t comprehend how anyone would prefer IE over Firefox. Using nightly builds and following the development of Mozilla products has allowed me to witness the efforts the Mozilla Foundation has made and is still making to release the best browser, e-mail client, … out there. I haven’t seen any products that begin to really compete with them when it comes to standards, user-friendliness, convenience, or just general development, by which the rate at which new features are added and bugs are fixed – for which Bugzilla continues to prove to be the most effective way. As a web developer, I need to be able to test things all the time. Reloading pages a dozen times and messing with (standards-compliant) code has clearly demonstrated to me that 1/ IE6, which is a release, isn’t nearly as stable as the average Firefox nightly build I use, which is supposed to have bugs and is kind of allowed to crash 2/ to this day, it’s still hard sometimes to predict whether that same version of IE will have problems interpreting the code that Firefox takes without any trouble. Add to that the feature set of Firefox (and let’s not get into third-party software for IE) and it makes you wonder how anyone could "love this browser" when there’s clearly at least one far better product out there. I’m sure many of you will argue that my code is to blame in at least some cases, but I can assure you that using Mozilla products has in fact made me very aware of standards and I do everything in my power to adhere to them – standards which are in fact partially defined by Microsoft. Finally, I’d like to add that I started out as an IE3 user, then upgraded to 3.02, then IE4, IE5, IE5.5 (which, incidently, molested my system) and finally 6. I’ve been a web developer for quite a while and I have to admit that I rarely bothered to test with pre-Mozilla.org Netscape products, because I’m willing to acknowledge that those were junk. But so did Netscape itself, and they’ve been making huge improvements, as I’ve just been saying. So if anything, I hope IE will get at least the same improvements with (or, though unlikely, without) Firefox breathing down its neck, because it appears considerable competition is the only way to startle the browser business. And to all of you who are just flaming or complaining here: try to be constructive. I hope I was. come on, this blog is a rotten april fool. How can somebody seriously prefer IE for daily usage ? The only thing I like in IE is its fast Javascript + rendering engine ( not too hard, since it’s not standard compliant and deeply rooted in the OS ). Oh, and even in Javascript, there a little thing that do not work in IE. It’s the access to a character of a string via the [] like described in the 3rd example for the String object in the references of JavaScript 1.3 ( ), released in 1999. Joonas Mäkinen: In the two years since a major jump in the version number of IE the Mozilla program has come into existance and surpassed IE in many area, some of which include css support and security. When IE 6.0 was released, mozilla.org didn’t even exist. The last update, per the Microsoft web site, of IE was Sept. of 2002. Since then Mozilla has had 11 releases. So I applaud Scott and the IE teams efforts, the have a Sisyphusian task ahead of them. "I’ve tried to stay objective, but comparing my experiences with MSHTML and Gecko over the past 5 years or so, I just can’t comprehend how anyone would prefer IE over Firefox. " Will Tim, I can give you one. If Firefox provides detailed enough documentation telling me how to _use_ it programmatically, I’d love to switch. The source code is there, you may argue, but not everyone has the leisure to get lost in such a huge source "forest". IE exposes COM interfaces for programming. Although complex and not-so-easy to use, it makes things possible. What I’d like to see in future IE is, + Neat, clean, managed interface. It’s so painful to use COM Interop dealing with those ISomethingCrap … Why can’t I just use myBrowser.FileDownload += myDownloadHandler ?? + Allow me to set the timeout of one instance, thanks. I know I can do it inside registry, but that’s for all instances. + Make it in the namespace under something like Microsoft.InternetExplorer, not SHDocVw nor mshtml in global namespace BTW, XP2 SP2 RC2 IE (wow, sounds like rap!) is quite impressive, nice job! I think the most worrying aspect of the lack of IE development for years is big bad bill’s atempt to stagnate browser development in general. As somebody a lot wiser than me once said and i’ll roughly quote here… "If the browser is allowed to develop into a mature platform for delivering applications then that reduces windows to nothing more than a slightly buggy set of device drivers" The important part here is that if you dont continue to develop ( and i mean develop not fix, which is what you are doing now ) the browser, IE, unitl longhorn ( which is years off and for all practical terms that may as well be decades ) then your going to have an obsolete piece of software before too long… Think about it… > [Tonetheman] The problems with IE are numerous, the main one is that MS made the decision to bundle it into the OS. Go back to college and ask your OS professor if the browser is really important to the OS. No, IE is NOT NECESSARY part of Windows. For some special uses Microsoft offer completly uninstalling browser from the system. It’s not offer for BU, but for manufacturers of fridges and so on (it’s for example normal Windows XP system, only without IE; the explorer become to be win95 like). > [Tonetheman] Bundling a browser into an OS is just a bad idea. It shows that people who make decisions at MS do not understand what an OS really is… for that matter the connection between IIS and the OS is just about as bad. There is another "good feautere" for the developer. You have no legal possibility to run more then one version of IE together. It’s very useful for developers… How can I test pages for enough of IE-bug-patches on IE (for example) 5.5 and 6.0 on single machine? Enjoy: > [Thomas] Yes, IE RISES the prize of web developing. Why? The developer (which has abilities to be signed as a developer, not ignorant with WYSIWYG editor) writes the sources cerresponding to the structure and design of page. He/she starts testing in browsers. He/she sees there is no problem (or only few cosmetic) in the most browsers (Firefox, Mozilla, Opera, …) except IE. Knows, the IE is major browser, he/she starts generating patches to make it viewable in IE in a seansible way. As a result, he make the sources messy and not very readible due to loads of unlogical (enforced by IE) parts. > [Kevin Freitas] The standards support issue is also huge since a site’s code can be so much cleaner and effecient when separating style [CSS] from content. That’s my words… > [P01] How can somebody seriously prefer IE for daily usage? Because they do not know anyone else, or the are paied to saying this. "I may be a little too confident, but my guess is that this will be quickly fixed. Love it if you want. After all, some people still use Netscape 4 too. :)" I can’t say I love any browser… and I use Firefox, as I already said. I just don’t like offensive arguments. Oh yeah, Netscape Navigator… that still exists? 😛 — I’m not so familiar with CSS problems to give out my opinions on those. Though, I learned a new thing that needs fixing. Thanks, Kevin. What I found out about formatting problems with Firefox was at 3D Realms Forums () when quoting other users’ posts gave some glitches. The browser also mysteriously crashed there two times and once on some other site I don’t rmember. I couldn’t find a reason for that. :- Then, I couldn’t write news posts using Mambo open source, the buttons in the editor just don’t show up in Firefox so I have to use IE. (I also use IE to access Windows Update.) What I also found out (not a big thing, though, a bit annoying) was that in UBB forums clicking a button to place an emoticon causes the emoticon to be placed on the bottom and not where the cursor is. In other words, not much. 🙂 (This blog doesn’t like my last name. :-P) Okay, it seems that the 3D Realms Forums get a "This page is not Valid XHTML 1.0 Transitional!" warning also… I’m actually a big fan of ie…. but ie for Mac. Or as least I was a fan of ie while it was still being developed. Explorer 5 for the mac was arguably the first real web standards compliant browser. Other than it’s speed Explorer for windows has always been a bastard child. I now use Safari mainly and Firefox when I’m my PC. I hope to see the new ie make big leaps forward in standards compliance, security, and HI/UI… I’d like to come back to the fold. > [Scott] The last update, per the Microsoft web site, of IE was Sept. of 2002. …and I think it was only because of "adding Windows 2003 support"… Scott, I’m glad you are open to feedback. For the sake of all of us developers, please make your product fully CSS compliant. Thanks. With Firefox 0.9: I click the happy little orange and blue icon. Within five seconds, Firefox is up and running, even on my five-year-old computer. I go to Bookmarks -> Bookmarks Toolbar Folder -> Open in Tabs. All of my daily websites are open, just like that. On a cable connection, it takes roughly thirty seconds for all twenty of them to load simultaneously. I scan the page open on the first tab, press CTRL+W to close it. One down, on to the next one. Read it. CTRL+W. And so on. I’m finished reading everything in about two minutes. One of the pages I check daily is CSS Zen Garden, mentioned in the comments above. I look at one of the newest designs. It’s beautiful, almost brings a tear to my eye, with transparent menus and clever graphic design. With IE 6 (WinXP SP2 RC2): Internet Explorer has been "removed" from my computer, so I hit Windows Key + R to open the Run dialog. I type "iexplore" and hit Enter. Ten seconds passes, the browser is open. The interface is stylish and fits will with the Windows XP theme, but nothing compared to Firefox’s changable XUL theming support (I use Smoke <>). I go to Favorites and open the first one on the list. I read the page, center click a link. Nothing happens. Oh yeah, no tabs here. I want to come back to this page, so I leave it open and open the next bookmark in a new window. Five seconds later, it has rendered. Badly. This is CSS Zen Garden. Perfectly standards-compliant designs that don’t work in IE. I skip this, plan to check it out in Firefox later. I finish the bookmarks, opening each in a new window. To close them, I have to contort my hand crazily in order to press CTRL+F4. Who came up with that combination? Finally, I am back to the page I started reading earlier. I start reading. Uh-oh, a pop-up. Close it. Another one. Close it. CTRL+W, CTRL+W. Wait, that doesn’t work. CTRL+F4. Ouch, it burneth. And one more thing: I develop websites for a living too. Mozilla Firefox’s Web Developer Toolbar extension rocks. Where can I find this for IE? Wait, IE doesn’t support extensions, but it has *ActiveX*. Great, one more thing to turn off, along with the browser itself. I’d be quite interested to see a Microsoft IE person sort of "set the record" on this.. -What are the plans for usability things like "tabbed browsing" -What are the plans for CSS1 and CSS2 complete compliance? It’s as simple as that. There is no WAY Firefox is going to take over the 97% market share that IE has – so unless things are still going the same with with IE a year from now, I’m not going anywhere near Firefox (for regular use or testing). As a side note, how can any sane person say that IE6 + WinXP SP2 RC2 which weigh around 310 Mb has a real bad support of the web standards and many severe security holes. FireFox and Opera takes respectively 14 and 7 Mb, have much more features and a solid support of the web standards. That’s not serious. I fully agree that Firefox and Mozilla are miles ahead of IE in every possible aspect, but let’s keep things accurate: 1. Ctrl+W does close IE windows 2. Ctrl+F4 doesn’t (perhaps you meant Alt+F4?) Prog. I am sorry that there have been so many rude comments. I respect that some people prefer IE and especially the decision to create a blog open to feedback. That said, I am a Mozilla Firefox user as well, for reasons you have probably heard a thousand times over. It seems like things like pop-up blocking, tabbed browsing, and UI changes should be easy to implement; MyIE2, Avant Browser, and others have done so using the IE engine. But the most important point is that Internet Explorer’s CSS and other standards support has been very frustrating to me as a web developer. Floats and positioning seldom work correctly, and while it has been mentioned already, there are a host of CSS2 rules that other browsers implement that IE doesn’t. Many of these are extremely useful. PNG support is especially frustrating because I know that IE is actually capable of rendering them, but it requires propriety tags and attributes (). While there may be technical reasons why IE doesn’t just do this automatically, they aren’t widely known. So it appears that Microsoft is just spiting the standard. Please support standards. Don’t let anti-MS folk put you off Firefox. It isn’t "good because it’s not MS" – it’s honestly a better browser. If Microsoft made Firefox, I’d still gladly use it. I also agree entirely with Jim (). It’s a shame that MyIE2 et al. exist – they allow people to have Firefox-like UI while still using IE-style rendering. This reduces the Firefox’s "pull" for end-users, who don’t know or care that IE screws up page display. Can you not use IE/Mac’s rendering engine for Windows? Or just admit failure, quit, and use Gecko or KHTML? Please? You’d redeem yourself by it… a little. I’d just like to add a couple of things to what I said previously. It’s really frustrating when Microsoft add in a feature that they know is annoying, and only offer non-standard ways of switching it off. For instance, the proprietary autocomplete attribute. It would be dead simple to have implemented it as a meta element, but instead Microsoft have given web developers the ultimatum of annoying behaviour or invalid code. It’s easy to ignore "acceptable" errors like this, you say? It isn’t when you are set up to get notified via email every time one of your pages is invalid. It isn’t when you have so many "acceptable" errors in your pages that you miss the one really important error hidden amongst them. Especially annoying is the fact that you’ve implemented some workarounds as using meta http-equiv elements (which were intended to be read by web servers and emitted as proper HTTP headers), but you don’t pay attention to the actual HTTP headers themselves when transmitted properly! A lot of people don’t like "doctype switching", and somebody suggested using a meta element to determine which rendering mode to use. No doubt you think that this will be too prone to regressions and incompatibilities with existing documents. So have an "X-Internet-Explorer-Standards: true" HTTP header that can also be put in a meta element. That way, I can update a single configuration file, and invoke the standards mode across all our servers at once, for all our documents. It’s also standards-compliant, implementable by people who don’t have any control over their server, and will not affect any existing documents, so it’s perfectly backwards-compatible. One last thing: let’s try and keep it civil, guys. Nobody wants to read a bunch of posts all saying how great Firefox is and how shit Internet Explorer is. We all know that already, so let’s try to be constructive in our comments instead of just cheerleading or flaming. That helps nobody. The immaturity level of this discussion is astonishing. Both the Mozilla side and IE side are doing themselves no favors with all this hyperbole and unwarranted flamage. How are the developers supposed to improve IE with this kind of feedback? My only wish is that the IE developers look long and hard about supporting W3C specs to the letter. I think the determining factor will be whether IE marketshare drops significantly over the next couple years. If it doesn’t, then Microsoft will likely make a power play on the web using XAML and a bunch of proprietary technology to push the technological envelope. But if people start coding advanced sites that don’t work in IE, then Microsoft may have to go the mile to support those standards. So, to the IE developers, PLEASE do the right thing and get standards support up to speed in addition to your proprietary extensions. I know it doesn’t make business sense, but for the good of humanity we need standards we can use. Microsoft is beholden to it’s cash cows Windows and Office, but as Microsoft internally reworks an outdated old OS over and over, the amount of waste is incredible. Think what could happen if Microsoft bent its resources towards developing the next level of innovation on top of Linux. The low-level plumbing and fundamental security issues would basically take care of themselves, and Microsoft could develop truly mind-blowing applications. Instead we see a protectionist policy that relies on all innovation to come from Microsoft, even though it comes at the expense of interoperability. IE developers! Please please please do the ethical thing and implement CSS2, 3, and XHTML correctly so we can develop sites that work across platforms. The world will thank you! One other comment about the Firefox propaganda.. is disk space REALLY an issue anymore.. I mean, at ALL? Is it even on the charts? With 160GB hard drives that are $139 () – is the difference of even a gigabyte even relevent? I mean, your 310mb vs 14mb – that’s the difference of 0.193% and 0.009% of the hard drive. If you’ve going to defend something – you need something stronger than disk space. The small size means you can carry Firefox around on a USB stick. There are a lot of people out and about who have to still get their internet via dialup. Many of my students do. Downloading 310 mb via dialup is not fun. There’s 3 problem with the size of IE6+WinXP SP2 RC2. 1. it takes ages to download 2. it doesn’t fix the security holes found in june. 3. why the hell do we need to put 260Mb on top of many more security patches to "patch" a soft that should work and be secure in the first place ? "security issues and perceived lack of innovation" Don’t bullshit us, we’re not idiots. "perceived" lack of innovation? It’s a blatant, outright dead product! It hasn’t had any rendering updates since 2000! As a web app developer, I lose measurable hours and money to this browser. It’s going to take a lot more than smiling words to win back any respect from me, and no doubt the overwhelming majority of other web developers. IE is not 310 megabytes big. Hear, hear, Matt. I don’t think I stressed this point enough when I posted it before. I actually went through a period of implementing designs as if Internet Explorer didn’t exist, purposefuly using useful CSS that I knew Internet Explorer didn’t support, and then going back and altering them to work with Internet Explorer. I didn’t go out of my way to trip it up, just use what I would normally if I wasn’t aware of Internet Explorer’s deficiencies. It was informative to see how much time I am wasting on Internet Explorer. Take multiple column layouts. Instead of: * Floats, * Clears, * Dummy wrapper div elements with padding instead of margins to avoid box model problems, * Explicit heights, hidden from other browsers, to avoid making text jump about during :hover events, * Spurious position: relatives to avoid disappearing text, * God knows how many other hacks, I just used display: table-cell. It worked in all major browsers except for Internet Explorer. I’d urge any web developer who doesn’t think Internet Explorer’s CSS shortcomings are a big deal to actually do what I did and measure the time you are wasting on this browser. Measure the money it is costing your company. I also agree with Matt’s other point. Please don’t be so condescending as to try and write off the negative opinions of Internet Explorer as a mere "percieved" lack of innovation. I can’t think of a single innovative feature Internet Explorer has had first, except possibly "channels" in Internet Explorer 4, which were a precursor to RSS. I’m open to correction, of course. Joonas: It is if you apply the WinXP SP2 RC2 to "patch" the latest severe security holes. And 310 Mb is a low estimation which do not take into account the previous security patches spread here and there in the various folders of Windows. But, indeed if you never apply a security patch, IE is "only" ~50 Mb big. SCOTT STEARNS, THE TEST MANAGER FOR INTERNET EXPLORER AT MICROSOFT, jumps into the blogspher with a big ‘KICK ME’ sign on his rump with the post I Love This Browser! I hopefully got your attention with the title ofmy. Strange he should say that when his real achievement has been to make the worst browser on the web the top browser. Yes, by dint of his unremitting tream management, attention to design-flaw detail, and star class software rewriting team, Internet… Just to comment on someone’s mention of IE having ~97% market share: that’s not a particularly accurate figure. From a few high traffic sites I either administer or have access to the statistics of, it’s looking *much* worse than that for IE, presently. The recent scares have sent large numbers over to alternatives. From one site that gets the majority of its traffic from mentions in newspapers and radio, and has a non technical but US focused audience: IE: 68.5% Mozilla: 18.8% Safari: 5.8% Netscape: 2.2% Opera: 2% The lack of substantial updates and innumerous bugs and standards deficencies makes me hate it. I’m stuck developing on it at work, and end up cursing at it nearly every day. :~( Ok, let’s not pussy foot around. If you’ve got a blog, you’ve got to be able to say something about what’s actually going to happen. Scott, Dean? The big question: Is IE going to get rendering engine updates, and are those updates going to cover the W3C standards? CSS2? 3? W3C DOM? Anything else? That is the time, money, and business critical question for me, and I’m guessing many other web developers. Say something about what’s going to happen, and what’s happening, or this blog will serve little purpose other than PR fuzz. Sorry to come across so harsh, but you can’t sit on a product for four years without updates (other than maintenance patches) in a software development area as dynamic as the web and not expect to take heat for it. I believe it is apparent from the above posts that IE now losing share to other (said alternate) browsers particularly Firefox.. But what I have heard about the XP SP2 till now I am SERIOUSLY considering NOT TO apply SP2. What happens in this situation ? What about the users who are using Windows 98/Me/2000/20003 ? WILL WE NEVER GET A STANDARD COMLAINT BROWSER FROM MICROSOFT ? I hope Mr Stearns can hear the web developers complaints about IE. You might think IE is a super browser but believe me Firefox, Opera and Safari teams have worked hard when IE’s development almost stopped years ago, and now they are eons ahead of IE at least from compliance with standards and innovative features (bettr control, pop-up blocking, tab browsing etc) perspectives. I feel that IE has been only in "mintenance mode" for years, maybe this is because of Microsoft’s dream of "windows is the client for internet" and "we believe in Harddrives and fat clients" "trhin clients are evil" strategy, or some kind of "we have %90 of web, everybody using IE with its faults, so who gives a damn" carelessness. I hope you can at least care a little and fix some of the most serious problems mentioned above. You love IE???, i love Osama!!! Seriously, if you prefer IE above normal browsers like Firefox, Mozilla and Opera, you should try Mosaic. Or Lynx (does that have a win32 port?) Your product makes my working life a lot harder. Follow Standards! Get proper Alpha Support for PNGs. Do padding like *all* the other browsers. "…and I really love browsing with IE." Look, that kind of transparent nonsense won’t fly. Obviously you will have used many other browsers such as Firefox that have improved on the basic browsing experience. One cannot "love browsing" with a browser that doesn’t block popups unless one doesn’t mind popups. Frankly, the experience of "browsing with IE" is at best mundane, like browsing your files with Windows Explorer, and it’s the baseline tool at best. SInce IE is really only defined by its deficiencies these days, which of its failings is it that makes you love it, exactly? bredend: Lynx for Win32 is available at No matter what you feel about the other posters, please, leave those irrationalities alone. "Seriously, if you prefer IE above normal browsers like Firefox, Mozilla and Opera…" If IE is a widely used browser, it should be considered normal. "I have spend the better part of the last year working long hours and weekends to push IE forward with XP Service Pack 2, which is about increasing security while balancing application compatibility, but that is not all." No, the main and obvious goal is to further merge IE into the system which is clearly proving to be a horrible and useless idea, forcing the app to stagnant for the 10 years it takes to get SP2 and Longhorn out and increasing security risks. Great. Another Manager who can’t do sh1t for his product but what the lawyers and execs tell him to…. Get a good standalone upgrade out. I don’t care about SP2 or Longhorn. I don’t know what this guy is thinking, but in a way, I respect him. Apparently the guys who work on Internet Explorer have, within the last 24 hours, wised up to the fact that their browser might blow chunks,… As a web developer who regularly curses IE, I have to admit my skepticism to this blog. I’m sure many of the developers on the IE team are fine folks who are really trying to do a good job, but MS’s track record on web standards is, to put it mildly, weak. Looking at the source of the blog does nothing but increase my skepticism and make me wonder if the person(s) who wrote .Text even looked at the W3 specs. The pages declare HTML 4.0 Transitional, and then mix and match HTML and XHTML syntax along with a generous helping of proprietary MS garbage tags along with some sytax, that as far as I can tell, was just made up (the style sheet links for instance). If you want me to believe that you care about web standards, putting the IE blog into a tool that knows how to generate something resembling syntactically correct HTML would be a good place to start. After you tackle that, you can continue to gaiin my trust by fixing rendering bugs and implementing the huge chunks of the CSS specification that you’ve chosen to ingnore so far. A few suggestions: Fix the whitespace rendering bugs. A rendering engine that renders pages differently because a space or a linefeed is brain-dead. Fix the CSS rendering bugs mentioned here: and the peek a boo bug: Add support for min and max height and width Fix background-attachment: fixed And don’t even think about fixing the various CSS parsing bugs that we developers use to make pages render properly on IE before you fix the CSS rendering bugs. Why does validate so horribly? It scored a "This page is not Valid HTML 4.0 Transitional!" result on the validator… oh and I have to agree with: "Frankly, the experience of "browsing with IE" is at best mundane, like browsing your files with Windows Explorer, and it’s the baseline tool at best. SInce IE is really only defined by its deficiencies these days, which of its failings is it that makes you love it, exactly?" When I read that someone absolutely LOVES browsing with IE I couldnt help but shake my head in bewilderment. Who really LOVES IE? What about it would someone LOVE? True Story: In order to get a little modern with their development, the Microsoft Internet Explorer Development Team has opened their own team blog. In one of the most entertaining MSIE related blog posts I’ve seen in quite a long… Has anyone from the IE development team responded to any of the comments here? I have to agree with the earlier post about IE being deliberately held back to allay monopolistic fears. My question is: What is the best reason why someone should switch away from Firefox to your dream-version IE? IE is by far the best browser I have ever used it also keeps my company intranet safe Arthur, I never said Gecko was perfect. I don’t develop extensions or themes myself, but I’ve heard that it can be a pain because of the lack of proper documentation. Which is apparently not a priority at the moment. Why? Because Firefox (I’ll use it as an example) is primarily a Web browser, so the stress is quite logically on delivering a quality browser to the users. Once the beta period ends, I’m sure the developers will release tidy unambiguous documentation. Right now, the specification (which is probably a bad word in this stage) is subject to change at any time and it would be confusing and tedious to keep updating it as development progresses. And to the authors: I would appreciate it if there were anchors for every comment, so we could reference them, and perhaps quote. Also, like someone pointed out, get rid of the Microsoft-proprietary markup (are you blogging from Office or something?!) and make a few attempts to make the page validate. Please. ." I have the SP2 preliminary installed now. To my knowlege, and in my exprience with it not a single standards compliance issue or bug is fixed in it so I don’t know where this person heard that. 3px jog – Still there "A good start would be setting up Bugzilla, to get tot know precisely what bugs are around." Exactly. is the IE team even aware of all the bugs in IE? I’m unable to find any MS resource describing any of the bugs web developers love so much in IE. Its unbelievable to have to surf all over, when MS could have provided some centralized resource. Of course if they did there might be some expectation that they planned to do something about all these issues. "If you want me to believe that you care about web standards, putting the IE blog into a tool that knows how to generate something resembling syntactically correct HTML would be a good place to start. " Here here! Frankly speaking, I don’t love this browser. I don’t want to appear like a troll, just tell my opinion. Since I switched to Linux, I’ve never missed it. However, if you want me to use it, you should release a linux version of it, or at least a version that doesn’t lag as much as it does when using WINE. I’ve tried it and typing in a textbox like this was a real pain, animated gifs would flicker and on and on. Besides, IE is way behind in CSS (selectors among others), box modell and especially the DOM. Oh and transparent PNGs anyone? I’m teaching standards based web-design (for people who want to learn for tomorrow, not yesterday) and IE disqualifies itself. The first thing we do is install Mozilla with the handy DOM-Inspector before I start teaching. Asa Dotzler rapporte que l’équipe de développement d’Internet Explorer a mis en place un blog collaboratif sur MSDN. Dean le Product Unit Manager d’IE présente les buts de l’IEBlog :. p.s. we promise an explanation of Microsoft titles, roles, and responsibilities in a future post. Scott Stearns, Test Manager d’IE, renouvelle sa profession de foi pour IE (l’emphase est de lui) :. … I think the problem is that other browsers have advanced so much, and IE has been left behind. Lots of people can see the new features and benefits of other browsers, and IE just doesnt compare. The way we browse the web has changed, and IE failed to realise this. its too late now. And also, i would like to see the % usage of other browsers if they were shipped with windows. People who think IE is safe have obviously been stuck in a nuclear bomb shelter for the past 10 years. ever heard of mozilla? +1 for OSS I’m just happy that Apple dumped IE. 🙂 I can’t test ie because i’m using linux… but whatever. You can afcourse say that I.E. is so great but you didn’t explain why. Why should I use I.E. and not mozilla or firefox? I guess a mom gotta love her children however ugly they may be and boy is IE FUGLY. Want to know how to make IE better? Download Mozilla source code and clone it. glad you do. But then I guess you have to. as a user, the insecurity of IE, and Windows generally (together with sheer bloat), is what led me to finally abandon MSOS after almost 20 years, and switch to a Mac. as a professional, full time, web developer, I waste hours of time trying to ensure that CSS code which works perfectly with all DOM compliant browsers will render properly in your beloved software. it would be a service to the web community if you could get it sorted. hehehe, the replies are the only thing reading in this ‘blog’. Is this ‘blog’ viewed as a cheap marketing tool? Because if your going to convince people, you may want to: [b]GIVE AT LEAST 1 REASON WHY[/b] (:D) you love ie so much. Oh, not even one eh? Well, uh, i guess i might notice your ‘improvements’ in a year or so when i upgrade ie/sp2(for when I use it once every 2 months). Meh, i don’t even use it, i don’t even like opening it for a second…. who cares just posting to swell the tide of posts that’ll wake-up anyone who actually believes the drivel that comes out of any corporation’s ‘thunk-tanks’. Geweldig. Ik heb het vreemde gevoel dat IE qua uiterlijk héél erg gaat lijken op Firefox. I forgot to mention IE’s Poor handling of the <object> tag: see: and I also use Firefox for everyday use, and have got so used to it that I had almost forgotten what IE was like. (I’m not a zealot – Firefox isn’t perfect; just try looking at and scroll down [Note – I used an extra tab to check that URL], but it does give me a much better day-to-day browsing experience than IE.) On a recent business trip, the only web connection in one hotel was a machine on the reception desk running IE, and I’m afraid that using it was a real eye-opener. Animated ads, pop-ups, and I thought that my middle finger had been amputated. I’ve also done a lot of web development over the years, using ActiveX controls and so forth. IE has its own set of quirks and extensions, like any browser, but as many people have said, its support for certain *standard* ways of doing things is patchy at best. The recent security problems have also made it worrying to use. I recommend Firefox to everyone now, and it will take a serious amount of effort to overtake this to a point where I actively want to switch back. OK, guys. Surprise us! ok you made me chukke. and i agree that most webmasters i know, including me, are really pissed off by the non-respect of standards. with all the money you have this is the best you can do ? I think that if you continue to delibaratly break standards, people will get tired of it and swith to open source solutions, wich are obviously able to observe standards.. – Yet Another pissed off webmaster. "If you want to try out the latest IE browser, I strongly encourage you to download and run the latest release candidate for XPSP2 Service Pack 2" Hahaahahahahahahahahahahaha! You seriously expect people to download a 264 megabyte service pack RELEASE CANDIDATE – which could actually BREAK their existing OS install just so that they can make Internet Explorer do some of the things they can already do with Mozilla / Firefox / Opera, and have been able to do for several years? I used to think that Microsoft deliberately pulled the plug on IE development. Now I’m reminded of Robert Hanlon’s quote: "Never attribute to malice that which is adequately explained by stupidity". IE is BUG! You ask why? Because it gives me headaches. We develop our sides under our browser of choice and that happens to be Opera. The nice thing is, Opera does exectly that what you want it to do. After that, we check the sides with Gecko and KHTML based browsers (Mozilla, Safari, you name it), and at most we get some minor glitches, but normally code that works for one of them works for the other too. But the IE test often causes real pain. That a lot of code that is w3c valid and works does not work with IE – we got used to it. That some, for example, popup code works with IE in one context but not in another – well, annoying. I do not use IE and I don’t think I will, but some things I think you should change: – clean the code. As I said, some things work here, but not there. This isn’t supposed to be. – CSS [23] support – Tabbed Browsing – Cookie Management – "The Zone Model" > /dev/null – Either completely cat "Active X" > /dev/null or make a second, lightweight IE binary for use with windowsupdate only. But the everyday-usage-www-browsing IE isn’t ought too have a functionality that gives that much access-rights to a computer. You need it to update the system, yes. But you do not need it to browse the web. – Fine Grained Options, easy to access. For example the "All scripting or none" option at the moment. That isn’t userfirendly. – Your status bar (the one in the down right corner). All the info you can get from it is that it’s moving. You aren’t told what the IE does at the moment and the progress of the bar is not related to the progress of the asked for task. Either make it useful or drop it. Well, I guess over the years I got too biased. So, clone Opera but try to make it not too plump. Or, like Adobe did, license the Opera engine and give it a new skin. For all the love Opera got from Microsoft, I am already rather sure what the next IE will look like. A lot like Opera. Small, powerful and works – three words that do not come to your mind when you think of IE right now. But you are here to change that and I wish you luck – you really need it. Maybe the web will benefit from this, in that developers can write one side and it will work in all browsers. But, from past history, I do not count on it. There will be new IE-centric code snippets, highly used by frontpage, and the barrier-free web won’t be come true. Proof me wrong, that’s a defeat I would love to take. I love firefox more. at least they appear to be actively developing a sound browser that is smaller and lighter than IE and its rendering engine is way faster…. KDEs Konquer is a nice example of a feature rich browser. it would be nice to show some respect for the peoples that browse this blog using other browsers than IE. Try Opera and see how it looks. How can anyone even consider using IE. No tabs, no nice plugins like Adblocker, horrible usability, settings are cumbersome and many things are not even configurable. Seems to me That Scott has never tried out a good browser. I tried latest IE and it sucks big time, and I’m not even talking about security here. I am really not surprised to see the usual Microsoft bashing people appear on this site. I am currently developing a software that generates Webpages via XML and XSLT (100% standard stuff) and the only browser that displays the result without any errors is the Internet Explorer. Opera completly freaks out and displays npthing useful at all. Firefox comes pretty close to the intented result, but has some display errors. So yes, IE has bugs like any other software, but a lot of good points also. Web designers – including MS update site should think harder about things like: and As a browser, IE is nicely integrated in windows. Its tie into the OS offers an up and a down side. I think, and I may be wrong, that inside microsoft, its developers, and its developers whom work outside Microsoft fundamentally do not understand the critical state of the browser. If I were running a company with a full AD, Full infrastructure, SMS, SUS, then maybe we would be able to set things up to patch and cover our asses, but we don’t. And we won’t any time soon. And EVEN if we did, the consession that that is the state we are in is a defeatist, apologist, disaster of an ideal. How a leading tester of IE can make the comments made at the top of this page show the level of astonishing lack of understanding about the issues surrounding IE outside of Microsoft. How can you really laugh of a state where a company is only offering a fix for its product by an unavailable (read non beta) SP2 package? Right now, IE is the biggest hole in Windows. I can’t recommend it to friends, family or business. If I do, I know I’m going to be right there installing patching to any such machine forever. Its taken over from Outlook (a product now nicknamed Lookout by many) as the current security and operational nightmare. Its built into your systems guys, its not easily removed, its not easily maintained, its not secure, its a bloody night mare? Can you think of another browser that has to have the follwoing installed JUST to have any semblence of hoping to protect the machine?: A pop-up blocker BHOdemon1/2 Ad-Aware Full AntiVirus And thats before we cover wether people will ever absorb the constant stream of windows updates. The fact that the core is so riddled, and the numbers of updates required by say, dial up users, is now guaranteed to limit take up of your updates. I’m not anti-microsoft, BUT dammit, sometimes you guys are your own worst nightmare. In recent months MS has re-iterated that its serious about security. Right now, IE needs to come with a heath warning. It needs major work in education of end users so they can protect themselves. Most users outside of a development or IT enviroment simply are not aware of how bad IE is, and they make assumptions about an application in regard to IE that will lead to their machines being taken. But all of that is because IE is *REALLY* that bad. Its really that riddled, open, bugged. Right now, in my company, from the cleaners, the users, right through to Management, there is not a soul who has faith in IE, and thus microsoft. Blithly chalking things down to ‘We suggest you get SP2’ when SP2 is still merely a realease candidate is a wind up. Every day of my life is now taken up with windows updates for IE to a large degree, its taken up with removing the junk, backdoors, spyware, adware, browser helper objects, ADODB.stream infestations, keyloggers, and you know what, the consensus is always thats its our fault, the end users fault, a lack of security, firewalls, policy, staff behaviour, or that we should change our whole structure by implementing an SP2 that is still only a ‘release candidate’. Thats me, on the arse end of you guys and your ‘development’ between a rock and a hard place. Guys, PLEASE PLEASE PLEASE UNDERSTAND that I can’t remove IE. Thats your doing. I can’t goddamn continue to commit workaround after workaround on such a core, broken, bugged component. Is your intention to drive all end users who have any semblence of intelligence away? You do know anyone with a shredd of background info is moving off IE, even if they can’t remove it. People are running to the hills. The browser is just another component like office or otherwise that if you lose on, you lose on it big. People can use Linux from browsing the net, do you want that? I no longer give a rats ass about new function in IE. I really mean that. I’m not interested in IE adding more for developers. I want a damned browser that is not the new Outlook. I want it simple, secure, solid. And if your answer is what I am seeing so far, I’m going to take my whole company IT structure, and I swear I’ll get rid of this myself. I don’t care that I may be a small customer, I don’t care wether you read this blog, or take notice of what I have said, I don’t care if no one at MS cares, either you guys get damned serious, right now, or you’re going bye bye. stewart@gci.ac.uk I am an opera user too. I checked out this Brwoser and the first i loved were the mouse-gestures. Once used them – you never whant to miss it. I just use IE for sites not working properly with Opera. But everytime i whant to use this gestures in IE… But they are not there… So, if it is possible that you make the IE more safety and include this mouse-gestures – maybe i will turn back to ie… BTW: A pop-up blocker will be a great bonus too! 😉 one more thing: If anyone can tell the team working at the usual Explorer (Windows-Explorer) that they maybe include them too, so that i can browse in Windows without having to click to a button in the to left corner, this will be wicked! Joonas Mäkinen is the anti-christ. I certainly find Firefox a lot better for browsing than IE now. Please fix all the CSS stuff. Anyway, fellow web designers, even if they make IE7 CSS2 compliant we’ll still be forced to write code that will run on IE6 for many years to come I imagine. So I can’t see that we’ll be able to safely use CSS2 for at least, what, 3 more years? Minimum. Well said Darren, I currently run 3 browsers, Opera 7.53, Mozilla Firefox 0.92 and IE. The only reason it hasn’t been taken out already is I require it for windowsupdate, otherwise every computer I have ever worked on would be running Firefox. Though I’m begining to think removing it, and it can be removed as demostrated in the Anti-Trust case, would actually be a very good thing even though I would not be able to access windowsupdate from the browser. I don’t see any other downsides, does anyone else? re:Paul-Robert Archibald I don’t want to say it, but I feel like I’m on the moon screaming at mission control here, and the radio link is out. I’m agnostic in terms of systems, I’ve run and used everything from 286’s throught to AS/400 systems, and IE is an operational and security NIGHTMARE, and no one at MS seems to absorb this. They have taken to writing blogs where they start with ‘I would’nt use anything else’. I’d like the whole Dev team charged with IE to be forced to install NOT SOME LATEST BUILD across the MS network, but XP pre or post SP1, and then put themselves in a dial up enviroment, without any other products, and then ask them to spend half a day surfing. Throw in a handful of searches for the following: Porn Warez Hack At the end of that half a day, examine the cookies, add ins, BHO objects, run ad-aware/spyware removal tools and carry out a check on what changes have taken place merely by using that browser and ONLY the browser. My feeling, is each of these developers is living on a corp network, where they get latest machine builds with all the security updates in place. This enviroment is a disaster for me, because I now have the whole dev team coming here and on other blogs saying ‘We really love it and would’nt use anything else.’ Its delusional, its not real world. Its damn scary. Add in they are all probably on SP2 now, living on the bleeding edge, while the community of users in the real world is trailing trying to live on SP1, on dial up, in people’s homes, small businesses, where updates are not the priority for people’s general day to day living. The next MS staffer who suggests changing my production enviroment with a beta SP2….. no, I’m not going to get angry. I’m trying to be constructive.. Whatever they do with IE, it should be backward installable back to 2000, I don’t wanna see anymore rubbish about people having to go get SP2 for XP. IE: – is *NOT* standards-compliant, for a good example pls see Mozilla/Firefox, let alone the implemented standards are faulty, many know now the usual "embrace & extend" tactics of MS! – costs me darn too much time as a developer, all those CSS & JavaScript bugfixings for IE (I should sue MS for my time actually) – is slow, even though it’s part of the OS, again see Firefox & Opera – has no up-to-date features, e.g. popups, tabbed browsing, etc. – has caused me much too trouble as an admin. I can’t bear the idea of how MS first integrated a browser in the OS and dumped the development, letting us developers and those users completely lost! Again for this we should sue MS! How in the earth can you love "that" browser?! I’m using Firefox and dictating the users do the same on every machine here. And you know what, even if IE’s new version has all those features above, it’s predestined to lose the 2nd wave of browser-wars. You either rectify it standards-compliant and making a specific OS much less needed thus shoot yourself on the leg, or make it W3C-incompliant and lose the war anyway. Your arrogance and malicious provoking won’t make the browser better, only learning to code and listening to *users* will do, not the marketing-guys! I really don’t care what the new IE will bring, much too ppl learned the importance of standards, and don’t care about who implements it correctly, as long as it’s correct! when are you going to implement "tabbed-browsing" in Iexplore? it’s so much more convenient. I used to love it… but then I got a virus and switched to Phoenix (later Firebird and then Firefox). I’m a developer for a partner of MS and have to use IE at work… where I only recently got a download.ject trojan. Such are the joys of using IE… and that’s before we start on the CSS2 thing, which has wasted several months of my professional career (this is how you make developers HATE a browser!). Balmer did that dance, you know… developers, developers, developers. You should be able to put the pieces together yourself. I now use Firefox, and my website is in standards complaint code, and my home PC still hasn’t had a virus. My work PC uses IE, has had 1 virus and 1 trojan in the last 9 months. I used to love IE… but not any more. Now I love Firefox, even though I remain a developer for MS platforms and software. Be careful Microsoft, you’re losing a lot of developers… and when we lose faith and trust in you you’re onto a bad thing. I love browsing with IE too Scott. Never mind the abuse you get from all the baby geek ‘I can do better’ Bill Gates wannabees. Never mind w3c/css compliance, 80% marketshare is the standard. Never mind security issues, they’re like child diseases, we all get them and in the end it will make us stronger. I can only imagine IE getting better and stronger. I love you Scott. I have yet to find a more sluggish browser. And thats not all, IE seems to have this strange affinity for spyware and adware, beef up the security level and 3/4 of the sites wont work. I used MyIE2 too, but it turned out that it was using some IE component for rendering, however it did have tabbed browsing, that was so much easier for wnidow management. Hello, If you you are ambitiouos to compete with industry strengt browsers such as Firefox and Opera you should come in par with them within several fields such as standards compatibility, CSS, interface – tabbed browsing, you know this stuff. But, one very basic thing that I find rarely mentioned is cross plattform availability. A browser not existent on the Macintosh, the premier platform for content creation just isnt worth to mentioned. Huh, there is an IE on Macintosh? Do you talk about that rotten piece of code called IE 5.2.3? Not maintained since half a century? Not the faintest similarity to its Windwos counterpart? Why should I ever bother to test my pages on this one? Come on, get serious and work together with your inhouse fellows from the Mac Business unit to create something reasonable. IE for Mac was a nice thing back in the late 90ies. The scrapbook feature was ahead of its time by then and it should be kept in a new version. Apart from that there is nothing a could still remember. The same is true for the Linux platform. By the time your new browser will be ready for prime time, this operating system will probably have taken the place, Windows occupies nowadays. So, ignoring this would be a serious fault. Dont even think about using proprietary Windows technologies (or, support Mono!). But then again, I am really asking myself would could be there that would make me switch back to IE once? Advantages that could outrule those issues that will undoubtly be added by your marketing staff in the end, such as Bookmarks that cant be removed, hidden transmission of web searches to MS servers and other annoyances that your companies is a synonym for. Well you will have to work like hell to revive IE to be a no. 1 product in some years when Mozilla will already have taken this place on the majority of computers. I wish you al the best. You will have to code from scratch and it will take several years and I would not rely on Visual Source Safe for code mgmt. during this project if I were in your place ;-). Just my 2 cts. Bye, Christian If IE had no security flaws at all, firefox, opera etc are still the better browsers. Hi, without a doubts. It was long time one of the fastest and stable browser on this planet. But….. we didn’t wonder. It comes from the biggest software company with the lagest money for developing on their own platform… so no wonder!! BUT it’s not good when over 150 People develop that tool and everey week there is a new security whole in it witch caused and can cause hudge costs for companies who have lost data but paid so much monex for MS products!!! I don’t use ist any more… sorry i preper an open dialog about standards and not the way….. we are the ones… we decide what happens!! HEY your IE doesnt support even the PNG format!!!! I better use a small nice tiny fast browser like firefox… no other choice and it’s more than a political opinion! Your attempt to discredit criticism by saying you know there will be some, failed. While most people don’t know why IE is bad, and the firefox fanboys hollar about popup blockers, "extensions", and tabbed browsing. That’s not the real issue, maybe that’s what a lot of users want. And I’m glad you stayed up all year pissing your time away creating frivalous updates that have already been done by third parties. The fact is IE is in such a sad state that people have taken it upon themselves to try and fix your outdated browser. <b></b> IE needs CSS2 support (CSS3 is in the recomendation stage CSS2 is finalized) and full PNG/MNG support this is long over do. I mean I appreciate your proprietary CSS:filters in an effort to combat cross browser compatibility, oh wait no I don’t. It’s just great you guys at Microsoft feel the need to create your own standards to try and lock out further competition. I’m just sorry the stuff you create isn’t that good. The alpha:filter for example only has 100levels of transparency, while a PNG has 256. Boy that was worth it! "I know bob we don’t need to support PNG we’ll just do something to give all graphics that power, we’ll just do it crappily" oh and not to mention that the alpha:filter affects the enter graphic. While a PNG can have parts that are transparent and parts that are 100% opaque. Your stupid filters can’t do that, and even if they could not nearly as well or as flexibly. It would take me 2 or 3 images and lots of code to do something in IE that a browser that supports PNG can do with 1 image. So why doesn’t IE support PNG yet? Is it just stubborn pride or what? What is the point in not supporting the PNG format? I’d better never hear "but we do support it" either. I’ve already demonstrated that you do not, at least not completely. I don’t care about popup blocking and tabbed browsing for IE, it’s been done already with the help of 3rd party addons. The fact is the only reason IE has such a ridiculous user base is that you intergrated it into Windows in an attempt to sidestep monopoly charges. People don’t choose to use IE because they like it. They use IE because it’s already in Window and most people don’t know enough to want to change. Some people think IE is the only thing available they just don’t question it. The things a lot of Firefox fanboys scream about don’t even matter, the real issue is standards not pretty make up. Then you have the firefox fanboys that thing a 4% userbase is enough to start making pages that don’t work in IE by following standards. I know MS left the W3C in march 2003 but IE wasn’t even in danger of being properly updated until then. Since the rumor is we won’t see IE7.0 until longhorn comes out which could be years from now it’s just disheartening to know that I’m going to have to put up with crappy CSS and PNG support. It makes me feel so annoyed in a sense I sort of hope hackers and crackers grind supposed SP2 security fixes into the dust. I really hope underhanded media scare tactics undermines support for the "best browser in the world". Just because I’m a selfish jerk who wants to be able to use CSS2/3 and PNG’s like their meant to be used. I would love IE if I could get those 2 simple wishes. I’m willing to bet if and when alternative browsers take a big enough chunk out of your user base so that web pages are developed to take advantage of new standards people will see how out of date and feeble IE is. I bet if such a situation where to occur all of a sudden we’d see "real" updates to the IE rendering engine. *gasp* But sadly I think that scenario will never happen so MS will be safe to dick around as they please in the blind face of the begging being done by web designers and devlopers. "Look at the innovation! We changed IE’s icon!" Bah, why do I still use IE? … using Mozilla was like coming home after a long long time. I just had to push myself to accept 5% of non-standard sites not loading properly, now I am in browser heaven. I am doing market researches with Mozilla on an old notebook, I have 20 tabs open, everything is under my control in the blink of an eye and …..ah……. no popups without dealing with 3rd party anti-popup bars. And blazing fast. … but after putting 3 billion in the research, IE will be better than Mozilla I guess. One day. I will stick with CERTS recommendation and throw IE in the bin where it belong. Using IE is like walking in a live mine field! — Mozilla rocks ! IE sucks ! I used to agree, but not anymore. Getting coverage on the Inquirer drebin, about disk space, a whole lot of people still have like 6GB big hard disk drives at work. Moreover, my Linux machines haven’t been reinstalled for 2 years on such disks, and they won’t need reinstalling for another 2 years at least. So, your 1GB web browser on my /usr partition would half-fill it while I already have 2 entire desktop environments with web browser<b>s</b>, and I won’t change hardware or reinstall because it still works as well as I need it to. Ah, you’re talking about innovation? One of my browser is mozilla, and it renders XML applications just fine since about 2001, on this very hardware. What’s the minimal recommended hardware for your future equivalent? Have a nice day. If your’e REALLY serious about IE, why dont you start a ‘support forum’ ??? the MSKB is still a very one sided place to search… a cast of thousands is needed… I think this is the main reason other browsers get better…. because the makers listen, and *actually* improve the software… "I really love browsing with IE" You honestly expect people to believe you love using a tool to browse the web? Isn’t the web much more interesting? How can you say this! You honestly expect me to believe that you love clicking the backwards button, stop button, home button, file exit, file print, bookmarks? Where’s the pleasure in that, are you gonna marry IE? As for firefox same thing applies, it’s just a tool. Admittedly it’s better than IE, but it’s just a tool. My god, how can you not love it when it pays your bills. But really, you love something that does not exist on this planet yet, say that you love it after you release it. For now, the IE that everybody has, is the most … how should I say, …. buggy, insecure, crashing, exploitable, time/money eating piece of software in existance on this planet. Given the fact that almost everybody use it, not because you love it, but because they don’t know that something else exists. Anyway, I REALLY hope is as good as you say, because the whole world (the MS World) will be using it in a few years. Good luck., and happy bug hunting. 😉 I suppose you use it only to consult your corporate intranet, microsoft public websites and msn . Full Stop. Because IE as so many issues that it is not usable without incredible amount of securiware ! What avantages ? VBScripts ? unactivated in my company. They even asked us to use Opera or something else. I think I will try Firefox or Mozilla as so many people told me they are fabulous. I knew commercial american tv could have severe impact onto good sense, but corporate integrism is worst… How come every time you update IE our portal crashes? ‘error on page’ For you its the best browser beacause is the only browser you tried. Choice: IE 5 or IE 6? Choice. When M$ gets round to porting it to Linux I will try it out. However if it comes with the millstone of Windows……..well forget it. khorben, You’re talking about two different things. Thing 1: using old software and hardware and being content with it (good for you!) and Thing 2: keeping up with latest hardware and software. You can’t take the worst part of both sides and then complain. You can’t take the small disk space of your old hardware and the high disk space requirements of new hardware.. stick with one or the other. If you are happy with Netscape 3.0 on your Linux box – more power to you!! And if you’re a Linux fluffer, why are you even commenting here unless it’s only to start trouble. I was hoping for something much more productive here. 🙁 You have a nice day too! 🙂 How did you get and keep the position you have when you display such bad judgement? The end is at hand! It matters not which browser you get the news on. I’d like to draw everyone’s attention to nLite. This program will compile a new installation ISO of 2000/XP/2003 with a boat-load of components removed, including Internet Explorer. Use this to remove IE and install Firefox instead. I have absolutely not looked back, EVER, since doing this. And if you really, really need to access Windows Update, you can still do so by opening an ordinary Explorer window and typing into the address bar since, in their wisdom, MS built the IE core into explorer. Trust me on this, once you’ve used Firefox for a few hours you’ll have trouble remembering what the initials I and E even stood for. drebin, what I mean is that my 2 years old PC (800/256), with any average OS, let me run _state of the art_ browsers (eg any Mozilla 1.x), while consuming far less disk space than 1GB, and far less than the browser you love so much. This is what I call being satisfied with both hardware and software. This is what I call writing software consciously. As of all this mail one receives these days, size does matter. And being productive, you’re right. I LOVE MY BROWSER FIREFOX 0.9 IE is very bad, and not support ccs2 Internet Explorer is really great to use in applications. Having the rendering engine to display data – just great. On the other hand for browsing IE is not useful at all. Since I fear, that malicious websites will compromise my system, when I browse with IE, I just don’t use IE for browsing other sites then Intranet. So, if you want technicians like us using IE – make it safe and bulletproof. By the way, I use NT4 as desktop OS and don’t want to change it just for being able to install an IE patch. And if I need to change the OS, I won’t garantee, that the next OS is from Microsoft at all. Our servers are running well already on Linux for quite a while. Mozilla runs well and safe on NT4. Sure… anyone who loves Swiss Cheese will surely love "The Swiss Cheese Browser" (full of security holes) I use Mozilla. I’m not amused with the Microsoft Java Virtual Machine that seems to be designed to break the Java standard. ActiveX is a security disaster as well. I will not log on to ANY web site using IE if security is critical. For example, I will never do any on-line banking using IE. The only reason why people use Internet Explorer is because it’s free. Just try charging money for this piece of crap and see how many people continue to use it. Sorry, I started out with NCSA Mosaic in early 90s, then switched to Netscape, until IE5 came out and left Netscape in its dust. Now firefox (since 0.8) seems to have done the same with IE. What happens after 1.0 ? You guys better get off your butts and really start developing IE again FAST. Just adding some popup stopping code to go with SP2 won’t cut it. You have to match it feature for feature, better yet, match the most popular plugins which make it rediculously configurable too. Do I still use IE ? at home, only for windows update (nothing else). At work for eneterprise web app (which happens to use some activex ) Oh and I even have a plugin on Firefox that lets me right click anywhere on a page and open it in IE just in case it uses activex. Embrace the competition, don’t insult it !!!. Oops, somehow I’m in the wrong entry! Please delete this post and my previous one. I believe that between pointless rants there have been a lot of use comments here. It’s been more than a day since Scott posted his starting comment, and still no response from any Microsoft Official… Is this their way of saying they are not taking webdesigners (I’m one myself and I agree with nearly all points made above) serious? If I still used windows, I wouldn’t object overly to using IE, except the lack of direct alpha channel support with PNGs erks me. Why is IE the only browser in the world that knows what a PNG is that can’t do this? Since the court case with Netscape has been settled, the anti-trust case is over, most state lawsuits are over, and Microsoft is being sued by people like Eolas for broswer technology how about a change for IE 7. Make the broswer more of a stand alone. It doesnt need to be integrated into the OS as it was for antitrust purposes. Unwielding it from the OS will allow you to: 1. more easily protect the OS revenue from Eolas type patent suit. 2. have more clearly defined interfaces for your use between the broswer and the OS which will make security fixes, architectural changes, and broswer inovation easier, quicker, and more transparent. 3. inovate new corporate products (anitvirus, software firewall) that sit between the Broswer and the OS >Some of us have our individual blogs today, but we also wanted >to have one that was focused on what we do every day at work How much does Bill pay folk to talk BS then? ;o) As long as IE holds the majority audience, I will continue to use it as the primary development target. I may not like it sometimes, but that’s life. Besides which, I’ve seen some awesome front-end development using IE as the client. So great things are possible with IE. The "community" here leads me to believe greater things are possible with "standards-compliant" browsers. Why? If I exploit the functionality of a majority platform to its full extent, delivering applications that target the customers needs, and that they are pleased with, then my job is done. IE is a browser only a mother could love. I love li’l Internet I love li’l Internet Mozilla firefox is best browser Sorry, did you mean: "Mozilla Firefox is the best browser." Look, no one *chooses* IE. The only reason for the current marketshare is undereducated, lazy inertia. In my experience, few users know what the word "browser" means. Its good that web browsing has become ubiquitous, but it’s bad that people don’t even realize they have a choice. This is likely by design, and certainly what MS means when speaking of IE as "part" of the OS. Don’t believe me? Do a study: prompt the user for a browser choice when initializing their profile. Be sure to randomly sort the options to avoid order bias. I can already tell you what the results will be: most users will pick the first item in the list, some feel strongly against MS, some feel strongly pro-MS, and a few are excited by alternatives. I can absolutely guarantee that IE would not garner 96% of the selections. What features makes IE an attractive choice? Backward compatibilty is probably the most motivating factor; IE is still living in 1997. ActiveX can do some neat things (I love the Date and Time Picker and Month View controls, though the WHAT WG may soon obviate the need for proprietary date/time entry), but the cost is too high: adware and other malware. ActiveX is a buit-in back door, and doesn’t offer any more than Java applets (except speed, perhaps). What else is there about IE? Joonas – you said: ?" Formatting: That, once again, is Microsoft’s fault. Microsoft’s web-development tools comply with IE’s non-standard ways of doing things, not WC3 standards. So websites developed with those tools will only format properly in a browser that is compliant to IE’s non-standard. A standards-compliant browser will format the broken html according to the WC3 standards, and since the html is broken, so is the formatting. I challenge you: post a link that doesn’t format properly in Firefox, but does in IE. I will show you exactly what’s wrong with the HTML on the linked page. brianiac, *like the site btw* …but, I have to disagree slightly. The single most pervasive reason for a development team to choose IE is that it’s built (right or wrong) into the operating system of approx 87% (maybe lower) of client computers. Thus you can ensure a wide installed base. You cannot WIN using Micro$oft products, but you are certain to Lose. Poor quality software, poor service, terrible license – and horrible security… Micro$oft LOSEDOZE operating system – where’s it going to blow today? Well, if it was necessary to work long days and weekends, something is seriously wrong. That makes me very suspicious regarding the bugs that are still to come to light… I suggest reading Steve Maguire’s book "Writing Solid Code" and "Debugging the Development Process", where he recounts his experiences at turning around the Excel group (with a big part focusing on getting them down from their 80-hour weeks…)? With that said, IE is not perfect, there are bugs and security flaws, and rendering problems to some extent, CSS support is lacking badly (not that competion doesn’t have bugs). My main problem with microsoft’s position on the browser is that they have publicly stated they stopped full on production and only plan to incorportate new versions into service packs and OS releases. I hope MS gets some sense and figures out that just because your on top now doesn’t mean that you will always be there, and non IE competions market share will start growing like it has over the last half a year. Eventually MS will find itself in a position where its no longer the leader, and people do not design websites for its browser, making it a difficult fight back. Most controversial first post ever? What I see in your postings is that you say, 80% of the target group is sufficient for your work, don’t care about the rest. What the "community" says is that if you stick with the standards, 100% of users will be satisfied, and it wouldn’t matter whatever is his browser’s name! But then, that’s exactly what Microsoft would wanna avoid, isn’t it, because it would make people OS-_in_dependent, right? Sorry, we see you through! And you’ve already lost the 2nd browser wars, only you haven’t realized it yet! > I don’t see how all you "web developers" design your sites for/with foxfire. I mean if you were working for serious web companies you would clearly look at the statistics, and see i.e. still has 94% of the market share 6% is a lot of people, even if the 94% was accurate (browser use varies with a number of factors, such as the target audience for a website). We don’t design sites _for_ Firefox. We develop sites for HTML and CSS user-agents. Firefox is the most compliant, so it is the most useful to use as a reference rendering when developing. Targetting the HTML and CSS specifications rather than any individual browser means that even if we can’t test in a particular browser with particular settings on a particular platform, we still have a reasonable expectation that it will work in them. I don’t think many people are saying that they don’t support Internet Explorer, only that they are frustrated in producing workarounds to try and prop it up to the HTML + CSS baseline the other browsers manage with relative ease. Firefoxen. Hey, it may be a little buggy, but it’s not v1.0 yet, and it doesn’t invite adware and malware onto the user’s PC either. Ummmm Whys I.E known as Internet Exploder If Its So Good, I Think it rubish, and every one should use Mozilla <a href="">DownLoad Mozilla</a> Now Mozilla, Opera, Firefox. IE is off the list. Get a version 7 out that supports all OS. Also, why on some OSes does IE use the explorer.exe thread and put pages in there so if IE crashes so does the shell. Add support for popup blocking and stop allowing Home Search and other horrific spyware and trojans to enter through IE, I have to use SpyBot, Ad-Aware and HiJackThis (and HSRemove) on client’s machines all the time to clean up after BRAIN DEAD thinking – allowing the arbitrary installation of lethal code. Also, release a Unix version again. What’s wrong with IE on Solaris and OS X? You know what this blog comment is? A Flame-baiting troll, you can’t seriously suggest IE is any good – not being updated, security flaws, not supported on tons of OS, susceptible to spyware, trojans and lame infections. Cure: Get a version 7, support Solaris, OS X, OS 9, all Windows, stop using explorer.exe and make sure the parent for browsing is IEXPLORE.EXE or whatever, and add a popup blocker and add STERN warnings when people insert "functionality" and prevent people from putting newdotnet and other trash in the LSP. Otherwise myself and all the other systems administrators REQUIRE the use of Mozilla/Firefox, just so you know. People who use this get 99.9% less infections, spyware and trojans and it has a popup blocker. Tah tah, Bill’s brainwashed whipping boy. Glad to see that working at MSFT bends space and time in a way where a human can actually believe what you just said. <–Mozilla Firefox, but there are certain sites in which I couldn’t see without the use of Internet Explorer… Well this was an easy way for a test manager to get a comprehensive list of bugs to see if any important ones haven’t yet been squished by the current version of XP SP2. Are you nutz or have you never tried another browser? Do you still live in the 90s? My experience with Internet Exploiter on fully updated, patched,fixedWinXp (yesterday!) after 1 day of sufing with IE we found 28 (!!!) security threats (spyware, malware, virii) After 1 week surfing with mozilla Firebird we had NONE! Even if you don’t consider the fact that firebird is atleast 1,5 times faster than IE, blocks all popus and commercials, comes with tabbed browsing and renders webpages much nicer JUST from a SECURITY perspective DON’T USE IE! i hate IE and i only keep it fore easy updating of my Tamagotschi like O.S. that needs daily care… LINUX here i come! Scott Stearns Test Manager, IE You are without a doubt the worlds greatest liar! I hope some consumerorganisation will sue you for deliberately MISINFORMING the General Internet Public! Shame on you hypocrite! I just wish Microsoft would support web standards for the good of the internet community as a whole, so that creativity and innovation is maintained. When web developers focus only on a proprietary browser ingenuity becomes stiffled. I hate to see that happening. Kasey As a user I haven’t used IE in about 2 years and have managed to switch my entire company over to Firefox (about 200 employees) after my boss realized he was fighting an up hill battle when it came to spyware. Since the switch we no longer have any problems with spyware and have even been able to extend the use of the T1 we installed the Adblock extension since now banner adds and popups aren’t just hidden there URLs aren’t even resolved saving tons of bandwidth. And since the realease of 0.9 I have yet to find a website that dose not display properly even those using the proprietary FrontPage extensions. But that aside the fact is Firefox is 1. Faster (blindingly so) 2. Smaller 3. More feature rich 4. Standers compliment 5. More secure they have only had one security issue and that was more of a problem with windows then the browser For IE to catch up it would need to be rebuilt from the ground up there are just too many problems. ActiveX is to big of a security hole and everything it dose can be reproduce by other means. The compliance with standers is a joke. The plugin system is a joke compared to the extension system Firefox uses. And that’s just the tip of the iceberg. Though not a programmer I have a fealing that some of the Issues are imposable to fix simply because there too deep in the Browser/OS I would use IE if it didn’t crash machines so GOD damn much. I start using Firefox because my main machine crashed anytime I opened IE. So I installed firefox and No problems since then. I have now Converted at least 10 people to use firefox and they love it. Simple Updates tons of cool features. FireFox plugin capabilities are just plain sweet. Heck I can block 99% of popups and even individual Banner ads. All my frequently vistied websites are BANNER FREE. On thing that pisses my off the most is the fact that IE has NO option To allways Mis-trust or Dis-Trust certain Certificates. How hard would it be to put a option in the Certificate pop up to always Dis-Trust this website, you have Always trust this website. Because of the lack of this feature your constantly BOMBed with DO you trust this website Certificate crap. And most people "noobs" just click yes. Then the problems start. The Spyware the Adware/Malware/Crapware and a whole crap load of stuff that come with those idiotic certificates are mind bogling. Because IE is tied into the OS the computer becomes SO slow you want to stick a red hot needle in your eye. I love Microsoft and I think you should bring out more shity software so I can charge more for fixing problems on peoples computers. Microsoft is a Goldmine because of this lack good software design. Hell I should easily break 60 K this year and that because my friends at microsoft keep releasing garbage software. THUS I love IE because it makes me money. Hey Bill G, I know a great way for you to make even more money! Let scott and these other "developers" go free! it will save you a lot of money and it will save your customers a lot of money. MS seems to be incapable of developing" a half-way decent browser. give it up man and cut your losses. Can some of you Firefox advocates please give me just a few examples of websites that look "perfect" in Firefox but crappy in IE? After reading through some of the comments I was actually excited to go download Firefox and take a look. I thought "oh good, maybe they fixed some of the issues that I dealt with in the past." (I won’t go into the fact that the installation crashed my system even though I have 3.2 ghz and 2 gigs of ram.) The first three sites I visited had dispaly issues that looked and worked great in IE but did not perform equally as well in Firefox. I’ve been a web developer / systems analyst for years and my experience has been the opposite of many of those posted on this forum. I would write HTML and put together a page the best way I knew how and open it in IE and it looked great. Then I would cross check in in Netscape and sure enough even the simple things that should work fine were broken. Trying to fix Netscape issues that worked seemlessly in IE consumed the majority of my troubleshooting time. I’m serious about the examples. I would really like to see the light here. So far I’m not impressed. 99% of all the websites I visit look great in firefox. Except for ASP embeded ones like Microshaft Winblows Crapdate. You want honest feedback? Please read, understand, and learn from this: 1. I don’t like feeling insecure while surfing the web. IE has PROVEN itself to be nothing less than insecure. We all know this. I am sorry, but your "security focus" is really quite ineffective. I should not have to cite evidence, we all know the issues. 2. I don’t like unrequested popups and flashy ads interferring with my web experience. IE provides NO way to mitigate that. And please don’t give me the "you can install a third party app" response. Its weak and misses the point. 3. I don’t like the fact that IE is entangled with the OS to the point of extending its native vulnerabilities to my OS, thereby placing my personal files and the security of my PC at risk. These are my big 3. These reasons are the only reasons I switched to Phoenix and have stayed with it up to Firefox 0.9.2. (and BTW, Thunderbird for email – which rocks). I am not a programmer or developer. I am a home user. After CERT put out is recommendation about IE I sent a group memo to our department urging everyong to switch browsers, and I provided them with links to Mozilla, Firefox, and Opera. Most have switched already. I also conviced my father in law, my mother, and my sister to switch. I continue to recommend these alternatives whenever I have a chance and while not everyone I talk to switches, most do. And they like what they see. I don’t think you will really take my words to heart because I know you are ultimately bound by the chains of the corporate heirarchy which are naturally resistant to criticism. I imagine you will place my comment in the "just another Firefox zealot" column. And you know what? That’s ok, because what I have said is given freely for you to do with as you choose. My desire is to use a reliable, standards compliant, cutting edge tool to interact with the Internet. I have found that tool and it is not IE, so I really don’t think about IE or its features anymore. They are irrelevant to me now. And for what its worth, I have Suse 9.1 on my laptop and XP on my PC. Its great to be able to use the same browser on both platforms(!). Where’s tabbed browsing? Where’s popup blocking? Why are there so many exploits? Where are the skins/themes? Where are mouse gestures? Why do you think IE is more fun to browse the web with than Opera or Mozilla? How can you say that when it’s soooo much easier and more efficient to manage many different pages with tabbed browsing? Why does it take you guys so long to get the really useful features that power users love that the other browsers have had like forever? You have half the money in the world and all the resources you need, yet you’re being beaten by these other two small browsers. Observant outsiders can only conclude then that this is just a classic case of monopoly economics at work – you won the monopoly, then you stop innovating. Prove us wrong. PS – WE WANT 100% STANDARDS COMPLIANCE!!! > Can some of you Firefox advocates please give me just a few examples of websites that look "perfect" in Firefox but crappy in IE? I don’t surf in Internet Explorer, so I couldn’t say. What I can say, however, is that most of the websites I construct look fine in Mozilla, Safari, Opera, etc, and _would_ look like a hideous mess in Internet Explorer, _if_ I wasn’t forced to work around all its bugs due to its overwhelming market share. When you talk about your own experiences, you are using the past tense. It sounds very much like you arereferring to Netscape 4 era. Is that so? There’s practically no similarities between Mozilla and Netscape 4. As I said elsewhere, Internet Explorer is the new Netscape 4 – remember all the frustration you felt at trying to get Netscape 4 to cope with your markup, and then simply substitute "Internet Explorer" for "Netscape 4". Then you’ll have some idea of what we feel. I always find it interesting that people involve so much emotion when discussing software. I tend to approach these things very pragmatically. Software is about solving technical problems. There are plenty of non Microsoft products that I use that I think are great. Conversly there are some Microsoft products that I use that are very mediocre at best. Since I just downloaded Firefox an hour ago I cannot give you detailed analysis of the product. I can restate the fact that the first few websites I visited had some of the same display issues that I witnessed a couple of years ago when dealing with Netscape. I am seeing a vast improvement over Netscape 4 though so keep up the good work. I am simply challenging these allegations that there are websites that look like a "hideous mess" in IE but look great in Firefox. Please just give me one example. Mr Whatever, I should have mentioned: I was replying to the implication I’ve seen coming out of Redmond that IE is the leader because the marketplace has determined it to be better. My point is that IE is only where it is because it was bundled with Windows, and everything stems from that. If IE and Firefox were released today in their current forms, and had a level playing field (no illegal bundling), Firefox would mop the floor with IE. MS did exactly what so many were afraid of: they won the war, then abandoned the browser. When I show Firefox to people, it’s like they are stepping out into the sunlight. They smile, they say "that’s cool" when I show them tabbed browsing, the AdBlock extension, mouse gestures, and themes. They like that this is a product built for the love of the technology, by skilled browser artisans and hobbiests, that anyone can contribute themes, extensions, or to the browser itself, and that the bug database is open for all to see and contribute to, and vote on. I show them examples of what the Internet could be, like alternate stylesheets, transparent PNGs, smarter forms that understand relevance, and perform better validation, faster, more flexible pages that are ready for technologies outside of current expectations, and they are irritated about the foot-dragging. It shouldn’t be an either-or choice for developers. Doing it right, once, could mean that it works everywhere, including with future technologies. If you write to IE, your code comes with an expiration date. Any change (a change in browser audience, an upgrade or security patch, different screen resolution, low color depth, new device, printing, …) upsets the specific set of circumstances that you have written for. Developers are justifiably mad that this potential is being tantalizingly dangled before them, but is unavailable, not because IE accels in other areas, but because nobody even knows they have a choice. Byron – the underlying point that is being made is that if all browsers support the same standards then we won’t see (very many) differences in the rendering output, and web developers will have an easier time developing. Is that point being heard? (serious question) IE SUCKS. OPERA RULES! WHY? Install it and u will saee. There are SsOOOO many features in Opera that it will take 150 mil. years for the IE developers to get in IE. Good luck! Firefox is great. It’s still got a few bugs to be worked out, but I would choose it over IE anyday of the week. I just dont trust IE. I dont like to surf the web and wonder what hijaker. Adware, Apyware I may have gotten from IE. I fill safe useing Firefox. I Fill safe knowing I have a Team of people working on improving a product because thay want the best browser, Not because that are getting a paycheck. I too have converted the whole company to Firefox (150+ people). I’m not a Microsoft hater. I have XPpro and a hacked 98se based kernal on my home computers. I do also run Mandrake on my 3rd computer. Firefox may need some work, but IE has lots more. It would take alot to get me to come back to IE. Regards -Chris "the underlying point that is being made is that if all browsers support the same standards then we won’t see (very many) differences in the rendering output, and web developers will have an easier time developing. Is that point being heard? (serious question)" Yes I hear you. And I am simply iterating that point by telling you that my frustration has been that my stuff tends to work great in IE and then I have to go back and tweak it for all of these other browsers. Like I said, I am seeing vast improvements in Firefox over what I have seen from the Mozilla/Netscape camp in the past but I hardly think that they have far surpassed IE in the fashion that is being alluded to on this forum. That said, I do think there are some extremely valid suggestions and criticisms of the product that have been expressed. So my post is in no way meant to invalidate the constructive thinking of smart people. I am simply challenging this claim that IE is a vastly inferior product. I’m still waiting for some tangible examples of sites that look great in Firefox and terrible in IE. Please send the URL’s. Maybe IE is a good browser in Iraq or Afganistan, but in the real is a old browser, unsecure, and with a lot of bugs. Firefox is the best option is we are talking about browsers. You have to learn first to code a html document before to talk about this topics. This page is not Valid HTML 4.0 Transitional! A good browser always respect the standards, this is not the case. I think Scott opened up a can of worms with this one… You’ll need somebody else to beam you up out of this one, Scotty! > And I am simply iterating that point by telling you that my frustration has been that my stuff tends to work great in IE and then I have to go back and tweak it for all of these other browsers. What kind of things do you have trouble with? > I am simply challenging this claim that IE is a vastly inferior product. I’m still waiting for some tangible examples of sites that look great in Firefox and terrible in IE. Please send the URL’s. Like I said, people work around Internet Explorer’s shortcomings – you aren’t going to find many websites where the authors have allowed Internet Explorer to screw things up. It *is* a vastly inferior product. Refer to my list near the top of this page. Is it possible you are in Drebin’s position – that the only code you are aware of is the stuff that works in Internet Explorer? That is a very skewed starting point if you want to measure the browsers objectively. Perhaps "your stuff" works great in Internet Explorer, but normal code that works across a range of other browsers often fails completely in Internet Explorer. Byron, >Yes I hear you. And I am simply iterating that point by telling you that my frustration has been that my stuff tends to work great in IE and then I have to go back and tweak it for all of these other browsers. Your frustration stems from the fact that you are developing backwards! Look, if you want to code for maximum compatibility, starting from IE is not a good choice. Start from Firefox, then add the workarounds for IE’s shortcomings (IE’s broken box model, no support for CSS 2 selectors, incorrect percentage calculations, bad positioning and z-order, etc.). Familiarize yourself with the standards; your mouth will water at the potential. Funny how when you search google for "web browser" IE doesn’t show up until page two. We all know how Google works ^_^. And since I messed it upthe first time with bold tags… one of the better examples of people trying to fix IE from sucking so much. Just wanted to add my comment to the overflow of opinions here. Some very interesting reading here. I mean, I knew IE was bad, but I didn’t quite realize it was this bad. The comparison with the NN4/IE situation a few years back is kind of relevant, only we didn’t know how bad IE was when we took it on… So, I truly hope the world wakes up and realizes there are so much better things out there, available for free. It’s happening as we speak (see the june google zeitgeist), the question is only how far this developement gets before MS’s actions result in an increasing IE browser share again… I guess a situation like the one of Google vs Yahoo & Altavista search engines is possible. Google rose from nothing but good ideas and speedy innovation, and is now the nr 1 site in the world for information. (Looks like they’re going to have a go at crushing poor msn/hotmail with their gmail too… :-)) Mozilla will, by the looks of things, stay ahead of MS, and continue (with increased pace?) to innovate in the browser market. Hopefully, this will make people stay with mozilla even when MS does include a pop-up blocker in IE. OK, Byron – you want sites? Well here’s one: (And I made it that way, cos I wanted it to look that way – i.e. the way it looks in standard compliant browsers – not to be a pain.) I recently discovered through The Inquirer that the IE development team has started a new IE Blog. Is this some… IE Sucks I don’t like FireFox, but I cannot afford to use IE anymore, as much as I think it supports so many more features. Here’s priority #1 with IE Next Generation: – Don’t put the kitchen sink it. We don’t need XML data islands, ADODB support, ActiveX controls, VRML, etc, etc, etc. Give me XHTML 1.0, limited Javascript, CSS2 that just rocks the world and its ridiculous fast (i.e. not written in Java) and I’ll be happy. Make it extensible and let the community add things like tabbed browsing, pop-up blockers, gesture-input, etc. Off topic but… Chad, Java’s not so slow anymore… IE is a SON ABOUT BITCH, suck suck suck every version of IE is a piece of SHIET viva mexicoooooooooooooooooooooo viva OPERA / MOZILLA you are smart people, do you are¿? in that case use another browser stupid moron lover of BILL GATES M$ is a great congregation of MONKEYS and not any MONKEY the are STUPID MONKEYS pinche putos de mierda jajajajaja los que aman windows XPorqueria con Microsft Orifice y Internet Exploter y saber que ya me canse por eso chingas a tu puta madre Good rebuttal. As an aside, I do have one gripe about Internet Explorer that I’m not sure if anyone has covered here, but here it is: PRINTING! I mean, I have some appreciation for how difficult this can be given that sites aren’t designed for print (although the media css attrib comes in useful here), but Firefox does a much better job at reproportioning content to fit the printed page. I’ve never had any problems with developing for IE. I’ve done and seen done some cool things using the age old combination of DHTML and server side processing. I know there are some great (actually: wonderful) advances in Firefox’s rendering engine (mostly becuase it’s standards compliant I guess, and because the development team are pushing the browser all the time) that would give me even more to play with but maybe it’s the numbers game… or maybe it’s because most of my clients use IE and have invested too much in applications for the browser… or maybe it’s for other reasons. Whatever. Firefox (and let’s not forget Opera, Opera was doing some of the new stuff like gestures first, wasn’t it?) are better products, and it’s my hope that the IE team take a good look at their competition and try and compete. But maybe they shouldn’t be doing it to regain market share and kill off competitors. Their competitors don’t deserve it; tech wise they’re ahead. Maybe they should be doing it because it needs to done, because it gives them a chance to prove they can innovate, and, because halting IE development was a bad thing for a significant number of people. Good enough should be better. When I can submit the URL to W3C’s html validator (current score: 168 errors!) and not have it barf, THEN I’ll take Microsoft seriously. Until then, no matter what the spin, they’re still trying to "embrace, extend, and extinguish" the very standards that comprise the internet. No thanks. The best thing M$ could possibly do with Interfect Explodus is bury it. Not only is it a pisspoor browser in the current climate of <a href=> free open source browsers</a>, it’s a liability and a huge security risk. Fixing pop-ups with a blocker in SP2 is not sufficient. If you take yourselves and security seriously, ActiveX has to go. As does the tie-in with Windows Update. <b>Reduce the attack profile, kill Internet Explorer. </b> Let’s face it, you’ve already lost the argument and the hearts and minds of anyone that knows enough about computers to care about their browsing experience and their online security. The bottom line is, you engineered a virtual browser monoply by bundling IE with Windows, and then you sat back, fat, dumb and happy that the browser market share had been won. <b> For 2 years. </b> If you said Goodbye to IE development 2 years ago, why not go the distance and say goodbye to IE forever? And do everyone a favour at the same time.. get a clue, the only reason that people use IE is because they are used to it and is "integrated" into windows. that does not make it a better browser then say mozzila or firefox ie is full of many many many bugs and has not been developed on for 3 years IE was a great tool when I first saw a computer, but now when I know that it has so many bugs and is a huge security problem for my system, I chose not to use it. If I could I would completly uninstall it, but I can’t, I still need it for WinUpdate and a few dumb banks that do not know that is a security risk for their customers to force them use IE. Anyway, when it crashes takes the whole system with it, unlike the other browsers that IF they crash, they can be easily restarted . I really don’t hope for new features in the new IE, only hope it will not have so many security bugs. Also I am really curious about the next generation of PopUps, given the fact that their favourite platform will kill them now. As an IE developer, I think your statements regarding the browser are made out of pure ignorance for how things really are out in the wild. I don’t mean that as an insult, just an observation that you likely use IE within very controlled situations where IE’s many faults and shortcomings do not affect you. Ignoring the lack of standards compliance, the ever-growing torrent of security patches, the lack of tabbed browsing, the lack of a built-in effective and flexible pop-up blockers, the rarity of usable extensions, the lack of spam filtering capability in the bunclled mail client, the lack of themes, the lack of ability to block images from specific servers without a tedious and time-consuming workaround, and the other shortcomings of IE in terms of functionality, I think it’s biggest, most immediate, and most threatening problem right now is its inherent insecurity. Let’s face it – the ‘zones’ model is inherently insecure, and ActiveX is hopelessly insecure. Now, as a developer, I understand that most, if not all of your browsing is done on the latest IE build available. The advantage (for you) of this is that your browser is not being bogged down by the spyware, adware, and other advertising bots and trojans that have riddled the computers of the average user for years now. Most recently, things have progressed to the point where the sophistication and aggressiveness of spyware applications like CWS (CoolWebSearch) make them often impossible (I’m not kidding, you have to reload the OS) to remove. The one thing that virtually all of these types of advertising programs have in common is that they take advantage of the inherent insecurity of the Internet Explorer web browser. Much of this is caused by the heavy integration of that browser into the Windows operating system. Thus, a problem in the MS Java machine becomes a problem with the browser, thanks to some clever software which uses the Java machine vulnerability to install itself into the web browser. Using Mozilla, as I have for the past couple of years, I’ve yet to experience having my homepage hijacked, having my search page changed to an obscure offshore search engine, having all my web traffic re-routed through some unknown company’s servers, having my personal information sent to a company without my consent, incessant pop-ups that slow even the fastest machines to a crawl, crashes due to corrupted files when some spyware program decides to start replacing dlls with its own (corrupted copies) thanks to IE’s willingness to give anyone and anything complete access to the computer system, or any of the other problems general users of IE encounter. Your "best" browser allows for the general user’s computer to be hijacked and corrupted in so many ways, that even paid programs/services like Pest Patrol and Spy Sweeper find themselves unable to keep up. The developer of CWShredder, a program specifically created to remove numerous varients of the CWS spyware/trojan application, gave up trying to keep up at the end of June. Meanwhile, the question you should be asking yourself is: where does this leave my users? The answer to the question is: in line at the repair shop, waiting to have their computers repaired at an out-of-pocket expense. When they ask the folks working at the repair shops why they’re having to spend this money (on a 1-year old super fast machine that can barely boot up anymore), just what is it you think they’re being told? When spyware has infected the computer to the point that it’s been brought to a halt, and when all attempts at cleaning the infection fail because the creators of the spyware applications find ways to infect the system faster than anti-spyware application developers can find out how to remove the spyware applications, just who do you think it will be who gets blamed? What I can tell you is that I’ve yet to see, among friends, family, and co-workers, a single computer brought to its knees by spyware where the primary web browser is something other than Internet Explorer. Now, I understand that much of this stuff requires user actions to work, but a lot of it doesn’t (so long as you’re using IE). Gator got in trouble a while back for its ‘drive-by’ installations, which didn’t require the user to do anything other than point IE at the wrong website. No user of Mozilla, Opera, or any other alternative to IE ran into this problem – and this was an application that sent personal information over the web. If users understood more about technology, their computers, and the internet, you guys would have seen just how well the EULA holds up in court numerous times by now. In the end, you can certainly disregard the opinions of everyone who’s said something negative about IE, but you should also remember that the average users – your bread and butter – are running away from IE as spyware brings their brand new systems down to a crawl. These folks are having to spend money hand over fist because the web browser *they* like is letting them down in the security department. It’s letting spyware and trojans flow into their system, and things are getting to the point where users have no choice but to seek an alternative in order to protect themselves. That spells a huge decline in marketshare in a very short period of time. Forget the new features – strip out ActiveX and start protecting people from spyware or lose the web browser war forever. Those are your options at this point. I honestly could not have said it better, thank you Loki_1929! Loki_1929 RIGHT ON BRO. Well said. I concure wholeheartedly. Hello Byron, > And I am simply iterating that point by telling you that > my frustration has been that my stuff tends to work > great in IE and then I have to go back and tweak it for > all of these other browsers. Is your code valid HTML/CSS? Do you use proprietary MS JScript or standard compliance JavaScript? If your sites validate without any errors and you still see problems with Mozilla/Firefox, that don’t appear in IE, then this is probably a Mozilla issue, but I bet that you just made the errors. Tell me some URLs of the sites you are talking about. > Like I said, I am seeing vast improvements in Firefox And have not seen any improvement in IE for almost four years now. > I’m still waiting for some tangible examples of sites > that look great in Firefox and terrible in IE. Please send > the URL’s. As someone else said, a lot of people design websites, that are 100% standard compliance and look great in Mozilla, Safari or Opera and then they test them with IE and almost everything is broken. Then they spend a lot of time to fix this IE issues and remove features, that IE doesn’t support – so you will not find many sites, that looks bad in IE, but they are doing it only because of IE’s market share. Ok, let’s give you some URLs. I have not tested them in IE, but I bet they will not be displayed correct. Try these sites with IE and Mozilla/Mozilla Firefox and see the differences: (use the menu in the upper right corner) (browse the different designs on the right menu) Just think of the many things IE does not support, like PNG alpha transparency, XHTML 1.1 (IE does not support the correct MIME type application/xhtml+xml), CSS issues (:hover for every element, position:fixed, box model bug, CSS2) and many many more. And please do not forget to show us the URLs of sites, that doesn’t work properly in Mozilla. –Thomas Live-at-Blog » Yo amo… Thanks to you, over 90% of PCs over the world sontain spyware. I worked at a networking/computer service job at my university campus last fall & spring basically spending 4 hours a day fixing problematic internet connections for dormitory students. 95% of the cases were networks down due to IE’s insecurity of adware. Everyday I’d basically do the same thing: get on the PC, clear IEs cache, configure MSCONFIG and get rid of crap startup items, download/install/update/run Norton Antivirus, run LavasoftUSA Ad-aware, remove any adware programs from Control Panel -> Add/Remove programs, enabled their Xp firewall (how I wish this was on by default), and then recommend the students to Mozilla Firefox. Most of the time I made something up of how installing Mozilla Firefox was the last step I had to take to getting their internet fixed, even though IE would have sufficed, simply because I know college students visit spamfiled dirty sites and that IE would only consume all the material and fill their computer up with utmost amounts of garbage. Anyhow, fun job! 😉 Heh, gotta make money somehow. I did enjoy helping people and curing (although it’s more like temporary relieving) their ignorance on how to fix their computers. I wish Microsoft could reach out to its customers more effectively and make known the procedures needed to secure their computer from viruses and spamware. 99% of the 100 or so people I worked on this last year don’t even know what WindowsUpdate is! So much ignorance even in the college students. It’s a sad world. As a web developer, just as another guy said–perhaps in this thread, I always recommend people to Firefox. Not sure for security or standards compliance, but features and web development tools. IE lacks much. ?" There are two words that sum up ALL the advantages of coding to a known standard (what you call desgining ‘sites for/with’ Firefox): QUALITY CONTROL! If you code to a standard, and you can test with a tool that *correctly renders that standard* (guess which browser I am NOT referring to…), you can then systematically identify and (if necessary) correct the rendering bugs of other browsers (such as IE). Starting with the standards-compliant code and tools for testing said code guarantees that you can isloate rendering bugs, but coding ‘tag soup’ style as for ‘quirks-mode’ IE *provides NO guarantee that you will not encounter the same rendering bugs.* The difference, the CRUCIAL difference is that in ‘quirks-mode’, you may have no reliable cue a) to what caused the problem in the first place, and b) no way to tell that your fix for the first bug will not be responsible (possibly together with some other factor) for the occurence of a later bug… QUALITY CONTROL! Every other productive industry in the world uses measurable standards for QC, and almost every other industry on Earth produces more consistently high-quality products than the web-development community does. This problem did not start with Microsoft alone, but Microsoft is more massively implicated in the continuance of the problem than any other single entity or combination of entities. -BHC I Fear This Browser! (and people named "Test Manager") – Why don’t you fix 1 year old security holes? – Why do you ignore web standards to make the IE W3C compliant? – Why do you get money from MS for this lousy work? (btw, whatever do you do?) Thanks to Loki_1929 and his posting: Better us a browser like Firefox or Opera! Small, fast and much secure! I fully agree with Loki_1929. IE is only usable when it is locked down like the default in ws2k3 ——- with activex + active script + java script disabled. If left those "features" enabled you can expect IE to be hijacked in 2 days and you machine boat loaded with torjans. Without javascript IMO the browser is’nt really usable. Having a Internet facing program bundle deep into the gut of the OS is the exact cause of it. Have it your way if you still thinks IE is the best browser here. Just wanted to comment on all the "IE is insecure" comments. yes, its true, BUT IE is also the prime target, seeing as it is the 90+% browser. If and when Mozilla reaches those numbers, the focus will move to finding exploits in that browser. And exploits will be found. Even if browsers get locked down, the problem will move elsewhere – to sofwtare installers, etc etc. Hello Damien, > BUT IE is also the prime target, seeing as it is the > 90+% browser. Yes, monoculture is always bad. > If and when Mozilla reaches those numbers, the focus > will move to finding exploits in that browser. And > exploits will be found. There are a lot of people *now* and *in the past* who tried to find security flaws in Mozilla. Although it is much easier to find this vulnerabilities in Mozilla, because the source code is available to the public, the number is really small according to the number of security related bugs in the Internet Explorer. But the big difference is, how Mozilla and Microsoft react to security holes: Mozilla normally fixes the bug in a very short time, when Microsoft needs weeks and month to fix the problem. There are a lot of unpatched security holes now, with exploits available, that are known for month. Another factor is, that Mozilla is not that deeply integrated into the operating system, does not support unsecure technologies like ActiveX at all, and was always developed with security in mind. –Thomas ME LOVE SPYWARE. ME LOVE WINSOCK FIXES. ME LOVE IE. Loki_1929 Quote: That spells a huge decline in marketshare in a very short period of time. Forget the new features – strip out ActiveX and start protecting people from spyware or lose the web browser war forever. Those are your options at this point. /Quote That is what I find so worrying about Microsoft’s approach. They now only make a move, because they rapidly are loossing market share. All the security problems, the lack of supporting standards, the user unfriendly features, nothing has move Microsoft to do anything, they even halted operations on its development. Now they open up, pretend to really want to make an effort, but for how long? Until they regained their position in the market and then the starting to give a toss again! Scott, this isn’t about improving IE. This isn’t about complying with standards, about security and all this stuff. This is purely about shareholder value. Thus, I quote myself. Quote: # re: We’ve been Scoblized Dear Scott and IEBlog team, My major problem I am having with IE is the attitude it stands for. You see, there was that innovative company Netscape making the web accessible. Then Microsoft moved in took over the market (which is fine with me, as you guys really made an effort). Having a nice market share of 90% and all of a sudden you stopped devoting resources. I mean it is not just happened yesterday that people started complaining about the lacking features expected of a modern browser (download manager, pop-up blocker, tabbed browsing, skin support, etc). Most of all having such a huge market share, you failed to recognise the responsibility you are having on making sure that this thing is well-secure. You, to me, showed a high level of dissappointing ignorance towards these problems. Now I see, that you are realising the threat from other browsers in terms of market share and all of a sudden Microsoft feels the need to do something about it. I think this is totally two-faced and morally wrong. You dissappointed me once and I won’t let that allow to happen again. Instead, I support those people who are committed to create the best browsing experience for me – not because of market share, but because that’s what they love to do. No matter what you are going to implement, you will always continue to play this kind of game I utterly do not appreciate. Therefore, I cannot and do not want to use IE. Naturally speaking I do not recommend IE to anybody, it’s rather the opposite. While I do believe your sincere intends Scott, your company and the perceived spirit it embodies is inappropriate and incompatible with me, making most of your undoubtably good software become a necessary evil 🙁 . Kind regards Soenke /Quote I don’t us IE at home now, I use proper browsers like Mozilla Firefox and Mozilla, and the slightly less secure Opera, on occasion. IE is excrement it has fatal DESIGN flaws in security and even full patched causes really stupid layout flaws for legal HTML. At work I have to use MS Junk, but I only use it when absolutely necessary e.g. for email and testing customer websites. All PC, I use regularly, have masses of vetted security software loaded, to protect me against unknown, but expected security leaks in Microsoft software, at home the main defence is a NAT Firewall router because hell do I know which port will be vunerable next. Just to give you any idea how much I hate IE; at home I have deleted, renamed, misdirected (in the registry to the Mozilla control if possible), deleted entries etc. all this because I am sick and tired of getting malware _even_ when I don’t use IE. I only have to go to to such extremes because Microsoft were too greedy to design in security at the start, deliberately compromised security, gratutious integrating IE into Win98/NT/2K/XP then bodging in fatally flawed security later, to make it worse Microsoft made the API public so that other blithering idiot developers used MS browser components too e.g. McAfee, Symantec, BigFix etc. OK I can’t use Windows update at home now, big deal most of the update (kludges) were IE security bug fixes + can be downloaded, also I cannot use Windows HTML help … yet, but a clever developer can always find a way! Lastly … GET BENT for supporting such unspeakableness. If you had tried the latest opera 7.53, you would see it is the best and most secure… and smaller, easier to use, and does not need ‘add-ons’ like firefox… Because I don’t need it on Linux! Come on guys, don’t dream. Think realistic. If you don’t need porn on the net you don’t need buggy & dangerous IE. It’s a security risk. Whole Windows is a security hole. Quite an emotive issue, this one! Regarding ‘add-ons’ for Firefox, illiad. You miss the point, evidently. Firefox is open source. Opera is not. Firefox doesn’t "need" add-ons, but the modular nature of its extension system means that you are free to code functions into the application where you need them. From the user’s point of view, Firefox is fully fledged and ready to go straight out of the proverbial box, with a core set of features that leaves little missing. If you want extra functionality, you install extensions. If you don’t need them, you don’t install them. The one size fits all paradigm invariably leads to increased bloat with evey new release of an application. Think "Clippy" and you’ll get the picture.. Firefox, on the other hand, gets smaller with every release, whilst retaining the core functionality and evolving core functions. Opera may well be a mighty fine browser.. that it’s several notches up the evolutionary ladder in terms of IE is certainly undeniable. But it’s still commercial and closed source. Doesn’t mean it’s inferior, but it also does mean that it doesn’t have the same community and vision as Firefox/Mozilla. If the web is an online shopping mall, IE wants to be the store manager, the distribution chain and the agent supplying the goods. Some browsers, on the other hand, work on the premise that the web is a collaborative tool for info exchange, and don’t try to break standards, off-road competing technologies and force the end-user into a trap. When you look at a browser, don’t just ask yourself "Is it cool?" but also ask "What’s the agenda of the developer?" and "Is it standards compliant?" Standards are the level playing field.. proprietary extensions are the illegal steroids.. Pop Vox: When Bill G visited Acorn Computers (Cambridge, England) in the mid 80s, they had a network infrastructure in place (econet) and Bill didn’t get it. He’d never encountered networking before, apparently. "What’s a network?" he was reported asking. — | Xen & The Arse of XP Maintenance IE is a joke. Face it. Firefox is beautiful software. Face it. I just don’t believe that IE is ‘secure’. I know too many people who have had their computers become full of malware (as in STUFFED full) because of IE’s holes. QUOTE: "If you had tried the latest opera 7.53, you would see it is the best and most secure… and smaller, easier to use, and does not need ‘add-ons’ like firefox…" I’m sorry, but that is just ridiculous. Firefox doesn’t "need" add-ons, It’s good as it comes, I could happily use it stripped down, but you add whatever you want and customize to your own needs — this is awesome because the browser doesn’t come with a load of unneccessary, intrusive crap that you have no control over. Opera is one hell of an ugly browser too, page rendering is horrible, and last time I looked (not so long ago) it was absolutely full of bugs. A GOOD, BASIC FIREFOX GUIDE: Microshaft may as well ditch IE and write some software we can take seriously. Go on, guys, create a whole new browser and admit IE is total rubbish. I dare you. Whoops, I should also add — Opera isn’t free. IE is to browsers what AOL is to ISP’s… well, maybe AOL isn’t quite that bad. RIGHT IN NINJASTYLE. The link in your post says it all: Many web developers might have told you this already, but I will sleep better if I stress it again. It’s that simple. IE will never cut it as a browser, even if you managed to fix all the problems and improve it enough to woo some people into enjoying it. I turned my back to IE and I can guarantee you I’m not going back. Scott you smoked your lunch! As a MS professional… I can say at the present times MS certification and $0.75 I might get a cup of coffee… IE blows big time! Get real! Keep on working. I love this browser, too. Improve it – yes. But it is the only browser 4 me. thanx. I think I’d rather swim in a lake of sharks than download a beta security pack for the operating system to make a browser work a little better. Why would I want to do something that drastic when tremendous alternatives already exist? I, for one, think Opera is the classiest of the bunch. One of the biggest errors a commercial operation can make is to produce a product which people either can live very happily without, or are absolutely delighted to be rid of. I can not think of a single person, that I have ever encountered in any sphere who has chosen to use IE 6 over the alternatives (once they know the difference). Having IE 6 installed on a PC is like have an alien (movie type) living in the basement. The damage it does to the karma of the whole system including the file manager is simply unbearable. I do not know why I am bothering to tell you. MS have made the lives of web developers, clients, and users absolute misery for years. I really hope you now get whats coming. We do not need your product. Period. The biggest service you could supply to *upgrade* it would be to publish comprehensive instructions on how to disable or uninstall all of it. And the html mark up and css of this very blog could have been done by a ten year old. As usual on your sites. IE continues to shun web standards, and rely upon MS-centric code which is much to blame for the (sad) current state of existing we pages. Mid-90’s developers came to rely upon MS-centric code (document.all anyone?), rendering them incompatible with standards compliant browsers. This has serverd to retain IE’s market share, albeit in an underhanded fashion. Standards-compliant browsers are no buggier than IE; the accusations usually stem from the fact that they don’t support MS-centric pseudocode. In an attempt to add concise constructive comments: When browsers meant IE4 vs. NS4 it quickly became clear to any discerning developer that IE4 was far superior.. at that time, I was very happy with IE.. as a developer it gave me so much freedom, it’s DOM was comprehensive in comparison to any other browser.. you could say as a web developer I "loved" it.. Today things are very different.. there is no comparison between Firefox 0.9.x and IE6.. FF is lightyears ahead, both from a web development/standards perspective and a web user/usability perspective.. I "love" Firefox because it is better.. in so many ways, most of which have already been mentioned many times already.. I recommend it to anyone and everyone I meet.. as far as I can tell most people who even use the web for 1 minute every month would enjoy that minute far more using FF.. Word is spreading.. people are discovering these options, with the sincerest goodwill I offer you the same advice as I have to many other people (who have ALL responded positively).. try Firefox for one month.. and I predict that after that month you will never want to use IE again for everyday browsing.. If that doesn’t help shift your perspective, even if you are unable to communicate it due to your current occupation.. then clearly you have a different experience to every single other person I’ve recommended it to.. My thanks to you and the MS developers for all your efforts on IE.. I hope you continue to improve it for both users and developers.. but in it’s current state I’m sorry to say I just can’t find any reason at all to "love" it. Regards Dan <BLINK> Ha ha, what a great blog. Really. But i must comment anyway! Reading through the comments already, I have converted at least 15 people to Firefox over IE. People always complaining about how IE has popups, gets spyware. Mine doesnt even open anymore. I’m uninstalling it as we speak. lol ha. well there would have to be some extreme overhaul of the overall backend and look to IE for me to go back. recommending downloading sp2 before using it, well, really makes the point, doesn’t it! IE has serious security holes and a lack of compliance with standards. and you love it. to be honest, i think you should look for another career if you think this is the best browser. Anyone that in anyway believes that the latest version of IE (Internet Explorer) [”>] is better than the latest versions of Mozilla [] or Opera [] is seriously misinformed or ignorant of the superiority of the latter mentioned browsers. IE is riddled with security flaws and is seriously lacking comparatively in regards standards support. The former of these is of great concern and can be of financial cost to both users and financial institutions all the time, and the latter troubles web developers who wish to be standards compliant (thus creating highly accessible, efficient and fast websites) every single day. It is a disgrace to Microsoft [] (a multi-billion dollar company) that it’s web browser is inferior to an open-source web browser. I am sure that Microsoft could easily overtake both Mozilla and Opera in the area of standards support in a relatively short period of time if they wanted to. In my mind Microsoft are just thinking of themselves and the only way in which they would even consider begin implementation of the demands of web developers was if the browser wars were to be restarted like they were in the good old days or if they had a dramatic mind shift, both of which are unlikely from my point of view. Whilst I do have strong opinions regarding IE, I am not a stereo-typical “Microsoft hater”. I use Microsoft Windows and Microsoft Office – both of which I have no problems with. It is just IE which I find to be highly inferior and annoying. For all web users, both in organisation and individual situations, I urge you to move over to using a browser such as Mozilla (or Mozilla Firefox []) or Opera – you will not be disappointed. I also pass this recommendation to web developers, as well as passing a strong suggestion to use the web standards developed by the W3C [], such as XHTML [ and] for markup, CSS [] for style and PNG [] for imagery. And like a lover you seem so blinded by this love that you can’t actually notice the object of your affection has gallivanting senility. Bravo to you! Amidasu | Gedanken zum Leben, dem Universum und den ganzen Rest Wow, this site was coded "so well" that I couldn’t even post from Opera. I kid you not, the "Title" "Name" and "URL" textboxes didn’t appear at all. Firefox does a good job of rendering mangled code, thank goodness. Oh well, moving on. The gaping security holes are obvious, I don’t want to get into that. Other people more knowledgable than me have covered that already. Me understand not the points of given out for arguments Internet Explorer so good being. Being know Internet Explorer compliants standards not many people. Design good look not regarding, other reasons compliants standards important is for Internet. If not compliants standards, guess browsers to render. If guess browsers to render, render pages the same not. OK, it’s getting a little hard for me to type like that. But did you get what I was trying to say? No, not what I literally wrote, but what I was trying to imply. Standards to HTML/XHTML and other web languages are the equivelent of grammar to English and other languages. If we didn’t have a standard for proper grammar in English, we would still sort of understand what we’re saying to each other, but a lot of guesswork is involved. Having standards and grammar lets us portray ideas to each other in an easily understandable manner. And isn’t that the point of the Internet? Sharing ideas in an easily manageable and understandable environment. Sure, it works without complying to standards. But that defeats one of the main purposes of the Internet. That defeats a fundamental concept of communication. Now, I don’t think MS is purposely freezing development on IE for avoiding the monopoly fiasco. What I really think is that they’re dedicating their resources to Longhorn, XBox, and other projects in which they actually make money. As for why they wouldn’t use the money they gave away to investors … well, let me put it this way. If you went to a restaurant for the second time, and the manger remembered you and gave you a 10% discount, would you be more likely to return to that restaurant to eat? They’re devoting their resources to things that make them money. The problem with that is, while MS keeps making more and more money, the state of the world-wide Internet community is worsened. The public is getting the much talked about shaft, as innovation for web design is stifled by IE’s lack of standards compliancy. Web designers have to make sure their site works properly for IE, or else over 90% of the population won’t be able to view it. Making a page work for IE is more of a priority than making use of advanced CSS and CSS2 properties to enhance the delivery of content. Web designers pushing for standards compliance are a minority. Most people who make their own pages could care less, and would rather the rules be less strict. By trying to make more and more money, and not having any further developments on Internet Explorer, Microsoft is effectively screwing the public. And the public, by and large, is already screwed so much that it’s simply too numb to care. Whoops. Don’t mean to double post, but let me finish: I’m glad that this IEBlog is up to help keep us up-to-date with current developments. And I think that’s what most people really want – to know what’s going on. A big kudos to taking a giant step towards bringing the entirety of the web on to the next level. I love IE too. It has always been way ahead of its time but has been plagued by attacks from the open-source community who are trying desperately to compete with it! Give up guys, most people are happy with the way IE is going and "tabbed browsing" just aint enough to make us use another browser. Mozilla and their ilk all suffer from rendering inconsistencies, and many have proprietary (non w3c) CSS syntax. Complete hypocrisy. To the geeks who ankle-bite Microsoft, I say this: Do something constructive – use blogs like this to help MS develop IE. Eugene I disagree. We do care. and We are actively seeking ways to get away from Microsoft. Chris Beach – Examples? … Thought not. Troll. If you "love this browser", then you haven’t tried Firefox. 🙂 If your job is to actually IMPROVE IE, how are you going to do that by only praising its present condition? Isn’t a bit of criticism necessary to improve anything? Oh, before I forget: 1 – FOLLOW STANDARDS INSTEAD OF ALWAYS TRYING TO DICTATE THEM 2 – FIX CSS2 Can you imagine the amount of trouble you’ve caused developers for your lousy support of CSS? Apple or micro$oft…um hard decision, not! I would choose apple every time and after recentley switching hate to use my XP pc now with buggy software and prone to crashing and hackers. XP is VERY outdated and is visually dreadful, alothough I agree the IE isn’t too bad. I personally use Mozilla or Safari but also have IE due to incompatibility problems, which I have to say is alot better on the mac as most Micro$oft products are. Hmm is this a cheap Advertising stunt? No well, of course you love IE, its YOUR baby. For the rest of the web Mozilla rules supreme over your ugly, ugly child. As a corporate user — Amen! I love this browser! As a pr0n addict at home, this browser is the must hijack susceptible, security unconscious, hard-to-use and integrate multiple security scheme, either you have to block everything or nothing… browser on the planet. I’ll continue to use it at work, I’ll continue not to at home… A blogger who loves IE?? That’s a rare occurence. "Eugene I disagree. We do care. and We are actively seeking ways to get away from Microsoft." We are a minority. A really, really tiny minority. Most casual users are happy with Internet Explorer, because it works on all major sites, and people purposely cater to Internet Explorer with their code. The general public, the hundreds of millions surfing the web, don’t really care. We are but a few, too insignificant for Microsoft to spend more resources to lead major developments to a project that doesn’t make them money. Don’t get me wrong, although I do hate the state that IE is in now, I geniunely hope that this blog is a sign for great things to come. I’m not anti-Microsoft, I’m not pro-Microsoft. I’m pro-progress, pro-innovation. If Microsoft can actively bring that us to a new age of innovation on the web by supporting full CSS and w3c specs, then I will heavily respect Microsoft from doing so. Do you think there would be so many books on the market right now if grammar never existed? Grammar brought about many ways to bring out ideas in an innovative manner. XHTML and CSS is the new grammar, and believe me when I say the web will be a lot better off with everyone complying to the specs. People will still be able to portray information and imagination in different styles, but in a way that’s easily understandable. I want Microsoft to succeed in this. Microsoft is the primary factor in pushing the web to the next level. Whether or not you support the company, you cannot deny that fact. And I’m 100% behind the IE team if they’re really trying to actively improve IE as a standards compliant browser. You can argue that people can switch to Firefox if they don’t like IE, but the fact is, most people won’t. It’s simpler to stick with IE for most people. To the IE team: You have the chance right now to revolutionize the web. If you hear our pleas, and if you incorporate the suggestions of serious web designers, the entire Internet community will be grateful. I cannot stress enough the importance of the IE team to the entirety of the Internet. Know that serious web designers support you 100% in trying to make progress with IE. We are not Microsoft haters, we are web lovers with a vision that has thus far been stifled by IE. Many of us are concerned with security and web standards. I am also concerned about what IE 6 does to any system it is installed on. It takes over the whole thing and runs riot. Settings are reset. The computer crashes and then reboots mysteriously to an earlier config. Other apps start playing up, crashing or being deleted. The file manager becomes unuseable. Plugins stop functioning. It sets itself as default for just about everything. IE starts updating itself without our consent, and all the time the freakin monster is communicating to and from MS – all of which the user is blissfully unaware of. Then it cant be uninstalled. Any one here who even thinks MS wants a better browser is not in the real world. It works the way it does because they like it that way. The integration of the browser and the OS, allied to the Windows update, is MS entree to annual licensing for everybody, the end of choice and legacy systems, and the loss of control of the *client* into MS hands. Longhorn is going to be the nadir. It is pointless talking about security. MS like it that way so their wierd proprietary stuff can do its thing. *balanced with application compatability*. What does that mean? What applications? People it is time to get real. The CERT warning is the MS Chernobyl. They are in meltdown. IE is to browser as Kazaa is to P2P. Both are virus invested wastelands. Firefox rocks IE = a joke why would you waste time with having to update your browser every otherday when you can get a beta version of firefox which is stronger fast safer and easyer to use microc0cks learn from the little guy once in a while. I second the original authors opinion – I Love This Browser Why? It generates income for me. When combined with Outlook or Outlook Express it provides a solid amount of business clearing virus’ and other malware. It also gives a good lead in to selling antivirus software. On the down side, it gets very boring. I would far rather being doing more interesting work. As a tech savvy user I was most embarrased to get caught by malware myself after following a search result that lead to something other than what I was expecting (they’re a cunning lot these malware people) – and this was on a fully patched Windows XP Pro with antivirus, but not (unfortunately) anti-malware software. Still, this was an unusual situation since I cannot afford to risk my own business to Windows and Office (including IE and OE/Outlook). I use Linux from server to desktop (apart from a test machine or two) and it is far more productive and easier to use (I will admit there is a certain amount of familiarity here, but I’ve used Windows from v3.0 including administering servers, so I’m not exactly a novice!). As a web developer IE is the thorn in my side. Because of its market share you cannot ignore it, but I’m afraid the fact that it doesn’t conform to internationally defined standards for writing web pages it is holding the Internet back. It is very reminiscent of when I had to design an Intranet and ensure that my pages would work on a 640×480 resolution in 16 colours. When I think what I could code up for websites quickly and easiliy if I didn’t have to consider IE it is depressing (but then again, the longer the work the better the money – although also the more frustrating and less interesting!). It has to be said that I am increasingly inclined to make sites work in IE, but include a page explaining how much better the experience could be in something else and include links to downloads – maybe even a branded version of Opera or Mozilla / Firefox! Full PNG support is crucial. It wil make the browser look much better. CSS should be implemented, but it is true that CSS sucks, and I would not be too disappointed to see you guys ‘innovate’ a new style syntax, preferrably xml-y ( W3C standards have not been good lately. I would not mind cutting losses on CSS, admitting that it was a failure and starting a-new. I doubt however that everyone would agree with me.) . The xaml syntax looks promising (certain layouts are near impossible and CSS, and the layout model feels broken or limited). It seems to me that the html browser is a dying item. The model seems to be evolving to a browser that supports viewing all sorts of content – XML, RSS, Images, SVG, VRML, XAML, — whatever –, and that the browser should be come more of a universal document browser. Even more crucial in the futire will be some aspect of the browser that manages resources (location, caching, searching[ I want to see a list of all of the web pages I have seen in the last week that have the phrase ‘Lance Armstrong’], subscriptions, and notifications). Other things that you simply must implement are some proper way to use document definitions to tell the browser how to process the markup. You should definitely have complete standards mode, and you should definitely have complete support for XHTML. To not have full support for these standards is embarrassing an reflects very poorly on Microsoft’s ability to produce software. As a company that I think is the best in the world at producing software, this crucial weakness is a glaring mistake that seriously undermines Microsoft’s credibility as a software company, and that simply should not be. (This probably seems scattered, but the key is, if you re going to provide support for a spec, do not do it half-assed. Microsoft should have zero trouble implementing a spec properly, and you should have been able to avoid back-compat problems with document declarations.) IE is the best browser? Yeah, right! I might have thought that too, before I discovered FireFox. Saying IE is the best browser is like saying that Windows 98 is the best server OS. It ain’t true. C’mon. At the point where Opera far surpasses IE in support for web standards, you guys should wake up and start working. I don’t know if anyone’s mentioned this yet, but since so many of us around the world are stuck on dial-up, it would be nice if Microsoft would include a download manager in IE that would allow us to resume downloads of Windows updates. It’s really annoying to be 95% through downloading a critical update and then lose my connection. Throw us a bone, Microsoft! I only use IE when I have to, for everything else I use Firefox. So do the developers ever post anything?? I would love to hear an official response to at least a FEW of the above posts. I propose the letters stay the same (so it’s easier to avoid), but the actual title of IE be changed to Interfect Explodus from here on in. Just to better reflect its nature. Intercept Exfoliate doesn’t have quite the same ring… — | bullshit & banner free.. CAN YOU SAY BLOATWARE. It attracts pop ups, makes browsing multiple websites at once damn near impossible, and It smells like cabbage. It’s time for a real browser. Firefox treats me kind at night, and I don’t need to get a pop up blocker for it or a google bar or all sorts of bug fixes. sheesh. Microsoft needs to hire some people who use the internet. So another day later and not one post from a dev. How do they expect us to think they give a rats a$$ what people think if they are not going to participate on their own blog?. Opera is and has always been light years ahead of its competition. I think the IE team could learn a lot about improving the browser from simply using Opera for a month or two. Obviously, there are the basics that Opera has had since before 2000: tabbed browsing, mouse gestures, ability to zoom the page, and customize practically every aspect of the experience. There are also other features – for example, you can set Opera to start up where you left off. Imagine you’ve got fifteen different sites open when you need to shutdown or log off the machine. In any other browser, you’d have to bookmark each page, and open them later. If you’d accidentally close the browser instead of one page, you’d have to dig through the history to find them again. In Opera, you just reload the browser whenever you want and there are the pages you were looking at. Opening a folder full of bookmarks is something else that Opera has had since at least 1997, but has only just been added to Firefox in the last version. Being able to turn on and off Javascript or Java at will through a shortcut key. Being able to toggle images on and off at will. Switching between author and user CSS files if you’re CSS-inclined. Fast and smart display of cached pages (pages that IE or Mozilla will reload every time) when all you want to do is flick back a page or two to re-read something. I’ve seen people claim Opera is full of bugs, but I defy these people to provide even one example – I use Opera for hours on end every day, and have not come across a single bug that wasn’t related to bad web page design. IE team: Use Opera for a few months – get used to it, explore the options, and above all,browse with it constantly. You will soon see why Opera users are the most vocal about their browser. No other comes close (but if IE would improve to this level or beyond – wow! Longhorn would be on my shopping list before you could blink). Internet Explorer???? Internet Exploiter more like. No really. it’s better than that shower of shite called Internet Explorer. Wanker. Hi Scott Stearns. You’re kidding … right? Every sane web surfer knows IE is a security nightmare. With its plethora ActiveX and BHO security holes, it’s no longer a question of “if” its next security hole will be exploited; it’s only a question of “when”… … And now, the “when” time interval tends to zero. Even some insane web surfers know this, but they continue using IE under the sanguine assumption they’ll never get stung. They’re behind a firewall and promptly apply Microsoft’s vast multitude of security patches… … And lately, the patch time interval tends to infinity. But they’ll get stung. It’s only a matter of time before an IE security failing, and its hooks into the OS, ensures their PC is becomes a zombie, one bot among many in a bot network. Another day, another security patch or two to internet explorer. Quality product from a quality company. You are not very bright then. I love you Two words: Mouse Gestures. They go really well with tabs. ok i dont think there is a browser out there which integrates better with windows that IE..but i think that MyIE2 has better features even thought its using the IE engine..ok there are security issues but honestly…how many ppl even care about it..if ur using ur credit card over websites like amazon or any website using the paypal system…u are secured…so i dont think this is much of an issue. btw thnk it will be better if IE has a download manager of its own..like opera…its easy to use and it also reduces the number of open windows. > if ur using ur credit card over websites like amazon or any website using the paypal system…u are secured This is completely untrue. If somebody has put spyware on your system through one of Internet Explorer’s many security holes, there is nothing Amazon, Paypal, or anybody else can do to prevent disclosure of your credit card details. Just because there is a padlock symbol, it doesn’t mean anything is secure. It means your computer is communicating with a server via HTTPS – spyware running on your computer can eavesdrop, it’s just that somebody with no access to the two computers can’t eavesdrop. Whenever you let something run on your system, it can do anything you can do. If you can see your credit card details, so can it. Don’t let a shiny padlock icon lull you into a false sense of security. All of this is true no matter which browser you use. It’s just that Internet Explorer has far more security holes than other browsers, which is why we are complaining. These security holes _matter_. Over here in the UK, two people have been arrested for dealing in kiddy porn, gone through hell, and finally aquitted themselves by proving that their computers were running software that had gotten in through security holes. Right now, spammers use many insecure computers to send spam. Unless you are fine about helping these scum, you should care about security.. What is IE??? someone call this program "html browser", but since it doesn’t comply html/css and even has no intention… what is it??? Hi, please don’t fix anything. It’s fine the way it is. – Burt Burt, You are either a Microsoft shill or retarded. When the department of homeland security tells people to stop using Internet Explorer, you can damn well bet there is something wrong. Owen, Can you smell the irony? Leave Burt alone, he’s fine. Rather, save your ire for Interfect Explodus.. united we stand.. — It can’t be said enough times: what we want is CSS3, proper xml/xhtml support, and a full and complete DOM. Give us these things, and you won’t need your COM-based ActiveX. Oh yeah, and tabs. Rogue, Sorry. I’ll wipe the foam from my mouth and try again. 🙂 I used to love IE 5-6, only when the only other alternative was Netscape 4. Two years ago IE was absolutely the best browser around. This ceased to be the case when Mozilla 1 came out and I starded developing with XHTML and CSS2 according to W3C specs. There is not point in yelling here and calling IE and people who developed it names. I trust they did the best they could with resources and time provided to them by Microsoft. But now the browser is simply outdated – plain old (love it or not), and it’s definitely time to upgrade it. So until 2006 – happy Firefoxing everybody! I was once a fan of IE, and never ever used to use other browsers. Later IE was dumped with security holes which literally scared me to use IE. Later switched to Firefox. Honestly I don’t want to blame Microsoft or Mozilla. Any human should try to accept thier mistakes and try to rectify them, rather than saying "The Best browser in the world" Stick to the standards w3c.org… Oh i foregot, microsoft invent their own standards when they don’t get their own way. Down with IE. Up with Mozilla FireFox! (From a web developer who loves Mozilla and codes for both ie/mozilla). PingBack from PingBack from PingBack from PingBack from
https://blogs.msdn.microsoft.com/ie/2004/07/21/i-love-this-browser/
CC-MAIN-2017-26
refinedweb
32,238
71.44
<< Sadettin Senberber974 Points How can I add the boolean expression in this code? In this instance should I write "public bool(xx xxx)" expression or like "bool a = true" expression. What I suppose to do? Thank you. int value = -1; string textColor = null; return ((value < 0) = textColor = "red") ? textColor = "green"; 1 Answer Steven Parker215,939 Points The instructions say to " Use a ternary if statement instead of an if/else statement to initialize the textColor variable". You won't need to add a new boolean expression, though you'll probably want to re-use the one that was originally in the "if" statement. You also won't need a "return", those are only valid inside functions anyway. Without providing an explicit spoiler, an assignment using a ternary might have this basic structure: variable = (expression) ? true-value : false-value;
https://teamtreehouse.com/community/how-can-i-add-the-boolean-expression-in-this-code
CC-MAIN-2022-27
refinedweb
138
63.59
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world Getting Rails .find(... :order => Text_field To Sort Alphabetically Ignoring Upper Case // my problem was that a Rails Find :order(ed) on :description (a text field) was putting Upper case values ahead of all the down case values. This was written using the Ruby sort_by code. Perhaps someone will come behind me and post how this could have been done in 1 line. I welcome it. def Prayer.in_alphabetical_order all_prayers = Prayer.find(:all) unsorted_prayers = [] all_prayers.each do |p| unsorted_prayers << {:prayer => p, :description => p.description.downcase} end sorted_prayers_container = unsorted_prayers.sort_by{ |i| i[:description]} sorted_prayers = [] sorted_prayers_container.each do |p| sorted_prayers << p[:prayer] end return sorted_prayers end John Lannon replied on Wed, 2009/09/23 - 11:14pm chiery luvly replied on Wed, 2009/09/02 - 6:45am Snippets Manager replied on Thu, 2009/03/12 - 9:32am def Prayer.in_alphabetical_order Prayer.find(:all).sort_by{|p| p.description.downcase} end
http://www.dzone.com/snippets/getting-rails-find-order
CC-MAIN-2014-10
refinedweb
173
59.09
Python Tkinter Entry Advertisements The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget. Syntax Here is the simple syntax to create this widget − w = Entry( master, option, ... ) Parameters: master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. Methods Following are commonly used methods for this widget − Example Try the following example yourself − from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop() When the above code is executed, it produces the following result: python_gui_programming.htm Advertisements
http://www.tutorialspoint.com/python/tk_entry.htm
CC-MAIN-2016-40
refinedweb
164
57.27
Now here's the thing that I'm most excited about. POST requests! It's likely that you've already been doing those with Next before, but usually it involves creating api-routes, posting with fetch, and managing client state with swr or react-query. No more! Let's get right to it. #handle » post import { handle, json } from 'next-runtime'; export const getServerSideProps = handle({ async post({ req: { body } }) { await db.comments.insert({ message: body.message, }); return json({ message: 'thanks for your comment!', }); }, }); I mean, how cool is that? By adding the post handler, we'll be able to submit forms (post data) to the same route as the one that's responsible for rendering the page. No context switching between the page component, getServerSideProps, and api-routes. And here as well it comes with a free api route. Post FormData to it, or JSON. They both just work. Possibly unnecessary, but here's a form that could be submitting data to this getServerSideProps. export default function MyPage({ name, message }) { if (message) { return <p>{message}</p>; } return ( <form method="post"> <input name="name" defaultValue={name} /> <input name="message" /> <button type="submit">submit</button> </form> ); } That's right. Just a standard HTML form. Note that patch, put and delete methods are supported as well. Those behave the same as post requests. #Upgrading to <Form> These standard POST requests are sweet! You'll have forms implemented in no-time. Don't make react control the state. Use defaultValue and no onSubmit handler. Let your server do its validation, and move on. But sometimes, we want more. Faster responses, or prevent the page from reloading. In such cases, you'll use Form. import { Form, useFormSubmit } from 'next-runtime/form'; export default function MyPage({ name, message }) { const { isSubmitting } = useFormSubmit(); if (message) { return <p>{message}</p>; } return ( <Form method="post"> <input name="name" defaultValue={name} /> <input name="message" /> <button type="submit" disabled={pending}> {isSubmitting ? 'submitting' : 'submit'} </button> </Form> ); } Note that we now import Form from next-runtime/form, and use a hook to see if the form is currently being submitted. By using Form instead of form, the form is submitted using javascript ( fetch), and the page won't refresh upon submission.
http://next-runtime.meijer.ws/getting-started/4-data-updates
CC-MAIN-2022-33
refinedweb
367
59.7
Oracle Data Integrator 11.1.1.5 Complex Files as Sources and Targets By Alex Kotopoulis-Oracle on Jun 20, 2011 Overview ODI 11.1.1.5 adds the new Complex File technology for use with file sources and targets. The goal is to read or write file structures that are too complex to be parsed using the existing ODI File technology. This includes: - Different record types in one list that use different parsing rules - Hierarchical lists, for example customers with nested orders - Parsing instructions in the file data, such as delimiter types, field lengths, type identifiers - Complex headers such as multiple header lines or parseable information in header - Skipping of lines - Conditional or choice fields Similar to the ODI File and XML File technologies, the complex file parsing is done through a JDBC driver that exposes the flat file as relational table structures. Complex files are mapped to one or more table structures, as opposed to the (simple) file technology, which always has a one-to-one relationship between file and table. The resulting set of tables follows the same concept as the ODI XML driver, table rows have additional PK-FK relationships to express hierarchy as well as order values to maintain the file order in the resulting table. The parsing instruction format used for complex files is the nXSD (native XSD) format that is already in use with Oracle BPEL. This format extends the XML Schema standard by adding additional parsing instructions to each element. Using nXSD parsing technology, the native file is converted into an internal XML format. It is important to understand that the XML is streamed to improve performance; there is no size limitation of the native file based on memory size, the XML data is never fully materialized. The internal XML is then converted to relational schema using the same mapping rules as the ODI XML driver. How to Create an nXSD file Complex file models depend on the nXSD schema for the given file. This nXSD file has to be created using a text editor or the Native Format Builder Wizard that is part of Oracle BPEL. BPEL is included in the ODI Suite, but not in standalone ODI Enterprise Edition. The nXSD format extends the standard XSD format through nxsd attributes. NXSD is a valid XML Schema, since the XSD standard allows extra attributes with their own namespaces. The following is a sample NXSD schema blog.xsd: <?xml version="1.0"?> <xsd:schema xmlns:xsd="" xmlns:nxsd="" elementFormDefault="qualified" xmlns:tns="" targetNamespace="" attributeFormDefault="unqualified" nxsd: <xsd:element <xsd:complexType><xsd:sequence> > The nXSD schema annotates elements to describe their position and delimiters within the flat text file. The schema above uses almost exclusively the nxsd:terminatedBy instruction to look for the next terminator chars. There are various constructs in nXSD to parse fixed length fields, look ahead in the document for string occurences, perform conditional logic, use variables to remember state, and many more. nXSD files can either be written manually using an XML Schema Editor or created using the Native Format Builder Wizard. Both Native Format Builder Wizard as well as the nXSD language are described in the Application Server Adapter Users Guide. The way to start the Native Format Builder in BPEL is to create a new File Adapter; in step 8 of the Adapter Configuration Wizard a new Schema for Native Format can be created: The Native Format Builder guides through a number of steps to generate the nXSD based on a sample native file. If the format is complex, it is often a good idea to “approximate” it with a similar simple format and then add the complex components manually. The resulting *.xsd file can be copied and used as the format for ODI, other BPEL constructs such as the file adapter definition are not relevant for ODI. Using this technique it is also possible to parse the same file format in SOA Suite and ODI, for example using SOA for small real-time messages, and ODI for large batches. This nXSD schema in this example describes a file with a header row containing data and 3 string fields per row delimited by commas, for example blog.dat: Redwood City Downtown Branch, 06/01/2011 Ebeneezer Scrooge, Sandy Lane, Atherton Tiny Tim, Winton Terrace, Menlo Park The ODI Complex File JDBC driver exposes the file structure through a set of relational tables with PK-FK relationships. The tables for this example are: Table ROOT (1 row): Table HEADER (1 row): Table CUSTOMER (2 rows): Every table has PK and/or FK fields to reflect the document hierarchy through relationships. In this example this is trivial since the HEADER and all CUSTOMER records point back to the PK of ROOT. Deeper nested documents require this to identify parent elements. All child element tables also have a order field (HEADERORDER, CUSTOMERORDER) to define the order of rows, as well as order fields for each column, in case the order of columns varies in the original document and needs to be maintained. If order is not relevant, these fields can be ignored. How to Create an Complex File Data Server in ODI After creating the nXSD file and a test data file, and storing it on the local file system accessible to ODI, you can go to the ODI Topology Navigator to create a Data Server and Physical Schema under the Complex File technology. This technology follows the conventions of other ODI technologies and is very similar to the XML technology. The parsing settings such as the source native file, the nXSD schema file, the root element, as well as the external database can be set in the JDBC URL: The use of an external database defined by dbprops is optional, but is strongly recommended for production use. Ideally, the staging database should be used for this. Also, when using a complex file exclusively for read purposes, it is recommended to use the ro=true property to ensure the file is not unnecessarily synchronized back from the database when the connection is closed. A data file is always required to be present at the filename path during design-time. Without this file, operations like testing the connection, reading the model data, or reverse engineering the model will fail. All properties of the Complex File JDBC Driver are documented in the Oracle Fusion Middleware Connectivity and Knowledge Modules Guide for Oracle Data Integrator in Appendix C: Oracle Data Integrator Driver for Complex Files Reference. David Allan has created a great viewlet Complex File Processing - 0 to 60 which shows the creation of a Complex File data server as well as a model based on this server. How to Create Models based on an Complex File Schema Once physical schema and logical schema have been created, the Complex File can be used to create a Model as if it were based on a database. When reverse-engineering the Model, data stores(tables) for each XSD element of complex type will be created. Use of complex files as sources is straightforward; when using them as targets it has to be made sure that all dependent tables have matching PK-FK pairs; the same applies to the XML driver as well. Debugging and Error Handling There are different ways to test an nXSD file. The Native Format Builder Wizard can be used even if the nXSD wasn’t created in it; it will show issues related to the schema and/or test data. In ODI, the nXSD will be parsed and run against the existing test XML file when testing a connection in the Dataserver. If either the nXSD has an error or the data is non-compliant to the schema, an error will be displayed. Sample error message: Error while reading native data. [Line=1, Col=5] Not enough data available in the input, when trying to read data of length "19" for "element with name D1" from the specified position, using "style" as "fixedLength" and "length" as "". Ensure that there is enough data from the specified position in the input. Complex File FAQ Is the size of the native file limited by available memory? No, since the native data is streamed through the driver, only the available space in the staging database limits the size of the data. There are limits on individual field sizes, though; a single large object field needs to fit in memory. Should I always use the complex file driver instead of the file driver in ODI now? No, use the file technology for all simple file parsing tasks, for example any fixed-length or delimited files that just have one row format and can be mapped into a simple table. Because of its narrow assumptions the ODI file driver is easy to configure within ODI and can stream file data without writing it into a database. The complex file driver should be used whenever the use case cannot be handled through the file driver. Should I use the complex file driver to parse standard file formats such as EDI, HL7, FIX, SWIFT, etc.? The complex file driver is technically able to parse most standard file formats, the user would have to develop an nXSD to parse the expected message. However, in some instances the use case requires a supporting infrastructure, such as message validation, acknowledgement messages, routing rules, etc. In these cases products such as Oracle B2B or Oracle Service Bus for Financial Services will be better suited and could be combined with ODI. Are we generating XML out of flat files before we write it into a database? We don’t materialize any XML as part of parsing a flat file, either in memory or on disk. The data produced by the XML parser is streamed in Java objects that just use XSD-derived nXSD schema as its type system. We use the nXSD schema because is the standard for describing complex flat file metadata in Oracle Fusion Middleware, and enables users to share schemas across products. Is the nXSD file interchangeable with SOA Suite? Yes, ODI can use the same nXSD files as SOA Suite, allowing mixed use cases with the same data format. Can I start the Native Format Builder from the ODI Studio? No, the Native Format Builder has to be started from a JDeveloper with BPEL instance. You can get BPEL as part of the SOA Suite bundle. Users without SOA Suite can manually develop nXSD files using XSD editors. When is the database data written back to the native file? Data is synchronized using the SYNCHRONIZE and CREATE FILE commands, and when the JDBC connection is closed. It is recommended to set the ro or read_only property to true when a file is exclusively used for reading so that no unnecessary write-backs occur. Is the nXSD metadata part of the ODI Master or Work Repository? No, the data server definition in the master repository only contains the JDBC URL with file paths; the nXSD files have to be accessible on the file systems where the JDBC driver is executed during production, either by copying or by using a network file system. Where can I find sample nXSD files? The Application Server Adapter Users Guide contains nXSD samples for various different use cases. Hi David, I have a requirement here at the project which is becoming a little complicated, here is the thing: I need to invoke a web service using a request file, which is ok, the invocation is working I get the response xml file, now, the thing is in the request file I am passing parameter like user, pass, so far so good, however , the start_ date and end_date I must pass the values dynamically to do that what I thought and what have done in other integration using flat file is storing the values on the database and passing into a variable, but in the case I have tried to generate the XML file with ODI interfaces but there st_date and end_date are in a different node in the XML, If you could help with this that would be great, Many thanks, Alan Posted by guest on May 08, 2014 at 05:48 PM PDT # Hi Alan How/where are you building up the request file? Cheers David Posted by Alan on May 09, 2014 at 06:58 AM PDT #
https://blogs.oracle.com/dataintegration/entry/oracle_data_integrator_11_1
CC-MAIN-2016-26
refinedweb
2,063
55.27
IRC log of owl on 2008-09-03 Timestamps are in UTC. 16:45:50 [RRSAgent] RRSAgent has joined #owl 16:45:50 [RRSAgent] logging to 16:46:26 [IanH] IanH has changed the topic to: 16:46:50 [IanH] Zakim, this will be owlwg 16:46:50 [Zakim] ok, IanH; I see SW_OWL()1:00PM scheduled to start in 14 minutes 16:47:03 [IanH] RRSAgent, make records public 16:55:24 [uli] uli has joined #owl 16:56:15 [msmith] msmith has joined #owl 16:58:07 [Zakim] SW_OWL()1:00PM has now started 16:58:12 [Zakim] +msmith 16:58:15 [Zakim] +Peter_Patel-Schneider 16:58:39 [pfps] pfps has joined #owl 16:59:24 [Zakim] + +0190827aaaa 16:59:28 [MartinD] zakim, aaaa is me 16:59:28 [Zakim] +MartinD; got it 16:59:32 [Zakim] +??P4 16:59:35 [MartinD] zakim, mute me 16:59:35 [Zakim] MartinD should now be muted 16:59:40 [uli] zakim, ??P4 is me 16:59:40 [Zakim] +uli; got it 16:59:44 [uli] zakim, mute me 16:59:44 [Zakim] uli should now be muted 16:59:55 [uli] scribenick uli 16:59:56 [sandro] sandro has joined #owl 17:00:04 [bcuencagrau] bcuencagrau has joined #owl 17:00:36 [JeffP] JeffP has joined #owl 17:00:39 [uli] scribenick: uli 17:00:44 [Zakim] +IanH 17:00:57 [IanH] zakim, who is here? 17:00:57 [Zakim] On the phone I see Peter_Patel-Schneider, msmith, MartinD (muted), uli (muted), IanH 17:01:00 [Zakim] On IRC I see JeffP, bcuencagrau, sandro, pfps, msmith, uli, RRSAgent, Zakim, IanH, bmotik, MartinD, ewallace, trackbot 17:01:06 [Zakim] +Sandro 17:01:10 [uli] ScribeNick: uli 17:01:15 [ivan] ivan has joined #owl 17:01:40 [Zakim] +??P13 17:01:44 [bcuencagrau] Zakim, ??P13 is me 17:01:44 [Zakim] +bcuencagrau; got it 17:02:01 [IanH] zakim, who is here? 17:02:01 [Zakim] On the phone I see Peter_Patel-Schneider, msmith, MartinD (muted), uli (muted), IanH, Sandro, bcuencagrau 17:02:03 [Zakim] On IRC I see ivan, JeffP, bcuencagrau, sandro, pfps, msmith, uli, RRSAgent, Zakim, IanH, bmotik, MartinD, ewallace, trackbot 17:02:05 [Zakim] +StuartTaylor 17:02:16 [Zakim] +??P15 17:02:16 [JeffP] zakim, StuartTaylor is me 17:02:17 [Zakim] +JeffP; got it 17:02:22 [bmotik] Zakim. ??P15 is me 17:02:26 [bmotik] Zakim, ??P15 is me 17:02:26 [Zakim] +bmotik; got it 17:02:32 [bmotik] Zakim, mute me 17:02:32 [Zakim] bmotik should now be muted 17:02:34 [IanH] zakim, who is here? 17:02:34 [Zakim] On the phone I see Peter_Patel-Schneider, msmith, MartinD (muted), uli (muted), IanH, Sandro, bcuencagrau, JeffP, bmotik (muted) 17:02:36 [Zakim] On IRC I see ivan, JeffP, bcuencagrau, sandro, pfps, msmith, uli, RRSAgent, Zakim, IanH, bmotik, MartinD, ewallace, trackbot 17:02:59 [ivan] zakim, code? 17:02:59 [Zakim] the conference code is 69594 (tel:+1.617.761.6200 tel:+33.4.89.06.34.99 tel:+44.117.370.6152), ivan 17:02:59 [uli] sure 17:03:04 [baojie] baojie has joined #owl 17:03:07 [Zhe] Zhe has joined #owl 17:03:29 [uli] Topic: Agenda Amendments 17:03:34 [uli] none 17:03:44 [Zakim] +Danny 17:03:48 [uli] Topic: Previous minutes 17:03:50 [ivan] zakim, Danny is ivan 17:03:50 [Zakim] +ivan; got it 17:03:51 [Zakim] +baojie 17:03:54 [pfps] minutes look fine to me 17:04:18 [uli] IanH: minutes accepted 17:04:22 [Zakim] +Zhe 17:04:27 [Zhe] zakim, mute me 17:04:27 [Zakim] Zhe should now be muted 17:04:33 [uli] Topic: Pending actions 17:04:43 [pfps] q+ 17:04:55 [IanH] q? 17:04:59 [IanH] ack pfps 17:05:35 [uli] pfps: action 182 and 183 have emty bodies 17:05:41 [IanH] q? 17:05:44 [uli] s/emty/empty 17:05:58 [uli] IanH: something should be done 17:05:59 [baojie] +q 17:06:11 [uli] pfps: or we say now that they are done 17:06:37 [uli] IanH: we agree that action 182 and 183 are done, even though their bodies are empty 17:06:48 [IanH] q? 17:06:58 [IanH] ack baojie 17:07:09 [uli] baojie: there is an incomplete version on the wiki 17:07:35 [uli] IanH: asks for a pointer to this version 17:07:42 [IanH] q? 17:07:42 [pfps] q+ 17:08:03 [uli] I will run down the corridor and remind bijan 17:08:32 [baojie] A incomplete pdf of Quick Reference Guide: 17:08:40 [baojie] s/A/An 17:08:47 [uli] back! 17:08:57 [uli] i think so 17:09:13 [uli] IanH: action 150 17:09:22 [IanH] q? 17:09:28 [pfps] q- 17:09:34 [uli] baojie: we have come to a conclusion, so it should be done 17:09:52 [baojie] 17:10:02 [uli] ...we changed the ?? specification 17:10:42 [uli] IanH: can you come forward with a proposal re. internationalized string? 17:10:44 [bmotik] q+ 17:10:50 [bmotik] Zakim, unmute me 17:10:50 [Zakim] bmotik should no longer be muted 17:10:58 [IanH] q? 17:11:07 [IanH] ack bmotik 17:11:18 [uli] bmotik: I think there is a draft with the basics 17:11:24 [baojie] preliminary spec: 17:11:45 [m_schnei] m_schnei has joined #owl 17:11:56 [pfps] what is the status of the wiki page, and what should happen to it? 17:12:01 [uli] IanH: who take care of looking at this spec and see how we modify ours? 17:12:06 [IanH] q? 17:12:15 [bmotik] q+ 17:12:17 [uli] ACTION: bmotik to modify OWL spec accordingly 17:12:17 [trackbot] Sorry, couldn't find user - bmotik 17:12:25 [Zakim] +??P21 17:12:28 [bmotik] ACTION: bmotik2 to modify OWL spec accordingly 17:12:28 [trackbot] Created ACTION-206 - Modify OWL spec accordingly [on Boris Motik - due 2008-09-10]. 17:12:36 [m_schnei] zakim, ??P21 is me 17:12:36 [Zakim] +m_schnei; got it 17:12:40 [m_schnei] zakim, mute me 17:12:40 [Zakim] m_schnei should now be muted 17:12:41 [bmotik] q+ 17:12:43 [IanH] q? 17:12:45 [bcuencagrau] Zakim, mute me 17:12:45 [Zakim] bcuencagrau should now be muted 17:12:53 [uli] pfps: it would be odd if, in our spec, we would point to a wiki page 17:13:16 [uli] sandro: we could publsih the (content of) wiki as a working draft 17:13:32 [uli] IanH: as a RIF or as an OWL publication? 17:13:34 [ivan] can be a joined 17:13:35 [IanH] q? 17:13:41 [sandro] sandro: I think it's OKAY as long we're only making the reference from a WD (pre-LC). Maybe we should make it a WD? 17:13:42 [IanH] ack bmotik 17:13:43 [ivan] q+ 17:14:17 [IanH] q? 17:14:19 [IanH] ack ivan 17:14:28 [uli] bmotik: we make the draft a WD and then reference it 17:14:54 [IanH] q? 17:15:04 [uli] ivan: I had a look at this and it looks as if its publication shouldn't cause any problems. 17:15:18 [uli] ivan: we can even have a joint RIF/OWL publication 17:15:44 [bparsia] bparsia has joined #owl 17:16:04 [uli] ACTION: sandro to take this publication plan forward 17:16:04 [trackbot] Created ACTION-207 - Take this publication plan forward [on Sandro Hawke - due 2008-09-10]. 17:16:21 [uli] (I chose sandro already - he said 'yes' first) 17:16:26 [uli] wellcome, ivan 17:16:35 [Zakim] +??P22 17:16:46 [bparsia] zakim, ??p22 is me 17:16:46 [Zakim] +bparsia; got it 17:16:50 [bparsia] zakim, mute me 17:16:50 [Zakim] bparsia should now be muted 17:16:57 [msmith] q+ 17:17:02 [IanH] q? 17:17:03 [uli] IanH: action 192 re. UNA and OWL QL has been done as seen in an email 17:17:07 [IanH] ack msmith 17:17:14 [uli] msmith: yes, we can close that one 17:17:29 [pfps] The consensus should result in a discussion / resolution agenda item for next week. 17:17:44 [IanH] q? 17:17:54 [uli] IanH: action 202 must wait for next week, as must 172 17:18:09 [uli] IanH: I will chase Achille re. 172 17:18:13 [bparsia] I've had no action joy this week 17:18:32 [uli] IanH: action 168 has been on for some time 17:18:37 [IanH] q? 17:18:41 [bparsia] zakim, unmute me 17:18:41 [Zakim] bparsia should no longer be muted 17:18:59 [uli] q+ 17:19:05 [IanH] q? 17:19:20 [bparsia] zakim, mute me 17:19:20 [Zakim] bparsia should now be muted 17:19:24 [IanH] q? 17:19:25 [uli] zakim, unmute me 17:19:25 [Zakim] uli should no longer be muted 17:19:29 [IanH] ack uli 17:20:07 [bparsia] works for me! 17:20:23 [bparsia] zakim, unmute me 17:20:23 [Zakim] bparsia should no longer be muted 17:20:27 [IanH] q? 17:20:38 [uli] bparsia: have done some testing, am waiting for Robert 17:21:01 [uli] uli: perhaps we should see whether there is some w3c official route and not bother Robert 17:21:23 [uli] bparsia: there are some easy problems, e.g., diagrams not alt-ed correctly 17:21:33 [IanH] q? 17:21:49 [uli] sandro: doesn't know of official w3c 'route' 17:22:15 [uli] bparsia: we could do a proper accessibility audit 17:22:32 [uli] IanH: so action 168 remains on you? 17:22:46 [bparsia] zakim, mute me 17:22:46 [Zakim] bparsia should now be muted 17:22:52 [uli] bparsia: couldn't we move it to a general "to-do" list? 17:22:56 [uli] IanH: ok, will do 17:22:58 [bparsia] agreed 17:23:01 [IanH] q? 17:23:14 [bparsia] works for me 17:23:15 [uli] IanH: action 170 is mooted by events 17:23:33 [IanH] q? 17:23:34 [uli] IanH: action 174? 17:23:37 [bparsia] zakim, unmute me 17:23:37 [Zakim] bparsia should no longer be muted 17:23:52 [bparsia] zakim, mute me 17:23:52 [Zakim] bparsia should now be muted 17:23:53 [uli] bparsia: actually yes, bit also might be mooted shortly 17:23:58 [bparsia] yep 17:24:08 [uli] IanH: ok, so we move it by 1 week 17:24:17 [uli] Topic: Reviewing 17:24:26 [uli] IanH: I saw already some reviews 17:24:32 [m_schnei] yes, thanks for the reviews so far! 17:24:37 [uli] ...anybody else? 17:24:40 [pfps] perhaps the review page could be updated as reviews come in? 17:24:47 [uli] ...reviews are due on september 8, in 5 days 17:24:52 [bmotik] Zakim, mute me 17:24:52 [Zakim] bmotik should now be muted 17:24:57 [IanH] q? 17:25:00 [bmotik] I just muted me 17:25:04 [uli] zakim, mute me 17:25:04 [Zakim] uli should now be muted 17:25:08 [bmotik] myself 17:25:45 [uli] IanH: a slight problem with the profiles document, other docs should be able to be reviewed by september 8 17:25:58 [pfps] q+ 17:26:11 [IanH] q? 17:26:16 [uli] IanH: the SKOS people have their SKOS reference out for last call 17:26:34 [uli] pfps: I have already produced a review for the SKOS semantics document 17:26:48 [uli] IanH: and this is different from the reference? 17:26:49 [m_schnei] only the SKOS ref is in LC 17:26:58 [ivan] 17:27:02 [ivan] SKOS Reference 17:27:14 [IanH] q? 17:27:15 [uli] pfps: forget - I meant powder! 17:27:19 [IanH] ack pfps 17:27:38 [m_schnei] q+ 17:27:42 [uli] IanH: so, volunteers to review LC draft for SKOS reference? 17:27:42 [pfps] -1 17:27:43 [m_schnei] zakim, unmute me 17:27:43 [Zakim] m_schnei should no longer be muted 17:28:15 [m_schnei] zakim, mute me 17:28:15 [Zakim] m_schnei should now be muted 17:28:18 [uli] m_schnei: I started to do a personal look-through, but only with OWL full glasses on, and would prefer to keep it that way 17:28:23 [JeffP] I could try 17:28:23 [ivan] +q 17:28:25 [ivan] q+ 17:28:26 [uli] IanH: anybody else? 17:28:40 [IanH] ack m_schnei 17:28:43 [m_schnei] q- 17:28:51 [IanH] ack ivan 17:28:56 [uli] ivan: the major issue is related to the annotation discussion -- where are we with ours? 17:29:08 [IanH] q? 17:29:14 [m_schnei] but does skos refer to owl 2 at all? 17:29:43 [uli] Ivan: all the rest isn't really complicated, but we should check on issues around annotations 17:30:07 [uli] IanH: ok, I will send emails around to likely suspects 17:30:15 [uli] IanH: F2F4 17:30:18 [m_schnei] true, skos:related and skos:broaderTransitive are intended to be disjoint properties 17:30:30 [uli] Topic: F2F4 17:30:49 [uli] IanH: you need to book early if you want to profit from special rate 17:31:17 [m_schnei] i found a hotel for about 70EUR in the neighbourhood :) 17:31:29 [uli] sandro: 'special rate' is insane, I suggest to look around in the neighbourhood 17:31:47 [uli] IanH: or you can look around on the internet? 17:32:11 [uli] sandro: but then you don't contribute to the meeting room rates 17:32:38 [IanH] 17:32:40 [uli] IanH: and don't forget to register to TPAC 17:32:49 [sandro] s/insane/shockling high, esp in US$/ 17:33:06 [uli] sandro, we can remove all the above 17:33:32 [uli] 17:33:33 [bparsia] Perhaps a link to tpac from the f2f4 page? 17:33:35 [sandro] REGISTER HERE: 17:33:39 [ivan] there is a link on the wiki page, too 17:34:07 [uli] Topic: Issues 17:34:54 [uli] Ian: Issue 131, 141 and 130 seem to be related, a bit more to discuss on 130. 17:34:56 [IanH] q? 17:35:10 [m_schnei] q+ 17:35:14 [m_schnei] zakim, unmute me 17:35:14 [Zakim] m_schnei was not muted, m_schnei 17:35:16 [uli] ...but with the drafts we have in the wiki, perhaps we can resolve 131 and 141 17:35:54 [uli] m_schnei: I am perfectly happy with proposal for 116 17:36:11 [m_schnei] zakim, mute me 17:36:11 [Zakim] m_schnei should now be muted 17:36:24 [uli] IanH: any other opinions? 17:36:38 [Zhe] q+ 17:36:42 [IanH] q? 17:36:44 [m_schnei] q- 17:36:45 [Zhe] zakim, unmute me 17:36:45 [Zakim] Zhe should no longer be muted 17:36:52 [uli] IanH: I have discussed this earlier with Alan, and he seems ok 17:37:02 [uli] i can't hear you, Zhe 17:37:29 [IanH] q? 17:37:36 [IanH] ack zhe 17:37:37 [Zhe] I thought we are waiting for RPI's response on unification idea 17:37:48 [uli] Zhe: I didn't follow this discussion closely 17:38:00 [Zhe] s/Zhe/Jie/g 17:38:37 [bparsia] +1 to move forward and let people react 17:38:38 [uli] IanH: I have discussed these with Jim, and seems to be fine and he will review the document anyway. 17:38:39 [JeffP] reasonable 17:38:53 [uli] sorry, Zhe, baojie, I couldn't tell who was talking 17:39:04 [Zhe] np 17:39:14 [baojie] Uli: was me 17:39:59 [sandro] from my notes "Alan: Close issue-131 by saying we're happy with the current structure of Profiles. There's one semantics for OWL RL, which the OWL Full semantics...." 17:40:22 [uli] PROPOSED: resolve issue 131 and 116 as per Ian's email 17:40:35 [bmotik] +1 17:40:40 [bcuencagrau] +1 17:40:41 [bparsia] +1 17:40:46 [sandro] Sandro: we're still haggling about conformance, which is no longer connected here. 17:40:56 [uli] thanks, sandro 17:41:13 [m_schnei] +1 (FZI) 17:41:33 [pfps] +1 (ALU) 17:41:35 [msmith] +1 17:41:49 [uli] we could be more precise saying "under 1 in Ian's email" 17:41:57 [sandro] +1 (with us being clear that CONFORMANCE is not addressed here) 17:42:01 [IanH] +1 17:42:04 [Zhe] +1 17:42:06 [uli] +1 17:42:16 [baojie] +1 17:42:16 [ivan] +1 17:42:22 [MartinD] +1 17:42:28 [uli] RESOLVED: resolve issue 131 and 116 as per Ian's email 17:42:28 [JeffP] +1 17:43:09 [uli] s/and 116/ 17:43:21 [IanH] q? 17:43:24 [uli] IanH: can we have a similar resolution wrt 116? 17:43:53 [uli] PROPOSED: resolve issue 116 as per Ian's email 17:44:01 [pfps] +1 17:44:02 [bmotik] +1 17:44:09 [sandro] +1 17:44:11 [sandro] :-) 17:44:29 [JeffP] :-) 17:44:35 [ivan] this just makes the point that we really really resolved it 17:44:53 [uli] IanH: rules generating literals in subject position 17:45:06 [IanH] Q? 17:45:10 [IanH] q? 17:45:12 [uli] IanH: issue 141 17:45:13 [Zhe] q+ 17:45:24 [IanH] ack zhe 17:45:28 [uli] IanH: this is already made clear in the document 17:45:57 [ivan] not predicate but subject position 17:46:08 [uli] Zhe: just to make sure: if this "literal in subject position" happens, what do we do? 17:46:42 [uli] IanH: the rule sets works on a generalization of triples 17:46:46 [IanH] q? 17:47:09 [uli] Zhe: what is the best approach to avoid generation of "illegal rfd triples"? 17:47:32 [JeffP] They are triples but not RDF triples 17:47:39 [uli] IanH: we already say in the spec that these are "generalized" triples, so this is ok 17:47:53 [uli] ...and you won't see these since you can't ask for them 17:48:03 [ivan] q+ 17:48:05 [uli] Zhe: I see - so I guess it's fine 17:48:11 [IanH] q? 17:48:13 [ivan] 17:48:14 [IanH] ack ivan 17:48:19 [uli] ivan: editorial 17:48:28 [pfps] As far as the basic conformance is concerned, there is no way to tell if the system is generating these generalized triples. 17:48:50 [uli] ...the above is a note regarding the same problem which could be added to the document 17:49:08 [m_schnei] one implication is that you get with generalized triples every entailment which you got before (without) 17:49:12 [IanH] q? 17:49:44 [uli] PROPOSED: resolve issue 141 as per Peter's email 17:49:46 [pfps] +1, surprise :-) 17:49:46 [JeffP] +1 17:49:48 [bmotik] +1 17:49:48 [bijan] +1 17:49:49 [bcuencagrau] +1 17:49:50 [uli] +1 17:49:52 [IanH] +1 17:49:54 [MartinD] +1 17:49:54 [m_schnei] +1 (FZI) 17:49:58 [ivan] +1 17:50:03 [Zhe] +1 17:50:06 [msmith] +1 17:50:34 [sandro] +1 17:50:38 [baojie] +1 17:51:03 [uli] RESOLVED: resolve issue 141 as per Peter's email 17:51:22 [IanH] q? 17:51:33 [IanH] q? 17:51:35 [uli] IanH: for issue 130, we have a proposal 17:51:39 [IanH] q? 17:51:49 [sandro] q+ 17:51:53 [IanH] q? 17:52:05 [uli] IanH: so, can we resolve it like this next week? 17:52:06 [bmotik] Zakim, mute me 17:52:06 [Zakim] bmotik was already muted, bmotik 17:52:52 [uli] sandro: I still see the issue that Michael raised, and I would like a simple solution to this 17:52:56 [IanH] q? 17:52:59 [uli] sandro, which problem is this? 17:53:04 [m_schnei] q+ 17:53:08 [sandro] ack sandro 17:53:45 [IanH] ack sandro 17:54:04 [uli] IanH: perhaps sandro has overlooked the precise meaning of this, i.e., that reasoners cannot flip flop between answers 17:54:28 [m_schnei] zakim, unmute me 17:54:28 [Zakim] m_schnei should no longer be muted 17:54:29 [uli] sandro: perhaps the problem isn't so bad 17:54:32 [IanH] q? 17:54:38 [IanH] ack m_schnei 17:54:47 [uli] m_schnei: all I wanted with my remark was to explicate this 17:54:51 [sandro] q? 17:54:54 [uli] m_schnei, what? 17:55:12 [sandro] m_schnei: I just wanted it documented 17:55:32 [IanH] q? 17:55:37 [m_schnei] m_schnei: I want to clarify that I just want to have this conformance behaviour made explicit, I do *not* deny this 17:55:59 [uli] IanH: we should say that, all conformant systems should always agree on their answer 17:56:17 [uli] sandro: what about negative entailments? 17:56:32 [uli] ...do we need another reasoner for this? 17:56:37 [IanH] q? 17:56:53 [IanH] q? 17:57:15 [IanH] q? 17:57:26 [m_schnei] you cannot always say from "false" that the converse is true, in particular not under OWA 17:57:36 [IanH] q? 17:57:39 [uli] sandro: oracle wasn't interested in negative/theorem 1 checks 17:57:50 [sandro] Sandro: Are people going to implement the theorem-1 check? 17:57:53 [uli] Zhe: flexibility for user is a good thing 17:58:30 [uli] Zhe: it will be difficult to tell which rules are bottleneck, so theorem 1 check could be useful 17:58:51 [IanH] q? 17:58:57 [uli] Zhe: I don't know yet what exactly we will implement, but we may implement it 17:59:28 [bijan] SHOULD! 17:59:28 [uli] IanH: for the test, should we strengthen 'may' to 'should'? 17:59:34 [IanH] q? 17:59:37 [ivan] q+ 17:59:58 [sandro] ack ivan 18:00:18 [IanH] q? 18:00:27 [bijan] I'll call at MUST 18:00:33 [uli] ivan: I would prefer 'may' since otherwise the implementor load is too high 18:01:04 [bijan] zakim, unmute me 18:01:04 [Zakim] sorry, bijan, I do not know which phone connection belongs to you 18:01:14 [ivan] q+ 18:01:16 [bparsia] q+ 18:01:17 [uli] sandro: we shouldn't allow reasoners to say 'false' unless it's really false 18:01:19 [IanH] q? 18:01:36 [bparsia] zakim, unmute me 18:01:36 [Zakim] bparsia should no longer be muted 18:01:39 [m_schnei] zhe, even if you only implement a /partial/ /forward/ chainer, then you have an implicit entailment checker: just look in the resulting inference graph and only say "yes", if some entailment is in, and say "no" otherwise 18:01:39 [uli] ...call that part 'must' and otherwise, use 'unknown' 18:01:42 [bparsia] +1 to sandro's must proposal 18:02:03 [sandro] sandro: How about you MUST do theorem-1 checking before returning FALSE, BUT you can return UNKNOWN if you don't want to do that checking. 18:02:27 [bparsia] zakim, mute me 18:02:27 [Zakim] bparsia should now be muted 18:02:38 [uli] bparsia: I like sandro's suggestion - having this check available will enhance interoperability, and the 'unknown' option is a good compromise 18:02:57 [IanH] q? 18:03:03 [ivan] ack bparsia 18:03:12 [IanH] ack ivan 18:03:16 [uli] IanH: but if we change to "must", then we must explain what implementors could do who wouldn't want to implement the test 18:03:42 [sandro] sandro: absolutely -- we need text here which makes sense to people without thinking it all through at this level. 18:03:54 [IanH] q? 18:03:57 [IanH] q? 18:04:03 [uli] ivan: from Zhe's presentation in Manchester, how would the 'must' work with this? 18:04:04 [Zhe] q+ 18:04:35 [uli] IanH: tricky since we talk about entailments, but we are also interested in queries 18:04:36 [IanH] q? 18:04:44 [IanH] ack zhe 18:04:52 [uli] ...so a false is then a 'no, it's really not in the query' 18:04:55 [sandro] Ian: in real life, people do query answering. so the "false" is kind of like not answering the query. 18:05:22 [uli] Zhe: I would prefer 'may' since 'should' or 'must' would be a burden 18:05:41 [uli] IanH: but sandro's proposal also allow you to return 'unknown' 18:06:08 [uli] ...and this gives us more honesty: 'false' really means false! 18:06:14 [IanH] q? 18:06:15 [bparsia] q+ 18:06:28 [bparsia] (to answer this) 18:06:32 [bparsia] zakim, unmute me 18:06:32 [Zakim] bparsia was not muted, bparsia 18:06:36 [IanH] q? 18:06:36 [uli] Zhe: but in a forward chaining system, where could be return such an 'unknown'? 18:06:39 [IanH] ack bparsia 18:06:48 [sandro] ack bparsia 18:07:14 [uli] bparsia: on load time, or in the query 18:07:15 [IanH] q? 18:07:39 [uli] sandro: so, user asks query 'q', and didn't get a certain result 18:08:07 [uli] ...does this mean that rules couldn't find this result or that it shouldn't be in answer? 18:08:10 [IanH] q? 18:08:14 [m_schnei] q+ 18:08:26 [uli] Zhe: but how would 'unknown' be helpful there? 18:08:27 [IanH] q? 18:09:07 [sandro] sandro: on query results, systems should include a flag saying whether complete reasoning was done or not. that's the equivalent of this false/unknown thing in the conformance definition. 18:09:09 [uli] bparsia: with SPARQL owl, i looked at racerPro and Sher, and there it is important as well to have a mechanism to indicate to the user how complete you are 18:09:24 [m_schnei] zakim, unmute me 18:09:24 [Zakim] m_schnei was not muted, m_schnei 18:09:24 [IanH] q? 18:09:29 [bparsia] zakim, mute me 18:09:29 [Zakim] bparsia should now be muted 18:09:34 [IanH] ack m_schnei 18:09:38 [IanH] q? 18:10:05 [uli] m_schnei, I can't understand you 18:10:52 [sandro] m_schnei: you have to at least implement the full ruleset, and have it not FOL entailed, before you can return FALSE 18:10:55 [uli] heavy breathing 18:11:14 [sandro] (I have a response to m_schnei, but .... maybe I'll save it.) 18:11:45 [IanH] q? 18:11:51 [uli] IanH: using 'unknown' would be a mechanism to indicate to the user that the results to a query may be partial 18:12:06 [uli] Zhe: i don't see the additional valie 18:12:10 [uli] s/valie/value 18:12:26 [bparsia] q+ 18:12:31 [IanH] q? 18:12:33 [uli] IanH: it prevents implementors from having unsound systems and calling them conformant 18:12:34 [m_schnei] m_schnei: you are only allowed to say "False", if the entailment does not exist w.r.t. the /complete/ ruleset. so the NULL reasoner is not allowed. An implementer MAY go beyond the whole ruleset, up to the complete full semantics 18:13:03 [bparsia] zakim, unmute me 18:13:03 [Zakim] bparsia should no longer be muted 18:13:17 [uli] sandro: I would like to have a flag that distinguishes complete from incomplete reasoners 18:13:40 [uli] sandro: but can any OWL RL rule implementation ever be conformant? 18:13:53 [m_schnei] the /ruleset/ is the lower bound of RL conformance 18:13:58 [IanH] q? 18:14:08 [uli] IanH: sure - they are *sound*, we only talk about non-entailments, cases where things are *not* returned 18:14:16 [IanH] q? 18:14:19 [IanH] ack bparsia 18:14:25 [uli] sandro: and then you could use theorem 1 to find complete cases 18:14:31 [m_schnei] btw, if the ruleset entails something, then you can savely say "True", because then OWL Full would produce the same entailment 18:14:49 [sandro] ian: Theorem 1 gives you the completeness guarantee -- it says that if the ontology looks like this, complete-rule-reasoning is complete-ontology-reasoning. 18:15:08 [uli] bparsia: users from bioontology really value complete reasoning, and so we should be able to signal this 18:15:35 [ivan] q+ 18:15:37 [bparsia] zakim, mute me 18:15:37 [Zakim] bparsia should now be muted 18:15:39 [IanH] q? 18:15:41 [uli] IanH: let's take the discussion on-line, implement the suggested modifications and discuss next week 18:15:57 [sandro] q+ to ask if query answering should be covered in Conformance 18:16:07 [sandro] q- ivan 18:16:12 [uli] ivan: i would still like to see the consequences for an implementation being written down 18:16:27 [IanH] q? 18:16:32 [IanH] ack sandro 18:16:32 [Zakim] sandro, you wanted to ask if query answering should be covered in Conformance 18:16:47 [Zhe] q+ 18:17:01 [uli] sandro: let's write it down - but where do we write about query answering? In the conformance document? 18:17:04 [IanH] ack zhe 18:17:21 [bparsia] I'd be open to flagging it as "depeding on implementor feedback" 18:17:33 [bparsia] I'd rather have the stronger and weaken, then do the weaker and then strengthen 18:18:02 [uli] IanH: the tricky bit is the dependency between profiles and conformance 18:18:04 [bparsia] zakim, unmute me 18:18:04 [Zakim] bparsia should no longer be muted 18:18:10 [IanH] q? 18:18:28 [uli] ...we can't review profiles before we fixed conformance 18:18:53 [bparsia] zakim, mute me 18:18:53 [Zakim] bparsia should now be muted 18:19:03 [uli] bparsia: why don't we make conformance really strict (so that poking holes in it is easier) and then review them together 18:19:07 [IanH] q? 18:19:16 [uli] sandro: who updates the draft? 18:19:38 [uli] ACTION: IanH to update the conformance document with 'unkown' 18:19:38 [trackbot] Sorry, couldn't find user - IanH 18:20:12 [IanH] q? 18:20:29 [bparsia] zakim, unmute me 18:20:29 [Zakim] bparsia should no longer be muted 18:20:31 [m_schnei] I already saw the distinct "ox" namespace in the POWDER semantics ;-) 18:21:07 [uli] Topic: Issue 109 18:21:22 [IanH] q? 18:21:36 [uli] bparsia: it would be good to not have to change namespaces 18:22:11 [IanH] q? 18:22:22 [uli] sandro: can we have a pointer to this 18:22:26 [bparsia] zakim, mute me 18:22:26 [Zakim] bparsia should now be muted 18:22:59 [bmotik] q+ 18:23:01 [bmotik] Zakim, unmute me 18:23:01 [Zakim] bmotik should no longer be muted 18:23:03 [uli] Topic: issue 138 18:23:06 [IanH] ack bmotik 18:23:28 [ivan] q+ 18:23:29 [msmith] q+ 18:23:29 [bmotik] Zakim, mute me 18:23:30 [IanH] q? 18:23:30 [uli] bmotik: let's use owl:datetime since the datatype is different from the xsd one 18:23:31 [Zakim] bmotik should now be muted 18:23:32 [bparsia] +1 to boris 18:23:58 [uli] ivan: [procedural] didn't we want to ask xsd people about that? 18:24:23 [uli] IanH: didn't sandro want to edit this message from peter? 18:24:36 [pfps] Sandro sent a message, but didn't ask for any action. 18:24:53 [pfps] I'm willing to edit the document, I guess. 18:25:07 [pfps] ?? 18:25:16 [IanH] q? 18:25:19 [uli] IanH: I observe confusion -- pfps, can you edit the mail and send it? 18:25:25 [uli] ...to make it more punchy? 18:25:27 [ivan] ack ivan 18:25:39 [uli] sandro: it should say more clearly what they should do. 18:25:42 [msmith] q? 18:25:52 [IanH] q? 18:26:08 [IanH] q? 18:26:09 [uli] IanH: would their answer have any influence of what we do about datetime namespace 18:26:13 [IanH] ack msmith 18:26:49 [uli] msmith: bmotik convinced me that xsd and owl datetime are really different, so perhaps we don't need to waste time by asking them? 18:26:52 [bparsia] +1 18:26:52 [IanH] q? 18:27:01 [bmotik] It already is owl:dateTime. 18:27:02 [IanH] q? 18:27:05 [pfps] +epsilon 18:27:07 [uli] IanH: so msmith suggest to just go ahead with owl:datetime? 18:27:17 [bmotik] I used owl:dateTime in anticipation of this discussion. There is an editorial comment about it. 18:27:24 [pfps] OK by me 18:27:30 [uli] ivan: we should keep the issue open, but use owl:datetime 18:27:40 [bmotik] q+ 18:27:43 [bmotik] Zakim, unmute me 18:27:43 [Zakim] bmotik should no longer be muted 18:27:44 [IanH] q? 18:27:49 [IanH] ack bmotik 18:27:49 [sandro] ack bmotik 18:28:04 [bmotik] Zakim, mute me 18:28:04 [Zakim] bmotik should now be muted 18:28:21 [pfps] +1 18:28:23 [uli] bmotik: we already use owl:datetime, so we can't do anything else on this now 18:28:33 [uli] IanH; AOB? 18:28:33 [Zhe] q+ 18:28:41 [IanH] q? 18:28:47 [IanH] ack Zhe 18:28:54 [uli] Zhe: i want to open an issue about base triples? 18:29:16 [uli] IanH: you raised it, and it is now open, and we can discuss this next week 18:29:24 [uli] IanH: AOB? 18:29:28 [JeffP] thanks, bye 18:29:32 [Zakim] -bmotik 18:29:33 [Zhe] bye 18:29:33 [uli] meeting is closed, thanks 18:29:33 [Zakim] -msmith 18:29:35 [IanH] bye 18:29:36 [Zakim] -JeffP 18:29:37 [Zakim] -Peter_Patel-Schneider 18:29:37 [Zakim] -Zhe 18:29:37 [msmith] msmith has left #owl 18:29:38 [Zakim] -bparsia 18:29:39 [Zakim] -bcuencagrau 18:29:40 [Zakim] -IanH 18:29:41 [Zakim] -uli 18:29:41 [Zakim] -baojie 18:29:41 [sandro] thanks, Ian. :-) 18:29:43 [Zakim] -ivan 18:29:49 [Zakim] -m_schnei 18:29:51 [Zakim] -MartinD 18:29:57 [MartinD] MartinD has left #OWL 18:30:04 [uli] sandro, ivan, can you please invoke the magic command? 18:30:18 [sandro] Ian is good at it these days. 18:30:32 [uli] Ian, could you please invoke the magic command? 18:30:55 [uli] could somebody... please...? 18:31:06 [IanH] I did it already 18:31:10 [IanH] at the beginning 18:31:16 [uli] ah, thanks! 18:31:35 [IanH] If you look at the scribe conventions page you will see what you have to do next :-) 18:31:59 [IanH] Let me know if you need help. 18:32:03 [uli] oups - didn't know it moved there 18:32:31 [IanH] It tells you how to convert the chat log into minutes using Sandro's new software tool 18:33:20 [IanH] The magic command that I issues was to make the chat log public 18:34:21 [uli] Wrong Credential 18:34:21 [uli] ...the irc log says: "Sorry, a password is required" 18:34:37 [uli] and "Sorry, Insufficient Access Privileges" 18:59:40 [ivan] ivan has left #owl 18:59:53 [Zakim] -Sandro 18:59:55 [Zakim] SW_OWL()1:00PM has ended 18:59:56 [Zakim] Attendees were msmith, Peter_Patel-Schneider, +0190827aaaa, MartinD, uli, IanH, Sandro, bcuencagrau, JeffP, bmotik, ivan, baojie, Zhe, m_schnei, bparsia 19:00:48 [sandro] RRSAgent, pointer? 19:00:48 [RRSAgent] See 19:01:05 [sandro] Sorry, Uli. Back now. Still stuck? 19:33:44 [IanH] I sorted it. 19:34:26 [IanH] And sent Uli an email. 19:50:20 [sandro] thanks 20:31:19 [Zakim] Zakim has left #owl 21:00:03 [alanr] alanr has joined #owl 21:07:39 [alanr] alanr has left #owl 21:09:17 [alanr] alanr has joined #owl
http://www.w3.org/2008/09/03-owl-irc
CC-MAIN-2015-18
refinedweb
6,170
72.8
Step by step using Typescript (TS) in Express (Node.js) Project In this tutorial, you will learn how to use Typescript(TS) in Express (Node.js) project. Requirements: - Basic knowledge in Typescript (TS), Node.js and Express - Having a Node version from v12 upwards, including Node 12. 1. Set up the project The first step is to create a directory for the project and initialise it. Run the following commands to create an empty directory called express-nodejs-ts, and change the current directory to it: mkdir express-nodejs-ts cd express-nodejs-ts Now that you are in the express-nodejs-ts directory, you have to initialise the Node project. To do so, run the following command: npm init -y Using the -y flag in the above command generates the package.json file with the default values. Instead of adding information like the name and description of the project ourselves, npm initialises the file with default values. The project is initialised, and thus you can move to the next section — adding the project dependencies. 2. Add dependencies The next step is to add the project dependencies (Express and Typescript) by running the following commands: npm install express npm install typescript ts-node @types/node @types/express --save-dev Why save everything Typescript-related as devDependencies? Even though you write the code using Typescript, the code gets compiled back to vanilla JavaScript. Typescript is not needed per se to run the application. Thus, since Typescript is used only by developers, it's saved as a dev dependency. Moving forward, your package.json should look as follows after installing all the dependencies: { "name": "express-nodejs-ts", "version": "1.0.0", "description": "Express project with TypeScript", customise the Typescript configuration. The newly created file contains lots of code, most of which is commented out. However, there are some settings you need to know about: - target -> using this option, you can specify which ECMAScript version to use in your project. For instance, if you set the targetto ‘none’, ‘commonjs’, ‘amd’, ‘system’, ‘umd’, ‘es2015’, ‘es2020’, or ‘ESNext’. The most common module manager and the default one is commonjs. - outDir -> with this option, we can specify where to output the vanilla JavaScript code. - rootDir -> the option specifies where are the TypeScript files located. - strict -> the option is enabled by default, and it enables strict type-checking options. - esModuleInterop -> this option is true by default, and it enables interoperability between CommonJS and ES modules. How does it do it? It does it by creating namespace objects for all imports. For in-depth information about all the options available, I recommend checking the TypeScript TSConfig Reference. 4. Create Express server With TypeScript configured, it’s time to create the Express web server. First of all, create the file index.ts (attention to the file extension) by running touch index.ts. After creating the file, write the following code inside: import express from 'express';const app = express();app.get('/', (req, res) => { res.send('Hello World - here an Express project with TS'); });app.listen(8000, () => { console.log('The application is listening on port 3000!'); }); Now you have a simple web server that shows “Well done!” when you access localhost:8000. The server is super simple, and without taking advantage of TypeScript. However, the purpose of this tutorial is to make the technologies work together and create a boilerplate. From here, you can build any application you want. Whenever you make changes and want to run the application, you need to compile TypeScript to vanilla JavaScript. To do that, you need to run: npx tsc --project ./ The command tsc compiles TypeScript to JavaScript. The flag --project specifies from where to pick the TS files. Lastly, ./specifies the root of the project. If you go into the build folder, you should see the compiled JavaScript code. That is, the code compiled from the TypeScript code you wrote. However, we can simplify the process a little bit, and you will see how in the next section. 5. Create scripts It can be tedious to write npx tsc --project ./ each time you want to compile your code. As a result, we can add a script in package.json to make the process easier. Add the following line of code in package.json under scripts: "build": "tsc --project ./" The final package.json should be like this: { "name": "express-nodejs-ts", "version": "1.0.0", "description": "Express project with TypeScript", "main": "index.js", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "@types/express": "^4.17.9", "@types/node": "^14.14.20", "ts-node": "^9.1.1", "typescript": "^4.1.3" }, "scripts": { "build": "tsc --project ./", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } Now you can run npm run build to compile your code. This way, it's simpler and quicker. Conclusion In this tutorial, you learnt how to create a TypeScript + Node.js + Express boilerplate. This is just the tip of the iceberg, so you can build any application you want from here. or you can use the boilerplate bellow
https://themeptation.medium.com/step-by-step-using-typescript-ts-in-express-node-js-project-fdd354433a4f?source=post_page-----fdd354433a4f-----------------------------------
CC-MAIN-2022-21
refinedweb
837
68.57
Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also #include <xti.h> int t_rcv(int fd, void *buf, unsigned int nbytes, int *flags); This function is part of the XTI interfaces which evolved from the TLI interfaces. XTI represents the future evolution of these interfaces. However, TLI interfaces are supported for compatibility. When using a TLI function that has the same name as an XTI function, the tiuser.h header file must be used. Refer to the TLI COMPATIBILITY section for a description of differences between the two interfaces. by means of t_open(3NSL) by means of the EM interface. On successful completion, t_rcv() returns the number of bytes received. Otherwise, it returns -1 on failure and t_errno is set to indicate the error. T_DATAXFER, T_OUTREL. On failure, t_errno is set to one of the following:: fcntl(2), t_getinfo(3NSL), t_look(3NSL), t_open(3NSL), t_snd(3NSL), attributes(5), standards(5) Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also
http://docs.oracle.com/cd/E19253-01/816-5170/6mbb5et63/index.html
CC-MAIN-2017-13
refinedweb
167
57.06
Math::BaseConvert - fast functions to CoNVert between number Bases This documentation refers to version 1.8 of Math::BaseConvert, which was released on Thu Apr 14 2016. use Math::BaseConvert; # CoNVert 63 from base-10 (decimal) to base- 2 (binary ) $binary_63 = cnv( 63, 10, 2 ); # CoNVert 111111 from base- 2 (binary ) to base-16 (hex ) $hex_63 = cnv( 111111, 2, 16 ); # CoNVert 3F from base-16 (hex ) to base-10 (decimal) $decimal_63 = cnv( '3F', 16, 10 ); print "63 dec->bin $binary_63 bin->hex $hex_63 hex->dec $decimal_63\n"; BaseConvert> fine Math::BaseCalc module. The reason I created BaseConvert was that I needed a simple way to convert quickly between the 3 number bases I use most (10, 16, && 64). It turned out that it was trivial to handle any arbitrary number base that is represented as characters. High-bit ASCII has proven somewhat problemmatic but at least BaseConvert can simply && realiably convert between any possible base between 2 && 64 (or 85). I'm happy with && $from are provided as parameters: cnv() assumes that $numb is already in decimal format && uses $from as the $tobs. When all three parameters are provided: The normal (&& most clear) usage of cnv() is to provide all three parameters where $numb is converted from $from base to $tobs. cnv() is the only function that is exported from a normal 'use Math::BaseConvert;' command. The other functions below can be imported to local namespaces explicitly or with the following tags: :all - every function described here :hex - only dec() && hex() :b64 - only b10() && b64() && b64sort() && cnv() :dig - only dig() && diginit() :sfc - only summ(), fact(), &&). Please read the "NOTES" regarding hex(). Assign the new digit character list to be used in place of the default one. dig() can also alternately accept a string name matching one of the following predefined digit sets: 'bin' => ['0', '1'] 'oct' => ['0'..'7'] 'dec' => ['0'..'9'] 'hex' => ['0'..'9', 'a'..'f'] 'HEX' => ['0'..'9', 'A'..'F'] 'b62' => ['0'..'9', 'a'..'z', 'A'..'Z'] 'b64' => ['0'..'9', 'A'..'Z', 'a'..'z', '.', '_'] 'm64' => ['A'..'Z', 'a'..'z', '0'..'9', '+', '/'] # MIME::Base64 'iru' => ['A'..'Z', 'a'..'z', '0'..'9', '[', ']'] # IRCu 'url' => ['A'..'Z', 'a'..'z', '0'..'9', '*', '-'] # URL 'rex' => ['A'..'Z', 'a'..'z', '0'..'9', '!', '-'] # RegEx 'id0' => ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] # ID 0 'id1' => ['A'..'Z', 'a'..'z', '0'..'9', '.', '_'] # ID 1 'xnt' => ['A'..'Z', 'a'..'z', '0'..'9', '.', '-'] # XML Nmtoken 'xid' => ['A'..'Z', 'a'..'z', '0'..'9', '_', ':'] # XML ID Name 'b85' => ['0'..'9', 'A'..'Z', 'a'..'z', '!', '#', # RFC 1924 for '$', '%', '&', '(', ')', '*', '+', '-', # IPv6 addrs ';', '<', '=', '>', '?', '@', '^', '_', # like in '`', '{', '|', '}', '~' ] # Math::Base85 summation of $numb down to 1. A simple function to calculate a memoized factorial of $numb. A simple function to calculate a memoized function of $ennn choose $emmm. The Perl builtin hex() function takes a hex string as a parameter && returns the decimal value (FromBase = 16, ToBase = 10) but this notation seems counter-intuitive to me since a simple reading of the code suggests that a hex() function will turn your parameter into hexadecimal (i.e., It sounds like Perl's hex() will hexify your parameter but it does not.) so I've decided (maybe foolishly) to invert the notation for my similar functions since it makes more sense to me this way && will be easier to remember (I've had to lookup hex() in the Camel book many times already which was part of the impetus for this module... as well as the gut reaction that sprintf() is not a proper natural inverse function for hex()). This means that my b64() function takes a decimal number as a parameter && returns the base64 equivalent (FromBase = 10, ToBase = 64) && my b10() function takes a base64 number (string) && returns the decimal value (FromBase = 64, ToBase = 10). My hex() function overloads Perl's builtin version with this opposite behavior so my dec() function behaves like Perl's normal hex() function. I know it's confusing && maybe bad form of me to do this but I like it so much better this way that I'd rather go against the grain. Please think of my dec() && hex() functions as meaning decify && hexify. Also the pronunciation of dec() is 'dess' (!'deck' which would be the inverse of 'ink' which -- && ++ already do so well). After reading the informative Perl module etiquette guidelines, I now appreciate the need to export as little as is necessary by default. So to be responsible, I have limited BaseConvert exporting to only cnv() under normal circumstances. Please specify the other functions you'd like to import into your namespace or use the tags described above in the cnv() section like: 'use Math::BaseConvert qw(:all !:hex);' Error checking is minimal. This module does not handle fractional number inputs because I like using the dot (.) character as a standard base64 digit since it makes for clean filenames. summ(), fact(), && choo() are general Math function utilities which are unrelated to number-base conversion but I didn't feel like making another separate module just for them so they snuck in here. I hope you find Math::BaseConvert useful. Please feel free to e-mail me any suggestions or coding tips or notes of appreciation ("app-ree-see-ay-shun"). Thank you. TTFN.() &&-gen (&&>)
http://search.cpan.org/dist/Math-BaseConvert/lib/Math/BaseConvert.pm
CC-MAIN-2016-44
refinedweb
866
63.9
from mojo.canvas import Canvas A vanilla object that sends all user input events to a given delegate. Canvas(posSize, delegate=None, canvasSize=(1000, 1000), acceptsMouseMoved=False, hasHorizontalScroller=True, hasVerticalScroller=True, autohidesScrollers=False, backgroundColor=None, drawsBackground=True) Methods All events a delegate could have that can be used: - draw() Callback when the canvas get drawn. - becomeFirstResponder(event) Callback when the canvas becomes the first responder, when it starts to receive user interaction callbacks. - resignFirstResponder(event) Callback when the canvas resigns the first responder, when the canvas will not longer receive user interaction callbacks. - mouseDown(event) Callback when the user hit the canvas with the mouse. - mouseDragged(event) Callback when the user drag the mouse around in the canvas. - mouseUp(event) Callback when the user lifts up the mouse from the canvas. - mouseMoved(event) Callback when the user moves the mouse in de canvas. Be careful this is called frequently. (only when accepsMouseMoved is set True) - rightMouseDown(event) Callback when the user clicks inside the canvas with the right mouse button. - rightMouseDragged(event) Callback when the users is dragging in the canvas with the right mouse button down. - rightMouseUp(event) Callback when the users lift up the right mouse button from the canvas. - keyDown(event) Callback when the users hits a key. The event object has a characters() method returns the pressed character key. - keyUp(event) Callback when the users lift up the key. - flagChanged(event) Callback when the users changed a modifier flag: command shift control alt Example from mojo.canvas import Canvas from mojo.drawingTools import * from vanilla import * class ExampleWindow: def __init__(self): self.size = 50) ExampleWindow()
http://doc.robofont.com/api/mojo/mojo-canvas/
CC-MAIN-2017-30
refinedweb
269
50.02
On Tue, Feb 18, 2003 at 09:45:44PM +0200, Dmitry Litovchenko wrote: > I certainly need a brief sample of how to use reactor.connectWith and > how to set up Protocol so that it correctly switches to another > Protocol and initializes it. > > Example with: > > self.__class__ = anotherProto.__class__ > self.connectionMade() You're probably better off proxying through to the other Protocol. Changing __class__ is horrible because the two classes may have conflicting assumptions about the self namespace. I don't know anything about connectWith, though. I think there's some other code somewhere in Twisted where one Protocol wraps another.. Anyone remember where? -- Twisted | Christopher Armstrong: International Man of Twistery Radix | Release Manager, Twisted Project ---------+
http://twistedmatrix.com/pipermail/twisted-python/2003-February/002996.html
CC-MAIN-2016-30
refinedweb
115
51.04
editfile Normal Usage Usage: EDITFILE_NAME [CATEGORY] [OPTIONS] default operation is to edit the file Options: -h this help -a append stdin to the file -l output the file to stdout -f output file path name to stdout -s <pattern> search for given pattern -t time track mode -c <name> copy the given item to the new name -i import [FILEPATH] -x export to [FILEPATH.tar] -d delete the file (Note these options are mutually exclusive) The key thought behind editfile is that a user shouldn't have to specify two words ('edit', 'this file') when editing regularly used files, but rather just a simple declaration ('notes', 'todo', etc). Obviously there are limits to this approach with the flat(ish) namespace of commands in the path, but I have found it helpful. Two things change it from a curiosity to something useful for me: - syncing across devices (via Dropbox) - not having to worry about where I am in the path -or where the target file - is means I use it all the time As a concession to complexity, it provides a two-level deep hierarchy, where for each command, a category can also be given (though isn't necessary). Examples These assume 'notes', 'todo', 'track' and 'blog' are editfile commands: # start editing the file associated with the 'notes' command $ notes # -a reads from stdin and appends to the file $ echo "This will be appended to the end of the notes files" | notes -a # -l dumps the file to standard output $ notes -l > notes.backup # editfile uses 'EDITOR' if defined, with gedit and vim as fallbacks # edit the 'errands' file in the notes namespace with emacs $ EDITOR=emacs notes errands $ notes errands -l # output content of the 'errands' category to stdout $ blog editfile -f /home/ben/Dropbox/editfile/blog/editfile.md # append content of 'todo' to 'notes/errands' $ todo -l | notes errands -a # can be given .rst or .md extension to override .txt default $ blog first-post.md # edit two different things at once, sort of bypassing editfile :-) vim $(notes -f) (work planning -f) # once file exists, extension is optional (priority: .rst, .md, .txt) $ blog first-post # will edit first-post.md # Copy the top level notes to a new editfile command 'jottings'. # Note if 'notes' has any sub categories, these are *not* copied in this # operation. $ notes -c jottings # Copy a sub-category, can be used as (very) primitive versioning... $ blog first_draft -c second_draft $ notes 2016_plan -c 2016_review # using -t enters a mode where the user is prompted with date and time # and enters text interactively. This is stored in the target file as # well as being entered in a readline history file. Ctrl-D to exit. $ track -t 2012/05/09 11:03 >> Add a new widget class to the WidgetFactory 2012/05/09 11:03 >> ^D # Deleting a note (this moves to a trash folder which will be displayed) $ notes 2016_plan -d Moved ~/Dropbox/editfile/notes/2016_plan.txt to trash: ~/Dropbox/editfile/trash/notes # moving a note from one 'base' to another $ notes super_secret_project -l | work super_secret_project -a $ notes super_secret_project -d # search through the given note for 'password' $ notes secret_project -s password ... File & folder layout editfile contains a hardcoded Dropbox path, '~/Dropbox/editfile', which it assumes is a sensible place to put things. The script currently needs editing if this isn't appropriate. When using a single level editfile command (e.g. 'notes' is a symlink to editfile and is run simply as 'notes'), the system will look for a file of this same name (with appropriate extension - see following) under ~/Dropbox/editfile/, and take the appropriate action (edit, list, append). When a second label is given after the command, then the file acted upon is instead under ~/Dropbox/editfile/<commandname>/, with its file name being the second label. Originally editfile always used '.txt' as the file extension appended to the appropriate command / label, but I've found that I want to use editfile for writing blog posts and code documentation, so ReStructured Text (.rst) and Markdown (.md) file extensions are also supported. When no file exists already, then .txt will be created unless an extension is specified. For existing files, if no extension is given then the first match in .rst, .md, .txt will be used. If more than one of these exists then it is up to the user to sort things out. Examples Tab Completion A tab-completion expander script is also provided as editfile-complete.sh, which needs sourcing in an appropriate place in the shells where it is to be used. This provides expansion of second level items under each editfile command. For example, notes <tab> above would result in a completion containing at least testing. This is a useful way of checking which sub-files exist for each editfile command. If options (-a, -l, -f) are given, these should be provided after the category (if it exists). 'Track' mode Using the -t option enters the 'time track' mode. In this mode, editfile enters a readline loop, where entered text is saved to the target file with a timestamp. In this mode, shell commands can be given by preceding them with '!'. A single exclamation mark simply runs the command; double '!!command' inserts the result into the target file. In addition, if a line is entered incorrectly then it can be replaced by prefixing the next entry with the '^' character, e.g. 2013/03/18 20:11 >> this is a 2013/03/18 20:11 >> ^this is a test will result in just a single line 'this is a test' being stored. Note that this functionality needs to edit the current file, so for safety a backup file is used to perform this operation, which will have the same name as the file being edited with a suffix of '~' - the same format emacs uses. Storing assets editfile is about reducing the friction in being able to write. No need to think about where the document ends up, no need to go through a long startup procedure when making a new document. And more. So in writing more, I found my next use-case is being able to store non-text data alongside the text. Ideally I'd like to be able to include a highly efficient DSL which creates SVG diagrams in all my documents, but I've not yet found anything ideal; blockdiag comes close, but I want something which is already right in it's default styling, and blockdiag isn't that, for me. Anyway, sometimes a diagram isn't enough anyway, and I need a photo, or a piece of music. Or some other binary file. Importing a file $ blog a-wonderful-blog-post -i ~/photo1.jpg $ blog a-wonderful-blog-post -i ~/photo2.jpg Exporting bundles $ blog a-wonderful-blog-post -x ~/blog-post.tar Exporting content TODO... Creating blank documents editfile can be used for more than just creating text documents. If given a fully-qualified basename + extension, it can be used as a document launcher. For example, with a editfile category of 'work', the command 'work super-secret-project.odt' would start libreoffice running. The currently supported document formats are as follows: (Note soffice may refer to libreoffice, openoffice, or even the original staroffice - like sensible forks, they can all use the same command name) Direct use of 'editfile' The normal use of editfile is via the commands symlinked to it, however by running editfile directly as a command, these symlinks can be managed. There are three options: Default installation Other than its dependency on a basic POSIX system running Bash, editfile assumes two other things: - a writable dropbox folder lives in ~/Dropbox (~/Dropbox/editfile/ is used) - editfile and appropriately named symlinks to it live in ~/bin or elsewhere in the PATH (somewhere writable is useful for editfile -n etc) Example installation Copy editfile to ~/bin, ensure it is executable. Create symlinks as appropriate to it in the same place, either directly or via the editfile -n command: $ editfile -n notes $ editfile -n today $ editfile -n blog $ editfile -n todo or: $ pwd /home/users/ben/bin $ ln -s editfile notes $ ln -s editfile today $ ln -s editfile blog $ ln -s editfile todo Ben Bass 2012-2017 @Ben Bass
https://bitbucket.org/codedstructure/editfile/src
CC-MAIN-2017-51
refinedweb
1,369
59.53
My previous post, Sequelize CRUD 101, covered the very basics of CRUD using the Node ORM, Sequelize. This post will cover two intermediate sets of concepts: - Querying multiple columns using a query object. - Creating, updating and deleting multiple records. You'll benefit from having an SQL database running locally (preferably PostgreSQL), and cloning the repo that goes with this post. The repo for this post extends that of my Sequelize 101 post, so please refer to my prior post for a walk through of the folder structure and code. READ: Returning a subset of data Before getting into complex querying, let's ease into Sequelize with something fairly basic - returning a subset of data. For example, imagine we have a table of pet information - owner names, ids, addresses, medical history, etc. - but we only want to return names and types from our query. Sequelize has an attributes option that allows us to declare which columns we want returned. db.pets.findAll({ attributes: ['name', 'type'], where: { city: 'Los Angeles' } }) .then(pets => { console.log(pets); }); The above query will return all pets with the city 'Los Angeles', but will only return the name and breed or each pet. Supposing there only two pets with 'Los Angeles' as their city, the JSON response would look something like this: [ { "name": "Max", "type": "cat" }, { "name": "Penelope", "type": "dog" } ] READ: Querying multiple columns Basic search functionality is a common feature of APIs, so let's build a search endpoint for our API. The following is an example of query that lets us search for cats in Los Angeles. The code is simple, here it is: db.pets.findAll({ where: { city: 'Los Angeles', type: 'cat' } }); If we were searching only one column, e.g. city, we could send a single variable as a payload from the client (this example uses the popular SuperAgent library): import superagent from 'superagent'; const petCity = 'Los Angeles'; superagent .post('/search') .send({ city: petCity }) .set('Accept', 'application/json') .end(function(err, res){ if (err || !res.ok) { // handle error } else { // handle success } }); As always, our API is built with Express.js. The endpoint to receive our query would look like this: app.post('/search', (req, res) => { const citySearch = req.body.city; db.pets.findAll({ where: citySearch }) .then(pets => { res.json(pets); }); }); NOTE: Although we are 'getting' data, and the Sequelize method we are using is findAll, our endpoint is not a GET endpoint. Since we are sending/posting an object from the client, we need to make this endpoint a POST route. But how do we search multiple columns, e.g. city and type, via our Express API? We'll have to pass an object to Sequelize, and this object will contain our query parameters. Our client code would look something like this: import superagent from 'superagent'; const myQuery = { city: 'Los Angeles', type: 'cat' }; superagent .post('/search') .send({ query: myQuery }) .set('Accept', 'application/json') .end(function(err, res){ if (err || !res.ok) { // handle error } else { // handle success } }); Our API endpoint would receive it like so: app.post('/search', (req, res) => { const multipleSearch = req.body.query; db.pets.findAll({ where: multipleSearch }) .then(pets => { res.json(pets); }); }); CREATE: Bulk creation Creating multiple records is the most straightforward of the bulk operations, because Sequelize has a bulkCreate method that accepts an array of objects. To create two users at once, we need to send our API an array containing two user objects. Here is the object along with the SuperAgent code the client should send the creation endpoint. const owners = [ { name: "John", role: "user" }, { name: "Sean", role: "user" } ]; superagent .post('/owners/bulk') .send(owners) .set('Accept', 'application/json') .end(function(err, res){ if (err || !res.ok) { // handle error } else { // handle success } }); Here is the endpoint that receives this POST request. app.post('/owners/bulk', (req, res) => { const ownerList = req.body.owners; db.owners.bulkCreate(ownerList) .then(newOwners => { res.json(newOwners); }) }); Sequelize's bulkCreate method returns the the newly created users. Here is the JSON response our bulk create request produces: [ { "id": "1c9fa4db-3499-43ed-8378-47c8f53e900a", "name": "John", "role": "user", "created_at": "2016-10-15T20:23:05.020Z", "updated_at": "2016-10-15T20:23:05.020Z" }, { "id": "b292ff23-9f56-4f15-84ca-68dae355da11", "name": "Sean", "role": "user", "created_at": "2016-10-15T20:23:05.020Z", "updated_at": "2016-10-15T20:23:05.020Z" } ] UPDATE: Updating multiple records Updating and deleting multiple records requires more effort on the part of the developer, because Sequelize doesn't have a method specifically for these operations. However, this gives us an opportunity to take advantage of the Javascript promise functionality built into Sequelize. There are two steps for updating (or deleting) multiple records. First, you query the records. Second, you update the records. The second step is the trickier of the two. Step 1: We are going to keep this part as simple as possible. For our API, the client will have to send an array of ids corresponding to the records to be updated. We'll use this array to retrieve the records from the database. We will also need an object containing the columns and values for the update. If we were to change the role of owners John and Sean from 'user' to 'admin', we would send the following code from the client: const updateObj = { ids: [ "1c9fa4db-3499-43ed-8378-47c8f53e900a", "b292ff23-9f56-4f15-84ca-68dae355da11" ], updates: { role: 'admin' } }; superagent .patch('/owners/bulk') .send(updateObj) .set('Accept', 'application/json') .end(function(err, res){ if (err || !res.ok) { // handle error } else { // handle success } }); Step 2: Since we are updating existing records, we need to create a PATCH route (note line 11 in our SuperAgent code, too). The first piece of logic we need to code is a query that will search for multiple ids. We can do this by using Sequelize's $in operator (see line 6 below). This operator will read each item in an array. app.patch('/owners/bulk', (req, res) => { const ids = req.body.ids; const updates = req.body.updates; db.owners.findAll({ where: { id: { $in: ids } } }); // update logic goes here }) In the code above, first we grab the ids and the updates from req.body. Then we query the owners tables using the $in operator and the array of ids. This query will return all the owners in the ids array. Now we need to apply the updates. To make sure all of our updates are made before we send a response to the client, we need to use Promise.all(). We've been using promises constantly, as shown by our use of .then(), but we've been dealing with one promise at a time. The general form of the logic we have been using is "first do X, then do Y, then do Z". Specifically, the logic has been "query the database, then send back a response" or "query the database, then update the record, then send back the response". In these cases, promises allow us to wait until an operation is complete before moving on to the next step. In the logic outlined above, we are dealing with one operations at a time; do this, then do that. Now that we are updating multiple records, the logic is different. Rather than "do this, then do that", we need logic of the form "Do many operations, once they are all resolved, then do X". This is where Promise.all() comes in. Let's look at the specifics of our implementation. app.patch('/owners/bulk', (req, res) => { const ids = req.body.ids; const updates = req.body.updates; db.owners.findAll({ where: { id: { $in: ids } } }) .then(owners => { const updatePromises = owners.map(owner => { // the line below creates a new item/promise for // the updatePromises array return owner.updateAttributes(updates); }); return db.Sequelize.Promise.all(updatePromises) }) .then(updatedOwners => { res.json(updatedOwners); }); }) After retrieving the array of owner records from the database, we take the array and use it to create a new array of promises. The Javascript .map() method takes an array (in this case owners) and creates an new array from it. On lines 9 - 13, we take the owners array and use it as material for creating an array called updatePromises. The latter contains one updateAttributes promise for every item in the owners array. We then pass the newly created updatePromises array to Promise.all(). Promise.all() waits for every promise in the updatePromises array to resolve before moving on to the next operation; in this case, sending a response back to the client. NOTE: The return statement in .map() is very important. If you leave it out, you'll produce a new array of null values. For more on Javascript array methods (which are essential for functional programming), check out this informative post. DELETE: Deleting multiple records Deleting multiple records is similar to updating. In fact, it's slightly simpler because we don't need an update object - an array of ids is all that's required. app.delete('/owners/bulk', (req, res) => { const ids = req.body.ids; db.owners.findAll({ where: { id: { $in: ids } } }) .then(owners => { const deletePromises = owners.map(owner => { return owner.destroy(); }); return db.Sequelize.Promise.all(deletePromises) }) .then(deletedOwners => { res.json(deletedOwners); }); }); On line 8, we see the .destroy() method at work. If your Sequelize model is set to paranoid: true, the .destroy() method will insert a timestamp indicating when the 'soft deletion' happened and the record will no longer be returned in queries. If the model is paranoid: false, then the record will continue to be returned in queries, but there will be a timestamp indicating when the record was 'deleted'. The response this route sends is an array of the deleted records, but it will contain the deleted_at column. Since our model is set to paranoid: true, these records will not be included in future queries. [ { "id": "1c9fa4db-3499-43ed-8378-47c8f53e900a", "name": "John", "role": "admin", "created_at": "2016-10-15T20:23:05.020Z", "updated_at": "2016-10-15T20:23:05.020Z", "deleted_at": "2016-10-16T16:16:22.365Z" }, { "id": "b292ff23-9f56-4f15-84ca-68dae355da11", "name": "Sean", "role": "admin", "created_at": "2016-10-15T20:23:05.020Z", "updated_at": "2016-10-15T20:23:05.020Z", "deleted_at": "2016-10-16T16:16:22.365Z" } ] If you'd like to be notified when I publish new content, you can sign up for my mailing list in the navbar.
https://lorenstewart.me/2016/10/16/sequelize-crud-102/
CC-MAIN-2018-51
refinedweb
1,707
66.84
Applying Attributes Use the following process to apply an attribute to an element of your code. Define a new attribute or use an existing attribute by importing its namespace from the .NET Framework. Apply the attribute to the code element by placing it immediately before the element. Each language has its own attribute syntax. In C++ and C#, the attribute is surrounded by square brackets and separated from the element by white space, which can include a line break. In Visual Basic, the attribute is surrounded by angle brackets and must be on the same logical line; the line continuation character can be used if a line break is desired.is the name of the property. In Visual Basic, specify name:= value. The attribute is emitted into metadata when you compile your code and is available to the common language runtime and any custom tool or application through the runtime reflection services. By convention, all attribute names end with Attribute. However, several languages that target the runtime, such as Visual Basic and C#, do not require you to specify the full name of an attribute. For example, if you want to initialize System.ObsoleteAttribute, you only need to reference it as Obsolete. Applying an Attribute to a Method The following code example shows how to declare System.ObsoleteAttribute, which marks code as obsolete. The string "Will be removed in next version" is passed to the attribute. This attribute causes a compiler warning that displays the passed string when code that the attribute describes is Feedback
https://docs.microsoft.com/en-us/dotnet/standard/attributes/applying-attributes?redirectedfrom=MSDN
CC-MAIN-2019-39
refinedweb
255
56.45
Objective: To configure UI5 based landing page for ESS, MSS, and HR Professional role in EHP 7 using NW 7.4 portal . In this case, we will configure HR Renewal 2.0 (initial shipment). This blog would describe the steps to configure EHP7 roles in portal and resolve the issues faced. It won’t cover the functional configurations done to make the end functionalities work. Pre requisites: You have referred the latest version of HR Renewal administrator guide from SAP Marketplace. -> SAP Business Suite Applications -> SAP ERP Add-Ons-> HR renewal . You have referred sdn blog by Raja Sekhar Kuncham: and Rashmi Singh : Steps followed: 1) The list of composite roles to be used: Make sure these composite roles are assigned to users in back-end client. 2) Upload back-end role in portal as mentioned in link : To upload ESS role: To upload MSS role:¤t_toc=/en/6a/5b82ff751c4377a15cfd76470dbcd5/plain.htm&node_id=7&show_children=false To configure HR Renewal Landing page: When you upload back-end role to portal , make sure the role is uploaded successfully in portal. Refer below mentioned notes in case of issues faced: 2011251 – Role Upload shows successful status but role is not created 1685257 – Upload of SAP delivered NWBC Roles to SAP Netweaver Portal Once the role is uploaded, assign role to user. One of the commonly faced issue post uploading role in portal and assigning to user is: “404 Resource not found”. To avoid this error, make sure you do below mentioned steps before uploading composite role to portal: Copy the PFCG role. In menu tab,append the landing page Web Address with &sapui5=true&sap-theme=sap_goldreflection. For example, if the web address for the landing page is /sap/bc/ui5_ui5/sap/ARSRVC_SUITE_PB/main.html?page=SPB_LANDING_PAGE then after appending the URL is/sap/bc/ui5_ui5/sap/ARSRVC_SUITE_PB/main.html?page=SPB_LANDING_PAGE&sapui5=true&sap-theme=sap_goldreflection. 3) Create RFC destination pointing to back-end client. Ensure the current user check box is ticked. 4) Ensure that value of Logon Data is maintained as 001 for services highlighted in screenshot below. 5) For the links in landing page to work, activate below mentioned services: Use t-code SICF. Startup Service: /default_host/sap/bc/ui2/start_up Image Upload Service:/default_host/sap/bc/ui2suite/image Choose default_host SAP-> bc-> bsp->-> bc-> ui5_ui5->-> public -> bc, select the following services: UI2 ui5_ui5 Activate the above services (either via right-click of the mouse and Activate Service or in the menu under Service / host Activate) 6) Create system alias as shown in screenshot below: 7) Use t-code /iwfnd/maint_service and activate the following OData services for the Suite Page Builder Catalog: •/UI2/PAGE_BUILDER_CONF •/UI2/PAGE_BUILDER_CUST •/UI2/PAGE_BUILDER_PERS Make sure all the gateway services mentioned in admin guide for end functionalities are activated. The alias created in step 6 should be used while activating services. 8) In some of the application like Employee Profile, SAP_HCM_PROXY alias is used in LPD_CUST. To make these applications work, create a system object with properties as shown in screen-shot below: 9) Use SPB admin page to add chips to catalog as per your requirement. http://<server>:<port>/sap/bc/ui5_ui5/sap/arsrvc_spb_admn/main.html?scope=CUST&sap-client=<clnt_num>&sap-language=EN 10) On executing, the landing page, sometimes we do face issues. To analyse issue, use t-code /iwfnd/error_log and check the error logged. For analysis of the error, set the error log level to full and reproduce the issue. Commonly faced error and resolution detailed below. Error: No service found for namespace, name <service name>, version <num> Solution: Use t-code /iwfnd/maint_service and maintain service <service name>. Error: Data Provider implementation does not exist. Example: Data Provider implementation ‘ZINTEROP_MODEL_0001_BE’ ’01’ ‘DEFAULT’ does not exist. For additional information about the error, click icon. Solution: If only one system alias has been assigned to the corresponding service (check in the IMG activity ->Assign SAP System Aliases to OData Service) .Delete the service completely in transaction /iwfnd/maint_service (Maintain Services ) and then re-create it. If more than one system alias has been assigned to the service (via IMG activity Assign SAP System Aliases to OData Service) you need to manually create the data provider assignment as well. For this you can use IMG activity Assign Data Provider to Data Model. Copy the existing entry for the model and replace the software version with version ‘DEFAULT’. Error: Task Facade not implemented for provider. Solution: Make sure service for Task Processing is activated. For this IW_PGW ADDON should be installed. System alias as maintained in screenshot below is configured.. Error: Chip can’t be added to page: HTTP 404: Resource Chip not found. Solution: Look into database table /UI2/CHIP_CHDR following the note 1942166. Run report /UI2/CHIP_SYNCHRONIZE_CACHE as per the note. Now please try again to run the admin UI. If the error still occurs, run report /UI2/CACHE_DELETE and try again. Error: In MSS role via landing page access Requisition Monitor application (Click on My Team services ->Requisition Monitor ) , Select a candidate and click on “GoTo Questionaire”. It gives OBN error. ” There is no iview available for system “SAP_ERP_TalentManagement” : object “questionaire” . For more information , contact your adminstrator “. The same functionality works when application is launched via detailed navigation panel. Solution: The issue was resolved by applying note 2078346 – OBN error for HR renewal requisition Well written… and much need… Thanks for sharing the steps Happy to help 🙂 HI Navya, Information you have shared are more useful. Thanks Great Blog!! Thanks for sharing… Excellent ……… 🙂 Thanks for Sharing! I rated 5 stars and liked it! Hello Navya, Good blog on configuring the HR Renewal. One Question. We are implementing the HR Renewal 2.0 FP3 along with eRecruitment in a separate system which is integarted to the SAP Portal 7.4 SP8. We have the same issues as like you mentioned for eRecruitment and we applied the below note and changed the lpd_cust settings to User Roles as mentioned in the note. 2078346 – OBN error for HR renewal requisition Still we are facing the OBN errors for the links under MSS Requisition applications. Please note that we have deployed only the below business packages. BP ERP Common Parts 1.61 Business Package for Recruiter 1.51 Business Package for Recruiting Administrator 1.51 We have not deployed the below business packages. BP ERP ESS and BP ERP MSS . Please let me know if we need to deploy these business packages as well. Thanks, Hi, Check OBN related settings done in that iview. Raise a separate thread with screenshots of issue faced and configuration done. Regards, Navya. Hi Navya, Nice blog. We are also planning to Implement HR Renewal 2.0. My query is does HR Renewal 2.0 support Ajax Framework Page in NW7.4. Any response is much appreciated! Regards, Pankaj Hi, Yes. It does support. Regards, Navya. Thanks. Do you have any guidelines document/link which shows Configuration/Integration steps performed in SAP Portal for HR Renewal 2.0 Regards, Pankaj Hi, This blog is for hr renewal 2.0 . Its from portal perspective. You can try following steps mentioned in this blog. Regards, Navya.
https://blogs.sap.com/2015/01/23/configuration-of-ui5-based-landing-page-in-hr-renewal-20initial-shipment/
CC-MAIN-2019-22
refinedweb
1,197
57.57
The div() function is defined in <cstdlib> header file. Mathematically, quot * y + rem = x div_t div(int x, int y); ldiv_t div(long x, long y); lldiv_t div(long long x, long long y); It takes a two arguments x and y, and returns the integral quotient and remainder of the division of x by y. The quotient quot is the result of the expression x/y. The remainder rem is the result of the expression x%y. The div() function returns a structure of type div_t, ldiv_t or lldiv_t. Each of these structure consists of two members: quot and rem. They are defined as follows: div_t: struct div_t { int quot; int rem; }; ldiv_t: struct ldiv_t { long quot; long rem; }; lldiv_t: struct lldiv_t { long long quot; long long rem; }; #include <iostream> #include <cstdlib> using namespace std; int main() { div_t result1 = div(51, 6); cout << "Quotient of 51/6 = " << result1.quot << endl; cout << "Remainder of 51/6 = " << result1.rem << endl; ldiv_t result2 = div(19237012L,251L); cout << "Quotient of 19237012L/251L = " << result2.quot << endl; cout << "Remainder of 19237012L/251L = " << result2.rem << endl; return 0; } When you run the program, the output will be: Quotient of 51/6 = 8 Remainder of 51/6 = 3 Quotient of 19237012L/251L = 76641 Remainder of 19237012L/251L = 121
https://cdn.programiz.com/cpp-programming/library-function/cstdlib/div
CC-MAIN-2019-51
refinedweb
211
70.73
I’m trying to learn ASP.NET but am really confused. All the tutorials seem to conflict with each other over whether I should be using MVC or Razor Pages? If you’re learning ASP.NET in this brave new .NET Core world and you want to build server-side web applications then it’s a straight fight between two contenders. Just to be clear, by sticking to “server-side” we’re deliberately ignoring another option; building Web APIs in order to serve front-end frameworks like Angular. In the blue corner we have MVC and in the red, the new kid on the block, Razor Pages. In truth they share a lot of the same underlying framework but there are some key differences. Before you decide which one to adopt for your next project, it’s worth taking a moment to directly compare them. MVC The old stager, been around since v1 all the way back in 2009. Here’s a rough overview of how MVC requests are handled by ASP.NET Core. The routing engine is key to how ASP.NET Core decides to handle your requests. It can be configured to route any request to any controller action. The default routing configuration uses a combination of the controller and action names. /<controller name>/<action name> So a request to /staff/index would route to the action called Index on the StaffController. public class StaffController : Controller { [HttpGet] public IActionResult Index() { return View(); } } Once the request reaches a controller action, the logic in the action is executed and a response is returned. Where does my code go? In MVC, your application code lives in the controller action. public class StaffController : Controller { [HttpGet] public IActionResult Index() { // logic here... // calls to services etc. return View(); } } It’s here that you’re going to validate the request, execute any business logic, call your app’s services etc, before eventually returning a response. You can use attributes to indicate which kinds of requests your action will accept e.g. GET, POST, PUT (or any of the other HTTP verbs). Where does my presentation code (markup) go? MVC actions don’t have to return a View but they typically do. It’s in these views that you’ll put all your HTML markup. When a view is returned, MVC needs to locate said view and it achieves this using some default conventions. Unless told otherwise, it will look in a Views folder for a folder with the same name as the controller, then a view with the same name as the action. e.g. Views\Staff\Index.cshtml The key thing to note here is that MVC requests are routed to the controller action and it’s up to the action to determine whether a view is returned (and if so, which view). MVC actions can easily override the default conventions and return a specific view (with a name which differs from that of the action). public class StaffController : Controller { [HttpGet] public IActionResult Index() { // logic here... return View("AnotherPage"); } } This example will cause MVC to go looking for a view called AnotherPage.cshtml in the Views\Staff folder. How do I display data in my views? You can create a ViewModel. This is a class which lives in a .cs file and has properties for the data you wish to show on your view. public class StaffProfile { public string FirstName { get; set; } public string LastName { get; set; } } Your controller actions can return this data alongside your views. public class StaffController : Controller { public IActionResult Index() { // would come from a database or something in real life var model = new StaffProfile { FirstName = "Jon", LastName = "Hilton" }; return base.View(model); } } Your views can then render this data. @model StaffProfile <h1>Welcome</h1> <p>Hey @Model.FirstName!</p> Folder structure Typically, MVC apps have a standard folder-based convention with separate folders for controllers, views and view models. Razor Pages Razor Pages is brand new in ASP.NET Core.. The Razor Page then acts as though it were a controller action. For a .cshtml file to qualify as a Razor Page, it must live in the Pages folder (using default conventions) and include @page in its markup. Where does my code go? Every Razor Page can have a corresponding Page Model. If we stick to the default conventions, ASP.NET will expect that model to have the same name as the corresponding Razor page but with a .cs appended. With Razor Pages your application code lives in these models, specifically in methods for the different HTTP verbs (e.g. GET, POST). public class ContactModel : PageModel { public void OnGet() { // logic here... // calls to services etc. } public void OnPost() { } } Where does my presentation code (markup) go? Well this is simple. Because the request was routed directly to the specific razor page that can handle it, there’s no need to go off locating a view, the view is the one the request was routed to e.g. Contact.cshtml. The default routing for Razor Pages is simple enough and respects subfolders, so \Pages\Staff\Profile.cshtml would be accessible via a request to /staff/profile. Worth noting that you can omit Index as it is the default page. In this example both /staff/ and /staff/index would take you to Pages\Staff\Index.cshtml. How do I display data in my views? Rather than have separate ViewModels you just need to add properties to your Page Model. public class ProfileModel : PageModel { public string FirstName { get; set; } public string LastName { get; set; } public void OnGet() { // would come from a database or something in real life FirstName = "Jon"; LastName = "Hilton"; } } You can directly set those properties from your Page Model methods (e.g. OnGet). Then it’s simple to render this data in the Page itself. @page @model ProfileModel <h1>Welcome</h1> <p>Hey @Model.FirstName!</p> Folder structure Everything lives in the Pages folder (by default). Each Razor Page consists of the View template (.cshtml) and a corresponding .cs file which effectively acts as a controller action, specifically for that view. In conclusion So there you have it. A quick comparison of MVC and Razor Pages. It’s early days for Razor Pages, they will almost certainly improve over the next few releases and it’s not clear whether there is any kind of widescale adoption of in the industry. What is certain is that MVC is here to stay. With so many existing apps written using it and the significant improvements which came with ASP.NET Core MVC, MVC isn’t likely to disappear anytime soon. Trying to learn ASP.NET Core MVC is hard; so many tutorials, docs and blog posts yet you still don't really know how to build anything of your own. Fast-forward to the fun bit (building features) with Practical ASP.NET Core MVC. "As a WinForms developer of far too long, I am thoroughly enjoying Practical ASP.NET Core MVC and consider it fantastic value for money!" Grahame Kelsey
https://jonhilton.net/razor-pages-or-mvc-a-quick-comparison/
CC-MAIN-2019-30
refinedweb
1,165
66.33
Configuring Folders Within a Content RootSourceResource RootTest SourceExcluded By default, any folder is treated as Source folder. In this section: PhpStorm consider the contents of the selected folder as unit tests, click the Tests toolbar button or choose Test Sources on the context menu of the selection. - To have PhpStorm consider the selected folder as the root for namespaces used in your project, click the Sources toolbar button of choose Sources on the context menu of the selection.. - To have PhpStorm ignore the selected directory during indexing, parsing, code completion, etc., click the Excluded toolbar button or choose Excluded on the context menu of the selection. - To enable Php>.
http://www.jetbrains.com/phpstorm/help/configuring-folders-within-a-content-root.html
CC-MAIN-2015-18
refinedweb
109
53
01 November 2010 16:01 [Source: ICIS news] WASHINGTON (ICIS)--The ?xml:namespace> The Institute for Supply Management (ISM) said that its closely watched purchasing managers index (PMI) rose to 56.9% in October, a gain from the 54.4% PMI recorded for September. Although the index has been bouncing up and down since its recent highpoint of 60.4% in April, it has remained above the 50% level, indicating that the nation’s manufacturing industries continue to expand, although more slowly than in the first quarter this year. The purchasing managers index is comprised of ten subsidiary measures of activity in 18 manufacturing sectors. A reading of 50% or higher indicates that manufacturing is expanding, while an index below that midpoint means that the sector is contracting. After its recent high-water mark of 60.4% in April, the index had fallen to 55.5% in July, rose to 56.4 in August and then tilted down again in September. “Since hitting a peak in April, the trend for manufacturing has been toward slower growth,” said Norbert “However, this month’s report signals a continuation of the recovery that began 15 months ago, and its strength raises expectations for growth in the balance of the quarter,” Ore said. He noted that despite the cooling pace of manufacturing expansion, the sector was growing. “With 14 of 18 industries reporting growth in October, manufacturing continues to outperform the other sectors of the economy,” Among the 14 manufacturing industries reporting expansion in October were chemicals products and plastic and rubber production. One of the unidentified chemical sector survey respondents told the institute that “Business is slowing down, but it is still double digits over last year”. In the ten subsidiary measures that make up the PMI composite, the institute noted especially strong gains in new orders, production and exports.
http://www.icis.com/Articles/2010/11/01/9406381/us-manufacturing-grows-in-oct-offsetting-slower-sept-pace.html
CC-MAIN-2014-49
refinedweb
307
53.81
REST, hypertext and non-browser clients I am confused on how a REST api can both be hypertext driven, but also machine readable. Say I design an API and some endpoint lists contents of a collection. GET /api/companies/ The server should return a list with company resources e.g: /api/companies/adobe /api/companies/microsoft /api/companies/apple One way would be to generate a hypertext (html) page with <a> links to the respective resources. However I would also like to make it easy for a non-browser client to read this list. For example, some client might want to populates a dropdown gui with companies. In this case returning a html document is inappropriate, and it might be better to return a list in JSON or XML format. It is not clear to me how REST style can satisfy both. Is there a practical solution or examples of a REST api that is both nice to browsers and non-browser clients? Answers What you're looking for is nowadays referred to as HATEOAS API's. See this question for examples: Actual examples for HATEOAS (REST-architecture) The ReST architectural style, as originally defined by Roy Fielding, prescribes "hypertext as the engine for application state" as one of the architectural contraints. However, this concept got more or less "lost in translation" when people started equaling "RESTful API's" with "using the HTTP verbs right" (plus a little more, if you're lucky). (Edit: Providing credence for my assertion are the first and second highest-ratest answers in What exactly is RESTful programming? . The first talks only about HTTP verbs). Some thoughts on your question: (mainly because the subject keeps fascinating me) In HATEOAS, standardized media types with precise meaning are very important. It's generally thought to be best to reuse an existing media type when possible, to benefit from general understanding and tooling around this. One popular method is using XML, because it offers both general structure for data and a way to define semantics, i.e. through an XML schema or with namespaces. XML in and by itself is more or less meaningless when considering HATEOAS. The same applies for JSON. For supporting links, you want to choose a media type that either supports links "natively" (i.e. text/html, application/xhtml+xml) or a media type that allows defining what pieces in the document must be interpreted as links through some embedded metadata, such as XML can with for example XLINK. I don't think you could use application/json because JSON by itself has no pre-defined place to define metadata. I do think that it would be possible to design a media type based on json - call it application/x-descriptive-json - that defines up-front that the JSON document returned must consist of a "header" and "body" property where header may contain further specified metadata. You could also design a media type for JSON just to support embedded links. Simpler media type, less extenisble. I wouldn't be surprised if both things I describe already exist in some form. To be both nice to browsers and non-browser clients, all it takes is respecting the Accept header. You must assume that a client who asks for text/html is truly happy with text/html. This could be an argument for not using text/html as the media type for your non-browser API entry point. In principle, I think it could work though if the only thing you want is links. Good HTML markup can be very well consumed by non-browser clients. HTML also defines way to do paging, through rel="next", rel="previous". The three biggest problems of a singular media type for both browsers and non-browsers I see are: - you must ensure all your site html is outputted with non-browser consumption in mind, i.e. embed sufficient metadata. Perhaps add hidden links in some places. It's a bit comparable from thinking about accessibility for visually impaired people: Though now, you're designing for a consumer who cannot read English, or any natural language for that matter. :) - there may be lots of markup and content that may essentially irrelevant to a non-browser client. Think of repeating header and footer text, navigation area's that kind of things. - HTML may simply lack the expressiveness you need. In principle, as soon as you go "think up" some conventions specific to your site (i.e. say rel="original-image means the link to the full-size, original image), then you're not doing strictly HATEOS anymore (at least, that's my understanding). HTML leaves no room for defining new meaning to elements. XML does. A work-around to problem three might be using XHTML, since XHTML, by the virtue of being XML, does allow specifying new kinds of elements through namespaces. I see @robert_b_clarke mentioning Microformats, which is relevant in this discussion. It's indeed one way of trying to improve accessibility for non-human agents. The main issue with this from a technical point of view is that it essentially relies on "out-of-band" information. Microformats are not part of the text/html spec. In a way, it's comparable to saying: "Hey, if I say that there's a resource with type A and id X, you can access it at mysite.com/A/X." The example I gave with rel=original-image could be called a micro-format as well. But it is a way to go. "State in your API docs: We serve nicely formatted text/html. Our text/html also embeds the following microformats: ..." You can even define your own ones. I think the following presentation as a nice down-to-earth explanation of HATEOAS: Edit: I only now read about HTML5 microdata (because of @robert_b_clarke). It seems like HTML5 does provide a way for supplying additional information beyond what's possible with standard HTML tags. Consider what I wrote dated. :) Edit edit: It's only a draft, phew. ;) Edit 2 Re a "descriptive JSON" format: This has just been announced . They have applied for their own mime type. It's by Yehuda Katz (Ember.js) and Steve Klabnib, who's writing Designing Hypermedia API's. Need Your Help Fix div height in right of div Obtain LWP id from a pthread_t on Solaris to use with processor_bind pthreads solaris setthreadaffinitymaskOn Solaris, processor_bind is used to set affinity for threads. You need to know the LWPID of the target thread or use the constant P_MYID to refer to yourself.
http://unixresources.net/faq/16328833.shtml
CC-MAIN-2019-13
refinedweb
1,095
63.8
19 September 2012 14:35 [Source: ICIS news] WASHINGTON (ICIS)--US new home construction activity rose by 2.3% in August, reversing a 1.1% decline in July, the Commerce Department said on Wednesday, but the number of building permits fell last month, suggesting a rocky road ahead for the housing recovery. In its monthly report, the department said that housing starts in August were at a seasonally adjusted annual rate of 750,000 units, a 2.3% improvement from the downwardly revised July figure of 733,000. However, part of the August gain in new home construction reflected a sharp downward revision to the July figures. The department had originally estimated housing starts in July at 746,000 but has now chopped that figure back by 13,000 units or 1.7% to 733,000. Had that initial July estimate held, the August improvement would have been a more modest 0.5%. In other words, the August gain appears stronger largely because the July downturn was worse than initially estimated. But however qualified the August gains might be, last month’s advance in housing construction was attributed chiefly to a strong 5.5% improvement in work on single-family homes, considered the core of the housing industry. In addition, new construction of single-family homes in August, put at 535,000 on a seasonally adjusted annual basis, was nearly 27% better than the pace of activity seen in August 2011.. Although the long-depressed ?xml:namespace> The department said that the number of housing permits issued in August fell by 1% from July, in contrast to the strong 6.8% gain seen in July. A downturn in building permits indicates that actual housing starts may show weakening numbers when the September data on residential construction are issued in October. Building permits are issued by local governments when contractors are ready to start work on a home or apartment project, so they are seen as an accurate real-time indicator of near-term prospects for the housing sector. US Housing Starts * Seasonally adjusted & annualised (
http://www.icis.com/Articles/2012/09/19/9596951/us-housing-starts-rise-2.3-in-aug-but-permits-edge-down-1.html
CC-MAIN-2015-22
refinedweb
344
54.32
UK High Altitude Society Ensuring your payload is fully tested for the following errors will maximise your chances of a recovery. There are a number of common and avoidable errors in code that can result in inaccurate information being uploaded to the tracker. The image below is an example of a payload which had both padding and a meridian error. The main cause of these issues is the conversion from a floating point value to a string for transmission. Below we will go through the issues and explain how to avoid them. Wherever possible, use functions provided by libc and gcc rather than writing your own! Seriously. The GCC and libc functions are probably faster and much more likely to be free of bugs. Here are two functions that can turn floats into strings: char s[30]; double lat = 54.086611; dtostrf(lat, 8, 6, s); // == "54.086611" char s[30]; double lat = 54.086611; snprintf(s, 30, "%.6f", lat); // == "54.086611" Unfortunately the second one might not always compile. With limited memory on a typical microcontroller, the printf() series of functions in AVR Libc (used by Arduino) do not by default support printing of floating point values using the %f operator. You can enable floating point support in printf, though it's difficult. It is common to divide up a floating point value into two integers and print it with two %i operators. We quite often see code like the below. Honestly, using dtostrf should be much easier. The notes below might be a useful read if you're not familiar with these common C mistakes anyway. char s[30]; double lat = 54.086611; int i1 = lat; // == 54, the integer part int i2 = (lat - i1) * 1000000; // == 21076 ... uh oh snprintf(s, 30, "%i.%i", i1, i2); // == "54.21076" -- that's not good. We wanted i1 to contain 54, i2 to contain 86611 and s to be the string “54.086611” - but that's not what happened. Don't use this code! Let's have a look at its problems. On the Arduino, an 'int' is 16 bits (and signed), so can only contain values from -32768 to 32767. Instead of 456611, the i2 contains -2414. When converting the decimal part of the above into an integer value you should be using the long data type, which is 32 bits wide and can therefore store from −2,147,483,648 to 2,147,483,647. Fixed code: long i2 = (lat - i1) * 1000000; // == 86611, the decimal part. You might actually get 86610 due to the wonders of floating point and the fact that the default conversion from float to int floors the float rather than rounds it. This is not really a big deal, but if you want to you can fix this: long i2 = lround((lat - i1) * 1000000); Excellent! However, s now contains the string “54.86611”, not “54.086611”. Oops. The padding error will appear when the decimal part is below 0.1. Our float of 54.086611 gets split into 54 and 86611, and the resulting string is “54.86611” instead of 54.086611. To correctly print this the second integer must be zero padded to the correct number of decimal places: snprintf(s, 30, "%i.%06li", i1, i2); In our example we are using six decimal places, so %06li will ensure that the second integer (86611) is printed as “086611” giving a final correct result of “54.086611”. The 'l' is there because i2 is now a long integer, and printf likes to know. In the UK and especially with our launch sites located around Cambridge the Prime Meridian comes into play. This is the 0' line of Longitude where the values of longitude go from east to west, or in decimal form from positive to negative. Suppose we used the same code as above to print our longitude values. char s[30]; double lon = -1.001234; int i1 = lon; // == -1, the integer part long i2 = lround((lon - i1) * 1000000); // == -1234 ... hmm snprintf(s, 30, "%i.%06li", i1, i2); // == "-1.-1234" -- lol. The solution is quite simple. We simply need to make sure i2 is always positive, using the labs() function. long i2 = labs(lround((lon - i1) * 1000000)); // == 1234 There's another case to consider. Clearly the idea is to split the float into the an integer and a fraction of an integer (i1 and i2 respectively). The intention is the above code is that the integer part will supply the negative sign if required. However, consider -0.7. i1 would be -0, but -0 == 0, and the result would be “0.7”. We'll have to handle negative numbers explicitly: snprintf(where, buf_size, "%s%i.%06li", (what < 0 ? "-" : ""), labs(i1), i2); Practically the Equator is not really an issue for us but worth mentioning for our Kenyan viewers. Really, you should place your float to string code in a separate function and call it for latitude and longitude. This also means that this function can be unit tested. You might need to #include stdlib for labs and lround. #include <stdlib.h> void print_float(float what, char *where, int buf_size) { int i1 = what; long i2 = labs(lround((what - i1) * 1000000)); snprintf(where, buf_size, "%s%i.%06li", (what < 0 ? "-" : ""), labs(i1), i2); } void loop() { double latitude, longitude; char lat_str[30], lon_str[30]; // get latitude, longitude print_float(latitude, lat_str, 30); print_float(longitude, lon_str, 30); // do something with lat_str, lon_str } It's advised you use a data type that can handle negative numbers for the altitude. Occasionally the GPS can report negative altitudes on the ground, if you're using an unsigned integer this overflows. As an example -4 meters would become 65531 metres. Impressive but we wouldn't be able to accept this as a record :) However, note also that flights regularly go above 32767 metres. Therefore storing it in a signed integer (int) is probably not appropriate. Use a long. You can view the debug log from the parser here. Simply upload a string or two with dl-fldigi and check that it said that it parsed it. There are a number of ways to simulate a flight. In this example we replace the GPS with a Windows PC running TroSys GPS and playing back an actual flight that crossed the prime meridian. For this example you'll need some sort of serial break out. I used an UM232R. You will need to get the free version of Tro Sys Gps Simulator Free. You can download the sample data here :icarus_nmea_data_sample.zip Test data around the Prime Meridian and Equator can be found here GPS Data This is what the above data should look like on google maps / tracker. Google Maps with link to KML Connect your FT232 up to the PC and check the port number assigned in device manager. You may need to force it to use COM1 - 4 as the software won't select higher numbered COM ports.This can be done under Device Manager → Properties on the port, Port settings then advanced. Connect the RXD and TXD to your flight computer in place of the GPS. You can use this code to check its working, load this code on the Arduino, open the Serial Monitor, then open the UM232R via hyperterm or similar. If you type on the hyperterm it should appear in the Serial Monitor window : #include <ctype.h> #include <string.h> #include <SoftwareSerial.h> int COUNT=0; byte GPS_TX=3; //GPS TX PIN byte GPS_RX=4; //GPS RX PIN SoftwareSerial GPS = SoftwareSerial(GPS_TX, GPS_RX); char SS_IN_BYTE; void setup() { pinMode(GPS_TX, INPUT); pinMode(GPS_RX, OUTPUT); GPS.begin(4800); // Amend Baud Rate as suits Serial.begin(9600); Serial.println("Serial Echo Utility"); } void loop() { while(1) { char SS_IN_BYTE = GPS.read(); Serial.print(SS_IN_BYTE); } } Once this is working open up TroSys GPS Simulator. Select log file playback. Select the relevant file and click load file.Set the delay b/w sentences as appropriate. Configure the COM port settings as appropriate and click Connect. Once done you can now hit Send. This should play the log back to your project and simulate a flight. There is also some software for doing this from various linux OS's GPSgen and GPS emulate written by Steve Randall with a couple of minor modifications by Robert Harrison Linux GPS emulation software Compile up the C programs GPSgen takes a KML file and converts it to NMEA GPS strings. ./GPSgen < test.kml > test.gps GPSemulate takes a GPS file and send the data out every second like a GPS device does ./GPSemulate < test.gps > /dev/ttyUSB0 Obviously you need to set up the ttyUSB0 device to the correct baud rate this can be done using stty -F /dev/ttyUSB0 4800
https://ukhas.org.uk/guides:common_coding_errors_payload_testing
CC-MAIN-2019-13
refinedweb
1,450
74.79
Android Native needs to be the first 10 digits of MOZ_BUILD_DATE (if set); Android native armv6 would have to be the first 10 digits of MOZ_BUILD_DATE decremented by one; and android-xul would be the first 10 digits of MOZ_BUILD_DATE, incremented by one. Background: 1) we pass in MOZ_BUILD_DATE to release builds to make sure the buildids are the same, a la make -f client.mk build MOZ_BUILD_DATE=20120717110313 2) android versionCodes are very important to get right in relation to each other. Until we fixed bug 760740, we had to upload android-xul after android native, and android-xul had to have a larger versionCode. Android-xul may no longer apply, but android-armv6 now does. 3) Merely going by build timestamp may result in the builds being built in the wrong order, with overlapping versionCodes. Since we're already passing in a shared MOZ_BUILD_DATE, let's use that instead of assuming the builds will build in the right order. 4) Since armv6 builds need to have a lower versionCode than android native armv7, I'm requesting that we also decrement that versionCode. This blocks our ability to build beta release builds of armv6. Created attachment 644575 [details] [diff] [review] patch I stole most of this from the XUL change, but I decrement instead of increment. I assume MIN_CPU_VERSION is ok to use and I am testing it the right way. This built ok for me in my armv7 build (I think... where can I see the version code?) I am pushing to Try too. Comment on attachment 644575 [details] [diff] [review] patch I think this will decrement. However, I think this is also dependent on the computer time, rather than using MOZ_BUILD_DATE... I might be wrong. This should be enough to let us build the two platforms at the same time, assuming android-armv6 starts before or in the same hour as android. We can tie in MOZ_BUILD_DATE at a later time. If we're unlucky and end up decrementing yyyymmdd00 or even yyyymm0100, does Google Play care ? aka does the buildID have to be valid says it just needs to be an integer, so never mind me. I'm trigger happy after bug 741688. Comment on attachment 644575 [details] [diff] [review] patch [Approval Request Comment] User impact if declined: won't be able to push ARMv6 and ARMv7 builds to google play as the same product Testing completed (on m-c, etc.): try run, just landed on inbound Risk to taking this patch (and alternatives if risky): should be zero risk. Alternative is for RelEng to do two seperate builds at least an hour apart String or UUID changes made by this patch: none Grepping for MOZ_BUILD_DATE gives me this chunk of code: . Maybe the long term fix is something like ifeq (,$(ANDROID_VERSION_CODE)) ifeq ($(MIN_CPU_VERSION),7) ifdef MOZ_BUILD_DATE ANDROID_VERSION_CODE=$(shell echo $(MOZ_BUILD_DATE) | cut -c1-10) else ANDROID_VERSION_CODE=$(shell $(PYTHON) $(topsrcdir)/toolkit/xre/make-platformini.py --print-buildid | cut -c1-10) endif else # decrement the version code by 1 for armv6 builds so armv7 builds will win any compatability ties ifdef MOZ_BUILD_DATE ANDROID_VERSION_CODE=$(shell echo `echo $(MOZ_BUILD_DATE) | cut -c1-10` - 1 | bc) else ANDROID_VERSION_CODE=$(shell echo `$(PYTHON) $(topsrcdir)/toolkit/xre/make-platformini.py --print-buildid | cut -c1-10` - 1 | bc) endif endif endif ? which is not very pretty, but will avoid release-day unpredictability. Knowing Murphy, this will happen on a chemspill day. Maybe we should be going off buildid instead. ifeq (,$(ANDROID_VERSION_CODE)) ifeq ($(MIN_CPU_VERSION),7) ANDROID_VERSION_CODE=$(shell cat $(DEPTH)/config/buildid | cut -c1-10) else # decrement the version code by 1 for armv6 builds so armv7 builds will win any compatability ties ANDROID_VERSION_CODE=$(shell echo `cat $(DEPTH)/config/buildid | cut -c1-10` - 1 | bc) endif endif ? Not sure if this will work, but if it does, I think that will solve this bug. Comment on attachment 644575 [details] [diff] [review] patch [Triage Comment] Let's only take this on Aurora for now, as we're still evaluating ARMv6 builds for Beta 15. Reopening until we use MOZ_BUILD_DATE or the buildid. Comment on attachment 644575 [details] [diff] [review] patch Review of attachment 644575 [details] [diff] [review]: ----------------------------------------------------------------- no longer needed on beta This seems to work on try: (). Any problems having the UA_BUILDID changed as well? (In reply to Chris AtLee [:catlee] from comment #14) > Any problems having the UA_BUILDID changed as well? No problem there. UA_BUILDID is no longer used for anything on Android. Created attachment 650364 [details] [diff] [review] use the buildid based on MOZ_BUILD_DATE for ANDROID_VERSION_CODE Transplanted to mozilla-beta:
https://bugzilla.mozilla.org/show_bug.cgi?id=776185
CC-MAIN-2017-26
refinedweb
754
62.48
TorchScript¶ TorchScript is a way to create serializable and optimizable models from PyTorch code. Any TorchScript program can be saved from a Python process and loaded in a process where there is no Python dependency. We provide tools to incrementally transition a model from a pure Python program to a TorchScript program that can be run independently from Python, such as in a standalone C++ program. This makes it possible to train models in PyTorch using familiar tools in Python and then export the model via TorchScript to a production environment where Python programs may be disadvantageous for performance and multi-threading reasons. For a gentle introduction to TorchScript, see the Introduction to TorchScript tutorial. For an end-to-end example of converting a PyTorch model to TorchScript and running it in C++, see the Loading a PyTorch Model in C++ tutorial. Mixing Tracing and Scripting¶ In many cases either tracing or scripting is an easier approach for converting a model to TorchScript. Tracing and scripting can be composed to suit the particular requirements of a part of a model. Scripted functions can call traced functions. This is particularly useful when you need to use control-flow around a simple feed-forward model. For instance the beam search of a sequence to sequence model will typically be written in script but can call an encoder module generated using tracing. Example (calling a traced function in script): import torch def foo(x, y): return 2 * x + y traced_foo = torch.jit.trace(foo, (torch.rand(3), torch.rand(3))) @torch.jit.script def bar(x): return traced_foo(x, x) Traced functions can call script functions. This is useful when a small part of a model requires some control-flow even though most of the model is just a feed-forward network. Control-flow inside of a script function called by a traced function is preserved correctly. Example (calling a script function in a traced function): import torch @torch.jit.script def foo(x, y): if x.max() > y.max(): r = x else: r = y return r def bar(x, y, z): return foo(x, y) + z traced_bar = torch.jit.trace(bar, (torch.rand(3), torch.rand(3), torch.rand(3))) This composition also works for nn.Modules as well, where it can be used to generate a submodule using tracing that can be called from the methods of a script module. Example (using a traced module): import torch import torchvision class MyScriptModule(torch.nn.Module): def __init__(self): super(MyScriptModule, self).__init__() self.means = torch.nn.Parameter(torch.tensor([103.939, 116.779, 123.68]) .resize_(1, 3, 1, 1)) self.resnet = torch.jit.trace(torchvision.models.resnet18(), torch.rand(1, 3, 224, 224)) def forward(self, input): return self.resnet(input - self.means) my_script_module = torch.jit.script(MyScriptModule()) TorchScript Language¶ TorchScript is a statically typed subset of Python, so many Python features apply directly to TorchScript. See the full TorchScript Language Reference for details. Built-in Functions and Modules¶ TorchScript supports the use of most PyTorch functions and many Python built-ins. See TorchScript Builtins for a full reference of supported functions. PyTorch Functions and Modules¶ TorchScript supports a subset of the tensor and neural network functions that PyTorch provides. Most methods on Tensor as well as functions in the torch namespace, all functions in torch.nn.functional and most modules from torch.nn are supported in TorchScript. See TorchScript Unsupported Pytorch Constructs for a list of unsupported PyTorch functions and modules. Python Functions and Modules¶ Many of Python’s built-in functions are supported in TorchScript. The math module is also supported (see math Module for details), but no other Python modules (built-in or third party) are supported. Python Language Reference Comparison¶ For a full listing of supported Python features, see Python Language Reference Coverage. Debugging¶ Disable JIT for Debugging¶ Setting the environment variable PYTORCH_JIT=0 will disable all script and tracing annotations. If there is hard-to-debug error in one of your TorchScript models, you can use this flag to force everything to run using native Python. Since TorchScript (scripting and tracing) is disabled with this flag, you can use tools like pdb to debug the model code. For example: @torch.jit.script def scripted_fn(x : torch.Tensor): for i in range(12): x = x + x return x def fn(x): x = torch.neg(x) import pdb; pdb.set_trace() return scripted_fn(x) traced_fn = torch.jit.trace(fn, (torch.rand(4, 5),)) traced_fn(torch.rand(3, 4)) Debugging this script with pdb works except for when we invoke the @torch.jit.script function. We can globally disable JIT, so that we can call the @torch.jit.script function as a normal Python function and not compile it. If the above script is called disable_jit_example.py, we can invoke it like so: $ PYTORCH_JIT=0 python disable_jit_example.py and we will be able to step into the @torch.jit.script function as a normal Python function. To disable the TorchScript compiler for a specific function, see @torch.jit.ignore. Inspecting Code¶ TorchScript provides a code pretty-printer for all ScriptModule instances. This pretty-printer gives an interpretation of the script method’s code as valid Python syntax. For example: @torch.jit.script def foo(len): # type: (int) -> torch.Tensor rv = torch.zeros(3, 4) for i in range(len): if i < 10: rv = rv - 1.0 else: rv = rv + 1.0 return rv print(foo.code) A ScriptModule with a single forward method will have an attribute code, which you can use to inspect the ScriptModule’s code. If the ScriptModule has more than one method, you will need to access .code on the method itself and not the module. We can inspect the code of a method named foo on a ScriptModule by accessing .foo.code. The example above produces this output: def foo(len: int) -> Tensor: rv = torch.zeros([3, 4], dtype=None, layout=None, device=None, pin_memory=None) rv0 = rv for i in range(len): if torch.lt(i, 10): rv1 = torch.sub(rv0, 1., 1) else: rv1 = torch.add(rv0, 1., 1) rv0 = rv1 return rv0 This is TorchScript’s compilation of the code for the forward method. You can use this to ensure TorchScript (tracing or scripting) has captured your model code correctly. Interpreting Graphs¶ TorchScript also has a representation at a lower level than the code pretty- printer, in the form of IR graphs. TorchScript uses a static single assignment (SSA) intermediate representation (IR) to represent computation. The instructions in this format consist of ATen (the C++ backend of PyTorch) operators and other primitive operators, including control flow operators for loops and conditionals. As an example: @torch.jit.script def foo(len): # type: (int) -> torch.Tensor rv = torch.zeros(3, 4) for i in range(len): if i < 10: rv = rv - 1.0 else: rv = rv + 1.0 return rv print(foo.graph) graph follows the same rules described in the Inspecting Code section with regard to forward method lookup. The example script above produces the graph: graph(%len.1 : int): %24 : int = prim::Constant[value=1]() %17 : bool = prim::Constant[value=1]() # test.py:10:5 %12 : bool? = prim::Constant() %10 : Device? = prim::Constant() %6 : int? = prim::Constant() %1 : int = prim::Constant[value=3]() # test.py:9:22 %2 : int = prim::Constant[value=4]() # test.py:9:25 %20 : int = prim::Constant[value=10]() # test.py:11:16 %23 : float = prim::Constant[value=1]() # test.py:12:23 %4 : int[] = prim::ListConstruct(%1, %2) %rv.1 : Tensor = aten::zeros(%4, %6, %6, %10, %12) # test.py:9:10 %rv : Tensor = prim::Loop(%len.1, %17, %rv.1) # test.py:10:5 block0(%i.1 : int, %rv.14 : Tensor): %21 : bool = aten::lt(%i.1, %20) # test.py:11:12 %rv.13 : Tensor = prim::If(%21) # test.py:11:9 block0(): %rv.3 : Tensor = aten::sub(%rv.14, %23, %24) # test.py:12:18 -> (%rv.3) block1(): %rv.6 : Tensor = aten::add(%rv.14, %23, %24) # test.py:14:18 -> (%rv.6) -> (%17, %rv.13) return (%rv) Take the instruction %rv.1 : Tensor = aten::zeros(%4, %6, %6, %10, %12) # test.py:9:10 for example. %rv.1 : Tensormeans we assign the output to a (unique) value named rv.1, that value is of Tensortype and that we do not know its concrete shape. aten::zerosis the operator (equivalent to torch.zeros) and the input list (%4, %6, %6, %10, %12)specifies which values in scope should be passed as inputs. The schema for built-in functions like aten::zeroscan be found at Builtin Functions. # test.py:9:10is the location in the original source file that generated this instruction. In this case, it is a file named test.py, on line 9, and at character 10. Notice that operators can also have associated blocks, namely the prim::Loop and prim::If operators. In the graph print-out, these operators are formatted to reflect their equivalent source code forms to facilitate easy debugging. Graphs can be inspected as shown to confirm that the computation described by a ScriptModule is correct, in both automated and manual fashion, as described below. Tracer¶ Tracing Edge Cases¶ There are some edge cases that exist where the trace of a given Python function/module will not be representative of the underlying code. These cases can include: Tracing of control flow that is dependent on inputs (e.g. tensor shapes) Tracing of in-place operations of tensor views (e.g. indexing on the left-hand side of an assignment) Note that these cases may in fact be traceable in the future. Automatic Trace Checking¶ One way to automatically catch many errors in traces is by using check_inputs on the torch.jit.trace() API. check_inputs takes a list of tuples of inputs that will be used to re-trace the computation and verify the results. For example: def loop_in_traced_fn(x): result = x[0] for i in range(x.size(0)): result = result * x[i] return result inputs = (torch.rand(3, 4, 5),) check_inputs = [(torch.rand(4, 5, 6),), (torch.rand(2, 3, 4),)] traced = torch.jit.trace(loop_in_traced_fn, inputs, check_inputs=check_inputs) Gives us the following diagnostic information: ERROR: Graphs differed across invocations! Graph diff: graph(%x : Tensor) { %1 : int = prim::Constant[value=0]() %2 : int = prim::Constant[value=0]() %result.1 : Tensor = aten::select(%x, %1, %2) %4 : int = prim::Constant[value=0]() %5 : int = prim::Constant[value=0]() %6 : Tensor = aten::select(%x, %4, %5) %result.2 : Tensor = aten::mul(%result.1, %6) %8 : int = prim::Constant[value=0]() %9 : int = prim::Constant[value=1]() %10 : Tensor = aten::select(%x, %8, %9) - %result : Tensor = aten::mul(%result.2, %10) + %result.3 : Tensor = aten::mul(%result.2, %10) ? ++ %12 : int = prim::Constant[value=0]() %13 : int = prim::Constant[value=2]() %14 : Tensor = aten::select(%x, %12, %13) + %result : Tensor = aten::mul(%result.3, %14) + %16 : int = prim::Constant[value=0]() + %17 : int = prim::Constant[value=3]() + %18 : Tensor = aten::select(%x, %16, %17) - %15 : Tensor = aten::mul(%result, %14) ? ^ ^ + %19 : Tensor = aten::mul(%result, %18) ? ^ ^ - return (%15); ? ^ + return (%19); ? ^ } This message indicates to us that the computation differed between when we first traced it and when we traced it with the check_inputs. Indeed, the loop within the body of loop_in_traced_fn depends on the shape of the input x, and thus when we try another x with a different shape, the trace differs. In this case, data-dependent control flow like this can be captured using torch.jit.script() instead: def fn(x): result = x[0] for i in range(x.size(0)): result = result * x[i] return result inputs = (torch.rand(3, 4, 5),) check_inputs = [(torch.rand(4, 5, 6),), (torch.rand(2, 3, 4),)] scripted_fn = torch.jit.script(fn) print(scripted_fn.graph) #print(str(scripted_fn.graph).strip()) for input_tuple in [inputs] + check_inputs: torch.testing.assert_allclose(fn(*input_tuple), scripted_fn(*input_tuple)) Which produces: graph(%x : Tensor) { %5 : bool = prim::Constant[value=1]() %1 : int = prim::Constant[value=0]() %result.1 : Tensor = aten::select(%x, %1, %1) %4 : int = aten::size(%x, %1) %result : Tensor = prim::Loop(%4, %5, %result.1) block0(%i : int, %7 : Tensor) { %10 : Tensor = aten::select(%x, %1, %i) %result.2 : Tensor = aten::mul(%7, %10) -> (%5, %result.2) } return (%result); } Tracer Warnings¶ The tracer produces warnings for several problematic patterns in traced computation. As an example, take a trace of a function that contains an in-place assignment on a slice (a view) of a Tensor: def fill_row_zero(x): x[0] = torch.rand(*x.shape[1:2]) return x traced = torch.jit.trace(fill_row_zero, (torch.rand(3, 4),)) print(traced.graph) Produces several warnings and a graph which simply returns the input: fill_row_zero.py:4: TracerWarning: There are 2 live references to the data region being modified when tracing in-place operator copy_ (possibly due to an assignment). This might cause the trace to be incorrect, because all other views that also reference this data will not reflect this change in the trace! On the other hand, if all other views use the same memory chunk, but are disjoint (e.g. are outputs of torch.split), this might still be safe. x[0] = torch.rand(*x.shape[1:2]) fill_row_zero.py:6: TracerWarning: Output nr 1. of the traced function does not match the corresponding output of the Python function. Detailed error: Not within tolerance rtol=1e-05 atol=1e-05 at input[0, 1] (0.09115803241729736 vs. 0.6782537698745728) and 3 other locations (33.00%) traced = torch.jit.trace(fill_row_zero, (torch.rand(3, 4),)) graph(%0 : Float(3, 4)) { return (%0); } We can fix this by modifying the code to not use the in-place update, but rather build up the result tensor out-of-place with torch.cat: def fill_row_zero(x): x = torch.cat((torch.rand(1, *x.shape[1:2]), x[1:2]), dim=0) return x traced = torch.jit.trace(fill_row_zero, (torch.rand(3, 4),)) print(traced.graph) Frequently Asked Questions¶ Q: I would like to train a model on GPU and do inference on CPU. What are the best practices? First convert your model from GPU to CPU and then save it, like so:cpu_model = gpu_model.cpu() sample_input_cpu = sample_input_gpu.cpu() traced_cpu = torch.jit.trace(cpu_model, sample_input_cpu) torch.jit.save(traced_cpu, "cpu.pt") traced_gpu = torch.jit.trace(gpu_model, sample_input_gpu) torch.jit.save(traced_gpu, "gpu.pt") # ... later, when using the model: if use_gpu: model = torch.jit.load("gpu.pt") else: model = torch.jit.load("cpu.pt") model(input) This is recommended because the tracer may witness tensor creation on a specific device, so casting an already-loaded model may have unexpected effects. Casting the model before saving it ensures that the tracer has the correct device information. Q: How do I store attributes on a ScriptModule? Say we have a model like:import torch class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.x = 2 def forward(self): return self.x m = torch.jit.script(Model()) If Modelis instantiated it will result in a compilation error since the compiler doesn’t know about x. There are 4 ways to inform the compiler of attributes on ScriptModule: 1. nn.Parameter- Values wrapped in nn.Parameterwill work as they do on nn.Modules 2. register_buffer- Values wrapped in register_bufferwill work as they do on nn.Modules. This is equivalent to an attribute (see 4) of type Tensor. 3. Constants - Annotating a class member as Final(or adding it to a list called __constants__at the class definition level) will mark the contained names as constants. Constants are saved directly in the code of the model. See builtin-constants for details. 4. Attributes - Values that are a supported type can be added as mutable attributes. Most types can be inferred but some may need to be specified, see module attributes for details. Q: I would like to trace module’s method but I keep getting this error: RuntimeError: Cannot insert a Tensor that requires grad as a constant. Consider making it a parameter or input, or detaching the gradient This error usually means that the method you are tracing uses a module’s parameters and you are passing the module’s method instead of the module instance (e.g. my_module_instance.forwardvs my_module_instance). - Invoking tracewith a module’s method captures module parameters (which may require gradients) as constants. - On the other hand, invoking tracewith module’s instance (e.g. my_module) creates a new module and correctly copies parameters into the new module, so they can accumulate gradients if required. To trace a specific method on a module, see torch.jit.trace_module Appendix¶ Migrating to PyTorch 1.2 Recursive Scripting API¶ This section details the changes to TorchScript in PyTorch 1.2. If you are new to TorchScript you can skip this section. There are two main changes to the TorchScript API with PyTorch 1.2. 1. torch.jit.script will now attempt to recursively compile functions, methods, and classes that it encounters. Once you call torch.jit.script, compilation is “opt-out”, rather than “opt-in”. 2. torch.jit.script(nn_module_instance) is now the preferred way to create ScriptModules, instead of inheriting from torch.jit.ScriptModule. These changes combine to provide a simpler, easier-to-use API for converting your nn.Modules into ScriptModules, ready to be optimized and executed in a non-Python environment. The new usage looks like this: import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) my_model = Model() my_scripted_model = torch.jit.script(my_model) The module’s forwardis compiled by default. Methods called from forwardare lazily compiled in the order they are used in forward. To compile a method other than forwardthat is not called from forward, add @torch.jit.export. To stop the compiler from compiling a method, add @torch.jit.ignoreor @torch.jit.unused. @ignoreleaves the method as a call to python, and @unusedreplaces it with an exception. @ignoredcannot be exported; @unusedcan. Most attribute types can be inferred, so torch.jit.Attributeis not necessary. For empty container types, annotate their types using PEP 526-style class annotations. Constants can be marked with a Finalclass annotation instead of adding the name of the member to __constants__. Python 3 type hints can be used in place of torch.jit.annotate - As a result of these changes, the following items are considered deprecated and should not appear in new code: The @torch.jit.script_methoddecorator Classes that inherit from torch.jit.ScriptModule The torch.jit.Attributewrapper class The __constants__array The torch.jit.annotatefunction Modules¶ Warning The @torch.jit.ignore annotation’s behavior changes in PyTorch 1.2. Before PyTorch 1.2 the @ignore decorator was used to make a function or method callable from code that is exported. To get this functionality back, use @torch.jit.unused(). @torch.jit.ignore is now equivalent to @torch.jit.ignore(drop=False). See @torch.jit.ignore and @torch.jit.unused for details. When passed to the torch.jit.script function, a torch.nn.Module’s data is copied to a ScriptModule and the TorchScript compiler compiles the module. The module’s forward is compiled by default. Methods called from forward are lazily compiled in the order they are used in forward, as well as any @torch.jit.export methods. torch.jit. export(fn)[source]¶ This decorator indicates that a method on an nn.Moduleis used as an entry point into a ScriptModuleand should be compiled. forwardimplicitly is assumed to be an entry point, so it does not need this decorator. Functions and methods called from forwardare compiled as they are seen by the compiler, so they do not need this decorator either. Example (using @torch.jit.exporton a method): import torch import torch.nn as nn class MyModule(nn.Module): def implicitly_compiled_method(self, x): return x + 99 # `forward` is implicitly decorated with `@torch.jit.export`, # so adding it here would have no effect def forward(self, x): return x + 10 @torch.jit.export def another_forward(self, x): # When the compiler sees this call, it will compile # `implicitly_compiled_method` return self.implicitly_compiled_method(x) def unused_method(self, x): return x - 20 # `m` will contain compiled methods: # `forward` # `another_forward` # `implicitly_compiled_method` # `unused_method` will not be compiled since it was not called from # any compiled methods and wasn't decorated with `@torch.jit.export` m = torch.jit.script(MyModule()) Functions¶ Functions don’t change much, they can be decorated with @torch.jit.ignore or torch.jit.unused if needed. # Same behavior as pre-PyTorch 1.2 @torch.jit.script def some_fn(): return 2 # Marks a function as ignored, if nothing # ever calls it then this has no effect @torch.jit.ignore def some_fn2(): return 2 # As with ignore, if nothing calls it then it has no effect. # If it is called in script it is replaced with an exception. @torch.jit.unused def some_fn3(): import pdb; pdb.set_trace() return 4 # Doesn't do anything, this function is already # the main entry point @torch.jit.export def some_fn4(): return 2 TorchScript Classes¶ Warning TorchScript class support is experimental. Currently it is best suited for simple record-like types (think a NamedTuple with methods attached). Everything in a user defined TorchScript Class is exported by default, functions can be decorated with @torch.jit.ignore if needed. Attributes¶ The TorchScript compiler needs to know the types of module attributes. Most types can be inferred from the value of the member. Empty lists and dicts cannot have their types inferred and must have their types annotated with PEP 526-style class annotations. If a type cannot be inferred and is not explicitly annotated, it will not be added as an attribute to the resulting ScriptModule Old API: from typing import Dict import torch class MyModule(torch.jit.ScriptModule): def __init__(self): super(MyModule, self).__init__() self.my_dict = torch.jit.Attribute({}, Dict[str, int]) self.my_int = torch.jit.Attribute(20, int) m = MyModule() New API: from typing import Dict class MyModule(torch.nn.Module): my_dict: Dict[str, int] def __init__(self): super(MyModule, self).__init__() # This type cannot be inferred and must be specified self.my_dict = {} # The attribute type here is inferred to be `int` self.my_int = 20 def forward(self): pass m = torch.jit.script(MyModule()) Constants¶ The Final type constructor can be used to mark members as constant. If members are not marked constant, they will be copied to the resulting ScriptModule as an attribute. Using Final opens opportunities for optimization if the value is known to be fixed and gives additional type safety. Old API: class MyModule(torch.jit.ScriptModule): __constants__ = ['my_constant'] def __init__(self): super(MyModule, self).__init__() self.my_constant = 2 def forward(self): pass m = MyModule() New API: try: from typing_extensions import Final except: # If you don't have `typing_extensions` installed, you can use a # polyfill from `torch.jit`. from torch.jit import Final class MyModule(torch.nn.Module): my_constant: Final[int] def __init__(self): super(MyModule, self).__init__() self.my_constant = 2 def forward(self): pass m = torch.jit.script(MyModule()) Variables¶ Containers are assumed to have type Tensor and be non-optional (see Default Types for more information). Previously, torch.jit.annotate was used to tell the TorchScript compiler what the type should be. Python 3 style type hints are now supported. import torch from typing import Dict, Optional @torch.jit.script def make_dict(flag: bool): x: Dict[str, int] = {} x['hi'] = 2 b: Optional[int] = None if flag: b = 2 return x, b
https://pytorch.org/docs/1.8.0/jit.html
CC-MAIN-2021-31
refinedweb
3,936
60.61
Slashdot Log In Microsoft Publishes Free XBox Development Tools Posted by ScuttleMonkey on Mon Dec 11, 2006 10:27 PM from the compile-once-crash-twice dept. from the compile-once-crash-twice dept..'" This discussion has been archived. No new comments can be posted. Microsoft Publishes Free XBox Development Tools | Log In/Create an Account | Top | 221 comments | Search Discussion The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way. Not quite free.... (Score:5, Informative) So it's not quite free. And you can't distribute the games to others....unless you distribute the source and they are also members of the creator's club. Re:Not quite free.... (Score:5, Insightful) () Re:Not quite free.... (Score:5, Informative) Not QUITE informative- not really even correct. (Score:4, Informative) () Here's the free code (Score:5, Funny) #include "creatorsclub.h" Re:Not quite free.... (Score:5, Insightful) (Last Journal: Saturday December 09 2006, @02:58AM). Is it just me... (Score:1, Interesting) Xbox 360 only (Score:5, Informative) ( | Last Journal: Friday September 14, @04:25PM) So I make a vijeo game for XBOX360 (Score:2) (Last Journal: Sunday November 06 2005, @10:30PM) Burger King ! (Score:4, Funny) () SNES (Score:5, Interesting) ( | Last Journal: Saturday February 05 2005, @03:50AM) Re:SNES (Score:4, Informative) (). Channel 9 Demo (Score:4, Informative) Non commercial (Score:5, Insightful). yeehaw! I'm gonna write me a program! (Score:3, Funny)). Take that Stallman! (Score:5, Funny) Q: What does XNA stand for? A: XNA's Not Acronymed Seems even the Evil Empire has a sense of humour.) is XNA worth the bits it's made of? (Score:1) Developers, developers, developers! (Score:3, Insightful) () Sony tried that 10 years ago (Score:1) I have lost interest in game consoles since then so i don't know how the PS2 w/linux did. Does anyone know? EverQuest like MMORPGs where participants produce experiences with each other under the domain of corporate context provider. These experiences are enriched by this appropriation and therefore accumulate social capital, and whats important to remember about capital is that is transferable. Its only logical that microsoft will try to capitalize on the home-brew game community. When those high up in the corporate hierarchy were shown a moded xbox and the home-brew software library, their question was not how do we stomp this out rather it was how do we appropriate this into our business model. The tragedy of corporate appropriation is the tendency to make things suck. For example by shifting around generated social capital (ie your coolness becomes our brand) Your youtube videos are 1.6 billion for a few people at the top and free hosting for those at the bottom. As the service model integrates the qualities/coolness of free & user generated software with open APIs, customizable interfaces and in this case low cost "development kits", the qualities that made free software so desirable are appropriated and generally potentially crippled as generated social capital is siphoned off to disproportionately support the (relatively minor) contributions of a few at the top. So we see the rise of free service models wikipedia, creative commons, participatory culture foundation, the linux platform etc. (they are still appropriated and ofcourse people profit disproportionate to their contributions but at least there are some structural qualities in place that limit the disproportional profitability such as the GPL, open platforms, copyleft etc. We should probably chose to participate in those spaces if possible or given circumstance and specific goals you decide to make content for microsoft/google/sony, that fine as long as you think about it first ;)) () Thoughts on microsoft's strategy (Score:1) Seriously, it sounds like this is an ok idea but the amount of restrictions seem to limit its potential. It appears to lower the barrier to entry...but does it really? It sounds like when you read the fine print they aren't really giving you much. I guess I can't blame them, they make their money on the games not the console...so if they started giving distribution rights away for free they would be screwing themselves. Microsoft has been trying to have their cake and eat it too by making cross platform games for windows/PC easy. Games are the main thing that ties you average home user to the windows platform. They've kind of been eating themselves since they jumped into the console arena. Cross-platform is a way of saying to users "you still need windows for PC games!" while still growing their console end. The trouble is, the PC has traditionally offered some advantages over the console in controls, community, etc. Perhaps advantages isn't the right word, rather differences. Most ported or even cross platform games feel like the PC support was stuck on as an afterthought these days, they have since the xbox came out. Its not a PC game...its a console game on your PC. Its only a matter of time before the PC gamers start just buying a xbox instead. And you can see that happening now, I hear a lot of people saying "its expensive upgrading my PC...I'm just going to buy an xbox360 or PS3 instead". Maybe thats what microsoft wants. But its also going to weaken their OS market because people are going to buy less new PCs and stay with their old ones longer. We'll see how this strategy plays out in the end. Frankly, I think MS would have been better offering a console that was very different from the PC as a gaming platform to prevent dilution of that brand. But, they're a computer company so its not a surprise they stuck with what they knew. (The original xbox pretty much was just a PC anyway right?) Why do you guys care about money so much? (Score:1) XNA is a waste. (Score:1, Troll) Well three reasons since you asked so nicely. 1. XNA allows you to build stuff for your PC for free, and pay 100 bucks a month for building for the 360? WOW! unless you care about the second half, ANY compiler allowed you to build stuff for your PC for Free. What's worse is unless a prospective employee has creators club (or wants to get it) they can't really see your work unless it's on the PC. So basically you're stuck. Instead you can get Visual Studio with just DirectX and learn how to REALLY program, rather then relying on an enviroment. If XNA is easy to use, everyone will use it and there will be a lot of worthless demos. Companies want to see that you programmed, not that you did something easy. 2. C# is not a great programming language. Ok it has uses. However making games is NOT one of them. If you program for a console you're probably in C++ if you're not programming for a console you use what language you want. C# might make some stuff easier, but unless you know C++ you're not going to be a real asset to a company. In addition C# is Microsoft's programming language. It's a bastard of C++ and Java, basically so Microsoft could own a language. Don't buy into it. Java and C++ are both good languages as well, I have heard of few jobs that want C# currently. 3. As people have mentioned to get access you need to pay 100 bucks a month then your friend has to pay 100 a month, then your other friend has to pay 100 a month. It's not a "cheap" development studio. A cheap development studio is your PC. Besides which unless you know how to do multi core processing (don't you DARE say you do unless you've done it and shipped a product, it's much harder then you realize) the 360 is going to be weaker then your PC. It's true you don't have a unified system, but even on the 360 you no longer have it with hard drives and non hard drives. In addition you have to submit to Microsoft's rules at times (mostly during production), which limits your freedom a little more. This might be an option for some people but if you're doing professional grade work you will almost definatly have a dev kit. If you arn't it doesn't really matter because the work is the important part, not the final product so skip XNA and work on other stuff. The only person who needs XNA is the idiot who MUST program in C# and must program on the 360. Just remember anything you do in XNA will likely be only for the PC and 360, and not for any other console. Microsoft is doing good positioning themselves, but if you look into their motives it's not for the fans. It's to improve their brands (C#, XNA, Xbox 360, DirectX). Unless you want to only support those brands you are better off moving on. self-publishing? (Score:2) () Now, I don't claim to unerstand the terms of the XNA license, but I got the definite impression that you couldn't self-publish games either onto the marketplace or for free distribution - it has to be published through Microsoft. You can't even share a game YOU wrote with a friend unless they also have a developer account, and even then, it has to be done over the XBL network. So not only is this bad for developers who want to release their work for free or under their own license, but it forces you into a position of relying on Microsoft to publish your work regardless of your own wishes. Am I simply misunderstanding something here, or is XNA really as idiotic as it looks to me? Yawn (Score:2) Re:Close, but no biscuit (Score:2) Nice way to make sure you don't do a port to something else. I think the DirectX part is more likely to restrict portability. C# can run on a lot of platforms, thanks to the mono team's work, you know? It had to be said, Pt. 2 (Score:1)
http://developers.slashdot.org/developers/06/12/11/2346244.shtml
crawl-002
refinedweb
1,731
72.36
IBM WebSphere Application Server 8.0 Administration Guide — Save 50% Learn to administer a reliable, secure, and scalable environment for running applications with IBM WebSphere Application Server 8.0 with this book and eBook) (For more resources on IBM, see here.) Dumping namespaces To diagnose a problem, you might need to collect WAS JNDI information. WebSphere Application Server provides a utility that dumps the JNDI namespace. The dumpNamespace.sh script dumps information about the WAS namespace and is very useful when debugging applications when JNDI errors are seen in WAS logs. You can use this utility to dump the namespace to see the JNDI tree that the WAS name server (WAS JNDI lookup service provider) is providing for applications. This tool is very useful in JNDI problem determination, for example, when debugging incorrect JNDI resource mappings in the case where an application resource is not mapped correctly to a WAS-configured resource or the application is using direct JNDI lookups when really it should be using indirect lookups. For this tool to work, WAS must be running when this utility is run. To run the utility, use the following syntax: ./dumpNameSpace.sh -<command_option> There are many options for this tool and the following table lists the command-line options available by typing the command <was_root>/dumpsnameSpace.sh -help: WebSphere 5.0: Server root context. This is the initial reference registered under the key of NameServiceServerRoot on the server. - WebSphere 4.0: Legacy root context. This context is bound under the name domain/legacyRoot, in the initial context registered on the server, under the key NameService. - WebSphere 3.5: Initial reference registered under the key of NameService, on the server. - Non-WebSphere: Initial reference registered under the key of NameService, on the server. Example name space dump To see the result of using the namespace tool, navigate to the <was_root>/bin directory on your Linux server and type the following command: - For Linux: ./dumpNameSpace.sh -root cell -report short -username wasadmin -password wasadmin >> /tmp/jnditree.txt - For Windows: ./dumpNameSpace.bat -root cell -report short -username wasadmin -password wasadmin > c:\temp\jnditree.txt The following screenshot shows a few segments of the contents of an example jnditree.txt file which would contain the output of the previous command. EAR expander Sometimes during application debugging or automated application deployment, you may need to enquire about the contents of an Enterprise Archive (EAR) file. An EAR file is made up of one or more WAR files (web applications), one or more Enterprise JavaBeans (EJBs), and there can be shared JAR files as well. Also, within each WAR file, there may be JAR files as well. The EARExpander.sh utility allows all artifacts to be fully decompressed much as expanding a TAR file. Usage syntax: EARExpander -ear (name of the input EAR file for the expand operation or name of the output EAR file for the collapse operation) -operationDir (directory to which the EAR file is expanded or directory from which the EAR file is collapsed) -operation (expand | collapse) [-expansionFlags (all | war)] [-verbose] To demonstrate the utility, we will expand the HRListerEAR.ear file. Ensure that you have uploaded the HRListerEAR.ear file to a new folder called /tmp/EARExpander on your Linux server or an appropriate alternative location and run the following command: - For Linux: <was_root>/bin/EARExpander.sh -ear /tmp/HRListerEAR.ear -operationDir /tmp/expanded -operation expand -expansionFlags all -verbose - For Windows: <was_root>\bin\EARExpander.bat -ear c:\temp\HRListerEAR.ear -operationDir c:\temp\expanded -operation expand -expansionFlags all -verbose The result will be an expanded on-disk structure of the contents of the entire EAR file, as shown in the following screenshot: An example of everyday use could be that EARExpander.sh is used as part of a deployment script where an EAR file is expanded and hardcoded properties files are searched and replaced. The EAR is then re-packaged using the EARExpander -operation collapse option to recreate the EAR file once the find-and-replace routine has completed. An example of how to collapse an expanded EAR file is as follows: - For Linux: <was_root>/bin/EARExpander.sh -ear /tmp/collapsed/HRListerEAR.ear -operationDir /tmp/expanded -operation collapse -expansionFlags all -verbose - For Windows: <was_root>\bin\EARExpander.bat -ear c:\temp\collapsed\HRListerEAR. ear -operationDir c:\temp\expanded -operation collapse -expansionFlags all -verbose In the previous command line examples, the folder called EARExpander contains an expanded HRListerEAR.ear file, which was created when we used the -expand command example previously. To collapse the files back into an EAR file, use the -collapse option, as shown previously in the command line example. Collapsing the EAR folders results in a file called HRListerEAR.ear, which is created by collapsing the expanded folder contents back into a single EAR file. IBM Support Assistant IB: - Search Information - Search and filter results from a number of different websites and IBM Information Centers with just one click. - Product Information - Provides you with a page full of related resources specific to the IBM software you are looking to support. It also lists the latest support news and information, such as the latest fixes, APARs, Technotes, and other support data for your IBM product. - Find product education and training materials - Using this feature, you can search for online educational materials on how to use your IBM product. - Media Viewer - The media viewer allows you search and find free education and training materials available on the IBM Education Assistant sites. - You can also watch Flash-based videos, read documentation, view slide presentations, or download for offline access. - Automate data collection and analysis - Support Assistant can help you gather the relevant diagnostic information automatically so you do not have to manually locate the resources that can explain the cause of the issue. - With its automated data collection capabilities, ISA allows you to specify the troublesome symptom and have the relevant information automatically gathered in an archive. You can then look through this data, analyze it with the IBM Support Assistant tool, and even forward data to IBM support. - Generate IBM Support Assistant Lite packages for any product addon that has data collection scripts. You can then export a lightweight Java application that can easily be transferred to remote systems for remote data connection. - Analysis and troubleshooting tools for IBM products - ISA contains tools that enable you to troubleshoot system problems. These include: analyzing JVM core dumps and garbage collector data, analyzing system ports, and also getting remote assistance from IBM support. - Guided Troubleshooter - This feature provides a step-by-step troubleshooting wizard that can be used to help you look for logs, suggest tools, or recommend steps on fixing the problems you are experiencing. - Remote Agent technology - Remote agent capabilities through the feature pack provide the ability to perform data collection and file transfer through the workbench from remote systems. Note that the Remote agents must be installed and configured with appropriate 'root-level' access. SystemOut.log file. Downloading the ISA workbench To download ISA you will require your IBM user ID. The download can be found at the following URL: It is possible to download both Windows and Linux versions. (For more resources on IBM, see here.) Installing the ISA workbench To start the ISA workbench installation run the following commands: - For Linux: rpm -ivh support-assistant-4.1.2.00-20101123_1610.i386.rpm - For Windows: setupwin32.exe In the following example, we are using a Windows installation; however, the process is almost identical for Linux, except that the installation location filepaths will be different. For Linux, the RPM installer will install ISA in the following location: /opt/ibm/ IBMSupportAssistant_4. Follow these steps for the installation wizard: - Once the ISA workbench installation wizard has loaded, Click on Next and then read and accept the License Agreement on the following page. Click on Next again. - On the Destination folder screen, choose the location where you wish to install the ISA binaries. Click on Next to continue. - On the next screen, you will be given an option to choose the location of where your user data will be stored. Choose an appropriate option to suit your requirement and click on Next to continue. In our example, we have chosen to use the default location. - On the last screen, review your settings and click on Install to begin the installation. - Once the installation wizard has completed click on Finish. Launching ISA One you have installed ISA, you can launch the ISA workbench application using the following commands: - For Linux: /opt/ibm/IBMSupportAssistant_41/rcp/rcplauncher - For Windows: C:\Program Files (x86)\ibm\IBM Support Assistant v41\rcp\ rcplauncher When ISA loads it will present the welcome page: The first time the ISA workbench is loaded, it will prompt to inform you that it needs to update the list of available add-ons. The update process runs as a background task to keep ISA up-to-date with available add-ons. (Move the mouse over the image to enlarge it.) By default, ISA is set to start the update process as a background task every time ISA is launched; however, you may wish to disable automatic updates or simply schedule updates to occur at certain times of the day. Using the File | Preferences | Updater Preferences menu, you can enable/disable updates via the Automatically find new updates and notify me checkbox option: Adding add-on tools ISA organizes the downloads of add-on tools, such as the Log Analyzer, Symptom Editor, Memory Analyzer, Garbage Collection and Memory Visualizer, and Dump Analyzer, to name a few, which are all very useful tools for WAS administration. There are many other tools and add-ons constantly being made available. The following steps explain how to install the Log Analyzer: - Ensure you have an Internet connection as ISA will be communicating with IBM remote repositories. - From the workbench menu, select Update | Find New | Tools Add-ons: - A background task will be initiated and ISA will return with a list of the latest available add-ons from IBM. - When the Tool add-ons to install window appears, expand the JVM-based tools option: - Select Log Analyzer 4.5.0.3 (or the latest version) from the list of available tools: It is possible to install several tools at the same time. - On the License of Add-ons to install screen, read and accept the license agreement and click on Next to continue. - You will now be presented with a summary of the add-ons that will be installed. Click on Install. - After the installation has completed, you will be prompted with a screen summarizing the results of the installation operations: (Move the mouse over the image to enlarge it.) - Click on Finish to complete and you will be prompted to restart ISA. Once ISA has been restarted, you can use the Log Analyzer add-on. Analyzing log files Now that we have installed the Log Analyzer, we can import a WAS SystemOut.log and analyze it. In our example, we will use a local copy of SystemOut.log, which has been copied from a WAS server and is located in C:\temp. - To analyze a log file, click on the Analyze Problem link on the workbench welcome page: - From the Tools Catalog list, locate Log Analyzer and click on Launch: - Once the Log Analyzer has loaded, select File | Import Log from the main menu: - On the Import Log screen, select the Import from the local system option and click on Next: - On the Import from the local system screen, browse for the log file, then click on the Add button to add the log to the Logs to be imported into Log Analyzer list and click on Finish. The log will be parsed by the Log Analyzer and imported. The result will be to display the log data as a list of rows in the right-hand panel. In the following screenshot, we see example entries which you might find in a SystemOut.log file: - Now you have imported a log file, you can navigate through the log data as a set of rows. Note that there is a toolbar located above the main log panel, as shown in the following screenshot: - This toolbar allows you to change the colors of specific error severities and select columns of field data as required. It also allows you to sort columns to make it easier to navigate through the log data in a structured manner. Just viewing logs is not a useful problem analysis activity until the log is compared against a database of known symptoms and recommended solutions. A symptom catalog contains three key types of information: - Symptoms: Common problems or error messages - Solutions: Reasons why the error may have occurred - Directives or resolutions: Possible resolutions for the error Within the example imported log as shown in the previous section, we can see that there is a CPU Starvation detected. We can import a symptom catalogue to get recommended solutions from the IBM support knowledge base. Use the following steps as a guide to import a symptom catalog: - Select File | Import Symptom Catalog from the main menu. - On the Import Symptom Catalog screen, choose an appropriate symptom catalog in the From remote host list: In our example, we are using a WAS 7 symptom catalog as, at the time of writing, there are no WAS 8 symptom catalogs available. Symptom catalogs are continually being added and updated by IBM support on a regular basis. Symptom catalogs are still very useful, even if they are for a previous version of WAS, as many errors are generic and similar across versions. - Click on Finish to import the symptom catalog. The symptom catalog will appear in the Log Navigator, as shown in the following screenshot: - Right-click the SystemOut.log entry in the Log Navigator and select Analyze. The result will be a report listing solutions and recommendations for known errors. The report is located in the bottom section of the right-hand log entry panel. - Locate the Symptom Analysis Result panel and select the symptom you are interested in to view details from IBM Support: - In the previous example, we have selected one of the CPU Starvation symptom records. To the right of the Symptom Analysis Result panel is another panel called the Symptom Definition panel. Here, details such as recommendations and solutions are described for the selected symptom. Often, there is a URL link (within the description field) to an online IBM support page detailing the error and known solutions: We have now completed a very simple log analysis. The ISA is a very powerful application. By demonstrating just one of the many add-ons, such as Log Analyzer, we see that the ISA is a very important administration tool. Summary In this article, we saw that WebSphere Application Server comes with some useful command-line tools. The dumpNameSpace.sh utility can be used to view the JNDI tree of a running application server, which is very useful in helping with debugging the root cause of application failures that involve JNDI resource lookups. Another tool we looked at was the EARExpander.sh utility, which can be used to unpack an EAR file during automated deployments, to manipulate the EAR file, and repackage it on the fly. It can also be used during problem diagnosis if the supplied EAR file has problems during deployment. Further resources on this subject: - Tuning WebSphere Security [article] - Replication Alert Monitor: Monitoring Management [article] - IBM WebSphere Application Server Security: A Threefold View [article]:. Post new comment
http://www.packtpub.com/article/ibm-websphere-application-server-administration-tools
CC-MAIN-2014-15
refinedweb
2,586
52.19
16 November 2007 15:59 [Source: ICIS news] By Nigel Davis LONDON (ICIS news)--Chemical producers don’t like the EU’s cap and trade approach to climate control but have had to learn to live with it. Emissions trading could work, the argument goes, but the current system is flawed. Chemicals makers are not alone. ?xml:namespace> Of greatest concern to industrial firms has been the way in which power producers have made windfall profits on carbon dioxide allowances. The situation defeats the ‘polluter pays’ principle, says chemicals trade group Cefic. It tilts the playing field to the disadvantage of That will not change next year when the second stage of the ETS begins. It is likely to get worse. High energy users particularly are expecting to be hit with higher prices. The European Commission (EC), keen to see better results from the ETS, has lowered the carbon caps allotted to So the region's power companies are expected to raise prices along with the expected rising cost of tradable carbon. The scheme, under which European industries must surrender allowances equivalent to their CO2 emissions, will reach the end of phase one in December this year. Its effectiveness was dented by an over-generous provision of allowances and what some argued to be an inadequate policing of the system. Already hit by a massive price increased over the past five years, high energy uses are fearful of more. Electricity prices in the A large proportion of these increases are due to the pass-through of ETS costs. A study from the EU’s Competition Directorate published in April this year suggested that 29% of the electricity price in Cefic says that since CO2 allowances have largely been distributed free of charge, electricity producers have included the opportunity cost, rather than real costs, in their prices - leading to a transfer of wealth from consumers to producers without environmental benefit. The entire industry is hit by higher power costs but chlor-alkali makers the most. To make one electrochemical unit (ECU), or one tonne of chlorine and 1.1 tonnes of caustic soda, they need about 3 MWh, thus magnifying any electricity cost increases. The real worry now is that costs will rise still further from 1 January as the new phase of the ETS comes into play. From 1 January the cost of carbon, which currently is around €20/€22 per EU allowance (equivalent to one tonne of carbon dioxide), will be factored into the cost of Europe’s electricity. High energy uses expect the playing field to be tilted further against them. Cefic’s Energy Intensive Users Group (EIUG) says that the price of carbon in 2008 is certain to be higher not only because of the new caps on allocation levels but also because of the ways in which allocations have already been made which has left some users already net short. As it pushes up energy prices the EU’s cap and trade system also works against producers wanting to increase capacity - it is cheaper to do so outside Europe in parts of the world where no such Kyoto Protocol-driven manipulation of markets exist. Chlor-alkali producers have had a tough 2007 and it does not look as though 2008 will be any easier. Against such a backdrop, vitally important investment decisions will not be made in And while the high energy users suffer on the cost front, chemical producers start to fall under the cap and trade mechanism for the first time. The major EU ethylene plants come under the cap and trade scheme from 2008 and the carbon allocations made on a national basis for the 2008/2012 period. The EC has made across the board cuts in national allocations that will ultimately affect these producers. One of the hottest topics of discussion in Brussels now is speculation on what carbon allocations will be made in the critical 2013-2020 period. Many believe that the commission feels entitled to move to ensure that 20% plus cuts in emissions (compared with 1990) can be put in place then. The across the board cuts could be as high as 30%. By that time the industry is rightly concerned as to who else globally will be subject to the ramifications of more serious carbon control. Europe's producers will have worked under the burden of the ETS for 15 years. Which of their competitors will be subject to similar
http://www.icis.com/Articles/2007/11/16/9079442/insight-look-out-for-carbon-trading-induced-costs.html
CC-MAIN-2015-18
refinedweb
742
57
CodePlexProject Hosting for Open Source Software Okay, I have been at this for days and I didn't even know where to start, so I decided to turn to these forums to see if this has been done before (either no one has or it's incredibly easy because I have found nothing on the internet about it) I have a working MVC project that I just finished writing. It uses multiple controllers, views, partial views, etc. It also uses a controller factory (Ninject) and I think that may be one of my problems. The program accesses and makes changes a database of my own (SQL), that it connects to through the appropriate connection string stored in Web.config. Now I am faced with the task of making it into a module or widget in Orchard. I have been scouring the internet and I haven't found anything about doing what I am trying to do. I've studied the Hello World tutorial on the Orchard site for hours trying to figure out what I might be missing. I tried making module.txt and Routes.cs files, with no luck. I've also tried adding the extra constructor and localization lines I found in the HelloWorld source download (that aren't actually shown in the online tutorial...). Every time I change something I just get a different random error. Often they are things like ADOExceptions somewhere in Orchards code, so I don't even know what I've done wrong. Does anyone have any insight on the task of converting an MVC project into a module? It would be much appreciated. And I apologize if I have missed any threads or guides on this that will solve all my problems. Thanks in advance I think you'll have to factor out Ninject - Orchard uses Autofac for dependency injection which covers controllers as well, so you'll likely get conflicts there. Otherwise it should be straightforward - if you haven't used MVC areas yourself, then your whole project should be able to just sit in Orchard as an MVC area (which is all that Orchard modules are behind the scenes). ADOExceptions can occur for a variety of reasons, sometimes it can be when you're passing IQueryables down into the view, but the transaction scope has expired by the end of your Action. So you need to .ToList() any data you're sending into your view. Otherwise if you can be more specific providing an exception detail and your code that's causing it, someone can probably help you further :) Well thank you for the quick response, randompete. I cheated out of using Ninject by hard coding my repository declaration into the controller (for now at least). I must apologize as I'm still pretty new to MVC as well, so it's possible I'm doing weird things all over. Anyway, with that hard coded and the use of a breakpoint or two, I have learned that it actually does run through the proper action in my controller, I hadn't thought it was getting that far. When it gets to my return View(viewModel); statement, it then jumps through a couple Orchard files and gets stuck on one called Repository.cs, giving me an error here: public virtual T Get(int id) { return Session.Get<T>(id); } (on the return statement) It's an ADOException, and here is the associated description I guess: While preparing SELECT contentite0_.Id as Id226_0_, contentite0_.Data as Data226_0_, contentite0_.ContentType_id as ContentT3_226_0_ FROM Orchard_Framework_ContentItemRecord contentite0_ WHERE contentite0_.Id=@p0 an error occurred Judging by what you've told me, I suppose it may be my viewmodel that's tripping it up. Here it is: public class ListViewModel { /* List of columns with information to be shown and additional necessary information */ public List<DBColumns> Columns { get; set; } /* Contains all of the firm names, used in the DDL to filter by firm */ public List<SelectListItem> FirmDropDown { get; set; } /* Used for displaying the firm name at the top of the ConfigTables partial view */ public string FirmName { get; set; } /* Used for transmitting the current DDL selected firm to the controller */ public string FirmID { get; set; } } The only part being used at this point is FirmDropDown. I'm not entirely sure if it's an IQueryable that can be fixed the way you said (is it not already a list?) I think it's exactly what I was saying; you need to enumerate your data *before* passing it into the view, but can you post your action code so I can see how you're creating the ListViewModel? Sure thing. public ActionResult List(int? firmID) { // view model containing only the firm drop down information // table data will only be rendered once user requests it var viewModel = new ListViewModel { FirmDropDown = (from cor in repository.cFM orderby cor.CN select new SelectListItem { Text = cor.CN, Value = cor.LFirmId.ToString() }).ToList(), FirmID = firmID.ToString() }; return View(viewModel); } Well, that should be fine - I take it that debugging you can see the correct data in the ViewModel? What's in your View code? Yes, the FirmDropDown is populated properly, the rest is null as it's not used at first. Here's my view, it's just a drop down list that updates a partial view when changed: @model ConfigMod.Models.ListViewModel @{ ViewBag.Title = "Sample"; } <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> <script src="/Scripts/jquery.blockUI.js" type="text/javascript"></script> @using (Ajax.BeginForm("ConfigTable", null, new AjaxOptions { UpdateTargetId = "result" }, new { id = "ajaxForm" })) { <div class="mainBar" > <p> <b>Firm:  </b> @Html.DropDownListFor(x => x.FirmID, Model.FirmDropDown, "--Select a Firm--", new { onchange = "fnSubmitOnSelect()" }) <b>What do you want to do?  </b> @Html.TextBox("Application", "This will be a dropdown eventually...") </p> </div> } <script type="text/javascript" > $(document).ready(function () { BlockUI(); $("#ajaxForm").submit(); }); function fnSubmitOnSelect() { BlockUI(); $("#ajaxForm").submit(); } function BlockUI() { $.blockUI({ message: '<h1>Just a moment...<br/><img src="/Content/images/ajax-loader.gif" /></h1>', overlayCSS: { backgroundColor: '#000', opacity: 0.3 }, fadeIn: 500 }); } $(document).ajaxStop($.unblockUI); </script> <div id="result"> </div> EDIT: I replaced the entire view with this: <h2>@T("Hello World!")</h2> and got the same error DOUBLE EDIT: With the view still nothing but Hello World, I also replaced the return statement in my action to read just return View(); If you do your own database access, you need to opt out of Orchard's ambient transaction. This is done by surrouding your data access code with a using (new TransactionScope(TransactionScopeOption.Suppress). Oh wowee. I don't understand it, but it worked! Thanks bertlandleroy and randompete for all the help :) Er.. new issue now though... It doesn't seem to like JavaScript very much, giving me things like "Microsoft JScript runtime error: '$' is undefined" and "Microsoft JScript runtime error: 'Sys' is undefined" Am I doing something else wrong? Or is this a known issue? Is JavaScript/Ajax not compatible with Orchard?? D: Also this: "Microsoft JScript runtime error: The value of the property '$' is null or undefined, not a Function object" I can explain: Orchard has an ambient transaction around its unit of work, so that you don't have to worry about transactions most of the time. Just modify your objects and unless you need to rollback the transaction you don't need to worry about it. In other words, we do not require code for the common case (everything is going well), but only when something went wrong (abort everything! revert what you just did!). Of course this breaks down if you need to write code that should not be included in the Orchard transaction, such as custom data access code to another database. Hence the suppression of the ambient scope. JavaScript is perfectly compatible with Orchard :). It's just that you are in a collaborative, modular architecture now so everyone needs to play nice with common resources. Scripts are common resources: more than one module may require jQuery for example and you don't want to include it twice. The API that you need to learn about are Script.Require and Script.Include. Specifically, you'll need to Script.Require("jQuery") instead of injecting a script tag. Okay, sorry to be a fish, but I tried adding @Script.Require("jQuery") to the top of my view, and now it gives me "The name 'Script' does not exist in the current context" I found a few threads on here addressing that, but I was still unable to solve my problem. I tried not using debug mode, and it still gave me that horrible yellow screen. I also tried merging as well as totally replacing my web.config with one from a different module, since mine was copied in from the pre-orchard MVC project. Still nothing. I can't remember at this point if I actually used codegen in the console to start this module, so I may be missing a reference a dependency or two. You probably need the right references and/or Web.config in your project. Did you use the codegen feature to make the new project, or are you trying to convert an existing one? Converting an existing one. Would it be better at this point to move my project out, codegen one of the same name, and copy the contents back in excluding web.config? Possibly excluding other things but I don't know what? It's mainly the Web.config and references; codegen an empty module and see what's in there. You'll also see things like each of the resource-type folders have a specific Web.config allowing static files to be served, things like that. The Web.config is very different to a usual MVC project I think. Okay I'm assuming I've fixed the web.config issue because I no longer get the error about Script not existing. However, I am now back to getting "The value of the property '$' is null or undefined, not a Function object" etc. I have tried adding @Script.Require("jQuery"); @Script.Include("jquery-1.5.1.min.js"); @Script.Include("/Scripts/jquery-1.5.1.min.js"); And I still receive the errors. The @Script. ... lines only seem to add "Orchard.UI.Resources.RequireSettings;" to the top of my view's output (like in the browser)... and when I look in the source, the references are not added anywhere. And for all three of the above lines I've tried, it always outputs the same thing. Has anyone seen this before? Oh and I also tried commenting my original <script> tags that included the necessary script files. @ is the Razor syntax for "print". You shouldn't use it for Script.Require etc. - you're not printing anything, you're making a function call. So wrap all those calls in an @{ ... } code block. I hope this explains it a bit better. What randompete says is to write it like so. @{ Script.Require("jQuery"); Script.Include("your_js_file.js");// this file is under YourModule/Scripts/your_js_file.js } I got it working, and am on my way to new errors and issues xD Thanks for the help guys! Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/262662
CC-MAIN-2017-13
refinedweb
1,926
65.62
Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering two ways to get the Greatest Common Denominator (GCD) of two numbers in just 3 lines of Python each! We’ve covered a lot of different kinds of programs in the Super Simple Python series. We’ve covered programs using the random library like the Dice Roll Simulator, infrastructural programs like the Card Deck Generator, and math programs like the Prime Factorizer. This one falls in the math category. Watch the video here: Euclidean Algorithm Euclid is a famous Greek mathematician. He came up with countless numbers of math theories, including the Euclidean Algorithm. The Euclidean Algorithm is a simple way to find the Greatest Common Denominator of two integers. Given two integers, we subtract the smaller from the larger until one of the numbers is equal to 0. The remaining positive integer is the Greatest Common Denominator. Let’s take a look at the Euclidean Algorithm in practice. Iterative Implementation in Python The first implementation of the Euclidean Algorithm in Python that we’ll take a look at is how to iteratively get the GCD of two numbers. This function will take two integers, x, and y, and return the Greatest Common Denominator. It doesn’t matter if you pick x or y for the condition in the while loop, for this example, we’ll pick y. While y is not yet 0, we’ll set the new values of x and y to y and the remainder when x is divided by y. At the end of the loop, y will be 0, and we return x as the GCD. def iterative_gcd(x: int, y: int): while(y): x, y = y, x%y return x Recursive Implementation in Python The second implementation of the Euclidean Algorithm in Python we’ll implement is the recursive implementation. Looking at the iterative function above, it looks like it does the same thing every single step right? That’s a surefire sign that there is a way to recursively implement this function. Just like our iterative function, our recursive function will take two integers, x and y, as input. In this case, we’ll build in an if statement to stop the recursion when one of the numbers is equal to 0. Once again, we choose y arbitrarily. We swapped x and y with y and the remainder when x is divided by y in the iterative version. In the recursive version, we’ll just return the function when the inputs x and y are swapped with y and the remainder when x is divided by y. def recursive_gcd(x: int, y: int): if y == 0: return x return recursive_gcd(y, x%y) Testing Now let’s take a look at some examples of our implementations. I’ve written 5 examples that we’ll test with both implementations. I’ve also commented the expected output next to them. print(iterative_gcd(10, 20)) # 10 print(iterative_gcd(33, 41)) # 1 print(iterative_gcd(48, 64)) # 16 print(iterative_gcd(99, 81)) # 9 print(iterative_gcd(210, 70)) # 70 print(recursive_gcd(10, 20)) # 10 print(recursive_gcd(33, 41)) # 1 print(recursive_gcd(48, 64)) # 16 print(recursive_gcd(99, 81)) # 9 print(recursive_gcd(210, 70)) # 70 When we run our program we should see something like the following image. Just like we expected.
https://pythonalgos.com/super-simple-python-two-ways-to-get-gcd/
CC-MAIN-2022-27
refinedweb
566
61.56
Entity Resolution on Voter Registration Data An Iterative Process by Prema Roman Entity resolution is a field that aims to find records in data sets that refer to the same entity by grouping and linking. Entity resolution is also called deduplication, merge purge, patient matching, etc. depending on the application. In voter registration, it is a useful technology to make sure voter rolls are up to date and can be used to see if a voter is registered in multiple states. There are many challenges to applying entity resolution. Different data sources have varying schema, collection standards and methodologies. Even the task of standardizing the data to link entities from these sources can be a cumbersome task. To further complicate matters, there can be spelling errors, transposed characters, missing values, and other anomalies. Why voter registration data? There has been a lot of discussion around voter fraud during the most recent Presidential election. The following article stated that there were 3 million people who were registered to vote in multiple states. Entity resolution is a tool that can be used to clean up voter registration data, ensure integrity in the election process, and prevent voter fraud, thereby helping to restore people’s confidence in the voting process. Voter Registration Data Source For the purposes of this project, DC voter registration data from 2014 was used. The data is available at this website. All of the information was compiled into a zipped-up csv file that contained a header row and 469,610 rows of voter registration data. The following are the most significant fields related to a particular voter: Since the data was provided as a csv file, it was an easy task to import the records into a table in a MySQL database. The data was imported into a database called dcvoterinfo and the table was named voterinfo. To make the task of entity resolution easier, certain fields were combined to form new fields based on logical groups. The fields LASTNAME, FIRSTNAME, MIDDLE, and SUFFIX were combined to create a new field called name. Similarly, the RES_HOUSE, RES_FRAC, RES_APT, RES_STREET, RES_CITY, RES_STATE, RES_ZIP, and RES_ZIP4 fields were combined to create a field called address. There was one record with a value in the REGISTERED field where the recorded year was 2223, which was clearly an error. Also, there were 40 records with REGISTERED year 1900, all with the date 01/01/1900, which was most likely a collection error. Grouping records by year reveals that prior to 1968, there was very little data. In fact, the total number of records prior to 1968 was 123, while the number of records in just 1968 alone was 8,628. These were left in the data set and did not appear to cause any issues with the results. Studying the data set revealed that the following fields were most likely to identify a unique entity: name, address, REGISTERED. Fields such as precinct and ward are dependent on the address field and are, therefore, redundant. One quick and dirty way to determine if there were possible duplicates was to use a SQL group by query to see if there was more than one record that matched an attribute or a set of attributes. The following is a query that was run to identify potential duplicates using the name and address fields: select name, address, count(*) from voterinfo group by 1, 2 having count(*) > 1; The above query generated 703 results - most resulted in two matches per group, and there were four groups that had three matches. The following is a snapshot of the results: Looking at the records for RUSSELL D SIMMONS revealed that the value for REGISTERED was different in these records: the first REGISTERED date was 3/23/1968, the second was 10/12/1996, and the third was 5/9/2006. It is possible that a father and son lived at the same address, but since we had three matches, it was possible that two of the records refer to the same entity. Adding REGISTERED to the sql query found 10 results with the same values for name, address and REGISTERED. The following are the records: The records for AKIL A LASTER showed that there were two records with a REGISTERED date of 11/4/2014 and another record with a REGISTERED date of 11/12/2014. It was very likely that these three records refered to the same person. Using Dedupe Without domain knowledge regarding the data set, we had to make some assumptions on how to identify duplicate records. Since the data spans several years, it was possible for someone to have moved and to have more than one address. But in the absence of the residential address history and to simplify the analysis, we made the assumption that name and address will uniquely identify an entity. While the sql queries revealed duplicates, the data set probably had other duplicates that were not caught because of misspellings in the name and/or address fields. This was where Dedupe came in. Dedupe is a Python library that performs entity resolution. Since the data set is in MySQL, it was a pretty straightforward task to use the mysql_example.py code from the dedupe-examples package. Some changes had to be made to the code, namely the data source, table name, fields etc. The following were the fields selected from the voterinfo table: VOTER_SELECT = "SELECT voterid, REGISTERED, name, address, " \ "precinct, ward, anc, smd from voterinfo" # ## Training if os.path.exists(settings_file): print('reading from ', settings_file) with open(settings_file, 'rb') as sf : deduper = dedupe.StaticDedupe(sf, num_cores=4) else: # Define the fields dedupe will pay attention to # fields = [{'field' : 'name', 'variable name' : 'name', 'type': 'String'}, {'field' : 'address', 'variable name' : 'address', 'type': 'String'}, {'field' : 'REGISTERED', 'variable name' : 'REGISTERED', 'type': 'String'}, {'type' : 'Interaction', 'interaction variables' : ['name', 'address']} ] Running the code against the data set resulted in 8,111 clusters. Several of these clusters contained 5 or more duplicate entities, which seemed excessive. It also took several hours to run. Upon examining the results, it was clear that name was over weighted. All the clusters had either the exact same name or names that were very close (such as Craig C Johnson Sr and Craig C Jonhson) regardless of the value in the address field. The following is a sample of the results: Forest Gregg, one of the creators of Dedupe, suggested installing and using dedupe-variable-name as the data set contained American names and would perform better in this example because there were multiple people who share the same address. He also suggested removing the Interaction variable. For people with Mac operating systems who have trouble installing dedupe-variable-name because of a gcc error, the following modification can be made to get past the error: env CC=/usr/bin/gcc pip install dedupe-variable-name In order to use dedupe-variable-name, the following additional import statement was added to the code and the name field was modified to use the "Name" type from this package. from dedupe.variables.name import WesternNameType fields = [{'field' : 'name', 'variable name' : 'name', 'type': 'Name'}, {'field' : 'address', 'variable name' : 'address', 'type': 'String'}, {'field' : 'REGISTERED', 'variable name' : 'REGISTERED', 'type': 'String'} ] This iteration produced 1,250 clusters and took 52 minutes to run, which was a significant improvement in performance. Since Dedupe also provides a special variable type called dedupe-variable-address, in the third iteration, the code was modified to include this package to see if the results can be further improved. The address field was modified to use the “Address” type. from dedupe.variables.address import USAddressType The field list was modified as follows: fields = [{'field' : 'name', 'variable name' : 'name', 'type': 'Name'}, {'field' : 'address', 'variable name' : 'address', 'type': 'Address'}, {'field' : 'REGISTERED', 'variable name' : 'REGISTERED', 'type': 'String'} ] Adding dedupe-variable-address resulted in 1,337 clusters and took 50 minutes to run, which was somewhat similar to the previous example. Comparison of results Remember that we made an assumption earlier that name and address will uniquely identify an entity. Taking that approach, the first set of results (produced without using dedupe-variable-name and dedupe-variable-address) was not meaningful because it identified duplicates solely on name. The second and third sets of results were very similar - both matched on 1,100 clusters containing a total of 2,224 records. There were 150 clusters in the second result set that were not in the third result set while there were 237 clusters in the third result set that were not in the second result set. Overall, both did a pretty good job in identifying records that had the same name and address, such as the following: There were also a number of records that they identified where there were spelling mistakes and inverted name mistakes. The following are a couple of examples. However, there were also a number of records where names that had a suffix were matched up with names that did not. The following are a few cases. There were also cases where records matched on last name and address but had completely different first names that were put together in a cluster. Looking at the results that were only in the second result set, it appeared that it contained a number of records that had similarities in name but were not exact. The following figure shows some examples. All these records should have been in different clusters. What was interesting was that there were some exact matches on name and address (but different values for REGISTERED) that were identified as belonging to the same cluster in the second result set but not so in the third result set. The following is an example: There were similar patterns in the records that were only in the third result set. Examples include: clusters with similarities in name, and clusters that matched on name and address but had different values for REGISTERED. In other words, there were cases where the third result set identified clusters while the second result set did not. The third result set identified a couple of clusters where the address was the same but the names were not the same. The following is an example. Conclusion Overall, Dedupe does a very good job of identifying duplicate entities based on name and address. It is able to effectively identify slight variations in the name such as spelling errors and inverted first name and last name. In that sense, it does a much better job than simply identifying exact matches using a group by SQL query or an Excel remove duplicates function. It appears, however, that it can use some improvement in discarding cases where there is more variation, such as examples where the first name is clearly different. The dedupe-variable-name package accounts for suffixes but it tends to cluster names with suffixes along with names that don't. A potential enhancement can be made to prevent such entities from getting clustered together. There have been several articles such as this one, which stated that people were registered to vote in more than one state. This was possible as people moved they failed to tell the voter registration agency in their old state that they have moved. The results that Dedupe produced seem to suggest that people have also registered to vote more than once in the same state. Further investigation needs to be conducted to determine if this was truly the case. If so, states can begin to use entity resolution to take measures to prevent this double-registering from happening in the future. In addition, entity resolution tools such as Dedupe can be combined with record linkage to identify voters who are registered in multiple states. Utilizing entity resolution to clean up our voter registries would be an important first step towards making our elections more fair and transparent.!
https://www.districtdatalabs.com/entity-resolution-on-voter-registration-data
CC-MAIN-2018-17
refinedweb
1,977
57.81
I want to display several figures with different sizes, making sure that the text has always the same size when the figures are printed. How can I achieve that? As an example. Let's say I have two figures: import matplotlib.pylab as plt import matplotlib as mpl mpl.rc('font', size=10) fig1 = plt.figure(figsize = (3,1)) plt.title('This is fig1') plt.plot(range(0,10),range(0,10)) plt.show() mpl.rc('font', size=?) fig2 = plt.figure(figsize = (20,10)) plt.title('This is fig2') plt.plot(range(0,10),range(0,10)) plt.show() In this case, the font size would be the same (i.e. also 10 points). Note that font size in points has a linear scale, so if you would want the size of the letters to be exactly twice as big, you would need to enter exactly twice the size in points (e.g. 20pt). That way, if you expect to print the second figure at 50% of the original size (length and width, not area), the fonts would be the same size. But if the only purpose of this script is to make figures to then print, you would do best to set the size as desired (on paper or on screen), and then make the font size equal. You could then paste them in a document at that exact size or ratio and the fonts would indeed be the same size. As noted by tcaswell, bbox_inches='tight' effectively changes the size of the saved figure, so that the size is different from what you set as figsize. As this might crop more whitespaces from some figures than others, the relative sizes of objects and fonts could end up being different for a given aspect ratio.
https://codedump.io/share/OhDNevBxZMkD/1/matplotlib---change-figsize-but-keep-fontsize-constant
CC-MAIN-2017-30
refinedweb
296
82.24
List of topic-wise frequently asked java interview questions with the best possible answers for job interviews. C++ Interview Questions in Java Question 1. What is C++? Answer: Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language while simplifying memory management and adding several features – including a new data type known as a class (you will learn more about these later) – to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management. Question 2. What Is Object-Oriented Programming? Answer: Object-Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects talking to each other. An object is a collection of data and methods that operate on its data. Question 3. Why OOP? Answer: The main advantage of OOP is better manageable code that covers the following. - The overall understanding of the software is increased as the distance between the language spoken by developers and that spoken by users. - Object orientation eases maintenance by the use of encapsulation. One can easily change the underlying representation by keeping the methods the same. OOP paradigm is mainly useful for relatively big software. See this for a complete example that shows the advantages of OOP over procedural programming. Question 4. What are the main features of OOP? Answer: - Encapsulation - Polymorphism - Inheritance Question 5. What is encapsulation? Answer: Encapsulation is referred to one of the following two notions. - Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in C++. - Bundling of data and methods together: Data and methods that operate on that data are bundled together. Question 6. What is Polymorphism? How is it supported by C++? Answer: Polymorphism means that some code or operations or objects behave differently in different contexts. In C++, the following features support polymorphism. • Compile Time Polymorphism: Compile time polymorphism means the compiler knows which function should be called when a polymorphic call is made. C++ supports compiler time polymorphism by supporting features like templates, function overloading, and default arguments. • Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea is virtual functions are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Question 7. What is Abstraction? Answer: Question 8. What is the difference between realloc( ) and free()? Answer:. Question 9. What is function overloading and operator overloading? Answer:). Question 10. What is the difference between declaration and definition? Answer: The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars ( ) //function declaration The definition contains the actual implementation. E.g.: void stars ( ) // declaratory { for(int j=10; j > =0; j - - ) //function body cout << *; cout << end1; } Question 11. What are the differences between references and pointers? Answer: Bothreferencesandpointerscanbeusedtochangelocalvariablesofonefunction inside another function. Bothofthemcanalsobeusedtosavecopyingofbig objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.. - are the main reason Java doesn’t need pointers. References are safer and easier to use: - Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location. - Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. the operator is needed only at the time of declaration. Also, members of an object reference can be accessed with a dot operator, unlike pointers where an arrow operator (->) is needed to access members. Question 12. Explain Copy Constructor. Answer: It is a constructor which initializes its object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it. Question 13. When do you call copy constructors? Answer: Copy constructors are called in these situations: - when the compiler generates a temporary object - when a function returns an object of that class by value - when the object of that class is passed by value as an argument to a function - when you construct an object based on another object of the same class Question 14. Differentiate between late binding and early binding. What are the advantages of early binding? Answer: - Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time. -. Question 15. What are the advantages of inheritance? Answer: It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional. Question 16. What do you mean by inline function? Answer:. Question 17. What is public, protected, private? Answer: that can be using friend classes. Write a function that swaps the values of two integers, using int* as the argument type. void swap(int* a, int*b) { int t; t = *a; *a = *b; *b = t; } Question 18. What are virtual constructors/destructors? Answer: Answer that declares. Answer. Question 19. Explain storage qualifiers in C++. Answer: - Const – This variable means that if the memory is initialized once, it should not be altered by a program. - Volatile – This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents. - Mutable – This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant. Question 20. What is the type of “this” pointer? When does it get created? Answer: It is a constant pointer type. It gets created when a non-static member function of a class is called. Question 21. How would you differentiate between pre and post-increment operators while overloading? Answer: Mentioning the keyword int as the second parameter in the post-increment form of the operator++0 helps distinguish between the two forms. Question 22. What are the advantages of inheritance? Answer: - It permits code reusability. - Reusability saves time in program development. - It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional. Question 23. What is a template? Answer: Templates allow the creation of generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until a certain point, they fulfill the functionality of a macro. Its prototype is any of the two following ones: template <class indetifier> function_declaration; template type name indetifier> function_declaration; The only difference between both prototypes is the use of keyword class or type name, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way. Question 24. Define a constructor – What it is and how it might be called (2 methods). Answer: Answer 1 Constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized. Ways of calling constructor: - Implicitly: automatically by complier when an object is created. - Calling the constructors explicitly is possible, but it makes the code unverifiable. Answer 2 class Point2D{ int x; int y; public Point2DO :. we have two pairs: new( ) and delete( ) and another pair : alloc( ) and free( ). Question 25. Explain differences between eg. new() and malloc() Answer: Answer 1: - “new and delete” are preprocessors while “malloc( ) and ffee( )” are functions, [we dont use brackets will calling new or delete], - no need of allocate the memory while using “new” but in “malloc( )” we have to use “sizeof( )”. - “new” will initlize. the new rnemoiy to 0 but “malloc( )” gives random value in the new alloted memory location [better to use calloc( )] Answer 2: new( ) allocates continous space for the object instace mallocO allocates distributed space. new( ) is castless, meaning that allocates memory for this specific type, mallocO, callocO allocate space for void * that is cated to the specific class type pointer. Question 26. What is the difference between class and structure? Answer:. Question 27. WhatisRTTI? Answer: Interview Questions – Homegrown versions with a solid, consistent approach. Question 28. W/hat is encapsulation? Answer: Packaging an object’s variables within its methods is called encapsulation. Question 29. W/hat is an object? Answer: Object is a software bundle of variables and related methods. Objects have state and behavior. Question 30. W/hat do you mean by inheritance? Answer: Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own. Question 31. Wffiat is namespace? Answer: Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces. The form to use namespaces is: namespace identifier { namespace-body } Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example: namespace general {int a, b;} In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put: general::a general::b The functionality of namespaces is especially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error. Question 32. What is virtual class and friend class? Answer:O has. Question 33. WTiat is the difference between an object and a class? Answer:. Question 34. What is a class? Answer: Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class. Question 35. WTiat is friend function? Answer: As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition. Question 36. WTiich recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array? Answer: Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time. Question 37. What is abstraction? Answer: Abstraction is of the process of hiding unwanted details from the user. Question 38. What are virtual functions? Answer:. Question 39. What is a scope resolution operator? Answer: A scope resolution operator (::), can be used to define the member functions of a class outside the class. Question 40. What do you mean by pure virtual functions? Answer:. Question 40. What is polymorphism? Explain with an example? Answer: “Poly” means“many” and“morph” means“form”. Polymorphismisthe ability of anobject(orreference)toassume(bereplacedby)orbecomemanydifferentformsofobject. Example: function overloading, function overriding, virtual functions. Another example can be a plus “+’ sign, used for adding two integers or for using it to concatenate two strings. Question 41. What is a conversion constructor? Answer: A constructor that accepts one argument of a different type. Question 42. What is the difference between a copy constructor and an overloaded assignment operator? Answer: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class. Question 43. Explain the ISA and HASA class relationships. How would you implement each in a class design? Answer:. Question 44. What is the Standard Template Library (STL)? Answer:. Question 45. In C++, what is the difference between method overloading and method overriding? Answer: Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class. Question 46. What is a modifier? Answer: A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’. Question 47. What is an accessor? Answer: An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations Question 48.. Question 49. Explain Stack & Heap Objects Answer: The memory a program uses is divided into four areas: - The code area – this is where the compiled program sits in memory. - The global area – the place where global variables are stored. - The heap – the place where dynamically allocated variables are allocated from. - The stack -the place where parameters and local variables are allocated from. Question 50. Explain deep copy and a shallow copy Answer: - Deep copy – It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining object. - Shallow copy -It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable. This happens because of the straight copying of references and pointers. Question 51. Explain virtual class and friend class Answer: a. Virtual Base Class: It is used in context of multiple inheritances of scope resolution operator A scope resolution operator (::) is used to define the member functions of a class outside the class. Mostly, a scope resolution operator is required when a data member is redefined by a derived class or an overridden method of the derived class wants to call the base class version of the same method. Question 52. What are virtual functions? Answer:) - A base class and a derived class. - A function with same name in base class and derived class. - A pointer or reference of base class type pointing or referring to an object of derived class. Question 53. What are the features that are provided to make a program modular? Answer:.
https://btechgeeks.com/c-interview-questions-in-java-2/
CC-MAIN-2022-21
refinedweb
2,493
57.47
In the java programming language, how do you set a new value for a public integer, so that an outside method in an outside class can get this value, by simply calling the variable name. I have example code: package build; public class Main { public static void main(String[] args) { Main main = new Main(); main.init(); } public int myVar = 1; EDIT: More specific question: How can I get the variable's updated value, not it's starting value without passing it on to a the method? public void init() { Retrieve ret = new Retrieve(); int i = 0; for(int n = 1; n > 0; ++n) { myVar = myVar + 1; System.out.println("Value: " + myVar); i = ret.init(); System.out.println("Retrieved Value: " + i); } } int getValue() { int b = myVar; return b; } } and for Return: package build; public class Retrieve { public int init() { Main main = new Main(); int a = 1; a = main.getValue(); return a; } } In the example above, how would I set the variable "myVar" to a value other than one, so that when I call the 'init' method in the 'return' class, it returns that new value, rather than 1, the starting value? There's something very wrong with your object relationship. The main problem is in Retrieve.init() public int init() { Main main = new Main(); int a = 1; a = main.getValue(); Every time you call init() you are making a new instance of main, so main.myVar will be 1. I assume you wanted to call the value of the first main. public class Retrieve { public int init(Main main) { int a = 1; a = main.getValue(); return a; } } and in Main.init change Retrieve ret = new Retrieve(); to Retrieve ret = new Retrieve(this);
https://www.codesd.com/item/how-to-set-a-new-value-for-a-public-int-in-java.html
CC-MAIN-2021-17
refinedweb
281
71.85
WinFS is a marriage with NTFS! It’s a file system that co-exists with and leverages the best of NTFS. There are areas where NTFS will not scale well in the future, not because as a file system it is inadequate but because the new requirements people will have in a world of digital data requires a more relational, query-orientated file system. WinFS is the solution to this problem. Looking back at the evolution of Windows file systems, the jump between FAT and NTFS was huge – everything from file layout to the algorithms for storage were completely revamped. WinFS does not represent such a huge shift, however – it is based on the same paradigms but offers stronger and deeper metadata support and a new querying model. Key WinFS Concepts The store is a top-level container for WinFS items. There is more than one store per NTFS volume, and stores for the system volume are created by default. WinFS effectively carves out a chunk of the C: drive (called the DefaultStore at present) as a file; WinFS then exposes as individual files. When you install WinFS, a second store called the CatalogStore is also created – this is a meta-store which contains information about the other stores on your system. You can also create your own stores on-demand against new or existing volumes. Manipulation of stores will be possible through the standard disk tools such as Disk Management, Disk Fragmenter, as well as new tools to do WinFS-specific operations such as consistency checking. WinFS will also integrate into the Plug’n’Play infrastructure, so that as volumes are plugged in, their stores are surfaced in the WinFS namespace. In summary, the ideal situation is that WinFS is transparent to the end-user from an operating perspective. Shares are a view that are carried forward into the WinFS world. WinFS shares can be created to any folder within WinFS. Again, by default, Longhorn creates a share called \\localhost\defaultstore, but you can create your own shares deeper in the store (for example, \\localhost\sharedpictures). You can then drill down deeper into those shares, e.g. \\localhost\defaultstore\contacts\tims. What is the default behaviour of WinFS when you install Longhorn? WinFS is not a NTFS replacement – as mentioned already, it is hosted within an NTFS volume. A fresh install will host the Documents, Pictures, Music and Videos folders in the DefaultStore. For upgrades, Longhorn will migrate this same content into the DefaultStore. For non-standard directories, a tool will be provided to migrate this content into the store. Developing for WinFS The ItemContext class can be used as a scoping object into the store. You can use a ItemSearcher to query against an ItemContext, optionally using OPath filters. Once you have found a document, you can create a standard StreamWriter object as a streaming interface into the file. The traditional Win32 API calls are also supported natively in WinFS – for example CreateFile, GetSecurity and so on. The same UNC namespace described above is common to both the managed WinFS API and the Win32 API. One caveat is that non-file backed items are not exposed via Win32. Every WinFS application starts with an XML schema which defines the types and relationships. Within this schema, a PromotionData section (containing PropertyMapping elements) allows Longhorn to promote custom properties from OLE Document, coupled with DocumentMapping elements to define which document extensions are to be included within the schema. This allows applications like Word to be able to build and expose WinFS metadata without having to have any knowledge of Longhorn or WinFS. Demotion is the opposite of promotion. Demotion is the process of taking metadata from WinFS items and moving it back into files so that legacy applications which only understand files can continue to get at this information. For example, if you edit a Word document custom property via the shell, it automatically gets updated in the underlying file itself as a result of demotion. Security A WinFS item is the lowest level of granularity for security control. Every item has a security descriptor, containing a discretionary ACL and a security ACL. As with NTFS, there is an inheritance mechanism that allows objects or containers to base their ACLs on a parent object. Inheritance can be blocked so that it does not propagate through the hierarchy. WinFS Event Handlers Every update to WinFS can be processed by an event handler before updating the store. In concept these closely resemble a SQL trigger. You can register your own event handlers (for example, an anti-virus software vendor might scan a file before it is updated). Event handlers can reject, accept, add to or replace an operation, and can accept just a subset of operations rather than having to monitor every item. It wasn’t clear from the session how the order of event handlers is managed – will every extension attempt to make itself the last event handler? There are however mechanisms to prevent a virus itself from registering itself as the final event handler. From a standard users perspective I would argue that WinFS is a bigger leap than from FAT32 to NTFS, although technologically FAT to NTFS was a big change, did it *really* change the way the majority of users used the file system? WinFS promises to do just that with the ability to view information in the way that people actually want to work, I think this is a *major* enhancement and I am very excited about it. You’ve definitely got a point, Steve. The difference between NTFS and WinFS is huge in terms of the potential it unleashes. I suppose the point the speaker was making was that from a purely technical perspective, this is still NTFS but just with extra extensions rather than a completely new file system. Thanks for distinguishing between these two things! Tim Having WinFS “stores” on an NTFS volume could lead to performance issues depending on how they get used in the real world. If it’s true that applications can create and use stores other than the default store it becomes possible for the container files to be fragmented. I haven’t seen the details yet but I assume fragmentation is also a possibility in the internal structure of the store. Will Longhorn include a defragger for NTFS volumes that can move portions of WinFS stores? What about a defragger for inside the store? Sorry if this isn’t the right place for this kind of inquiry or if it was covered in the session, which I regrettably was unable to attend. I’m just an interloper with an interest in high performance file streaming. Andrew, thanks for the question! Within NTFS, you can consider a store as just another file – in particular, imagine it in the same way as a SQL Server MDB file which contains BLOBs. Keeping stores defragmented is obviously a good thing, and perhaps Longhorn will set aside an area of NTFS for stores to reduce fragmentation. Within a WinFS store, the speaker indicated that there would indeed be defragmentation and consistency checking tools. Hope this helps a little. Tim dianying xia zai: movie down: mp3 xia zai: engage:
https://blogs.msdn.microsoft.com/tims/2003/10/29/cli326-winfs-file-system-integration-and-security/
CC-MAIN-2017-13
refinedweb
1,204
52.8
Axios is a library used to make HTTP requests from the browser. Read on to learn how to use Axios with React to make API requests and display the response. What is Axios? Axios is an hugely popular (over 52k stars on Github) HTTP client that allows us to make GET and POST requests from the browser. Therefore, we can use Axios with React to make requests to an API, return data from the API, and then do things with that data in our React app. Why Do We Need Axios? TL;DR: Axios allows us to communicate with APIs easily in our React apps. Most web and mobile apps store data in the cloud or make it easy for our apps to perform these commands. To learn more about fetching data from an API in a real application, check out our tutorial on building a complete React app with Airtable. Installing Axios To use Axios with React we need to install Axios. If you’re using NPM, open up a new terminal window, get to your project’s root directory, and run the following to add Axios to your package.json. npm i axios --save Open up App.js and import the Axios library at the top of the file. ... import axios from 'axios'; ... Retrieving Data with a GET Request The most common type of HTTP request is the GET request. It allows us to retrieve data from an API and use that data in a React app. There is plenty of free and open APIs to use. For this tutorial, we’ll use the Dog API, the internet’s largest collection of dog photos! 🐕 Although this API sounds trivial, the data response is very simple, therefore it’ll be nice and easy to understand how to use the data response in our React app. Let’s make our first API call to the Dog API using Axios. To App.js, add a componentDidMount method, and then add the following code: ... componentDidMount() { axios.get('') .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); } ... What’s happening above: - We make a GET request to the Dog API using axios.get - The Dog API documentation tells us that making a GET request to will give us a random dog photo. - We then output the API data response to the browser’s console, using console.log. Save your file, hop on over to your React app running in your browser and open up the developer console. You should see the following response, although your message will have a different value as we’re asking for random photos each time. { status: "success", message: "" } Great! You’ve made your first API call using Axios with React. Now let’s do something useful with that response. Using the API Data Response in React API calls are made asynchronously because we have to wait for the server to return the data to the app. In other words, once an API call has been made, there may be a few seconds of wait time before the API returns data. To show the photo of the dog in our React app, we need to store the API response in state. Add a constructor, with an initial state property called imageURL: ... constructor(props) { super(props); this.state = { imageURL: '', } } ... Now that we’re initializing the state, let’s update the state when the API request returns data successfully. ... componentDidMount() { axios.get('') .then(response => { this.setState({ imageURL: response.data.message }); }) .catch(error => { console.log(error); }); } ... We set the imageURL to be response.data.message because the image URL of the dog is found in the message key in the API response. Always read API documentation. Although good APIs should stick to good RESTful design standards, they will always be different. The best way to know how the data response is structured is to read the documentation. Finally, bring the imageURL state property into the render method, add an image element and set the image’s src to be the imageURL. ... render() { const { imageURL } = this.state; return ( <img src={imageURL} /> ); } ... Save your file, jump back over to the app in your browser and watch a random photo of a dog show up each time you refresh! If requesting photos of dogs from an API isn’t what the internet was created for, I don’t know what is. 🐶👍 Wrapping Up I hope you had fun learning about using Axios with React, making API requests and building a data-driven app! If you have any questions, leave a comment below and I’ll help you out. See you next time! 💻 More React Tutorials This was really helpful how to use express with react nice work it has worked for me how to foreach data with axios Thanks James ur da man! Where do you configure the path to your keystore ? extremely helpful james! how do i make the axios call to the API every 10 minutes? This tutorial is really helpful what if i want to call two different apis Thanks a lot for this work… Can we use this method with a PHP file (connecting database) as an API to get some informations from my database? I can’t explain how this was helpful for me. Started using react 3 days ago, because company game me a CRUD app to complete. I (saw) but didn’t pay much attention componentDidMount(){} until now. I was putting all my single axios requests in a file of their own and requiring them to my app, even though they were just simple get, put, delete… your article opened my eyes. Thanks Thanks for the article! I am, however, facing another issue. Since the server is responding with the index.html file, all api calls to said server are returning this file instead of the data requested for. any ideas? Nice article, It’s simple and helpful 🙂 hello james, nice article.. however, I found some error when accessing another API , the alert is “Access to XMLHttpRequest at ‘’ from origin ‘’ has been blocked by CORS policy” It seems missing “cors” policy in API request. could you know how to solved this matter?
https://upmostly.com/tutorials/using-axios-with-react-api-requests
CC-MAIN-2020-29
refinedweb
1,026
73.17
So far, you've seen how the MapView component can render the user's current location and points of interest around the user. The challenge here is that you probably want to show points of interest that are relevant to your application, instead of the points of interest that are rendered by default. In this section, you'll learn how to render markers for specific locations on the map, as well as render regions on the map. Let's plot some local breweries, shall we? Here's how you pass annotations to the MapView component: import React from 'react'; import { AppRegistry, View, } from 'react-native'; import MapView from 'react-native-maps'; import styles from './styles'; const PlottingPoints = () => ( <View ... No credit card required
https://www.oreilly.com/library/view/react-and-react/9781786465658/ch18s03.html
CC-MAIN-2019-22
refinedweb
122
63.39
4×4 matrix keypad with PIC16F877A. Before going into the detail logic and learn how to use the keypad, we will need to know few things. Why we need 4×4 Keypad: Typically we use single I/O pin of a microcontroller unit to read the digital signal, like a switch input. In few applications where 9, 12, 16 keys are needed for input purposes, if we add each key in a microcontroller port, we will end up using 16 I/O ports. This 16 I/O ports are not only for reading I/O signals, but they can be used as peripheral connections too, like ADC supports, I2C, SPI connections are also supported by those I/O pins. As those pins are connected with the switches/keys, we can’t use them but only as I/O ports. This is makes no sense at all. So, how to reduce pin count? The answer is, using a hex keypad or matrix keypad; we can reduce pin counts, which associate 4×4 matrix keys. It will use 8 pins out of which 4 connected in rows and 4 connected in columns, therefore saving 8 pins of the microcontroller’s. How 4×4 Matrix Keypad works: In the upper image a matrix keypad module is shown at the left. On the right the internal connection is shown as well as port connection. If we see the port there are 8 pins, first 4 from left to right are X1, X2, X3, and X4 are the rows, and last 4 from left to right are Y1, Y2, Y3, Y4 are four columns. If we make 4 rows or X side as output and make them logic low or 0, and make the 4 columns as input and read the keys we will read the switch press when correspondent Y gets 0. Same thing will happen in n x n matrix where n is the number. That can be 3×3, 6×6 etc. Now just think that 1 is pressed. Then the 1 is situated at X1 row and Y1 column. If X1 is 0, then the Y1 will be 0. By the same way we can sense each key in the X1 row, by sensing column Y1, Y2, Y3 and Y4. This thing happens for every switch and we will read the position of the switches in the matrix. Each green circles is the switch and they both are connected together in the same way. In this tutorial we will interface the key board with following specifications- - We will use internal pull up - We will add key de-bounce option But when the switches are not pressed we need to make the Y1, Y2, Y3 and Y4 as high or 1. Otherwise we can’t detect the logic changes when the switch is being pressed. But we couldn’t make it by codes or program due to those pins are used as input, not output. So, we will use an internal operation register in the microcontroller and operate those pins as weak pull up enabled mode. By using this, there will be a logic high enable mode when it is in the default state. Also, when we press key there are spikes or noise are generated with switch contacts, and due to this multiple switch press happens which is not expected. So, we will first detect the switch press, wait for few milliseconds, again check whether the switch is still pressed or not and if the switch is still pressed we will accept the switch press finally otherwise not. This is called as de-bouncing of the switches. We will implement this all in our code, and make the connection on breadboard. Material Required: - Breadboard - Pic-kit 3 and development environment in your PC, i.e MPLABX - Wires and connectors - Character LCD 16×2 - 20Mhz Crystal - 2 pcs 33pF ceramic disc cap. - 4.7k resistor - 10k preset (variable resistor) - 4×4 Matrix keypad - A 5 V adapter Circuit Diagram: We will connect the crystals and the resistor in the associated pins. Also, we will connect the LCD in 4 bit modeacross PORTD. We connected the hex keypad or matrix keypad across the port RB4. Programming Explanation: Complete code for interfacing Matrix Keypad with PIC Microcontroller is given at the end. Code is easy and self-explanatory. Keypad library is only thing to be understood in the code. Here we have used keypad.h and lcd.h Library to interface the keypad and 16×2 LCD. So lets see what is happening inside that. Inside the keypad.h we will see that we have used xc.h header which is default register library, the crystal frequency is defined for the use for the use of delay used in kepad.c file. We defined the keypad ports at PORTRB register and defined individual pins as row (X) and columns (Y). We also used two functions one for the keypad initialization which will redirect the port as output and input, and a switch press scan which will return the switch press status when called. #include <xc.h> #define _XTAL_FREQ 200000000 //Crystal Frequency, used in delay #define X_1 RB0 #define X_2 RB1 #define X_3 RB2 #define X_4 RB3 #define Y_1 RB4 #define Y_2 RB5 #define Y_3 RB6 #define Y_4 RB7 #define Keypad_PORT PORTB #define Keypad_PORT_Direction TRISB void InitKeypad(void); char switch_press_scan(void); In the keypad.c we will see that below function will return the key press when the keypad scanner function not return ‘n’. char switch_press_scan(void) // Get key from user { char key = 'n'; // Assume no key pressed while(key=='n') // Wait untill a key is pressed key = keypad_scanner(); // Scan the keys again and again return key; //when key pressed then return its value } Below is the keypad reading function. In each step we will make the row X1, X2, X3, and X4 as 0 and reading the Y1, Y2, Y3 and Y4 status. The delay is used for the debounce effect, when the switch is still pressed we will return the value associated with it. When no switch are pressed we will return ‘n ‘. char keypad_scanner(void) { X_1 = 0; X_2 = 1; X_3 = 1; X_4 = 1; if (Y_1 == 0) { __delay_ms(100); while (Y_1==0); return '1'; } if (Y_2 == 0) { __delay_ms(100); while (Y_2==0); return '2'; } if (Y_3 == 0) { __delay_ms(100); while (Y_3==0); return '3'; } if (Y_4 == 0) { __delay_ms(100); while (Y_4==0); return 'A'; } X_1 = 1; X_2 = 0; X_3 = 1; X_4 = 1; if (Y_1 == 0) { __delay_ms(100); while (Y_1==0); return '4'; } if (Y_2 == 0) { __delay_ms(100); while (Y_2==0); return '5'; } if (Y_3 == 0) { __delay_ms(100); while (Y_3==0); return '6'; } if (Y_4 == 0) { __delay_ms(100); while (Y_4==0); return 'B'; } X_1 = 1; X_2 = 1; X_3 = 0; X_4 = 1; if (Y_1 == 0) { __delay_ms(100); while (Y_1==0); return '7'; } if (Y_2 == 0) { __delay_ms(100); while (Y_2==0); return '8'; } if (Y_3 == 0) { __delay_ms(100); while (Y_3==0); return '9'; } if (Y_4 == 0) { __delay_ms(100); while (Y_4==0); return 'C'; } X_1 = 1; X_2 = 1; X_3 = 1; X_4 = 0; if (Y_1 == 0) { __delay_ms(100); while (Y_1==0); return '*'; } if (Y_2 == 0) { __delay_ms(100); while (Y_2==0); return '0'; } if (Y_3 == 0) { __delay_ms(100); while (Y_3==0); return '#'; } if (Y_4 == 0) { __delay_ms(100); while (Y_4==0); return 'D'; } return 'n'; } We will also set the weak pull up on the last four bits, and also set the direction of the ports as last 4 input and first 4 as output. The OPTION_REG &= 0x7F; is used to set the weak pull up mode on the last pins. void InitKeypad(void) { Keypad_PORT = 0x00; // Set Keypad port pin values zero Keypad_PORT_Direction = 0xF0; // Last 4 pins input, First 4 pins output OPTION_REG &= 0x7F; } In the main PIC program (given below) we first set the configuration bits and included few needed libraries. Then in void system_init functions we initialize the keypad and LCD. And finally in in the main function we have read the keypad by calling the switch_press_scan() function and returning the value to lcd. Download the complete code with header files from here and check the Demonstration video below. /* */lcd.h” #include “supporing_cfile/Keypad.h” /* Hardware related definition */ #define _XTAL_FREQ 200000000 //Crystal Frequency, used in delay /* Other Specific definition */ void system_init(void); void main(void){ system_init(); char Key = ‘n’; lcd_com(0x80); lcd_puts(“CircuitDigest”); lcd_com(0xC0); while(1){ Key = switch_press_scan(); lcd_data(Key); } } /* * System Init */ void system_init(void){ TRISD = 0x00; lcd_init(); // This will initialise the lcd InitKeypad(); } Read more detail:4×4 Matrix Keypad Interfacing with PIC Microcontroller JLCPCB – Prototype 10 PCBs for $2 (For Any Color) China’s Largest PCB Prototype Enterprise, 600,000+ Customers & 10,000+ Online Orders Daily See Why JLCPCB Is So Popular:
https://pic-microcontroller.com/4x4-matrix-keypad-interfacing-with-pic-microcontroller/
CC-MAIN-2019-18
refinedweb
1,447
66.17
Hi, to start, sorry for my English but I’m French so I’ll maybe do some mistakes. I’m totally new on Processing and I’d like to get bass of the song of my PC. To do it, I already found a code wich do a spectrograme of the sound of my PC. import ddf.minim.*; import ddf.minim.analysis.*; import ddf.minim.effects.*; import ddf.minim.signals.*; import ddf.minim.spi.*; import ddf.minim.ugens.*; Minim minim; AudioInput in; FFT fft; int w; void setup() { size(640, 840); minim = new Minim(this); in = minim.getLineIn(Minim.STEREO, 512); fft = new FFT(in.bufferSize(), in.sampleRate()); fft.logAverages(60, 7); stroke(255); w = width/fft.avgSize(); strokeWeight(w); strokeCap(SQUARE); } void draw() { background(0); fft.forward(in.mix); for(int i = 0; i < fft.avgSize(); i++) { line((i * w) + (w / 2), height, (i * w) + (w / 2), height - fft.getAvg(i) * 4); } } I saw that the 5th, 6th, 7th 8th and 9th columns correspond to the bass of the music : I would like to know, with my code when there are bass frequencies. I totally don’t know how to do it; Can you help me please ? Thanks a lot
https://discourse.processing.org/t/get-frequencies-of-sound/14004
CC-MAIN-2022-27
refinedweb
201
66.33
Configure the NRPT with Group Policy Published: October 7, 2009 Updated: October 7, 2009 Applies To: Windows Server 2008 R2 You can configure the rules directly to the Name Resolution Policy Table (NRPT) with Group Policy, rather than using the DirectAccess Setup Wizard. To complete these procedures, you must be a member of the Administrators group, or otherwise be delegated permissions to configure Group Policy settings. Review details about using the appropriate accounts and group memberships at Local and Domain Default Groups ().\Windows Settings, and then click Name Resolution Policy. - To create a new NRPT rule for DirectAccess, in the details pane, click DNS Settings for Direct Access, select Enable DNS settings for DirectAccess in this rule. Specify the namespace to which the rule applies, the certification authority and Internet Protocol version 6 (IPv6) addresses of Domain Name System (DNS) servers (if needed), and then click Create. - To modify an existing rule, click the rule in the NRPT, and then click Edit Rule. When you are done making changes, click Update. - To delete an existing rule, click the rule in the NRPT, and then click Delete Rule. If you arrived at this page by clicking a link in a checklist, use your browser’s Back button to return to the checklist.
https://technet.microsoft.com/en-us/library/ee649235(v=ws.10).aspx
CC-MAIN-2015-22
refinedweb
211
50.16
In today’s world everybody and everything is connected. I realized early on that in life you cannot achieve your maximum potential by yourself. You need family, coaches, friends, advocates, and a whole network to make a difference. Same with technology, there is a network effect that amplifies the value of a solution: the more people on Skype or IM, the more convenient it is to communicate. Traditionally, in the Enterprise, many IT solutions have been built in silos because of organizational structure, budget ownership, or just short-term thinking. Currently, however, many organizations are realizing that breaking silos needs to be a priority. Many CIOs have that on their top 3 list of priorities because the advantages are many: one view of the customer, streamlined transaction processing, more effective compliance processes, capacity optimization, higher utilization of resources, standardization, etc. How do you break silos? There are many layers: applications, security, infrastructure and data – to name a few. Honing in on data, there are many initiatives in the Financial Services industry about Big Data, data classification, and data governance in general. Over the years data has stayed within the business unit that collected it. If it was credit card usage, it stayed in the Credit Card databases. If it was mortgage information it stayed in the Mortgage group, and so on. The advent of Data Warehouses and Data Marts, was a first phase in the journey of breaking silos. But there is a lot of ETL and batch work to aggregate the data and then extract intelligence. The pioneers in this process have proved the value of aggregated data over and over again. But ultimately, the Data Warehouse itself is a silo. Technology has evolved to a point where it is possible to have relevant information at your fingertips, when you need it, where you need it; and by “you” I mean a financial analyst, a business decision maker, a stock analyst, a mortgage officer, a risk manager, or a sales manager – you name it. At NetApp we have Data ONTAP – like beer released from the silos of bottles. I had to say it! With the new Clustered Data OnTap you also get the always on capability and a single volume/namespace adds ubiquity and simplicity. With the IonGrid acquisition (now NetApp Connect), you get secure access to Enterprise data from mobile devices. When you combine these capabilities with a layer of policy-driven data movers, workflow automation, collaboration platforms and real-time analytics you get awfully close to the end vision of “information where you need it, when you need it.” NetApp has a culture of partnerships – another silo-breaker. With technology partners such as Microsoft, Cisco, Citrix, SAP, AWS, NTP Software and many others, there are more comprehensive solutions that address data lifecycle from cradle to cradle. The next silo to break is the vendor silo and the Open Source movement along with the Software Defined movement. Adoption by financial firms is still in the first innings, but the trend is clear: achieve agility and flexibility through programmability and standardization. Data is exploding and I, for one, can’t wait to partner with our customers to make the most of the new Open Data world in front of us. You must be registered user to add a comment. If you are a registered user, sign in to leave a comment. If you are not a registered user, please register for the NetApp Community to leave a comment.
http://community.netapp.com/t5/Industries/Breaking-Silos-information-where-you-need-it-when-you-need-it/ba-p/83961
CC-MAIN-2017-43
refinedweb
579
52.7
Execute stored procedures having a FOR XML clause in SQL Server using BizTalk Server An SQL SELECT statement can have a FOR XML clause that returns the query result as XML instead of a rowset. You can also have a stored procedure that has a SELECT statement with a FOR XML clause. FOR XML (SQL Server) has more information. You can use the WCF-based SQL adapter to execute such stored procedures. Important The “native” SQL adapter available with BizTalk Server requires stored procedures to have the FOR XML clause as part of the SELECT statement. You can use such stored procedures with the WCF-based SQL adapter without making any changes to the stored procedure definition. You can always use the schemas generated using the ‘native’ SQL adapter provided with earlier versions of BizTalk Server. For more information, see Using FOR XML queries with the WCF-SQL Adapter (). How to Invoke Stored Procedures with FOR XML Clause When you invoke a stored procedure with FOR XML clause in SQL Server Management Studio or using the SQL adapter available with BizTalk Server, the output is in the form of an xml message. To use these procedures with the WCF-based SQL adapter, you must have the schema for the output message. The WCF-based SQL adapter requires this schema while receiving the response message from SQL Server after executing a stored procedure with FOR XML clause. Note that the request message to invoke this stored procedure will be generated by the adapter itself. Apart from having the schema for the response message, you must also perform certain tasks to invoke a stored procedure with FOR XML clause using the WCF-based SQL adapter. Generate the schema for the response message for the stored procedure with FOR XML clause. If you already have the response schema generated by the “native” SQL adapter available with BizTalk Server, you can skip this step. Create a BizTalk project and add the generated schema to the project. Generate schema for the stored procedure with FOR XML clause using the WCF-based SQL adapter. This provides the schema for the request message that the adapter sends to SQL Server to invoke the stored procedure. Create messages in the BizTalk project to send and receive messages from SQL Server. The request message must conform to the schema of the request message generated by the adapter. The response message must conform to the schema of the response message obtained either using the “native” SQL adapter or by executing the stored procedure with FOR XML clause in SQL Server Management Studio. Create an orchestration to invoke the stored procedure in the SQL Server database. Build and deploy the BizTalk project. Configure the BizTalk application by creating physical send and receive ports. Start the BizTalk application. Generating Schema for the Response Message for Stored Procedure Note You do not need to perform this step if you have the response schema generated by the SQL adapter available with BizTalk Server. You can generate the schema for the response message for the stored procedure, provided the SELECT statement in the stored procedure has the xmlschema clause with the for xml clause. In this topic, we use the GET_EMP_DETAILS_FOR_XML stored procedure that retrieves the employee details for a given employee ID. To retrieve the schema by executing the stored procedure, the SELECT statement looks like the following: SELECT [Employee_ID] ,[Name] ,[DOJ] ,[Designation] ,[Job_Description] ,[Photo] ,cast([Rating] as varchar(100)) as Rating ,[Salary] ,[Last_Modified] ,[Status] ,[Address] FROM [Adapt_Doc].[dbo].[Employee] for xml auto, xmlschema Execute this stored procedure to get the schema for the response message. Note that the response from the stored procedure contains the schema as well as the data from executing the stored procedure. You must copy the schema from the response and save it to a text pad. For this example, you can name this schema as ResponseSchema.xsd. You must now create a BizTalk project in Visual Studio and add this schema to the project. Important Make sure you remove the xmlschema clause after you have executed the stored procedure to generate the schema. If you fail to do this, when you finally execute the stored procedure through BizTalk, you will again generate the schema in the response message. So, to get the response message as xml you must remove the xmlschema clause. To add the schema to a BizTalk project Create a BizTalk project in Visual Studio. Add the response schema you generated for the stored procedure to the BizTalk project. Right-click the BizTalk project in the Solution Explorer, point to Add, and then click Existing Item. In the Add Existing Item dialog box, navigate to the location where you saved the schema and click Add. Open the schema in Visual Studio and make the following changes. Add a node to the schema and move the existing root node under this newly added node. Give a name to the root node. For this topic, rename the root node to Root. The response schema generated for the stored procedure references a sqltypes.xsd. You can get the sqltypes.xsd schema from. Add the sqltypes.xsd schema to the BizTalk project. In the schema generated for the stored procedure, change the value of import schemaLocationto the following. import schemaLocation=”sqltypes.xsd” You do this because you have already added the sqltypes.xsd schema to your BizTalk project. Provide a target namespace for the schema. Click the <Schema> node, and in the properties pane, specify a namespace in the Target Namespace property. For this topic, give the namespace as. Generating Schema for the Request Message to Invoke the Stored Procedure To generate schema for the request message you can use the Consume Adapter Service Add-in from a BizTalk project in Visual Studio. For this topic, generate the schema for the GET_EMP_DETAILS_FOR_XML stored procedure. For more information about how to generate the schema using Consume Adapter Service Add-in, see Retrieving Metadata for SQL Server Operations in Visual Studio using the SQL adapter. Important You must generate the schema by selecting the procedure only from the Procedures node in Consume Adapter Service Add-in. Defining Messages and Message Types: Setting up the Orchestration You must create a BizTalk orchestration to use BizTalk Server for executing a stored procedure. For instructions on how to create a send port, see Manually configure a physical port binding to the SQL adapter. You must also specify the action in the send port. For procedures that contain the FOR XML clause, you must set the action in the following format. XmlProcedure/<schema_name>/<procedure_name> So, for this topic where we are executing the GET_EMP_DETAILS_FOR_XML procedure, the action will be: XmlProcedure/dbo/GET_EMP_DETAILS_FOR_XML For more information about setting action, see Configure the SOAP action for the SQL adapter . You must also set the following binding properties when executing a stored procedure with the FOR XML clause. For more information about specifying values for binding properties, see Configure the binding properties invoking procedures. Executing the Operation After you run the application, you must drop a request message to the FILE receive location. The schema for the request message must conform to the request schema for the procedure you generated using the Consume Adapter Service Add-in. For example, the request message to invoke the GET_EMP_DETAILS_FOR XML is: <GET_EMP_DETAILS_FOR_XML xmlns=""> <emp_id>10765</emp_id> </GET_EMP_DETAILS_FOR_XML>"?> <Root xmlns=""> <Adapt_Doc.dbo.Employee </Root> Notice that the response is received in the same schema as generated by executing the stored procedure. Also note that the root node and the namespace is the same you specified as values for XmlStoredProcedureRootNodeName and XmlStoredProcedureRootNodeNamespace binding properties respectively. Reuse adapter bindings. See Also Develop BizTalk applications using the SQL adapter
https://docs.microsoft.com/en-us/biztalk/adapters-and-accelerators/adapter-sql/execute-stored-procedures-having-a-for-xml-clause-in-sql-server-using-biztalk?redirectedfrom=MSDN
CC-MAIN-2017-51
refinedweb
1,283
62.98
- refcount differences in 2.5 - pyExcelerator bug? - How do I tell the difference between the end of a text file, and an empty line in a text file? - How do I count the number of spaces at the left end of a string? - try - Python Web Programming - looking for examples of solid high-traffic sites - Python-URL! - weekly Python news and links (May 16) - Typed named groups in regular expression - pyhdf - python shell - cPickle.dumps differs from Pickle.dumps; looks like a bug. - A bug in cPickle? - zipfile stupidly broken - Declaring variables - pymssql query - calldll for Python 2.5 - remove all elements in a list with a particular value - Unusual i/o problems - Execute commands from file - Garbage Collector in Zope 2.8 - Using control characters to break out of threads - Splitting a quoted string. - iteration doesn't seem to work ?? - os.walk() error ( Can anybody please help me) - GB2312 conversion into BIG5 - Problems with wx.TreeCtrl - A new project. - setting an attribute - removing common elemets in a list - Python Dijkstra Shortest Path - url question - extracting (2 types of) domains - Quote aware split - transparent images - Issue with MySQLdb wrapper - tkFileDialog.askopenfilename() - inherit from file and create stdout instance? - Name of function caller - Need a PC Computer Info Portal? - Vista: webbrowser module - Pyrex char *x[] - ctypes-1.0.2 for 64-bit Windows - Moving class used in pickle - File Dialog in Tkinter - Splitting a string - Finding the file availability - Getting a extension of a given filename - docs patch: dicts and sets - File record separators. - f2py problem - PyObject_Print in gdb - Get a control over a window - Urgently looking for Python with Django Developers - London - Storing and searching nodes of a tree - pyshell and unum hint - Antwort: How to calculate definite integral with python - howto get function from module, known by string names? - HappyDoc, Jython and docstrings - time format - Iron Python - Distributing programs depending on third party modules. - removing spaces between 2 names - Trying to choose between python and java - How to calculate definite integral with python - ClientForm .click() oddity - Generators in C code - Subprocess with and without shell - python import problem (different versions of python)? - Python Power Point Slides - How are variables stored in python? - Class name as argument - Timing suggestions? - Hello gettext - multi-line input? - swig %typemap generated list typeerror - customary way of keeping your own Python and module directory in $HOME - os.listdir(<file specifications>) doesn't work ?? - track cpu usage of linux application - tkinter button state = DISABLED - Sorting troubles - Trouble creating bsddb database - Pickle Stuff and Filename Recognition - deployment scripts - Yet Another Software Challenge - Beginner question: module organisation - Drawing QLabel into QFrame and overlying dragEnterEvent dropEvent and mousePressEven - ContextEvents and Tkinter - python and unix compatibility - python multithreading - Seeking Four Code Samples for Forrester Research Survey - A Call for Professional Trainers of Python - Element tree errors - multi threaded SimpleXMLRPCServer - Removing part of string - Asyncore Help? - "save as" python script - Weekly Python Patch/Bug Summary - How to do basic CRUD apps with Python - PyRun_String and related functions causing garbage when calling a parsed function from C. - GUI tutorial - Using "subprocess" without lists. . .? - elementtree and entities - PEP 3131: Supporting Non-ASCII Identifiers - Breaking down sentances - Real globals inside a module - Setting thread priorities - Py2exe Linux? - Problems with thread safety - __dict__ for instances? - Licence for webchecker module? - ctree data - Bug? import cp1252 - How to cleanly pause/stop a long running function? - Optimizing numpy - package rating system for the Cheese Shop - Read from Windows Address Book (.wab file format) ? - Creating a function to make checkbutton with information from a list? - Drawing Text on a Path - Finally started on python.. - Basic question - Dynamic subclassing ? - Popen and wget, problems - help with Python C-API, tuple object - os.popen on windows: loosing stdout of child process - need help with python - logging module and threading - docs patch: dicts and sets - BoxSizer problem - some help please - mmap thoughts - find out all threads? - matplotlib: howto set title of whole window? - py2exe LoadLibrary question - Recursion limit problems - Problems with grid() layout under tkinter - Time - name capitalization of built-in types, True, and False - Path python versions and Macosx - Interesting list Validity (True/False) - stealth screen scraping with python? - File writing success - matplotlib for graph script for python - Simple Python REGEX Question - PyGTK : a NEW simple way to code an app - Better way to isolate string - Dyla'07: 3rd Workshop on Dynamic Languages and Applications - software testing articles - vim e autoindentazione commenti - Custom Software Development - 4 byte integer - checking if hour is between two hours - auto refresh and status bar? - module error for elementtree - Simple Tkinter Progress Bar - how to refer to partial list, slice is too slow? - setting extra data to a wx.textctrl - inherit from file and create stdout instance? - how to use cx_Oracle callfunc - How to find C source - Avenue Language to Python Conversion - do not use stunnix - File modes - Soultions deployment engineer - Symposium "Computational Methods in Image Analysis" within the USNCCM IX Congress - Submission ENDS in 5 days - reading argv argument of unittest.main() - searching algorithm - append - SQLObject 0.9.0 - Parse a DXF file for lines, circles and arcs - how to bind keypress event to function in using wxpython - Problem in Executing the Tkinter Modules in Python 2.4.4 - SQLObject 0.8.4 - SQLObject 0.7.7 - Read binary data from MySQL database - newb: Python Module and Class Scope - How to installo???? - keyword checker - keyword.kwlist - trouble with generators - Thread-safe dictionary - How to convert Unicode string to raw string escaped with HTML Entities - matplotlib problem - replacing string in xml file--revisited - how to update python in fedora? - the inspect thing - creating registry in windows very urgent - elegant python style for loops - EOL character - Erlang style processes for Python - Change serial timeout per read - WSGI spec clarification regarding exceptions - Comparing dates problem - File I/O - Behavior of mutable class variables - Checking if string inside quotes? - integer from argument - Unzip then Zip help - input - path stuff - Inheritance problem - preferred windows text editor? - socket.bind use a name as address - ctypes: Problems using Windows-DLL from VB example code - Single precision floating point calcs? - tkinter - Screen Resolution - Sorting attributes by catagory - Boost python : get the shape of a numpy ndarray in C++ code. - IDLE can't import Tkinter - Does RETURN_VALUE always result in an empty stack? - Boolean confusion - Questions about bsddb - Problems in string replacement - view workspace, like in MatLab ? - Multiple regex match idiom - Using the CSV module - MailingLogger 3.0.0 Released! - error in the if, elif, else statement ? - Minor bug in tempfile module (possibly __doc__ error) - which is more pythonic/faster append or +=[] - Parameter checking on an interfase - tokenize generate_tokens token[0] - String parsing - Win32: shortpathname to longpathname - RotatingFileHandler bugs/errors and a general logging question. - Timer...the basics - psycopg2 error - Question about file handles and windows handles @ Windows Operating Systems - Mod Python Question - Another easy pair of questions - chdir() - Suggestions for how to approach this problem? - tkinter get widget option value - fminbound - 1.#QNAN Solution - Atttribute error - Need help with this expense calculator - Towards faster Python implementations - theory - sys.path - How to pickle dictionaries? - XLRD Python 2.51 Question - pymacs - from c++ to python - ipython environment question - Newb question regarding DOS command-line from Python - Python and cgi help - Setting up python socket server with non-standard termination string. - changing a var by reference of a list - Somebody help with Tkinter Frame subclass - replacing string in xml file - File Name Format - Designing a graph study program - Windows, subprocess.Popen & encodage - interesting exercise - How to make Python poll a PYTHON METHOD - inspected console - integrating embedded interpreter with external controls - No module named urllib - Understanding list comprenesions (split from Copying the list elements) - randomly write to a file - is for reliable? - SOAPpy parameters in sequence - Simulating simple electric circuits - getmtime differs between Py2.5 and Py2.4 - Latest errors on pickled objects and blob datatypes in mysql - Regular Expression Help, getting over the newline \n - Python-URL! - weekly Python news and links (May 7) - Very simple Python program help... - SkimpyGimpy PNG canvas w/ Javascript mouse tracking - Recommended validating XML parser? - Unittest Automation - Can Python Parse an MS SQL Trace? - how do you implement a reactor without a select? - assisging multiple values to a element in dictionary - Bastion/rexec use cases? - Custom software development - matplotlib: howto redraw figure automatically, without stop in show()/draw()? - Properties on old-style classes actually work? - long lists - N00b question on Py modules - Help creating Tiger hash function in Python - Examples / Links needed - Fingerprint Verification System - CGI python use "under a curse" - import conflict - python hw blackjack game using xturtle HELP! - New Skype 4.1 Alpha released for linux. - msbin to ieee - c macros in python. - using boost to extend python with c++ - WebBrowser: How to cast the document object - howto make Python list from numpy.array? - Copying the list elements - tkinter - label widget text selection - Error when using Custom Exception defined in a different python module. - problem with quoted strings while inserting into varchar field ofdatabase. - exporting a record from a database to a MS Word document. - All what you are looking for and much more - MROW Locking - Did you read about that? - Emacs and pdb after upgrading to Ubuntu Feisty - Weekly Python Patch/Bug Summary - module console - Init style output with python? - Python Binding - How do I use the config parser? - Tkinter Spinbox - Problem with Closing TCP connection - progress - Do I have to quit python to load a module? - mod_python not found properly by Apache (win32) - change of random state when pyc created?? - Looping over lists - Python regular expressions just ain't PCRE - printing to a file problems - Problems Drawing Over Network - behavior difference for mutable and immutable variable in function definition - Further adventures in array slicing. - how to find a lable quickly? - Creating a Null list, seems to create a null tuple instead - How safe is a set of floats? - Plot with scipy - using pyparsing to extract METEO DATAS - Where are the strings in gc.get_objects? - importing modules from other packages - ftplib acting weird - High resolution sleep (Linux) - is there a module to work with pickled objects storage in database? - Non blocking sockets with select.poll() ? - invoke user's standard mail client - default config has no md5 module? - How to find the present working directory using python. - enable-shared - urllib.quote fails on Unicode URL - Getting some element from sets.Set - problem with py2exe and microsoft speech SDK 5.1 - How to call a Class? - New EasyExtend release is out - tkinter listboxes - How do I import a variable from another module? - Pyinstaller Command line options. - Decorating class member functions - Replacement for HTMLGen? - How do I output a list like the interpreter do? - When does input() return an empty string? - calling previously writen python scripts [How to use import] - adding methods at runtime and lambda - How do I get type methods? - Real Time Battle and Python - problem with py2exe and microsoft speech SDK 5.1 - NewB: Glob Question - Tkinter -> canvas -> make an obect move from one spot to next - cannot import name ..... - Python, WIN32 COM and MS Word - Organizing code - import question - Article on wxPython ToolKit for Mac OS X - _csv.Error: string with NUL bytes - Library Naming - getmtime in 2.5 reports GMT instead of local time - How to replace the last (and only last) character in a string? - Sybase module 0.38 released - pyscripter to slow - SQLObject 0.8.3 - SQLObject 0.7.6 - file Error - C in Python - 32 OS on 64-bit machine - problem with meteo datas - assigning to __class__ for an extension type: Is it still possible? - passing an array of variant in vb to a python COM object = win32com bug ? - wxPython - FlatNotebook help - Searching for a piece of string - FInd files with .so extension - how update a qListView in backgroud - Handling Infinite Loops on Server Applications - succint representation of struct arguments - Python COM and Delphi callback - win32com.client Excel Color Porblem - Basic question about sockets and security - curses mystical error output - Slicing Arrays in this way - Cannot execute Windows commands via Python in 64-bit - python,win32com,scipy and vb 6 : no module named scipy - unittest dependencies - __dict__s and types and maybe metaclasses... - Can I use Python instead of Joomla? - How to check if a string is empty in python? - xml sax and unicode utf8 - parser error: mismatched tag - Lazy evaluation: overloading the assignment operator? - hp 11.11 64 bit python 2.5 build gets error "import site failed" - Microsoft's Dynamic Languages Runtime (DLR) - gpp (conditional compilation) - Time functions - Logic for Chat client - ascii to unicode line endings - java to python communication - ignorance and intolerance in computing communties - Active Directory: how to delete a user from a group? - I need help speeding up an app that reads football scores and generates rankings - Refreshing imported modules - Is it possible to determine what a function needs for parameters - - open("output/mainwindow.h",'w') doesn't create a folder for me - Writing a nice formatted csv file - pack/unpack zero terminated string - Need Help in Preparing for Study of Python by Forrester Research - Leaving Python List - Calling Exe from Python - Calling Exe from Python - how to use python script in vc++ - What do people use for code analysis. - delay function [in wxPython] - DiffLib Question - how can you loop a code - how we increment a global variable value som few functions - Python and DLL - Tcl-tk 8.5? - python cgi - os.path.join - Read and Write the same file - python win32com excel problem - Garmin GPS and USB [PyGarUSB package] - ScrolledText? - Removing the continous newline characters from the pythong string - Python user group in Portland, OR? - pre-PEP: Standard Microthreading Pattern - How can I get the ascii code of a charter in python? - read list of dirnames and search for filenames - Python for Windows other way to getting it? - I wish that [].append(x) returned [x] - Using python with MySQL - Concatenating/Appending the list of elements - Grabbing the output of a long-winded shell call (in GNU/Linux) - Problem with inspect.getfile - Having problems accepting parameters to a function - SWIG, STL & pickle - SilverLight, a new way for Python? - Lisp-like macros in Python? - pymqi commit/rollback - Creating a double dimension array - scaling - Comparing bitmap images for differences? - PyGEP: Gene Expression Programming for Python - how to access module level variable in class - Problems with time - Why are functions atomic? - playing sound in mac osx - Log-in to forums (using cookielib)? - Python+Pygame+PyopenGL all in one package? - Want to build a binary header block - sqlite for mac? - logging SMTPHandler and Authentication - [Q] module name available in 'from ... import ...' statement - python TK scrollbar problem - Deletion of orginal Dict data - removing module - re-importing modules - Is it possible to merge xrange and slice? - OT somewhat: Do you telecommute? What do you wish the boss understood about it? - Can python find HW/SW installed on my PC - like Belarc? - Using try and catch - Throwing the error message in Tkinter - import structures - Re-running script from Tk shell - Problem with PyQt4 - socket module - recv() method - Are arguments to python __init__ method passed as pointers? In a threading.Thread? - Python-URL! - weekly Python news and links (Apr 30) - work with process - How to convert float to sortable integer in Python - Restricting the alphabet of a string - Writing Excel file - How do I parse a string to a tuple?? - anyone has experience on cross-compile python 2.5.1? - What's the life time of the variable defined in a class function? - Importing a csv file - Reading Data From an Excel Sheet - Reading From an Excel Sheet - regexp match string with word1 and not word2 - Qustion about struct.unpack - I/O Operations ..... - SonomaSunshine Get's a Little Peppier - Master's Thesis Help Needed - Chart drawing tool in python - Re: ctypes(python 2.5) cant work in win2000 platform!!! - Stopping pythoncom.PumpMessages in a windows service - Get Mac OS X google Desktop 5 Free - Launching an independent Python program in a cross-platform way (including mac) - help in debugging file.seek, file.read - fastest way to find the intersection of n lists of sets - opening a new tab in opera does not work - I can't inherit from "compiled" classes ? - exclusive shelve open - Counting - prevent an application to be closed by the user - howto check is object a func, lambda-func or something else? - Python ODBC - movable text - Could zipfile module process the zip data in memory? - While we're talking about annoyances - Asynchronous XML-RPC client library? - Tracebacks for `exec`ed code? - How to get HTTP error when using urlretrieve() - Any Good tools to create CSV Files? - CPython vs. Jython/JPython - python and activeX control - My Python annoyances - relative import broken? - how can I put an Exception as the key of a hash table - How to pass in argument to timeit.Timer - ImportError: No module named QtOpenGL - If you Got Questions? I bet We got Answers - I have a chance to do somting diffrent way not Python ?! - python function in pipe - tkinter undo - Numbers and truth values - Program runs in all directories, except one.. - Crystal Concepts offering PHP-MYSQL & JAVA/J2EE - Beginner Ping program - relative import problem - Weekly Python Patch/Bug Summary - Interop between C# and Python - Numeric + wxPython, can't understand a bug... - if __name__ == 'main': & passing an arg to a class object - Cgi File Upload without Form - how to create/ref globals in an alternate namespace? - python and COM - Import Problems - Returned mail: see transcript for details - Memory addressing - More urllib timeout issues. - wxPython (Flex)GridSizer Failing - editing scripts on a mac - Learning to use wxPython - use urllib library to have an upload status bar - building _tkinter module with .NET 2005? - Accessing SQL View with Python - getting rid of EOL character ? - creating an object from base class - Multiple select in wx.GenericDirCrtl - what python technology for my app? - How to open html files from python using internet explorer - List objects are un-hashable - searching a pattern in a file - video lectures on C, C++, Java, Python and other programming and Computer science. - regex question - pyqt4 signal/slot using PyObject* and shortcut - Command-line option equiv of PYTHONPATH - webbrowser.open works in IDLE and cmd shell but not from cygwin prompt - Correct behavior? - mysql "rows affected" - statistical functions for Date/Time data series - Getting a filename path from the path+filename - I25 barcode generator?
https://bytes.com/sitemap/f-292-p-31.html
CC-MAIN-2019-43
refinedweb
3,029
55.84
Xamarin.Forms should support CSS as a method of creating styles. In addition to the CSS style theming, we will include FlexBox style layout support. This model allows for a developer familiar with web technology and css to more easily adapt their layouts in Xamarin.Forms. Note: The demos below are intended to be short to showcase the API. A lot of them do otherwise silly things. Introduces quite a bit of new API, some of which is still being worked out. However, the bulk of it will be the following: public class FlexLayout : Layout<View> { // Attached BP's with public get/set methods public bool FlexEnabled; public bool IsIncluded; public float Flex; public float Grow; public float Shrink; public float Basis; public FlexAlign AlignSelf; // BP's with get/set properties public Direction Direction; public FlexDirection FlexDirection; public FlexJustify JustifyContent; public FlexAlign AlignContent; public FlexAlign AlignItems; public FlexPositionType Position; public FlexOverflow Overflow; public FlexWrap Wrap; } Enum values are pending implementation details. page.xaml: <ContentPage StyleSheet="page.css"> <StackLayout> <Label Text="Foo" StyleClass="test" /> <Label Text="Bar" /> <ContentView> <Label Text="Baz" StyleClass="test" /> </ContentView> </StackLayout> </ContentPage> page.css: label { background-color: green; font-size: 12pt; } label.test { background-color: yellow; color: grey; } StackLayout>label.test { background-color: purple; } CSS pages are embedded into the app via the resource dictionary. Each page can contain multiple different CSS files which define its full theming. The properties used in the CSS are named after the CSS properties, and not the Xamarin.Forms properties. They simply map down to Forms properties. CSS files are in practice just a different way to define a Xamarin.Forms.IStyle. Relationship selectors are supported as defined here: Note - All CSS embedding techniques shown here are just placeholders as the API around that is being reworked and finalized. All major CSS selectors will be supported. This functionality is not currently planned to be exposed through any mechanism other than CSS. page.xaml <ContentPage StyleSheet="page.css"> <FlexLayout> <FlexLayout StyleId="MainContainer"> <BoxView StyleClass="ABox" WidthRequest="100" HeightRequest="100" /> <Label Text="{Binding Content}" /> <Label Text="{Binding Content1}" /> <Label Text="{Binding Content2}" /> <Label Text="{Binding Content3}" /> <BoxView StyleClass="ABox" StyleId="EndBox" WidthRequest="100" HeightRequest="100" /> </FlexLayout> </FlexLayout> </ContentPage> page.css: flexlayout { display: flex; } #MainContainer { flex-direction: row; flex-wrap: wrap; justify-content: flex-end; } .ABox { align-self: center; } More details about how exactly the flexbox model allows for flexible layouts can be found here: Supported Flex Properties: No, it shouldn't. This isn't HTML. XAML has had an established way of creating Styles for over a decade. No need to fix what isn't broken. I think this is a great idea. One of the biggest problems with native UI development is that each platform re-invents the wheel when it comes to layout. We end up with all sorts of odd conventions like AutoLayout. HTML and CSS provide the best, most familiar UI solution to date. This would also lower the barrier to entry for many Web developers considering making a move to mobile development. If the UI layout and styling is familiar, that's one thing we don't have to learn. Not to XAML developers. There are tens if not hundreds of thousands of WPF developers from the last decade that have never dealt with HTML. The Xamarin noobies should get up to speed with the existing XAML conventions, not make all the experienced developers abandon what they have known and used for years. Web developers already have a big learning curve anyway, styles or CSS won't amount to much of a difference. There is no reason to try to foist all that CSS/HTML on to the existing XAML developer base. Not to mention SOOO MANY other things the folks at Xamarin could be fixing/working on, other than making a second style system when there is already a perfectly good one in place and has been in place for a long time. @ClintStLaurent > @ClintStLaurent said: @ClintStLaurent we're not suggesting to remove anything or replace XAML here. This proposal is to add support for an alternative that will allow other devs to be productive. If you don't need or want to use it, you'll still have everything you need. By contrast it's yet another DSL that developers not intimately familiar with web technologies will have to learn. I'm sure it's very powerful but it's desperately ugly and the syntax is very obscure. I would be very disappointed if it became the only way to create styles in Xamarin.Forms, especially since the existing way works well. Preferring CSS over the current system seems to me to be a re-hash of the old XML-is-bad-JSON-is-good argument. I'm not against this move per se. I'd be the first to admit that the current layout system is hard to work with. HorizontalOptionsand VerticalOptionsvery often don't do what I expect them to; I'm always having to add "filler" BoxViewobjects to get the StackLayoutto work properly; and so on. If the proposed FlexLayoutsolves those issues elegantly I'd be keen to adopt it. But please leave CSS out of it. I have a feeling that this small implementation will be the thin end of the wedge and we'll get more and more requests for "just this little bit of CSS" functionality. If that happens we might as well all give up and go with ReactNative. Facebook yoga () has a Xamarin wrapper. Maybe use this as the engine? Please note this from the Proposal: If you like CSS, you can use it. If you wish it would die in a fire, just pretend it doesn't exist. We are not proposing replacing the existing styling. Can you picture what the result of that would be? Picture a solution where someone has built half the styles in CSS and then another developers does some XAML styles using BasedOnand tries to point to the CSS styles. I have to agree with @DavidDancy I'm sorry if it hurts the feelings of web developers but the simple truth is... You need to get up to speed with the paradigms and technologies used for building applications - that run on the local hardware. IE: Desktop/platform executables. Programs are not web pages. The only justification I can find for working on a new layout system right now is that the old system is too bad to make it work fast enough on Android. If FlexLayoutcan solve the Android performance issues I'm all for it. BUT - and it's the biggest BUT I can summon - I'm sure Xamarin peeps do realise that there's a ton of legacy layout code that will need to be rewritten to take advantage of any speed increases that might come as a result of FlexLayout. Like somehow we're going to get managerial approval for tearing up all our stuff and doing it all over again - not. So my issue is not with the merits of FlexLayoutper se. I like it. I even have some issues with the current layout system. But why now? Is it really proving impossible to get the current system to work well enough? I hear you. Understood. I primarily here want to make sure we clearly articulate the proposal so we all understand it, and can have good discussion about it. @DavidDancy I hear ya. Though I did just read in another thread that Xamarin is working on an upgrade roadmapped for March release that should fix a lot of the performance lag in Android. I totally share your frustration, but would prefer to see man-hours spent on FIXING the parts that are bad, rather than patching over bad with a band-aide. We've all worked on those programs and its terrible. Putting that scheme in place within the Xamarin ecosystem would just kill it altogether. This isn't intended as a way to address deficiencies in our existing layout system. One of the major value propositions of Xamarin.Forms is as a productivity tool. We are more productive expressing our UI once and having it render to multiple platforms with a high degree of fidelity. This proposal is in keeping with that. We are seeing that many developers find this a productivity boost in terms of familiarity with their existing skills and as an ongoing way to quickly express styling and layout. Is that going to be true for 100% of developers, in particular those comfortable and productive with XAML and existing methods of styling? Likely not. Per conversation with @DavidDancy I've adjusted the current status of this proposal. I initially set it to "In Progress" to indicate it's not an "up for grabs" task, and the team has done some investigation. What I didn't intend to express was, we are actively integrating this into Forms today, right now, this past week, etc. A web dev has enough power with the webview control to show css styled HTML in Xamarin apps ( look at newspaper apps )! A Xaml dev would not touch css but, for me personally, would rather have a richer Xaml set. Uwp solved a lot for responsive design apps with Relative panel and visual state triggers. Set your prio on bringing that over to Xamarin forms. While I think the FlexLayout is a good idea, please don't even think on adding the CSS feature. It's a spec full of patches and workarounds (!important comes to mind) and it's the last thing we need the Xamarin team to focus on. Let's stop the trend on converging every technology into an HTML/web based approach. They are popular but they aren't the best option always. My opinion is that CSS should stay a library on it’s own and NOT be brought into Forms officially. It adds ambiguity on how styling should be done. Some things (as cool as they are) are better off as plugins or add-ins and not as a part of the official library. @DavidOrtinau FlexLayout = yes (once existing layout system stabilized), CSS = no. The existing XF layout engine is already completely riddled with minor bugs that cause many issues. (I should really file bug reports for these, but I'm only one guy and I get paid for building working apps, not filing bug reports ) I just mentioned these to highlight, I'm having enough trouble with layout system as it is, without introducing another way to define things via CSS, and hence introduce more issues. If the XF team developed far more comprehensive UnitTests than they have now with the Layout System, which they really should do, to stop these continuous regressions, then I might be more open to further expansion of the Layout system. Just to note, that last paragraph isn't said with any anger, just constructive criticism. I really think their layout system unit tests are lacking and need more focus. FlexBox layout: fantastic! Having a more flexible layout would be great! (wrapping,...) I would love to see css-based styling baked in! I have the impression that the resistence seen above comes from the fear that As David pointed out, this will not influence the roadmap (performance improvements,...). Xml vs Css As David also pointed out, css-styles compiles down to generated Style-objects - the same Style-objects that you are now used to write in XML. Compare writing styles in xml to writing styles in css: Css: Xml: Xml is overly verbose, distracts with many characters not needed to express the essence of your intended styling. And this is just a simple style. Vanilla Xaml-Styles vs Css Css offers you more than Xaml-Styles can give you. BasedOn). In css just add some css classes. Style-properties with a verbose markup-extension like {StaticResource nameOfStyle}. In css just add the css class. TextColorto Redon all inputs with validation errors? Currently you have to create an inherited style and switching it back and forth, remembering the previous one. Or setting the dependency-properties on the controls directly. In css just add a css class like validation-error. important, warning, default? Not available in xaml. In css this all is a no-brainer. (scss is even more powerful, but don't go off-topic) Adobe Flex: MXML and Css Had anyone of you used Adobe Flex with MXML and css? In that point it was a great combination and a pleasure to work with (I used it at work on a daily basis)! Adobe Flex Stylesheet Documentation "Using external style sheets" XamlCSS (Disclaimer: I'm the dev behind XamlCSS) Has anyone of you took the time and tried XamlCSS? Played around with it a little? It's free! It's here today! Binding, StaticResource, DynamicResource With additions to css like nested-selectors, variables, mixins you can get very productive and your styles concise. Property-Names Now to a point in the proposal I worry about: Not using property-names as-is, i.e. background-colorinstead of simply BackgroundColorcould be a problem in the long run. Without a mapping there is no mapping which has to be updated. On Css being a Pain... Without any offence intended to anyone: Who of you are really using css in their daily work? It is true, you can misuse css, you can get in a messy situation. But in my experience it mostly happens only if you use many different foreign css-stylesheets (from libraries, from cool website templates,...) But if you use it right it is a flexible, powerful and very concise way of expressing your styling. Endnotes Please let us not focus on if someone already knows or doesn't know, likes or doesn't like css - let's focus on what all of those knowing and/or willing to use css will gain if it were part of Xamarin.Forms! (Sorry, this post got pretty long ) If this is just an option, the ability to use CSS and FlexBox, that is - it's fully optional - and it doesn't hinder the progress of other features, why wouldn't it be a good idea? You don't like it, don't use it. Some of us would truly appreciate using this. I really think its a waste of resources. But as long as it does not come at the cost of other things, knock yourself out. The argument that Web Devs can benefits by transferring their skillset to XAML is weak. Microsoft tried that with WinJS. not a fan. why not focus on bringing more styling features over from "real" XAML? The people using Xam Forms are mostly XAML devs anyway. (oh and I really, really don't like CSS but I do love XAML) As Janneman said: Microsoft tried with WinJS to bring over the batch of Web Devs, it didn't work. Web Devs got their ways of doing cross platform, XAML devs got Xamarin Forms. Rather put effort in bringing over RelativePanel and VisualStateTriggers like Depechie proposed. CSS (in combo with multiple browsers) is the reason I don't do Web Dev. CSS and multiple OSes feels a lot like the same over again. Wouldn't it be nice if we could use iOS/Droid XAML user controls in Forms instead of always doing renderers? Wouldn't it be nice to have a single UI editor for Forms and platform UI? The list of synergies could go on. What is the Xamarin vision these days ? What are you guys aiming for in the mobile development department if not XAML/MVVM/.Net/etc ? I'm asking because suggestions like these makes me doubt that I understand where we are headed. With all due respect, this makes **ZERO **sense. XF is XAML. Period, end of story. Now that XF is part of Microsoft, the XF team must focus on **fixing **the current XF XAML grammar to match other Microsoft XAML stacks. How Height became HeightRequest is beyond me. Not DataContext but BindingContext, CRAZY. Microsoft, please normalize your XAML grammar, this will make it much easier for Enterprise and LOB developers to adopt your XF platform. Will also make it MUCH easier for XAML tooling (if we ever get that). Best, Karl Morning read: Catching up on all the comments over night. Trend I noticed: Many experienced WPF XAML developers (that would be the strongest base for Xamarin.Forms, right?) all saying the same thing: 1. Fix all the broken bits, 2. finish importing the missing bits 3. standardize what you have to the existing microsoft XAML spec ( Heightv. HeightRequestetc.) Something I notice nobody saying, but I think really needs to be said: Whether you agree or disagree with CSS as a second way to do styles is beside the point. Xamarin right now has PROVEN they can't or won't fix broken bits. How many Bugzilla reports do we all know about that have yet to even be confirmed/prioritized? My biggest fear is that this drive to bring in more web developers through CSS is going to backfire HUGE. Xamarin isn't taking care of the existing WPF migrators. If they split their man-power to hastily adding CSS all that's going to happen is there will be TWO BROKEN STYLE SYSTEMS, and that doesn't help the developers; and that doesn't help the eco-system. The last thing any of us want is to see Xamarin die the death of Silverlight. Xamarin has amazing potential and if they would just stay focused on making one complete, rich and functional system it could rule the mobile development market. If the folks at Xamarin want to add CSS as a way to bring in more developers - as a second system - more power to you. I hate the idea personally. But as long as it doesn't make things worst then I don't care if it is there since I can ignore it. But for Pete's sake PRIORITIZE. Fix all the existing problems and when you run out EXISTING XAML NEEDS to support, then start looking for stuff to bring in from other disciplines such as web. You guys at Xamarin are developers too, right? You know that if you have a busted foundation adding more weight on top is going to cause a collapse. Don't make that happen here by adding the weight of a million web devs piling on top of a system that already has issues. If you don't give everyone a solid foundation now, then 2018 will be the year we are all lamenting about how Xamarin joined all the other failed Microsoft technologies. I'm wondering when we will have bindings to listview select item event, datepicker/timepicker, and other issues. What I'm seem is focus on novelty not on basic things or bugs. Several of the comments here are about what the Xamarin.Forms team should be focusing on in the larger scope of the toolkit. That's fair, and I hear you loud and clear. The reason we have put this proposal into the forum is to give that added visibility, and if it meets with criticism, we need to know that. I'd like to ask that we focus the discussion on the proposal itself. If you don't think css/flexbox adds any value to the platform regardless of who proposes it, we welcome that perspective based on arguments of the merits of the proposal itself. We greet and welcome all other proposals with that same spirit, and I think it's fair to ask everyone do the same here. That's an interesting point. Does having multiple ways to do something like styling and layout create confusion? We can do layout in a few different ways today: XAML or code. Some of it is personal preference, and some of it is performance related. I think having these in a separate package would be a performance hit due to added reflection, but I could be wrong there. @DavidOrtinau when XAML was first introduced in the insiders forum, it was a huge deal. XAML is foundational to what Forms has become, and Forms wouldn't have the developer base it has without it. The same can be said for CSS in that there are a lot of developers out there who know CSS, and having it available might increase the user base. That being said however, I personally see this as a bell or a whistle, and not pivotal to the framework. As I said previously, keeping XamlCSS as a Nuget would be my vote. It's already mature(ish), has a user base, and is OSS for others to improve if need be. When multiple devs work on a project, you know as well as I do that the guidelines are just that "guides". Dev 1 will just shim in a Stylebecause that's what they know, and Dev 2 will meticulously maintain their CSS because maybe they came from web... so yeah, it's another layer of confusion. contrived Also, even thought I disagree with Xamarin introducing this as an officially supported/integrated library, I will stay that I'm looking forward to leveraging it in my next project! It's wonderful! How about this notion, and I base this off of an earlier comment pointing out that CSS and XAML take different approaches to achieve the same result. Css: Xml: Let's also not forget you can do all this same things in C# for those that don't like making UI in markup... And also in F# When you consider that the language doesn't really matter because it all gets compiled down anyway... The need remains that all the broken bits need to be fixed... {Just look at the volume of unhandled Bugzilla tickets} And the missing bits need to be written. For example: No merge dictionaries ala WPF. No multi-binding!? Not so much as a ListBoxequivilent that can show horizontally and something more than a vertical scroll list. I know I'm not the only dev tired of hunting for 3rd party WrapLayoutor FlowLayoutfor example. These are basic tool... But I digress.. Okay... Here's my proposal for how this proposal could be met: If the under-pinnings that EITHER markdown language would use and compile down to, would get finished THEN any and all languages and markdowns could hook into the same functions/controls/tools/bits/piecy-parts... it really becomes a personal preference for the developer. But until the low level parts ARE THERE to hook in to this proposal is a moot point. It doesn't matter if you want to bring in CSS or XSS or ABCSS if those languages try to make use of a function that Xamarin still hasn't gotten around to fixing or making. Fix and finish the underlying tools... Then let one team hook into those tools via XAML and another team can write the CSS parser. And in 5 years another team can write the new Widget markup parser... then the Thingie markup parser... It really doesn't matter which language you want. The original proposal isn't clear, and the wording might be a little wrong, generating quite a few of heated answers. So let me try to clarify a few things. stacklayout>label.testmeaning "only apply this style to a labelof class testshaving a stacklayoutas parent. If you never fell the need for this, or if you don't think this will be helpful in your application, you should totally stick to Styles. The default standard for having selectors is CSS, and that's why CSS was pushed forward. That doesn't mean we couldn't have Selectors on Styles... If Forms could understand CSS, we could incorporate apps like Zeplin into our workflows. It would be nice to be able to just plug this into a project: 2017-02-12 13.48.09.png?dl=0 A designer could design in Sketch, export to Zeplin, organize Zeplin, and then a developer could use that CSS to lessen their load work. With that said, I don't think this has be a runtime thing. If there was a Xamarin Studio or Visual Studio plugin that could generate the XAML to be compiled, I'd be happy to use that. It could also alleviate some concerns of taxing the Xamarin.Forms developers. This kind of work could be shifted to the IDE engineers (though they are most likely just as busy.) Ideally, this might be a good opportunity for a 3rd party shop, side project, school project, open source community, etc... The only reason I can see this been added is to try and tempt away NativeScript devs I guess....still if they like coding in JavaScript I doubt that would happen (beyond help ). Just my opinion but doesn't get my vote, once the roadmap has been implemented and is stable (as can be based on platform breaking stuff you can't foresee) then fair enough but it's a feature I'd never use. I don't want to repeat what the others have already said, except for one thing: there are better ways to serve your customers than to spend time on this. The styling isn't broken as such and I don't see almost anyone complaining about that. OTOH, many people still have issues with not-so-trivial bugs popping up all the time. If you can, fix what is broken, not what isn't. Also, CSS isn't really known as a cool, well thought out technology - just look at it as it is today and its evolution; it's a patchwork of things at best. Differently put, if you feel you absolutely must introduce an alternate way of styling XAML, please don't take CSS as an example syntax. As Stephane mentioned, the only real benefit to CSS is the selectors. But we currently have a painfully slow layout system, and I don't see the selector support doing anything else than further slowing it down. Sure, I'd love to add a class or select labels that are immediate children of a certain type of stackalyout. That's useful, but it's nowhere near urgent or most important to work on. The most painful thing about this is the deafness of the development team towards us, the core developers who push for Xamarin usage, who live and breathe Xamarin each day. Ever since Microsoft bought Xamarin, XF has been going down a very very bad path. We got "free" Xamarin... Well, no, nothing is free in life. Instead of paying for a product that keeps trying to be better, we are now getting a free product that keeps trying to sell us Azure subscriptions and get more and more web devs to also buy into azure. All that at the cost of the team actually improving the product. Xamarin Exec's top priority is marketing and amassing more and more developers. Building in CSS is so much better at attracting new devs than fixing a bug or improving performance is. Us existing developers are worthless to them since we stopped paying Xamarin subscriptions. Just sell sell sell those azure plans. Thanks Microsoft @Irreal I'm very sorry you feel that way. That troubles me deeply. We are presently working on bug fixes and performance improvements. Please msg me and let me know how else we might be able to help you. We need to keep the focus of this thread on the proposal, but I don't want to seem to ignore this. @DrazenDotlic I'm reading a growing consensus here that CSS as it is practiced on the web isn't useful or practical for mobile development. The primary gain we are considering with CSS as @StephaneDelcroix points out is the ability to use selectors. This isn't something you can do with just XAML and Styles. Given that the proposal is to map CSS properties to Styles, it is perhaps more appropriate to call it "css-like" or "css-inspired"? We certainly don't want to inherit unnecessary complexity as seen on the web. We do want to leverage power and productivity improvements of something like selectors. @Irreal, yes a very very real concern.
https://forums.xamarin.com/discussion/comment/252012/
CC-MAIN-2019-09
refinedweb
4,728
63.9
לפני מספר חודשים נפתחו באתר מיקרוסופט MSDN ישראל פורומים לפיתוח ו-IT. בחודש האחרון חל שינוי בפורומים, בקטלוג שלהם, וברשימת מנהלי הפורומים. כחלק מהשינוי אני שמח לבשר לכם על פתיחתו של פורום חדש לתחום הווב בניהולם של שלמה גולדברג (הרב דוטנט) ועבדכם הנאמן. בפורום ננסה לתת מענה לשאלות בנושאי פיתוח לעולמות הווב של מיקרוסופט – ASP.NET, ASP.NET MVC, Web Services, WCF, IIS, HTML/JS ועוד. להבדיל מהפורומים של MSDN, הפורומים במיקרוסופט ישראל מיועדים לקהל הישראלי, כתובים בעברית, ומעודדים כתיבה בעברית של שאלות ותשובות. למה בעברית? למה פורומים נוספים על אלו של MSDN? ובכן: 1. אנחנו לא היחידים – להרבה מדינות יש פורומים מקומיים, בשפה מקומית, שמיועדים לקהל המקומי. 2. עברית כשפת אם - לחלקנו קל להתבטא יותר בעברית במקום באנגלית. אני מכיר מפתחים מצויינים שעדין משתמשים בבודק איות לפני שליחת מייל באנגלית. כתיבה בעברית גם מאפשרת גישה לפורומים לקהל היותר צעיר של מפתחים. 3. יצירת קהילה – השתתפות בפורום תאפשר שיתוף פעולה יותר הדוק בין הקהל הישראלי והנציגים בארץ של מיקרוסופט. דרך הפורום נוכל ליידע אתכם על הרצאות בבתים פתוחים, כנסים בארץ,קורסים והכשרות. במקרים מסוימים ייתכן ואף נוכל לבצע אסקלציה של שאלות לגורמים במיקרוסופט ישראל ואף יותר מכך. לצערנו, עד כמה שנרצה, פורום לא יכול להסתמך אך ורק על המנהלים שלו שיענו, ולכן ההשתתפות שלהם חיונית להצלחת הפורום. אז גם אם אין לכם שאלה ספציפית, אתם מוזמנים להכנס לפורום מדי פעם, להגיב על שאלות, ללמוד משאלות של אחרים, וגם לספר לנו על משהו מעניין שמצאתם שאולי יכול לשמש אנשים אחרים. אם אתם נוהגים לעבוד עם RSS, אתם מוזמנים להוסיף את לינק ה-RSS של הפורום לרשימות שלכם. אז נתראה בפורום, בבלוג, בטוויטר ובאירועים השונים השנה.: 1. What’s new in WCF 4.5? let’s start with WCF configuration 2. What’s new in WCF 4.5? a single WSDL file 3. What’s new in WCF 4.5? Configuration tooltips and intellisense in config files: 1. There is a latency between the time the streamed message is received by ASP.NET and the time the WCF service method is actually invoked. 2. There is some memory consumption due to the buffering – the exact amount of memory consumed depends on the size of the message sent by the client, but it can even get to several hundred MBs if you increase the MaxRequestLength of ASP.NET, the MaxAllowedContentLength of IIS 7, and of course the MaxReceivedMessageSize and MaxBufferSize of WCF. 3. When ASP.NET buffers the request, it uses both memory and disk. The requestLengthDiskThreshold configuration setting of ASP.NET controls when ASP.NET starts to use the disk. If you upload multiple files to WCF at once, you will start to see some delays due to multiple files being written to the disk at once. BTW, the files are written to an “upload” folder under the web application’s temporary asp.net folder (under c:\windows\Microsoft.NET\Framework\vX.X.XXXX\Temporary ASP.NET Files\) and are removed after the request is handled.: 1 Client started upload on 17/01/2012 19:03:25 2 Available memory before starting is: 2701MB 3 Client finished upload on 17/01/2012 19:03:44 4 Available memory after finishing is: 2699MB 5 Available memory on ASP.NET is: 2701MB 6 ASP.NET received upload at: 17/01/2012 19:03:28 7 Available memory on WCF is: 2122MB 8 WCF started receiving file at: 17/01/2012 19:03:38 9 WCF finished receiving file at: 17/01/2012 19:03:43 File size is: 524288000 Press any key to continue . . . Some things to note about these results: 1. Client started / Client finished (line 1+3) – the total time the client waited for the service was 19 seconds; this includes the upload time, the buffering time of ASP.NET, and the time WCF handled the received stream. 2. ASP.NET started receiving the stream 3 seconds after the client began sending it (line 6). 3. WCF started receiving the stream 10 seconds after ASP.NET received started receiving it, and a total of 13 seconds from the time the client started sending it (line 8). In total, it took WCF 5 seconds to read the entire stream from ASP.NET (line 8+9). 4. Before the client sent the message, the available memory in the machine was 2701MB, which is also the available memory when ASP.NET first received the message. By the time WCF got the request and started handling it, the available memory was 2122MB – about 580MB were consumed from the memory for this operation (lines 2, 5, and 7). 5. As for the generated temp file, here is a screenshot of the temporary ASP.NET folder content:: 1 Client started upload on 11/27/2011 7:23:18 AM 2 Available memory before starting is: 942MB 3 Client finished upload on 11/27/2011 7:23:46 AM 4 Available memory after finishing is: 942MB 5 Available memory on ASP.NET is: 941MB 6 ASP.NET received upload at: 11/27/2011 7:23:20 AM 7 Available memory on WCF is: 942MB 8 WCF started receiving file at: 11/27/2011 7:23:20 AM 9 WCF finished receiving file at: 11/27/2011 7:23:46 AM. If. Yesterday I had two session in VS Live, one about the new features of WCF 4, and the other about the new way to develop web applications using ASP.NET MVC, the Razor view engine, jQuery, and IIS 7.5 Express. The slide decks and demo code for both sessions can be downloaded from here: I really enjoyed delivering both sessions, and congratulations to all the people that won Angry Bird balls for answering my questions, and for asking tough questions. Hopefully we will meet in next year’s VSLive (if my sessions are picked up again). Lately I’ve been writing and speaking a lot about WCF 4.5, but while delivering my “What’s new in WCF 4” session in Visual Studio Live yesterday I realized that there is one feature of WCF 4 that most people are not aware of, and do not really understand how useful it is – Standard Endpoints. In WCF we always have to specify a set of address+binding+contract (ABC) for our endpoints. If our endpoints also need to be configured, for example – change the binding configuration, or the endpoint behavior, then we need to add some more configuration. We can use default configuration (another feature of WCF 4), but if we have two common settings, we cannot set two defaults and we’re back to square one. Standard endpoints change the way we define endpoints – with standard endpoints we specify a special “kind” name in our endpoint, which automatically sets our endpoint’s address, binding, contract, binding configuration, and endpoint behavior. For example – if we define the following endpoint: <endpoint address="mex" kind="mexEndpoint"/> The above endpoint will automatically be set with the mexHttpBinding and the IMetadataExchange contract. If we define the following endpoints: <endpoint address="web" kind="webHttpEndpoint" contract="MyNS.IMyContract"/> We will get an endpoint which uses webHttpBinding, and automatically gets the webHttp endpoint behavior. Although this is quite nice, this is the least we can do with standard endpoints. The real use of standard endpoints is when you create some of your own. Image the following – you are a part of an infrastructure team in your organization and you need to explain to the dev teams which endpoint configuration they should use in their projects – “Please use NetTcp binding, with increased message size limits, with either security none or transport, and don’t forget to increase the send timeout”. One way to do this is to send a memo to all the dev teams, hoping everyone follow your instructions to the letter. Another way you can do that is to create your own standard endpoint with all of the above configuration and just send it to the dev teams to use. First of all you need to create your custom endpoint: 1: public class CompanyNameStandardEndpoint : ServiceEndpoint 2: { 3: private bool _isSecured; 4: 5: public CompanyNameStandardEndpoint(ContractDescription contract) 6: : base(contract) 7: { 8: this.Binding = new NetTcpBinding(); 9: ResetBindingConfiguration(this.Binding); 10: this.IsSystemEndpoint = false; 11: } 12: 13: public bool IsSecured 14: { 15: get 16: { 17: return _isSecured; 18: } 19: set 20: { 21: _isSecured = value; 22: if (_isSecured) 23: { 24: (this.Binding as NetTcpBinding).Security.Mode = SecurityMode.Transport; 25: } 26: else 27: { 28: (this.Binding as NetTcpBinding).Security.Mode = SecurityMode.None; 29: } 30: } 31: 32: } 33: 34: // Receive a dynamic object instead of creating separate methods 35: // for netTcp, basicHttp, WSHttpBinding... 36: private void ResetBindingConfiguration(dynamic binding) 37: { 38: binding.SendTimeout = TimeSpan.FromMinutes(5); 39: binding.MaxReceivedMessageSize = Int32.MaxValue; 40: binding.MaxBufferSize = Int32.MaxValue; 41: } 42: } Line 8 makes sure that your endpoint will use NetTcp binding. Line 9 will call a method that initializes the binding settings (lines 36-41). Note : the ResetBindingConfiguration method receives a dynamic object because for some reason some of the binding properties such as the MaxReceivedMessageSize and the MaxBufferSize are defined in each of the bindings instead of being defined in a base Binding class. The dynamic will allow us to change our code later on to support both TCP and HTTP bindings without duplicating our method for overloads. Line 10 specifies that this is a user-defined endpoint and not a system endpoint. Lines 13-32 are responsible of handling the user’s selection to whether the endpoint is secured or not by changing the security mode to either Transport or None. So now we have a new standard endpoint that initializes the binding to NetTcpBinding, sets the timeout and message size, and knows to set the security according to the user’s selection. We can now add this endpoint in code to our service by calling the following code: 1: CompanyNameStandardEndpoint newEndpoint = new CompanyNameStandardEndpoint( 2: ContractDescription.GetContract(typeof(IService1))); 3: 4: newEndpoint.IsSecured = false; 5: newEndpoint.Address = new EndpointAddress(tcpBaseAddress + "companyUnsecured"); 6: 7: host.AddServiceEndpoint(newEndpoint); To be able to add this endpoint configuration in the config file, you will need to add some boilerplate code: 1: public class CompanyNameStandardEndpointCollectionElement : 2: StandardEndpointCollectionElement<CompanyNameStandardEndpoint, CompanyNameStandardEndpointElement> 3: { 4: } 5: 6: public class CompanyNameStandardEndpointElement : StandardEndpointElement 7: { 8: protected override ServiceEndpoint CreateServiceEndpoint(ContractDescription contractDescription) 9: { 10: return new CompanyNameStandardEndpoint(contractDescription); 15: get { return (bool)base["isSecured"]; } 16: set { base["isSecured"] = value; } 17: } 18: 19: protected override ConfigurationPropertyCollection Properties 20: { 21: get 22: { 23: ConfigurationPropertyCollection properties = base.Properties; 24: properties.Add(new ConfigurationProperty("isSecured", typeof(bool), false, ConfigurationPropertyOptions.None)); 25: return properties; 26: } 27: } 28: 29: protected override Type EndpointType 30: { 31: get { return typeof(CompanyNameStandardEndpoint); } 34: protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ServiceEndpointElement serviceEndpointElement) 35: { 36: CompanyNameStandardEndpoint customEndpoint = (CompanyNameStandardEndpoint)endpoint; 37: customEndpoint.IsSecured = this.IsSecured; 38: } 39: 40: protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ChannelEndpointElement channelEndpointElement) 41: { 42: CompanyNameStandardEndpoint customEndpoint = (CompanyNameStandardEndpoint)endpoint; 43: customEndpoint.IsSecured = this.IsSecured; 44: } 45: 46: protected override void OnInitializeAndValidate(ServiceEndpointElement serviceEndpointElement) 47: { 48: 49: } 50: 51: protected override void OnInitializeAndValidate(ChannelEndpointElement channelEndpointElement) 52: { 53: 54: } 55: } The above code is a basic configuration element code. The most important part is lines 13-17 in which you need to repeat each of the properties you created in the custom standard element (for a mapping between XML and CLR) and line 24 where you add all the properties that can be set in the configuration file, so the configuration can be validated. Once you create the above code, you need just on more step to use the new endpoint kind in your configuration – you need to tell WCF that you have a new service endpoint. To do that you add the following XML in your <system.serviceModel> section: 1: <extensions> 2: <endpointExtensions> 3: <add 4: name="companyNameEndpoint" 5: 6: </endpointExtensions> 7: </extensions> Note: On MSDN you can find a good explanation on standard endpoints, but the extensions configuration part is incorrect, the above configuration is the correct one (the correct element in the <extensions> is <endpointExtensions> and not <standardEndpointExtensions> as it appears in the article). Now you are ready to declare your new endpoints and configure them: 1: <services> 2: <service name="TestWcfStandardEndpoints.Service1"> 3: <endpoint binding="basicHttpBinding" 4: 5: <endpoint address="mex" 6: 7: <endpoint address="companySecured" 8: kind="companyNameEndpoint" 9: endpointConfiguration="securedEndpoint" 10: 11: </service> 12: </services> 13: 14: <standardEndpoints> 15: <companyNameEndpoint> 16: <standardEndpoint isSecured="true" name="securedEndpoint"/> 17: </companyNameEndpoint> 18: </standardEndpoints> In lines 7-10 we define the endpoint with the new “kind” (line 9) and specify where we configure the rest of the endpoint (line 10). Lines 14-18 contains the configuration of the standard endpoint which we created. So to conclude, standard endpoints are an easy way to create fully-configured endpoints with binding configuration, contract settings, and endpoint behaviors. It’s mostly useful when wanting to create the same endpoint over and over again in multiple projects (which happens in 99.99% of the time). Don’t bother copy pasting all the above code – you can just download the complete solution from here Today I delivered a half-day talk about WCF on the following subjects: According to the events website at, it looks like this was the first Microsoft event worldwide about WCF 4.5. We like new technologies in Israel . We had a full-house (~100 people), got a lot of questions from people during and after the session, so it was lots of fun. I really enjoyed delivering the session, and I hope that in the coming year we will be able to see the RTM of Visual Studio 11 and .NET 4.5. If you missed today’s session, you have another chance to hear me talk about WCF 4.5 in the November meeting of the Web Developers Community (WDCIL) this Tuesday in Microsoft Raanana. You can get more information and register to the event at In the meanwhile, you can download the presentation and the sample code I’ve shown from my SkyDrive at – this also includes the WCF 4.5 demos I showed, so don’t forget to install VS 11 and .NET 4.5 (preferably on a VM). I want to repeat what I told people in the event today – the WCF team is eager to know what you think about WCF, what is missing in WCF to make your work easier, and if you encountered any bugs in the product. There are several ways by which you can contact them: If you want to read more about WCF 4.5, check out previous posts I published. I will publish new in-depth posts on the new features, so stay tuned. You can also follow me on Twitter @IdoFlatow If you want to learn more about WCF, check out the following WCF sessions we have at Sela’s DevDays next week: If . This do the following two changes: 1. Enable ASP.NET compatibility mode for the hosting environment in your web.config: <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> </system.serviceModel> 2. Set each of your services to support the compatibility mode, by adding the AspNetCompatibilityRequirements attribute. : 1. In the WCF Service Application project template, the aspNetCompatibilityEnabled attribute was added to the serviceHostingEnvironment element, and it is set to true by default. 2. The default value of the AspNetCompatibilityRequirements attribute has changed from NotAllowed to Allowed. Without this changed default, you would have needed to manually add the attribute to every new service. This is noticeable in the attribute’s documentation: WCF 4 - WCF 4.5 - ASP.NET compatibility mode is very useful if you need to use share next posts, so stay tuned. Orlando (December 5-9). Today I had my WebDev session about the new technologies related to web development: I enjoyed the session very much, and by the amount of tweets it looks like I wasn’t the only one. I hope no one got hurt from my flying balls You can download the session’s slides and the two demos I showed from here: I’m off to San-Francisco tomorrow for the North-America MCT summit. Visual Studio Live – thanks for having me, I will see you all again in VS Live Orlando in December. Yesterday I had my WCF 4 session in VS Live, where I showed some of the new features of WCF 4, including: I also talked a bit about some other new WCF 4 features such as the DataContractResolver type, the new ReceiveContext API for MSMQ bindings, Monitoring WCF with ETW and PerfMon, the new binary stream encoder, and the new throttling defaults. Those of you who stayed till the end also heard about some of the new features that will be in WCF 4.5. So if you’ve missed the session, had to step outside for an important call, or you just want to try out the samples I showed, you can go ahead and download the slides and samples from here: This is the seventh post in the WCF 4.5 series. In previous posts we’ve examined two new security features of WCF 4.5 and IIS – multiple client credentials support, and default HTTPS endpoint support, both new features are IIS-specific (or to be more exact, web hosting specific). In this post we will look into a new security configuration option in WCF 4.5 – the BasicHttpsBinding. Transport security is supported in WCF since day 1, and you can configure it by setting the security mode of your binding: <bindings> <basicHttpBinding> <binding name="secured"> <security mode="Transport"> <transport clientCredentialType="Windows"/> </security> </binding> </basicHttpBinding> </bindings> Declaring transport security based endpoints is quite an easy task in WCF, but does require writing some binding configuration in the config file. WCF 4.5 helps reduce the amount of configuration by adding a new type of binding – basicHttpsBinding. The basicHttpsBinding is similar to basicHttpBinding, only it has the following defaults: Setting up an endpoint with a basicHttps binding is quite simple: <services> <service name="WcfServiceLibrary1.Service1"> <host> <baseAddresses> <add baseAddress = "" /> <add baseAddress = "" /> </baseAddresses> </host> <endpoint address="" binding="basicHttpBinding" contract="WcfServiceLibrary1.IService1"/> <endpoint address="" binding="basicHttpsBinding" contract="WcfServiceLibrary1.IService1"/> </service> </services> If you want to change the default client credential type for the secured endpoints, you will need to create a binding configuration for the secured endpoint: <bindings> <basicHttpsBinding> <binding> <security> <transport clientCredentialType="Windows"/> </security> </binding> </basicHttpsBinding> </bindings> Note: Since this is a secured binding, the security mode can be either Transport or TransportWithMessageCredential only. TransportCredentialOnly is not supported for this type of binding.? 1. Set up SSL in your IIS; there’s an excellent tutorial for this in the IIS.NET website. 2. Create the WCF service and host it in a web application. 3. Set the web application to be hosted in IIS. 4. Verify that the service doesn’t have any endpoint configuration set for it, so it will use default endpoints.. October began yesterday with an email from Microsoft congratulating me for receiving Microsoft’s Most Valuable Professional (MVP) award. I’m a connected system developer MVP, which kind of describes my work – working with distributed systems, connecting clients and servers, building WCF services, ASP.NET applications, working with IIS servers, etc… This is the first time I receive the MVP award, so I’m quite excited. Special thanks to the people who helped with my nomination – Guy Burstein and Meir Pinto from Microsoft Israel, to my managers at Sela Group – David Bassa and Ishai Ram, and of course to all of you that are reading my blog, that come to my sessions in conferences, to the hundreds of people I trained over the years, and to those whose nickname I only know that marked my answers as correct in forums. Congratulations also to my colleagues in Sela – Arik Poznanski for his new MVP in Visual C#, and to Gil Fink for his third year in a row of being a Data Platform MVP. As I said before, this month bears many good news – next week I’m heading to Microsoft HQ in Redmond, where I’m going to attend an Azure Platform Metro course. Metro courses are special Microsoft courses that are constructed by DPE teams in Microsoft (developer and platform evangelists) and are intended to teach new technologies for eager developers. I’m going to participate in this course with several other trainers from all over the world, and learn the newest stuff in the Azure platform from Microsoft’s experts, so it’s going to be a great experience for me, and I’m very much looking forward to it. October goes on with good stuff – the following week after the course I’m going to attend the Visual Studio Live! conference in Redmond (17-21 of October), this time not as a listener, but as a speaker. I’m giving two sessions in the conference, about the new features of WCF 4, and about the new face of web development – ASP.NET MVC, jQuery, and Razor. And for the finale of October – after my two sessions, I’m catching a flight to San-Francisco to attend the North-America 2011 MCT Summit (Microsoft Certified Trainers Summit), which is also during 19-21 of October. In the summit I will be presenting yet again the new features of WCF 4, but will also probably spend some time talking about teaching tips for the official WCF 4 course (10263A) that I co-authored last year for Microsoft. If you are working in the area of Seattle or San-Francisco, and interested in WCF consulting or training, let me know as I have a few days off that I can dedicate to consultations and courses. I will be available in the Seattle area between 14-17 of October, and in the San-Francisco area between 21-22 of October. I also have a 9-hour connection in Newark on the 23rd, if you want a quick consultation October started great with my new MVP, and it’s going to end great with two weeks of learning and speaking in the US. This. In comes WCF 4.5, or to be more exact Visual Studio 11, with it’s! This is the fifth post in the WCF 4.5 series. This time we will demonstrate one of the new cool features of WCF 4.5 and IIS hosting – creating an endpoint that supports multiple authentication types. Note: The authentication mechanism in the following post refers to client authentication used in the HTTP transport (the Authorization HTTP header), either when using a secured transport (HTTPS) or a non-secured transport (HTTP). When hosting WCF services in IIS, a lot of developers struggle with the problem of declaring authentication types, since there are two places where you need to set the authentication type – in the service’s configuration and in the IIS configuration. If you don’t set the two properly, meaning if there is a mismatch between the endpoint’s authentication types and IIS’s authentication types, you might end up getting an error message like this: The authentication schemes configured on the host ('Basic, Anonymous') do not allow those configured on the binding 'WSHttpBinding' ('Negotiate'). <serviceAuthenticationManager> element, by updating the ClientCredentialType property on the binding, or by adjusting the AuthenticationScheme property on the HttpTransportBindingElement. The message informs you that you’ve declared basic and anonymous authentication in IIS, but you are trying to use Negotiate (Windows authentication using Kerberos) in your service configuration which isn’t supported by the host (IIS). Since this is very annoying, WCF 4.5 enabled you to inherit the authentication types from IIS, so you only need to declare them once. So how do we do that? It took me some time to understand how to set it up, since this is one of the new features which is not so documented; To save you the trouble, here is a set of instructions you’ll need to follow: 1. Create a service and host it in IIS. 2. Define the service’s endpoint to use any of the HTTP bindings (basicHttp, wsHttp…). 3. Create a binding configuration for the endpoint, and set the security to either Transport, or TransportCredentialsOnly (in basicHttp). 4. In the transport’s configuration, set the clientCredentialType attribute to InheritedFromHost – this is a new value that was added in WCF 4.5. This value is currently not documented in MSDN. At this point, your service configuration might look like so: <services> <service name="MyService"> <endpoint address="" binding="basicHttpBinding" contract="Mycontract" bindingConfiguration="secured"/> </service> </services> <bindings> <basicHttpBinding> <binding name="secured"> <security mode="Transport"> <transport clientCredentialType="InheritedFromHost"/> </security> </binding> </basicHttpBinding> </bindings> Note: if you use basicHttpBinding, you can use either transport security or transportCredentialsOnly security (use the last option only when not using basic authentication). For wsHttpBinding, you need to use transport security to get the InheritedFromHost credential type option. 5. Open IIS, and set the authentication types to the ones you require – anonymous, basic, digest, NTLM, windows, or certificate. Of course you can set several of these options. 6. After setting the authentication types in IIS, try browsing to the service’s WSDL file and check the reported authentication types: <wsp:ExactlyOne> <http:NegotiateAuthentication xmlns: <http:NtlmAuthentication xmlns: </wsp:ExactlyOne> Note: Anonymous authentication is not shown as an authentication type in the WSDL. For the list of authentication types that can appear in the WSDL file, check this MSDN article. 7. On the client-side, add a service reference to your service. The generated configuration will be set according to the authentication types you set in IIS:> One small thing to note regarding the default configuration – basicHttp and wsHttp have different default values for client credential type; if the authentication type in IIS is the binding’s default credential type, then you will see the following client binding configuration (this example is for the wsHttp binding): <wsHttpBinding> <binding name="WSHttpBinding_IService1"> <security mode="Transport"/> </binding> </wsHttpBinding> The default client credential for basicHttp is none, and the default for wsHttp is Windows. So for the above example, the binding configuration was generated because the IIS was set to Windows. I think that Microsoft should have invested a bit more on managing the configuration on the client side for this feature – it’s not clear to the client-side which authentication types are supported, and the generated configuration is only set to one of them. Another thing is that if you use anonymous authentication in IIS, it doesn’t show in the client configuration unless it is the only available authentication type. To conclude, without this feature, we need to declare several endpoints, one for each credential type, but our clients will able to see exactly which credentials the service expects; With the new feature, we only need one endpoint, and the rest is configured in IIS, but our clients will have more trouble understanding what is available to them. My score for this feature: Server-side +1, Client-side –1.
http://blogs.microsoft.co.il/blogs/idof/default.aspx?PageIndex=2
CC-MAIN-2013-20
refinedweb
4,470
50.67
Stas Bekman wrote: > Geoff, any chance we can get this one resolved? As we may make a new > release soonish, we can't have this collision in Apache::compat and > APR::Finfo get out from the dev release. I really don't know the answer to this. the new finfo API is a proper interface, and I don't see removing it just to appease the compat layer, especially since it's just exposing a problem that many compat methods have. >> what about a new namespace? instead of finfo_old make everyone using >> compat do this >> >> my $r = Apache::compat($r); >> >> then $r->finfo would be certain to call Apache::compat::finfo. actually, I meant Apache::compat->new($r) but you get the idea :) > It's a cool idea, but it 1) requires users to change their code, whereas > for most case they don't need to with the current Apache::compat 2) it > won't work for functions which aren't invoked on $r I :) > > So if we already require users to change their code, let's just rename > the method. How about adding _mp1 postfix for those methods that collide? > I don't think that's a good idea at all - you might as well not have a compat layer at all then. in the short term, though, I'd be in favor of removing Apache::compat::finfo() if the smoke failures are bothersome - finfo() just isn't all that popular (unfortunately). --Geoff --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@perl.apache.org For additional commands, e-mail: dev-help@perl.apache.org
http://mail-archives.apache.org/mod_mbox/perl-dev/200312.mbox/%3C3FD69D55.5010300@modperlcookbook.org%3E
CC-MAIN-2013-48
refinedweb
263
69.21
Once you've figured out the basics to a tkinter window, you might fancy the addition of some buttons. Buttons are used for all sorts of things, but generally are great to incite some interaction between the program and the user. Adding buttons is a two-fold thing in the end. In this video, we show just plainly how to add a button. The addition of a button and its button-like functionality is great, but, in the end, we actually want the button to do something. We'll get there, but first let's just show the button. Here's our new code: from tkinter import * class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() #Creation of init_window def init_window(self): # changing the title of our master widget self.master.title("GUI") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) # creating a button instance quitButton = Button(self, text="Quit") # placing the button on my window quitButton.place(x=0, y=0) root = Tk() #size of the window root.geometry("400x300") app = Window(root) root.mainloop() So here we see a few new concepts. The first is self.init_window(). Why have we done this? Well, in the world of window-making, what we might normally refer to as a "window," is actually correctly called a frame. So that outer edge that people generally call a window is actually the frame. In the first tutorial, we actually just created the frame for windows. I know, I know... earth-shattering things coming at you. So, once you have the frame, you need to specify some rules to the window within it. here, we initialize the actual window, which we can begin to modify. The next major thing we see is the init_window() function in our window class. Here, we give the window a title, which adds the title of GUI. Then we pack, which allows our widget to take the full space of our root window, or frame. From there, we then create a button instance, with the text on it that says quit. While tkinter is very basic and simplistic, I sometimes fear that its simplicity is very confusing to programmers. At least for me, I wondered, how we actually get "quit" written on the button. Surely it would take a lot of work? What about making the button go up and down like a button? All of this is just plain done for us. So when you say text="quit," that's really all you have to do and tkinter handles all of the rest. Finally, when we're done creating this button instance, we place it on the window. Here, we place it at the coordinates of 0,0. This can also be quite confusing, because 0,0 may make people expect the quit button to be at the lower left. Instead, it appears at the upper-left. When it comes to computer design, like css or here, 0,0 means upper left. Adding to x moves right, as expected. Adding to the y variable, however, moves down, which is contrary to what you're taught in your graphing lessons in school. With all of this done, you should now be greeted with a window that looks like:
https://pythonprogramming.net/tkinter-python-3-tutorial-adding-buttons/?completed=/python-3-tkinter-basics-tutorial/
CC-MAIN-2021-39
refinedweb
557
75.91
I'm new in python and I'm trying to dynamically create new instances in a class. So let me give you an example, if I have a class like this: class Person(object): def __init__(self, name, age, job): self.name = name self.age = age self.job = job variable = Person(name, age, job) persons_database = { 'id' : ['name', age, 'job'], ..... } Person Just iterate over the dictionary using a for loop. people = [] for id in persons_database: info = persons_database[id] people.append(Person(info[0], info[1], info[2])) Then the List people will have Person objects with the data from your persons_database dictionary If you need to get the Person object from the original id you can use a dictionary to store the Person objects and can quickly find the correct Person. people = {} for id, data in persons_database.items(): people[id] = Person(data[0], data[1], data[2]) Then you can get the person you want from his/her id by doing people[id]. So to increment a person with id = 1's age you would do people[1].increment_age() ------ Slightly more advanced material below ---------------- Some people have mentioned using list/dictionary comprehensions to achieve what you want. Comprehensions would be slightly more efficient and more pythonic, but a little more difficult to understand if you are new to programming/python As a dictionary comprehension the second piece of code would be people = {id: Person(*data) for id, data in persons_database.items()} And just so nothing here goes unexplained... The * before a List in python unpacks the List as separate items in the sequential order of the list, so for a List l of length n, *l would evaluate to l[0], l[1], ... , l[n-2], l[n-1]
https://codedump.io/share/zMA1Nj7nze3Q/1/dynamically-create-instances-of-a-class-python
CC-MAIN-2017-09
refinedweb
288
54.42
I have this working code but my teacher wants really specific things. codes always have to be OOP, and this needs to to have no more then 2 cout. i have 3 but cant seem to find away to take one out. my friend told me i should do this in arrays, but honestly im not really good at this so im really confused about what to do. again sorry if im posting this in the wrong place or posting it in a bad way. thanx u in advance. here is the code, // DiamondLoop.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include<iostream> using namespace std; class Diamond { private: public: Diamond(){ int i=0, j=0, NUM=3; for(i=-NUM; i<=NUM; i++) { for(j=-NUM; j<=NUM; j++) { if( abs(i)+abs(j)<=NUM) { cout<<"*"; } else { cout<<" ";} } cout <<endl; } } }; int _tmain(int argc, _TCHAR* argv[]) { Diamond shape; return 0; }
https://www.daniweb.com/programming/software-development/threads/375520/c-oop-diamond-loop-2-cout-count
CC-MAIN-2018-30
refinedweb
158
80.92
Handling CSV Files in Python As a buddy of mine always says "the nice thing about standards is that there's so many to choose from". Take CSV files for example. CSV, of course, stands for "Comma Separated Values", more often than not though, it seems that CSV files use tabs to separate values rather than commas. And let's not even mention field quoting. If you deal with CSV files and you use Python the csv module can make your life a bit easier. Dealing with CSV files in Python probably couldn't be much easier. For example purposes, let's use the following CSV file that contains 3 columns "A", "B", and "C D": $ cat test.csv A,B,"C D" 1,2,"3 4" 5,6,7 The following python program reads it and displays its contents: import csv ifile = open('test.csv', "rb") reader = csv.reader(ifile) rownum = 0 for row in reader: # Save header row. if rownum == 0: header = row else: colnum = 0 for col in row: print '%-8s: %s' % (header[colnum], col) colnum += 1 rownum += 1 ifile.close() When run it produces: $ python csv1.py A : 1 B : 2 C D : 3 4 A : 5 B : 6 C D : 7 In addition, the csv module provides writer objects for writing CSV files. The following Python program converts our test CSV file to a CSV file that uses tabs as a value separator and that has all values quoted. The delimiter character and the quote character, as well as how/when to quote, are specifed when the writer is created. These same options are available when creating reader objects. import csv ifile = open('test.csv', "rb") reader = csv.reader(ifile) ofile = open('ttest.csv', "wb") writer = csv.writer(ofile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: writer.writerow(row) ifile.close() ofile.close() Running it produces: $ python csv2.py $ cat ttest.csv "A" "B" "C D" "1" "2" "3 4" "5" "6" "7" My first task when starting to use the csv module was to write a function to try to determine what format the CSV file was in before opening it so that I could deal with commas and tabs and different quoting conventions: import os import sys import csv def opencsv(filename): tfile = open(filename, "r") line = tfile.readline() tfile.close() if line[0] == '"': quote_char = '"' quote_opt = csv.QUOTE_ALL elif line[0] == "'": quote_char = "'" quote_opt = csv.QUOTE_ALL else: quote_char = '"' quote_opt = csv.QUOTE_MINIMAL if line.find('\t') != -1: delim_char = '\t' else: delim_char = ',' tfile = open(filename, "rb") reader = csv.reader(tfile, delimiter=delim_char, quotechar=quote_char, quoting=quote_opt) return (tfile, reader) Being new to the csv module and making the common mistake of not reading the whole "man" page, I of course failed to notice that the csv module already contains something to do this called the Sniffer class. I'll leave using it as an exercise for the reader (and in this case the writer also).sv content formatting at csv file level I am writing out to csv files a lot using csv module: The content if fairly 3 to 6 lines for each cell. But when I launch the created csv file which is different every time I run it due to timestamp embedded in the file name, the cell only shows few of the text. Is there any function or fomatting along with the csv module which would enable the csv files to show all text for a cell for every cell instead of dragging the columns wider or going to format and autoformat each time. eg. POWERUPREASON : 0x00000080 BL_VERSION : 0x00000005 UBOOT_VERSION : 0x00000000 Above is content for one cell, but the generated cell in file shows only this much text "POWERUP" when I drag the cell it shows all text but not initially. Please help how to control precision with csv write Hi, I am writing & reading to both csv files (using the csv module) and to MS SQL databases (using pymssql). By default, they use different numeric precision levels. Specifically, the csv module uses only 12 digits while the DB module uses 17 digits. I may at times need precision greater than 12 digits, but I won't need beyond 17 digits. So I can use the pymssql default. But mostly, I'd like to know how to adjust these precision levels so that I have some control over it. Here is an example small code, but it's trivial to test out in whichever way you want: ================== import csv myWriter = csv.writer(sys.stdout) myWriter.writerow ( ('whatever', 12.345678901234567890) ) ================== will yield: testing, 12.3456789012 (12 digits, total) I know that I could do some sort of manipulation line by line, however the data that I am going to save is quite large, both in having many columns (of varying types) and in having many rows. I have read that python, by default, prints only to 12 decimal points precision. I am therefore hoping that is some sort of default that I can adjust, maybe with a command looking something like: float.precision(17) or something similar to change all print defaults to 17. Ideally, I'd like to change something global like that so that I can take a very large list of tuples and just do the following: myWriter.writerows(myData) and that's it. I am not sure how this thread works, but if I am not automatically notified via the e-mail address I provided, could you please e-mail any response to this.is.mvw@gmail? I don't check python or linux web pages frequently, as I am normally not working with either at any developer level. Thanks! Mike Convert to string If there is a way to change the default formatting precision for numbers I'm not aware of it. A fairly simple workaround would be to convert your numbers to strings before writing them. For example: Mitch Frazier is an Associate Editor for Linux Journal. thanks! Hi Mitch, Thanks so much for the suggestion! Somehow I hadn't though of that. :( I normally like to keep my variables in their "native form", but it doesn't matter if I'm sending it to a file anyway. Thanks! Mike thanks! this tutorial saved the day! thanks a million... CSV help How i can write this using CSV as input will be in CSV file. Input: a = 1 b = 2 c = 3 Output If i print a then it should give 1 If i print b then it should give 2 and so on.......... thanks Not clear It's not at all clear what you're asking. Mitch Frazier is an Associate Editor for Linux Journal. How would you select clumns to put in new file I came accross this code for perl:... perl -e " @cols=(1, -1, 2); while(<>) { s/\r?\n//; @F=split /\t/, $_; print join( qq~\t~, @F[@cols]), qq~\n~ } warn qq~\nChose columns ~, join( qq~, ~, @cols), qq~ for $. lines\n\n~ " all_cols > some_cols_chosen and I am trying to get a python code that does the same and will allow me to write say only the first 13 columns from a csv file to a new file. Thanks Shawn more info Hi, How about if i want to output it becoming... A : B A : C D 1 : 2 1 : 3 4 5 : 6 5 : 7 Thanks Try this This should do it: Mitch Frazier is an Associate Editor for Linux Journal. Nice Post Very nice. I use a lot of CSV files for data analysis using R. I hope to become more involved in building and standardizing options for doing data analysis in Python as Python opens up the world of 'real' programming languages: eventually using R's functionality with webapps/gtk/etc. CSV Files to HTML Hi ! I recently wrote a quick script to convert CSV files of the form: foo, bar, blah, blah into nice HTML displays. Here it is: Hope it is useful! Making the first example more Pythonic That first code example reads a bit more cleanly if you use some standard Pythonisms ( zip()and using the reader as an iterator, calling next()to get the header) import csv ifile = open("test.csv", "rb") reader = csv.reader(ifile) headers = reader.next() for row in reader: for header, col in zip(headers,row): print "%-8s: %s" % (header, col) ifile.close() -gumnos Thanks Actually, I'm fairly new to Python programming so I can use all the tips you got. For others not familiar with the Python builtin function zip(), this is from the docs: In other words, for the example here, it pairs each column with the corresponding header. Using the first data row from the test file, zip(headers,row) would return: Mitch Frazier is an Associate Editor for Linux Journal.
http://www.linuxjournal.com/content/handling-csv-files-python?quicktabs_1=2
CC-MAIN-2016-30
refinedweb
1,466
71.95
Playing with asyncio and aiohttp in Python as a C# developer. My script at the end looked like this (given it’s my first try, I would be happy if somebody corrects something suboptimal with my asyncio usage). import sys import time import asyncio import aiohttp from termcolor import colored urls = ["", ""] async def fetch(url, loop): async with aiohttp.ClientSession(loop=loop) as session: try: start_time = time.perf_counter() async with session.get(url, allow_redirects=False, timeout=10) as response: end_time = time.perf_counter() if response.status == 200: duration = (end_time - start_time) * 1000 return (url, duration) else: return (url, -1) except Exception: return (url, -1) async def main(loop): tasks = [] for url in urls: tasks.append(asyncio.ensure_future(fetch(url, loop))) await asyncio.gather(*tasks) results = map(lambda x: x.result(), tasks) for fetch_result in results: (url, result) = fetch_result color = "green" if result != -1 else "red" print(colored("{0:<40}".format(url[0]), color) + "{0:.2f}ms".format(result)) loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) First thing to test was whether it’s really asynchronous aka not creating any extra threads. Of course, it is. Otherwise I’m sure I wouldn’t be the first one to notice it. The “magic” keywords are same as in C# – async and await. The async marks method where the await will be used and await is where the magic happens. One thing to notice is the async with statement. The context manager needs to be able to suspend and resume the execution inside the with block. The plumbing is done with asyncio, i.e. in C# we have Task.WhenAll and here it is asyncio.gather (although there’s also asyncio.wait with bunch of options). What’s most interesting is the need to use event loop. In C# if you’re writing i.e. WinForms the concept of event loop (or message pumping in more low-level terms) is well known. But it’s not explicit and for example console applications don’t have such thing (even the abstraction – the SynchronizationContext – is null in console applications). Here, though my script is basically a console application, I had to specify it and specify it explicitly. From what I understood the event loop is where the calls and most importantly callbacks (and hence resumes) happen. I think about it as a scheduler and IO completion ports (in Windows terms). My understanding is, I’m sure, clear on high level, but the rubber meets the road when you dive deep. Although this was just a one or two afternoons playing with asyncio I enjoyed learning new stuff and applying it to what I already know. I wish I had more time to do this.
https://www.tabsoverspaces.com/233652-playing-with-asyncio-and-aiohttp-in-python-as-a-csharp-developer
CC-MAIN-2020-50
refinedweb
447
68.77
:45 - dynamic column in SUMPRODUCT formula I would like to change the last part of my formula to the more dynamic one so instead of putting letters (B, I, P, W etc.) I want my formula to sum every 7th column in range: ==SUMPRODUCT((LEFT(language!$A$3:$A$9773,8)>=TEXT($A$1,"yyyymmdd"))*(LEFT(language!$A$3:$A$9773,8)<TEXT($H$1,"yyyymmdd"))*language!$B$3:$B$9773) The first column that formula should sum up is B, the last column is DC. I've tried to use index formula but I receive #REF error: =SUMPRODUCT((LEFT(language!$A$3:$A$9773,8)>=TEXT($A$1,"yyyymmdd"))*(LEFT(language!$A$3:$A$9773,8)<TEXT($H$1,"yyyymmdd"))*INDEX(language!$B$3:$B$9773,0,7)) Best Regards, Adrian - Writing on different sheets, doesn't maintain entries on previous sheets I am writing a code (Python) where some processing is done on an entry in a column, then the result is written in the column next to it. The excel file has several sheets. But when I run it, it only updates the very last sheet and doesn't save the editing done in the previous sheets. My code is as following: from openpyxl import Workbook import xlrd FileName = "myFile.xlsx" workbook = xlrd.open_workbook(FileName) numSheets = workbook.nsheets for sheet in range(numSheets): worksheet = workbook.sheet_by_index(sheet) print ("sheet: " + str(sheet)) indexOfTargetColumn = -1 totalColumns = worksheet.ncols for y in range(0, totalColumns): if worksheet.cell(0,y).value == "Process this": indexOfTargetColumn = y break import xlwt from xlutils.copy import copy rb = xlrd.open_workbook(FileName) wb = copy(rb) w_sheet = wb.get_sheet(sheet) w_sheet.write(0, totalColumns, "Results") totalRows = worksheet.nrows if indexOfTargetColumn != -1: for i in range(1, totalRows): myTarget = worksheet.cell(i, indexOfTargetColumn).value #MY PROCESS w_sheet.write(i, totalColumns, myResult) wb.save("New Result File.xls") print ("End") - How to filter with Pivot table if I have two conditions that have to be true in the same time? I'd like to find out from a database, which voting districts have the most voters AND voted for opposition in the biggest proportion. So there are two conditions that I want to consider: 1. The voting districts have to be relatively big (let's say top 20%) 2. The district's votes have to be in majority opposition party votes (>50%) I don't know how to filter to make both statements true. - Excel VBA - Returning an array from function to main sub I'd like to store all tab names in a string array, that I'll later use for other things. My current problem is, that I'd like to populate my array in a separate function and when thats done, hand it back to my main sub. It throws Can't assign to array as an error, what am I'm not seeing here? Sub Captions_Formatting() Dim tabName() As String Dim totaltabs As Long Dim ws As Worksheet Dim captionlines As Integer totaltabs = get_Tabs tabName = getTabNames(ws, totaltabs) End Sub Function getTabNames(ws As Worksheet, totaltabs As Long) As String() Dim i As Integer ReDim tabName(totaltabs) For Each ws In Sheets If ws.Name <> "Overview" Then tabName(i) = ws.Name i = i + 1 End If Next ws getTabNames = tabName End Function Thanks a lot! - Macros take too much memory I have an Excel workbook with a bunch of macros in it. The Workbook has 4 worksheets, and each worksheet has different code implemented due to different restrictions based on each sheet has. Henceforth, when you close the workbook the size of it is around 80 MB. This is a problem as I cannot send the workbook via email due to its size. Is there any possibility to disable the macros so the size of the workbook to be reduce? What I mean is that I want the macros to still be in the workbook, but not to affect the size of it as they are not activate it. Only when I enable the macros, then the size to turn again to its 80 MB size. Maybe a button can be created that can disable the macros from the 4 worksheets and enable them when you press again? I am not sure how this can be approached or if there is a way to approach it, but any help would be must appreciated. Thanks in advance! - Start Do Until loop when a value in a column cell is found and end when empty column cell is found I have the following in my OptieRestricties tab in Excel: I have the following VBA code: Private Sub CommandButton_Click() Dim i As Long Dim p As Long Dim itemid As String Dim ifcond As String Dim thencond As String Excel.Worksheets("OptieRestricties").Select With ActiveSheet i = 2 Do Until IsEmpty(.Cells(i, 2)) p = 4 Do Until IsEmpty(.Cells(2, p)) ifcond = ActiveSheet.Cells(i, 2) thencond = ActiveSheet.Cells(i, 3) Item = ActiveSheet.Cells(i, p) If Not IsEmpty(Item) Then Debug.Print Item & " --- " & ifcond & " " & thencond End If p = p + 1 Loop i = i + 1 Loop End With End Sub The code returns the following result: Kraker_child --- [775](16).value=1 [775](12,13,14,15,17,18,19).visible=1 However, the code stops after the second row, which is logical since E2 is empty. How can the code be modified such that it returns the following?: Kraker_child --- [775](16).value=1 [775](12,13,14,15,17,18,19).visible=1 Kraker_child_1 --- [411](5).value=1 [411](10).readonly=1;[411](17).readonly=1 - Excel Date&Time vs value plot I am working on a dataset that has over 30,000 rows, and I need to create a time-value plot. My data consists of 4 columns item, date[YYYY-MM-DD], Time[00:00:00], and values. 15 names in total, and the values are recorded every 10 minutes for 14 days. If I want to create a graph that has 15 curves on it with date&time on the x-axis and value on the y-axis, how should I do it? I sorted the data with names, date, time, so I could do it manually by selecting the values and Date&time for each item which would be ridiculous. Would creating a Loop in Macro help and how to code it? or is there another way of doing it? -? - I want date after $ month from start and end date which enter by user I have two dates, start and end date, Now I want all middle dates, I have start date as 16-01-2018 and end date is 16-01-2020 and user select frequency like 6 months. So between start and end date interval of 6 months I want. Like start due end 16-01-2018 16-07-2018 16-01-2020 16-07-2018 16-01-2019 16-01-2020 16-01-2017 16-07-2019 16-01-2020 16-07-2019 16-01-2020 16-01-2020 I have developed some code like this; $freq = 6; for($i=1;$i<=$freq;$i++) { $due1 = date('Y-m-d',strtotime($start . "+$i months")); mysqli_query($con,"INSERT INTO amc_month(amc_id,freq,start,due,end,status,srno) VALUES('$amc_id','$freq','$start','$due1','$end','$status','$srno')")or die(mysqli_error($con)); } but this code save all date from today's date, but I want result like I explained. What I have to change in this? - MySQL Query to get date-wise data between start date and end date I have a MySQL table that contains 'startDate', 'endDate' and 'amount' to represent the amount required between start and end date. I want to get the date-wise records for all the days in a month. table: --------------------------------------- ID | STARTDATE | ENDDATE | AMOUNT | --------------------------------------- 1 | 2018-01-02 | 2018-01-04 | 1000 | 2 | 2018-01-03 | 2018-01-06 | 2000 | ...| ... | ... | ... | --------------------------------------- Required Result: ------------------------- Date | Total Amount ------------------------- 2018-01-01 | 0 2018-01-02 | 1000 2018-01-03 | 3000 2018-01-04 | 3000 2018-01-05 | 2000 2018-01-06 | 2000 2018-01-07 | 0 ... | ... ... | ... 2018-01-31 | 0 The result should generate a list of dates of the current month with respective Total Amounts. What should be the SQL query?
http://quabr.com/48249028/vba-excel-macro-for-a-button-that-selects-named-reference-from-a-named-range
CC-MAIN-2018-05
refinedweb
1,370
64.2
If command. We will now install kubernetes 1.4 on two Ubuntu 16.04 nodes. Preparing the machines Machines can be VM instances or physical servers. To prepare the machines, on all machines run: curl | apt-key add - This is key for new repository, and repository we add here cat <<EOF > /etc/apt/sources.list.d/kubernetes.list deb kubernetes-xenial main EOF And then we load the new repository list apt-get update To actually install, run following command: apt-get install -y docker.io kubelet kubeadm kubectl kubernetes-cni After running this on all nodes, we can proceed to making a cluster. Initializing the cluster After we installed everything needed, we need to pick one of the nodes to be a master. On master run: kubeadm init The command will work for several minutes and in the end will give you command you need to run on your node to connect it to this master. For example like this <master/tokens> generated token: "7fa96f.ddb39492a1894689" <master/pki> created keys and certificates in "/etc/kubernetes/pki" <util/kubeconfig> created "/etc/kubernetes/admin.conf" <util/kubeconfig> created "/etc/kubernetes/kubelet.conf" <master/apiclient> created API client configuration <master/apiclient> created API client, waiting for the control plane to become ready <master/apiclient> all control plane components are healthy after 23.051433 seconds <master/apiclient> waiting for at least one node to register and become ready <master/apiclient> first node is ready after 5.012029 seconds <master/discovery> created essential addon: kube-discovery, waiting for it to become ready <master/discovery> kube-discovery is ready after 13.005947 seconds <master/addons> created essential addon: kube-proxy <master/addons> created essential addon: kube-dns Kubernetes master initialised successfully! You can now join any number of machines by running the following on each node: kubeadm join --token 7fa96f.ddb39352a1894689 45.55.89.83 I have highlighted the kubeadm init command that is ran on master, and the kubeadm join command that it produces. Keep this later command secret, anyone having it could use it to connect his own nodes to your cluster. After your run the command kubeadm join to join the node to your master, you can run the following command on master to verify that all went well: kubectl get nodes But this doesn't yet mean you can already put the application to your cluster. There is couple more things you need to do. First is installing pod network on your master so that pods can communicate with each other: kubectl apply -f And second, to be able to have pods run on master as well as on nodes, use this command: kubectl taint nodes --all dedicated- That is useful if you have small number of machines running kubernetes, on this tutorial we have two, one master and one node. On bigger clusters, you might leave out that command as it is better security choice to have your master not run any pods. Deploying a test application First application we are going to try is micro-services example from kubectl manual. Lets start by cloning the application with git git clone Next we use kubectl command to deploy the application: kubectl apply -f microservices-demo/deploy/kubernetes/manifests This will take some time as there are quite a few containers to be created. You see the progress by typing kubectl get pods If there are pods which say ContainterCreating or anything other that Running, it means you need to wait some more, maybe get a sandwich or coffee. When all containers say Running, we can move to next command. Which is: kubectl describe svc front-end This will give you data about front end service (svc or service), and we need that data to be to acess the site from outside world. Name: front-end Namespace: default Labels: name=front-end Selector: name=front-end Type: NodePort IP: 100.77.43.252 Port: <unset> 80/TCP NodePort: <unset> 31939/TCP Endpoints: 10.40.0.5:8079 Session Affinity: None Or better with image: Most important here are Type:NodePort line and NodePort: <unset> 31939/TCP. LoadBalancer is not yet supported with kubeadm, so we use NodePort and it exposes the service to ouside world on some port on the ip of the master. So you take your master ip and add it port number from NodPort: line of above command, which is in this case 31939. So when you type that in your browser, you get our sample site with socks It is our example microservices application. If you want to delete sock application, run following command kubectl delete -f microservices-demo/deploy/kubernetes/manifests From here you can try some more examples for kubernetes Trying new commands in Kubernetes 1.4 The kubeadm was not only change in Kubernetes 1.4. Far from it. The kubectl also got an update. For example the kubectl hel command got more clear, and well... more helpful. Lets see what is says: Basic Commands scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController Cluster Management Commands:). Thre is new -n flag which enables you to issue commands to only one virtual cluster, or so called namespace. So this command: kubectl get nodes -n kube-system Will get you the pods belonging to kube-system namespace. kubectl get pods -n kube-system NAME READY STATUS RESTARTS AGE etcd-ubuntu-linoxide02 1/1 Running 0 4h kube-apiserver-ubuntu-linoxide02 1/1 Running 0 4h kube-controller-manager-ubuntu-linoxide02 1/1 Running 0 4h kube-discovery-982812725-dxj6r 1/1 Running 0 4h kube-dns-2247936740-n44pu 3/3 Running 0 4h kube-proxy-amd64-oe87p 1/1 Running 0 4h kube-proxy-amd64-tuzwv 1/1 Running 0 4h kube-scheduler-ubuntu-linoxide02 1/1 Running 0 4h weave-net-as39l 2/2 Running 0 4h weave-net-fc0v5 2/2 Running 0 4h There is also new kubectl top command which enables you to get cpu and memory usage in pods, but for that command you need to install heapster. Conclusion We ran trough basic scenario of installing Kubernetes with the new kubeadm utility. The kubeadm is still new and it is not feature complete, but it shows lots of promise. It greatly simplifies the creation of clusters and adding nodes on the fly. The Kubernetes developers have committed to make kubeadm feature complete, which means adding LoadBalancer support as well as other missing features. Until then, we can either use kubeadm without load balancer or if we need load balancer, we would have to do manual cluster configuration without kubeadm. This was all for this article, thank you for reading. Have anything to say?
https://linoxide.com/devops/setup-kubernetes-1-4-kubeadm-ubuntu/
CC-MAIN-2018-05
refinedweb
1,125
59.03
ImmutablePass class - This class is used to provide information that does not need to be run. More... #include "llvm/Pass.h" ImmutablePass class - This class is used to provide information that does not need to be run. This is useful for things like target information and "basic" versions of AnalysisGroups. Definition at line 255 of file Pass.h. Referenced by llvm::Pass::dump(). Reimplemented from llvm::Pass. Definition at line 269 of file Pass.h.<>. Reimplemented in llvm::CFLSteensAAWrapperPass, and llvm::CFLAndersAAWrapperPass. Definition at line 145 of file Pass.cpp. Referenced by llvm::PMTopLevelManager::addImmutablePass(). ImmutablePasses are never run. Implements llvm::ModulePass. Definition at line 272 of file Pass.h.
https://llvm.org/doxygen/classllvm_1_1ImmutablePass.html
CC-MAIN-2019-47
refinedweb
110
54.9
Using NetBeans IDE 6.0 and the Visual Web tools, you can write applications that connect to database tables using the Java Persistence API (JPA) in addition to the Visual Web JSF data provider components. After you establish the connection to the database table, you can use the Java Persistence API to perform database CRUD operations (that is, create, read, update, and delete operations). The ability to use the Java Persistence API gives you greater flexibility when developing a database-dependent application. This article (the first of two articles) takes you through the set-up steps for using the Java Persistence API from a Visual Web application. You will learn how to use the API to connect or bind to a database table, which gives you access to the data in the table. In the second article ("Modifying Database Table Rows with the Java Persistence API"), you will see how to use the API to add, update, and delete database table rows. In addition, the article includes tips for getting the most from the NetBeans IDE and its visual web article, the first in the series, starts by showing you how to directly bind a NetBeans IDE Visual Web Table Component to an array or list of Objects (also referred to as POJOs or Plain Old Java Objects). Those of you who are familiar with accessing database tables with the Visual Web tools have used the data provider components. You may have dropped a Table component from the Palette onto a page and then dropped a database table onto that Table component. When you dropped the database table onto the page, the Visual Web tools created a data provider component for you, and this data provider handled the database table binding and data access. Now you are going to bind the same Visual Web Table component to a database table without the data provider support; instead, you do the binding using the Java Persistence API. Using JPA, you can obtain the database table data as a list or array of entity beans (POJOs) and directly bind that array to a Visual Web Table component without the intermediate step of using an ObjectListDataProvider or ObjectArrayDataProvider. You can then use the Visual Web Table component features to manipulate the data. In addition to covering using Java Persistence API, we also showcase some of the features of the NetBeans IDE. You'll see how to use the IDE to: The subsequent articles will showcase using specific Visual Web components, such as the Grid Panel component to control page layout.. To find out more about the Java Persistence API, see the article "The Java Persistence API - A Simpler Programming Model for Entity Persistence" . For an in-depth guide to the Java Persistence API, see the article "Using the Persistence API in Desktop Applications". The step-by-step instructions that follow assume that you have set up a database called sample that includes a database table called Users. The Users table should have four columns, as follows: sample Users Users user_id userName You can add the Users table to the sample Derby database using the Databases node in the Services window. You can execute an SQL script from a file to create this table or execute each line of SQL code individually. The context menu functions for the database table nodes in the Services window (formerly called the Runtime window) include functions to create new tables and execute SQL code. The Execute Command function opens an Editor window to which you can enter one or more lines of SQL code. Execute the contents of the window by clicking the Run button. Be sure that the Connection field indicates you are connected to the sample database.. create table "APP"."USERS" ( userName VARCHAR(50), password VARCHAR(12), email_address VARCHAR (50), user_id INTEGER GENERATED always AS IDENTITY); alter table Users add constraint usersPK PRIMARY KEY (user_id); INSERT INTO Users VALUES ('Joe', 'joepw', 'joe@email.com',DEFAULT); INSERT INTO Users VALUES ('Sarah', 'mypassword', 'sarah@sun.com', DEFAULT); INSERT INTO Users VALUES ('Jane Doe', 'janie', 'jane@hotmail.com', DEFAULT);. com.samples.model textmodelapp.Main com.samples.model.Main Create the Visual Web project. From the New Project dialog, select Web as the category and Web Application as the project, then click Next. In the New Web Application dialog, set the project name to TestWebApp. The project location should default to the same location as the TestModelApp project. Click Next to go to the screen where you select the framework.: TestModelApp.jar In the Project Properties dialog, click the Libraries node in the Categories section on the left. Then, click Add Project. [app on APP] node and choose Connect. If you are using a different DBMS, then, if needed, set up a driver for that database and create a new connection, providing the necessary connection parameters. (If you keep the database name as sample it will be easier to follow the rest of this walk-through.) If you have not yet created the Users table, now is the time to do so. See Creating a Database Table. Create an entity class representing the Users table. As noted previously, the entity class is the Java Persistence representation of the database table definition. JPA uses Java language annotation feature to mark POJOs as JPA entities with information on object-relation mapping. Create the entity class from within the TestModelApp project using the Entity Classes from Database function.. The Entity Classes dialog displays. The IDE displays the database table name Users, and suggests a class name of Users. (Double click this class name to change it.) It is a good idea to verify that the persistence unit is created correctly. To do so, expand the TestModelApp Source Packages > META-INF node and double click.. After you create. @Id Since the Derby database supports the IDENTITY column type and thus can generate a unique value for the primary key, we pass that responsibility to the database. Thus, add the following line of code to the primary key definition: @GeneratedValue(strategy = GenerationType.IDENTITY). @GeneratedValue(strategy = GenerationType.IDENTITY) The Users.java code defining the table should look as follows after you make your modifications: public class Users implements Serializable { @Column(name = "USERNAME") private String username; @Column(name = "PASSWORD") private String password; @Column(name = "EMAIL_ADDRESS") private String emailAddress; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "USER_ID", nullable = false) private Integer userId; ... Note that the @GeneratedValue tag requires two classes: javax.persistence.GeneratedValue and javax.persistence.GenerationType. Use the Fix Imports function to import these classes. Right click anywhere in the source editor window and select Fix Imports from the pop-up menu.. You continue to work in the TestModelApp project, creating a new class called UserController in the com.samples.model package. (We provide the code for this class below, and you can paste it into your class.) Expand the TestModelApp > Source Packages > com.samples.model node. Notice that there are already two classes in the package: Main.java and Users.java. Right click the com.samples.model node and select New > Java Class. In the New Java Class dialog, set the class name to UserController (leave the location as Source Packages and the package name as com.samples.model). You should see the skeleton source code for this new class in the Edit window. Add the following code to the class:; import javax.persistence.EntityManagerFactory;. getUsers createQuery javax.persistence.EntityManager: Let's examine these steps in more detail. users private Users[] users; import com.samples.model.Users; Generate get and set methods for the users property. Right click the line of code you typed in and select the action Insert Code. Choose Getter and Setter from the popup menu. Then, select users: Users[]. users: Users[] The Insert Code action adds public get and set methods. When finished, SessionBean1 should include the following code. private Users[] users; public Users[] getUsers() { return users; } public void setUsers(Users[] users) { this.users = users; } updateUsers public void updateUsers(){ UserController usersController = new UserController(); users = usersController.getUsers(); } init updateUsers(); public void init(){ super.init(); try { _init(); } catch (Exception e) { log("SessionBean1 Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e: new FacesException(e); } updateUsers(); } Now you are ready to bind the users property you just added to a Table component. Drag a Table component from the Palette and drop it on the page in the Design window. It should as follows: Right click the Table component on the page and click Bind to Data from its context menu.. The Table component display in the Design window should change to the following. If needed, adjust the columns to be displayed. This article article article ("Modifying Database Table Rows with the Java Persistence API") shows how to use the API to add, update, and delete database table rows. Plus, it includes tips for getting the most from the NetBeans IDE and its visual web functions. Bookmark this page
http://www.netbeans.org/kb/60/web/web-jpa.html
crawl-001
refinedweb
1,482
55.74
0 for example if i wanted to add a list to another list, like: a = [a,b,c] b = [1,2,3] my code: def add(a, b): a = a.append(b) it would output ] what do i have to change to make it output without using the .extend() method? --- how can i create a function that can split a list into two lists with like equal elements in each list, which in the end both lists together would have all the elements in the original list? like: original = [1,2,3,4,5,6] it would output something like [1,2,3] [4,5,6] def half(l): a = [] b = [] for i in range(len(l)/2): a = a + l[i] for i in range(len(l)/2 - 1): b = b+ l[i] return a, b I know it's something wrong with my for loops, the range? --- Also just wondering is there any way to sort a list without using the .sort method? like [1,2,4,3,2] will output [1,2,2,3,4] Thanks for any hints/help.
https://www.daniweb.com/programming/software-development/threads/240173/wondering-some-things-about-lists
CC-MAIN-2017-39
refinedweb
183
71.78
proper-d 0.0.2 A simple library for reading simple property files. To use this package, run the following command in your project's root directory: Manual usage Put the following dependency into your project's dependences section: Proper-D Proper-D is a simple library of functions for interacting with property files (i.e. files that contain simple name value pairs). This is similar in nature to the functionality offered by the java.util.Properties class in Java but with a D twist. The library effectively provides a very basic file format for use as things like of configuration files. Building The library uses the dub package manager so you will need to install that. To build the unit tests for the library clone the repository and, from the root directory of the repository copy, run this command... dub build --build=unittest Once this successfully completes there should be an executable created in the same directory called proper-d.exe on Windows or proper-d on Linux. Run this executable to execute the unit tests. In terms of using the library the simplist thing to do is to copy the main source file (source/proper-d.d) into your project. It has no dependencies beyond elements of the D standard library. Usage In Java the Properties class completely wraps the functionality for handling property files but D provides associative arrays which would obviate the need for a complete class. With this in mind the Proper-D code is worked around creating associative arrays of strings indexed by strings. To make use of Proper-D include the source file in your project and then import it into the code to use it with a line such as... import properd; Next you can either load a file of properties or provide a string that can be parsed into an associative array. Some examples follow... // Load the ./examples.cfg file as a property file. auto properties = readProperties("./examples.cfg"); // Same as before but specified via a File object. properties = readProperties(new File("./examples.cfg", "r")); // Parse a string of text into a property list. properties = parseProperties("first = One\nsecond = 2\nThird = 3.14"); All of the function calls shown above return associative arrays of type string indexed by string (i.e. `string[string]`). No interpretation of the data is made but the library does provide an as() function that will attempt to convert the values from an associative array to a specific type. The following is an example of using this function... auto value1 = properties.as!(int)("second"); Here an attempt is made to convert the value indexed under the key "second" in the associative array `properties to an int`. If this fails then an exception will be raised. A specialization of this template function is provided for conversion of values to the bool type. This specialization will recognise "true", "1", "on" and "yes" (test is case insensitive) as being a boolean value of true. Anything else is false. License Consult the license.txt file for licensing information. - Registered by Peter Wood - 0.0.2 released 6 years ago - free-beer/proper-d - github.com/free-beer/proper-d - MIT - Authors: - - Dependencies: - none - Versions: - Show all 5 versions - Download Stats: 0 downloads today 0 downloads this week 19 downloads this month 18583 downloads total - Score: - 1.1 - Short URL: - proper-d.dub.pm
https://code.dlang.org/packages/proper-d
CC-MAIN-2022-21
refinedweb
562
58.48
Hi, How can we delete the objects initialised by the pointers automatically in a program without delete[]/delete keyword. Like for example java explicitly runs the garbage collector. Can we do that same way somehow?? thank you. Hi, How can we delete the objects initialised by the pointers automatically in a program without delete[]/delete keyword. Like for example java explicitly runs the garbage collector. Can we do that same way somehow?? thank you. "If knowledge can create problems, it is not through ignorance that we can solve them. " -Isaac Asimov(1920-1992) No, in C/C++ you don't have a garbage collector. In these languages you have to do most of the stuff by yourself. That's why they're so powerful (and not very good for begginers). Although I think there is some third-party code you can add to your app to make a sort of garbage collector, they're very slow. Wouldn't recommend it. Besides, it's a good practice to tidy up after you, even in programming. Use something from the standard library like an auto_ptr... Code:#include <memory> //for auto_ptr #include <iostream> using namespace std; template <class T> ostream& operator<< (ostream& strm, const auto_ptr<T>& p) { if (p.get() == NULL) strm<<"NULL"; else strm<<*p; return strm; } int main(void) { int x; auto_ptr<int> aPtr(new int); //create an auto_ptr object and allocate mem *aPtr=1; cout<<aPtr<<endl; //only works with overloaded << operator auto_ptr<int> aPtr2(aPtr); //now aPtr2 is equal to aPtr cout<<aPtr<<endl; //ERROR now aPtr is deleted cout<<aPtr2; //the end cin>>x; //just a quickie pause } "Think not but that I know these things; or think I know them not: not therefore am I short Of knowing what I ought." -John Milton, Paradise Regained (1671) "Work hard and it might happen." -XSquared MSVC++ .NET has a garbage collector. I haven't had any problems with using it although typically I like to clean up after myself anyway. Height, width, and for a limited time only... Depth! -sb Are you talking about managed or unmanaged code? Because if your talking straight C++ there is no garbage collector.Are you talking about managed or unmanaged code? Because if your talking straight C++ there is no garbage collector.MSVC++ .NET has a garbage collector. Here is a simple garbage collector example I wrote on the C board. Unfortunately, it hasn't been compiled, so you're on your own debugging-wise. But the basic concept is simple: 1) store the address of the pointer. 2) store the data that the said pointer points to. ie: char * ptr = new char[10240]; (1) char ** pa = &ptr; (2) char * p = ptr; So that: if(*pa != p) delete [] p; Of course you'll need a list or vector of these memory managers. Also, you can set up the garbage collection in a low-priority thread, but in most cases, there's no real justification to do so. Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
http://cboard.cprogramming.com/cplusplus-programming/43443-objects.html
CC-MAIN-2016-30
refinedweb
530
66.23
In this tutorial we will check how read content from the serial port, using the micro:bit board. We will use the micro:bit pins as serial Tx and Rx pins, like we have already covered in this previous tutorial. Introduction In this tutorial we will check how read content from the serial port, using the micro:bit board. We will use the micro:bit pins as serial Tx and Rx pins, like we have already covered in this previous tutorial. In order to test the communication, we are going to connect the micro:bit pins to a USB to serial converter, so we can use a computer and some serial software to send data to the board. Naturally, this is a procedure we are going to do for testing since, if our aim was simply to exchange data with a computer, we could directly use the uPython prompt, which operates over USB. Nonetheless, the true objective of analyzing how to establish serial connections using the micro:bit pins is opening the possibility of connecting the board to other devices that talk over serial. The electric diagram of the connection between the micro:bit and the serial to USB converter can be checked here. For this tutorial I’m using version 1.7.0 of uPython for the Micro:bit board. The code We will start our code by importing the uart object and the sleep function, both from the microbit module. from microbit import uart, sleep Then we will initialize the serial interface, using as Rx and Tx the micro:bit external pins 1 and 0, respectively. We will use a baud rate of 9600. Recall from the previous tutorial that, after we do this initialization, the uPython prompt will become unavailable. uart.init(baudrate=9600, tx = pin0, rx = pin1) Now, we can check if there are bytes available to read from the serial port. If there are none, we keep waiting until we can read some content. To check if there are bytes available in the serial port, we can simply call the any method on our uart object. This method call takes no arguments and returns a Boolean value indicating if there are bytes available. So, we will use the result of this method call as stopping condition of a loop that will execute until there are bytes to read. Since we don’t need to do anything inside our loop, we will use the pass statement, which basically corresponds to a null operation that can be used when the Python syntax requires an expression [1], which is the case of the body of a loop. while not uart.any(): pass After the loop finishes, we know that we should have content to read on the serial interface. So, after a small delay introduced with the sleep function, we will try to read all the bytes available with a call to the readall method on the uart object. This method takes no arguments and will try to read and return as much data as possible [2]. Note however that this is a non-blocking function that should return after a timeout, which means that if we try to send some content first and then more content later, the last content may not be obtained as result of this function call. We will store the content returned by the readall method call in a variable. sleep(400) content = uart.readall() As mentioned before, the uPython prompt will become unavailable as soon as we set the serial interface to work with the external pins of the micro:bit. Thus, after reading the content, we will bring the prompt back by re-initializing the serial interface, passing only as argument of the init method a baud rate of 115200. uart.init(baudrate=115200) To finalize, we will print the content obtained from the serial port. print(content) The final code can be seen below. from microbit import uart, sleep uart.init(baudrate=9600, tx = pin0, rx = pin1) while not uart.any(): pass sleep(400) content = uart.readall() uart.init(baudrate=115200) print(content) Testing the code To test the code, simply upload the previous uPython script to your micro:bit, using a tool of your choice. I’ll be using uPyCraft, a uPython IDE. Then, on your computer, open a serial tool of your choice. I’ll be using the Arduino IDE serial monitor. Then, establish a connection to the micro:bit using the COM port assigned to your Serial to USB converter. If you don’t know beforehand what is the COM port assigned to your device, a simple trick when using the Arduino IDE is disconnecting the device, checking the list of available COM ports, re-connecting the device and checking the new one that is added. After that, select a baud rate qual to 9600 (the one used when initializing the serial interface in the uPython code) and send some content. I will be sending a “TEST” string. If you go back to the uPython tool you are using, the prompt should now be available and the content you sent from the serial tool should have been printed, like illustrated in figure 1. Figure 1 – Receiving data from the serial port. Related posts - Micro:bit uPython: using external pins for serial communication - Micro:bit uPython: Pausing the program execution References [1] [2] 3 Replies to “Micro:bit uPython: Receiving data from serial port”
https://techtutorialsx.com/2018/11/11/microbit-upython-receiving-data-from-serial-port/
CC-MAIN-2020-16
refinedweb
906
60.55
A" For instance, the fmt package is used to format data either to an input or output. The word fmt is actually a shorthand for format. import "fmt" An example of this package in action is highlighted below: package main import "fmt" func main() { fmt.Println("Hello World") } Third-party packages are packages that are not originally designed by the creators of the Go programming language. These packages extend some functionality beneficial to developers. They are made by developers for developers. Third-party packages must be installed before being imported for use. It is usually installed using the keyword below: go get <link_of_package> The keyword go get is used to install binary tools and then create a dependency in the project which can be tracked via the go.sum file. Recent changes were made in Go version 1.16. One of such changes includes installing binary tools via the go get command which is deprecated. The go install command is the recommended method. More information can be found here. A custom-built Go package is a package tailored to provide a specific solution and in accordance with the developer’s long-term goals. The utilization of a custom-built package can be done with the import statement. import "insert_path_of_package_here" The path of the package can only be used when the custom package is already available as a directory within the current project. Otherwise, an installation has to be done before it can be imported for use. This tutorial aims at creating a Go package that helps developers easily implement the stack and queue methods in their projects. The first step involves creating a new directory named stacky. In your terminal, type cd into this directory and enable the use of Go modules by using the command: go mod init <name of package> It is common practice to prepend your directory name with a link to your GitHub. Therefore, we’ll initialize go mod in the following manner: go mod init github.com/yemmyharry/stacky A file ending with the .go extension will be created using the touch command. touch stacky.go In the .go file created, all the structs needed to successfully implement the methods of stacks and queues were added. //name of package package stacky // Stack struct with a field of a slice of items type Stack struct { items []int } // Queue struct with a field of a slice of items type Queue struct { items []int } //Push method adds to the top of the stack func (s *Stack) Push(i int) { s.items=append(s.items,i) } // Pop method removes from the top element in the stack and returns the removed item func (s *Stack) Pop() int { removable:=s.items[len(s.items)-1] s.items=s.items[:len(s.items)-1] return removable } // Peek method queries what the top element of the stack is func (s *Stack) Peek() int { removable:=s.items[len(s.items)-1] return removable } //IsEmpty method queries whether the stack is currently empty func (s *Stack) IsEmpty() bool { if len(s.items)==0 { return true } return false } //Enqueue method adds an item to the queue func (q *Queue) Enqueue(i int) { q.items=append(q.items, i) } //Dequeue method removes an item from the queue func (q *Queue) Dequeue() { q.items= q.items[1:] } In Line 2 of the code snippet above the package is named stacky because it is conventional to name a package after it’s directory name. Lines 5 and 9 are structs of the stack and queue respectively. The remaining lines of code are methods of the stack and queue. Congratulations, you successfully created a Go package. You can use your Go package locally by simply calling it in another .go file or in another Go package. To make it public and available for developers, you need to create a git repository and push the code to it. Anyone interested in using the package can simply copy the url and then install it as a dependency in their program by using: go get github.com/yemmyharry/stacky Then importing into the desired Go file : import ( "github.com/yemmyharry/stacky" ) To demonstrate this, let’s create a directory named “example”. Then initialize it to get our go.mod file before installing the stacky package using the go get command defined above. package main import ( "fmt" stacks "github.com/yemmyharry/stacky" ) func main() { //myStack is a variable of an empty stack myStack := stacks.Stack{} //the push method adds to the empty stack myStack.Push(10) myStack.Push(20) myStack.Push(30) //prints out the current state of myStack fmt.Println(myStack) //views the top of the stack fmt.Println(myStack.Peek()) // removes an item from the stack fmt.Println(myStack.Pop()) //views the new top of the stack fmt.Println(myStack.Peek()) //prints out the current state of myStack fmt.Println(myStack) //checks if the stack is empty fmt.Println(myStack.IsEmpty()) //myQueue is a variable of an empty queue myQueue := stacks.Queue{} //enqueue method adds to the queue myQueue.Enqueue(12) myQueue.Enqueue(20) myQueue.Enqueue(50) //prints out the current state of myQueue fmt.Println(myQueue) // removes an item from the queue myQueue.Dequeue() //prints out the new state of myStack fmt.Println(myQueue) } RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/how-to-create-and-utilize-packages-in-go
CC-MAIN-2022-33
refinedweb
879
66.03
A few days ago I answered this interesting question by Florian Kube in the Questions & Answers area. It struck me that the solution might be of more general interest, so in this blog I’m going to expand a bit on my answer. Florian’s scenario is this: He picks up an email with a sender Mail channel. The email has an XML attachment, and it is the contents of this attachment, he wants to process. He therefore needs to replace the message body with the attached XML document, and then proceed with mapping and so forth. I’m going to show you how to solve this problem using scripting. The code is written in Groovy, but if your prefer JavaScript, translating it is straightforward. Methods of the Message class Access to the body and attachments of a message is provided by the com.sap.gateway.ip.core.customdev.util.Message object, which the runtime passes to your Groovy function. There is no API documentation available for this class, but most of its methods are listed in the HCI Developer’s Guide. The two methods, we are going to use, are getAttachments and setBody. The former returns a java.util.Map object containing the message’s attachments, and the latter sets a new message body. Extracting the attachment contents Let us deal with the attachment first, since that is the more complicated part. The keys of the Map returned by getAttachments are attachment names, and the values are javax.activation.DataHandler objects. The DataHandler objects contain the actual attachment data. Given the scenario, we assume that the Map contains exactly one attachment, but we do not know its key ahead of time. In order to get the Map’s only value without knowing its associated key, I retrieve the Collection of all the Map’s values and iterate it once. The code looks like this (required import statements not shown): Map<String, DataHandler> attachments = message.getAttachments() Iterator<DataHandler> it = attachments.values().iterator() DataHandler attachment = it.next() (You could combine the three lines into a single line, if you are so inclined, but that would make the intention of the code less clear, IMHO.) Setting the message body The DataHandler class offers a couple of different ways to get at the wrapped data. We are going to use the getContent method, which returns a java.lang.Object object. Why? Because an Object instance is what the setBody method of the Message class expects. Here is the code that replaces the message body: message.setBody(attachment.getContent()) Putting the pieces together We are now ready to put it all together. Here is the complete script: import com.sap.gateway.ip.core.customdev.util.Message import java.util.Map import java.util.Iterator import javax.activation.DataHandler def Message processData(Message message) { Map<String, DataHandler> attachments = message.getAttachments() Iterator<DataHandler> it = attachments.values().iterator() DataHandler attachment = it.next() message.setBody(attachment.getContent()) return message } In order to use it, put the code in a Script step at the very beginning of your integration flow. After this step, proceed with whatever processing your scenario requires. How to handle messages with no attachments Keep in mind that the script assumes that the message has exactly one attachment. If it does not have any attachments, the code will fail. Determining why it fails, is left as an exercise for the reader 🙂 If this assumption is not always met in your particular scenario, you can test for the presence of attachments, by checking whether the Map returned by getAttachments is empty. You do this by calling its isEmpty method as follows: import com.sap.gateway.ip.core.customdev.util.Message import java.util.Map import java.util.Iterator import javax.activation.DataHandler def Message processData(Message message) { Map<String, DataHandler> attachments = message.getAttachments() if (attachments.isEmpty()) { // Handling of missing attachment goes here } else { Iterator<DataHandler> it = attachments.values().iterator() DataHandler attachment = it.next() message.setBody(attachment.getContent()) } return message }
https://blogs.sap.com/2017/02/19/replacing-the-message-body-with-an-attachment/
CC-MAIN-2017-13
refinedweb
662
50.63
Omega2-Powered Robot (with Pictures!) - Leif Bloomquist Here are a couple of pictures of my Omega 2 powered robot. I'm using the PWM Expansion on the Power Dock, and it's working not too badly. On the proto board is basically this circuit, one for each motor and using the PWM signal output instead. I had to switch the 270 ohm resistor for a 100 ohm resistor before the motors would move...not sure why? I also had trouble with stability at first. The Omega kept locking up/crashing and wouldn't come back after a few power cycles. Other times it would work perfectly. I ended up adding 4xAA batteries feeding the PWM Expansion through the barrel connector and that seems to have helped (fingers crossed). Note that the PWM controller keeps its last known setting if the Omega2 crashes/reboots, so I had a runaway robot a few times. Still tinkering, but I thought I would share with all of you. Right now I'm just using pwm-exp from the command line to control the motors, working on a Python script to run sequences and/or listen for UDP packets to control it with. Quick code... from OmegaExpansion import pwmExp import time def Stop(): "This stops the robot" pwmExp.setupDriver(-1, 0, 0) print "Stopped." return def Forward( speed, seconds ): "This moves the robot forward" pwmExp.setupDriver(7, speed, 0) pwmExp.setupDriver(8, speed, 0) print "Moving forward at " + str(speed) + "% for " + str(seconds) + " seconds." time.sleep(seconds) Stop() return def Left( speed, seconds ): "This turns the robot left" pwmExp.setupDriver(7, 0, 0) pwmExp.setupDriver(8, speed, 0) print "Turning left at " + str(speed) + "% for " + str(seconds) + " seconds." time.sleep(seconds) Stop() return def Right( speed, seconds ): "This turns the robot right" pwmExp.setupDriver(7, speed, 0) pwmExp.setupDriver(8, 0, 0) print "Turning right at " + str(speed) + "% for " + str(seconds) + " seconds." time.sleep(seconds) Stop() return pwmExp.driverInit() Stop() Forward(100, 2.5) Left(50, 2) Right(50, 2) i added remote control from a C# application and LEAP Motion (!) via UDP. Code is here if anyone's interested: - Josh Berry Awesome! How are you using the LEAP sensor? Do you have any videos? @Josh-Berry said in Omega2-Powered Robot (with Pictures!): Awesome! How are you using the LEAP sensor? Do you have any videos? I use the LEAP to detect hand position and turn it into motion commands. The robot follows your hand movements. I'll post a video "soon" ;-) - Douglas Kryder @Leif-Bloomquist thanks for the project write-up. it looks very simple yet effective. i also have a leap motion device and would love to put it to use as it has been in a box for over a year now. looking to read the code you have this weekend. good luck on continuing with the vehicle. looks fun. may have to do something similar with a omega on a arduino dock.
http://community.onion.io/topic/2136/omega2-powered-robot-with-pictures/4
CC-MAIN-2018-22
refinedweb
492
77.33
ImportError: No module named RealDistribution I'm fairly new to sage, so this may be a dumb question. On the web interface the following code T=RealDistribution('gaussian',.5) runs without issue, however on my local machine, sage throws a not defined error NameError: name 'RealDistribution' is not defined I found this strange because it worked fine on the web interface and is almost a line strait from the manual, but I thought that maybe just something wasn't importing or something like that, so I tried the following import statements, but to no avail. import sage.all import sage.gsl.probability_distribution.RealDistribution My questions are: why does it work on the online sagemath but not on my local machine, and what can I do to make it work? This should work without problem (i just tested it). How did you launch Sage on your local machine ? Which version ? Which OS ? I had the code saved in a file and then ran the file with For sage version, I have the current one off of the apt repos, which appears to be 6.7. My OS is a 64-bit Linux Mint 17. Do you want to use the Sage notebook or the command line ? Command line. I didn't think about doing it in notebook, and so I just went and tested that and it worked, but running it from the command line would be preferable. OK, i edited my answer accordingly, please tell us if it worked.
https://ask.sagemath.org/question/28590/importerror-no-module-named-realdistribution/?answer=28595
CC-MAIN-2019-39
refinedweb
249
68.3
How do I check if an object has a property x = {'key': 1}; if ( x.hasOwnProperty('key') ) { //Do this } I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results. It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.) If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect. Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution: var obj = { a: undefined, b: null, c: false }; // a, b, c all found for ( var prop in obj ) { document.writeln( "Object1: " + prop ); } function Class(){ this.a = undefined; this.b = null; this.c = false; } Class.prototype = { a: undefined, b: true, c: true, d: true, e: true }; var obj2 = new Class(); // a, b, c, d, e found for ( var prop in obj2 ) { document.writeln( "Object2: " + prop ); } function hasOwnProperty(obj, prop) { var proto = obj.__proto__ || obj.constructor.prototype; return (prop in obj) && (!(prop in proto) || proto[prop] !== obj[prop]); } if ( Object.prototype.hasOwnProperty ) { var hasOwnProperty = function(obj, prop) { return obj.hasOwnProperty(prop); } } // a, b, c found in modern browsers // b, c found in Safari 2.0.1 and older for ( var prop in obj2 ) { if ( hasOwnProperty(obj2, prop) ) { document.writeln( "Object2 w/ hasOwn: " + prop ); } } The above is a working, cross-browser, solution to hasOwnProperty, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
https://codedump.io/share/Ka7Y6J6YQxhZ/1/how-do-i-check-if-an-object-has-a-property-in-javascript
CC-MAIN-2017-09
refinedweb
403
66.03
Lesson 2. Write Functions in Python Learning Objectives - Describe the components needed to define a function in Python. - Write and execute a custom function in Python. How to Define Functions in Python There are several components needed to define a function in Python, including the def keyword, function name, parameters (inputs), and the return statement, which specifies the output of the function. def function_name(parameter): some code here return output def Keyword and Function Name In Python, function definitions begin with the keyword def to indicate the start of a definition for a new function. This keyword is followed by the function name. def function_name(): The function name is the name that you use when you want to call the function (e.g. print()). Function names should follow PEP 8 recommendations for function names and should be concise but descriptive of what the function does. Input Parameter(s) The input parameter is the required information that you pass to the function for it to run successfully. The function will take the value or object provided as the input parameter and use it to perform some task. In Python, the required parameters are provided within parenthesis (), as shown below. def function_name(parameter): You can define an input parameter for a function using a placeholder variable, such as data, which represents the value or object that will be acted upon in the function. def function_name(data): When the function is called, a user can provide any value for data that the function can take as input (e.g. single value variable, list, numpy array, pandas dataframe column). If you are defining a function for a specific object type, you can consider using a more specific placeholder variable, such as arr for a numpy array. def function_name(arr): Note that functions in Python can be defined with multiple input parameters as needed: def function_name(arr_1, arr_2): Return Statement In Python, function definitions need a return statement to specify the output that will be returned by the function. def function_name(data): some code here return output Just like with loops and conditional statements, the code lines executed by the function, including the return statement, are provided on new lines after a colon : and are indented once to indicate that they are part of the function. The return statement can return one or more values or objects and can follow multiple lines of code as needed to complete the task (i.e. code to create the output that will be returned by the function). Docstring In Python, functions should also contain a docstring, or a multi-line documentation comment, that provides details about the function, including the specifics of the input parameters and the returns (e.g. type of objects, additional description) and any other important documentation about how to use the function. def function_name(data): """Docstrings should include a description of the function here as well as identify the parameters (inputs) that the function can take and the return (output) provided by the function, as shown below. Parameters ---------- input : type Description of input. Returns ------ output : type Description of output. """ some code here return output Note that a docstring is not required for the function to work in Python. However, good documentation will save you time in the future when you need to use this code again, and it also helps others understand how they can use your function. You can learn more about docstrings in the PEP 257 guidelines focused on docstrings. This textbook uses the docstring standard that is outlined in the numpy documentation. Write a Function in Python Imagine that you want define a function that will convert values from millimeters to inches (1 inch = 25.4 millimeters). To define the function, you can work through each component below to build each piece and bring them together. def Keyword and Function Name Function names should be concise but descriptive, so an appropriate function name could be mm_to_in. Recall that the function name is provided after the def keyword, as shown below. def mm_to_in(): Input Parameter To decide on an appropriate placeholder name for the input parameter, it is helpful to think about what inputs the function code needs in order to execute successfully. You need a placeholder variable that represents the original value in millimeters, so an appropriate placeholder could simply be mm. def mm_to_in(mm): Return Statement You know that 1 inch is equal to 25.4 millimeters, so to convert from millimeters to inches, you will need to divide the original value in millimeters by 25.4. Using this information, you can write the code to convert the input value and store the converted value in an variable called inches. Then, you can write the return statement to return the new value inches. # Convert input from mm to inches def mm_to_in(mm): inches = mm / 25.4 return inches Docstring The function above is complete regarding code. However, as previously discussed, good documentation can help you and others to easily use and adapt this function as needed. Python promotes the use of docstrings for documenting functions. This docstring should contain a brief description of the function (i.e. how it works, purpose) as well as identify the input parameters (i.e. type, description) and the returned output (i.e. type, description). Function Description Begin with the description of the function. Some functions may require longer description than others. For the mm_to_in() function, it can be short but descriptive as shown below. def mm_to_in(mm): """Convert input from millimeters to inches. Parameters ---------- input : type Description of input. Returns ------ output : type Description of output. """ inches = mm / 25.4 return inches Input Parameter Description Next, think about the required input for the mm_to_in function. You need a numeric value in millimeters, represented by the variable mm in the code. You can identify the input in the docstring specifically as mm and provide a type (int, float) and short description that provides details on the units. def mm_to_in(mm): """Convert input from millimeters to inches. Parameters ---------- mm : int or float Numeric value with units in millimeters. Returns ------ output : type Description of output. """ inches = mm / 25.4 return inches Return Description By looking at the code in the function, you know that the final output is returned using the variable inches. You can provide a short description to specify that the returned output is a numeric value with units in inches. def mm_to_in(mm): """Convert input from millimeters to inches. Parameters ---------- mm : int or float Numeric value with units in millimeters. Returns ------ inches : int or float Numeric value with units in inches. """ inches = mm / 25.4 return inches Call Custom Functions in Python Now that you have defined the function mm_to_in(), you can call it as needed to convert units. Below is an example call to this function, specifying a single value variable that will be represented by mm in the function. # Average monthly precip (mm) in Jan for Boulder, CO precip_jan_mm = 17.78 # Convert to inches mm_to_in(mm = precip_jan_mm) 0.7000000000000001 Notice that the output is provided but you have not actually changed the original values of precip_jan_mm. precip_jan_mm 17.78 You can create a new variable to store the output of the function as follows: # Create new variable with converted values precip_jan_in = mm_to_in(mm = precip_jan_mm) precip_jan_in 0.7000000000000001 Placeholder Variables in Functions Notice that in the function call above, you provided a pre-defined variable ( precip_jan_mm) to the parameter mm using: mm = precip_jan_mm In the function, mm is the placeholder variable for the input and has not been pre-defined outside of the function. The same holds true for inches, which is the placeholder variable for the output of the function. Rather than containing pre-defined values, mm takes on the values of the input parameter to the function (e.g. precip_jan_mm), and inches holds the values resulting from the calculation in the function. Thus, mm and inches will hold different values each time that the function is called. Another important note about the placeholder variables in functions is that they do not exist outside of the function. If you try to call these placeholder variables (e.g. mm or inches) outside of the function, you will get an error. For example, the following code: print(inches) will return the error: NameError: name 'inches' is not defined This is because inches is used by the function to return the result of the code, but it is not actually stored as a variable that is independent of the function. Note that this is a difference from placeholders that are used in loops, which can be called when the loop is completed its run. Applying the Same Function to Multiple Object Types Since you know that numeric values can also be stored in numpy arrays, you can also provide a numpy array as an input to the function. # Import necessary packages import numpy as np # Average monthly precip (mm) for Boulder, CO avg_monthly_precip_mm = np.array([17.78, 19.05, 46.99, 74.422, 77.47, 51.308, 49.022, 41.148, 46.736, 33.274, 35.306, 21.336]) # Convert to inches mm_to_in(mm = avg_monthly_precip_mm) array([0.7 , 0.75, 1.85, 2.93, 3.05, 2.02, 1.93, 1.62, 1.84, 1.31, 1.39, 0.84]) Again, notice that the output is provided but you have not actually changed the original values of the numpy array. avg_monthly_precip_mm array([17.78 , 19.05 , 46.99 , 74.422, 77.47 , 51.308, 49.022, 41.148, 46.736, 33.274, 35.306, 21.336]) To do this, recall that you can save the output of a function to a new object: # Convert to inches avg_monthly_precip_in = mm_to_in(mm = avg_monthly_precip_mm) avg_monthly_precip_in array([0.7 , 0.75, 1.85, 2.93, 3.05, 2.02, 1.93, 1.62, 1.84, 1.31, 1.39, 0.84]) Similarly, you know that numeric values can be stored in a column in a pandas dataframe, so you can also provide a column in a pandas dataframe as an input to the function and store the results of the function in a new column. # Import necessary packages import pandas as pd # Average monthly precip (mm) in 2002 for Boulder, CO precip_2002 = pd.DataFrame(columns=["month", "precip_mm"], data=[ ["Jan", 27.178], ["Feb", 11.176], ["Mar", 38.100], ["Apr", 5.080], ["May", 81.280], ["June", 29.972], ["July", 2.286], ["Aug", 36.576], ["Sept", 38.608], ["Oct", 61.976], ["Nov", 19.812], ["Dec", 0.508] ]) # Create new column with precip in inches precip_2002["precip_in"] = mm_to_in(mm = precip_2002["precip_mm"]) precip_2002 Determining Appropriate Inputs to Functions Can the function mm_to_in() to take a list as an input? Look again at the code that the function executes. def mm_to_in(mm): """Convert input from millimeters to inches. Parameters ---------- mm : int or float Numeric value with units in millimeters. Returns ------ inches : int or float Numeric value with units in inches. """ inches = mm / 25.4 return inches Since you know that numeric calculations cannot be performed directly on a list, you know that this function will not execute successfully if provided a list as an input. This is an important idea to keep in mind as you write functions in Python. If the code will not execute outside of a function (e.g. numerical operation on a list), then the code will also not execute using a function, as the code is still subject to the rules governing the objects to which it is applied. This also highlights the importance of docstrings to provide clear descriptions of the type of inputs and outputs that are provided by the function. Call Help on a Custom Function Just like you can call help() on a function provided by a Python package such as numpy (e.g. help(np.mean), you can also call help() on custom functions. # Call help on mean function from numpy help(np.mean) Help on function mean in module numpy: mean(a, axis=None, dtype=None, out=None, keepdims=<no value>) Compute the arithmetic mean along the specified axis.. .. versionadded:: 1.7.0 If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `ufuncs-output-type` for more details.` method of sub-classes of `ndarray`, however any non-default value will be. If the sub-class' method does not implement `keepdims` any exceptions will be raised. Returns ------- m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. # Call help on custom function help(mm_to_in) Help on function mm_to_in in module __main__: mm_to_in(mm) Convert input from millimeters to inches. Parameters ---------- mm : int or float Numeric value with units in millimeters. Returns ------ inches : int or float Numeric value with units in inches. Notice that when you call help() on custom functions (e.g. mm_to_in), you will see the docstring that has been included in the function definition. The help() results for np.mean are simply longer because the docstring contains more information such as sections for Notes and Examples. Combine Multiple Function Calls on a Single Object in Python Imagine that you want to convert the units of a numpy array using the function mm_to_in() and then calculate a mean using np.mean(). You could write code to complete each task one at a time: # Convert units and save to new array avg_monthly_precip_in = mm_to_in(mm = avg_monthly_precip_mm) # Calculate mean and save value avg_monthly_precip_mean_in = np.mean(avg_monthly_precip_in) print(avg_monthly_precip_mean_in) 1.6858333333333333 However, you will end up with intermediate variables (e.g. avg_monthly_precip_in) that are not really needed. Luckily, in Python, you can actually combine the calls to both of these functions into one line. To do this, you can use the function call: mm_to_in(mm = avg_monthtly_precip_mm) as the input to np.mean() function, as shown below. # Convert to inches and calculate mean avg_monthly_precip_mean_in = np.mean(mm_to_in(mm = avg_monthly_precip_mm)) avg_monthly_precip_mean_in 1.6858333333333333 In this example, the values of avg_monthtly_precip_mm are converted to inches first and then the mean of the converted values is calculated and stored as a new variable avg_monthly_precip_mean_in. Notice that the original function call to mm_to_in() looks the same as when you have called it before: mm_to_in(mm = avg_monthtly_precip_mm) It is now simply enclosed within the parenthesis () of the np.mean() function to tell Python that the output of mm_to_in() will be the input to the function np.mean(). Combining related function calls into a single line of code allows you to write code that is much more efficient and less repetitive, assisting you in writing DRY code in Python. Congratulations! You have now written and executed your first custom functions in Python to efficiently modularize and execute tasks as needed. Share onTwitter Facebook Google+ LinkedIn
https://www.earthdatascience.org/courses/intro-to-earth-data-science/write-efficient-python-code/functions-modular-code/write-functions-in-python/
CC-MAIN-2021-43
refinedweb
2,527
55.03
#include <index.h> List of all members. Status of this data. bit 0 = stream offset set, bit 1 = temporal offset set, bit 2 = temporal diff set Flags for this edit unit. Key frame offset for this edit unit. Temporal offset for this edit unit. Difference between this edit unit and the edit unit whose stream offsets are store here. This is the opposite of TemporalOffset. Temporal Offset gives the offset from the entry indexed by a given edit unit to the entry unit holding that edit unit's stream offsets, and TemporalDiff give the offset from the entry holding an edit unit's stream offset to the entry indexed by that edit unit. Array of stream offsets, one for the main stream and one per sub-stream.
http://freemxf.org/mxflib-docs/mxflib-1.0.0-docs/structmxflib_1_1_index_manager_1_1_index_data.html
CC-MAIN-2018-05
refinedweb
127
74.49
Terms defined: Boolean, anonymous function, asynchronous, callback function, cognitive load, command-line argument, console, current working directory, destructuring assignment, edge case, filesystem, filter, globbing, idiomatic, log message, path (in filesystem), protocol, scope, single-threaded, string interpolation The biggest difference between JavaScript and most other programming languages is that many operations in JavaScript are asynchronous. Its designers didn't want browsers to freeze while waiting for data to arrive or for users to click on things, so operations that might be slow are implemented by describing now what to do later. And since anything that touches the hard drive is slow from a processor's point of view, Node implements filesystem operations the same way. How slow is slow? Gregg2020 used the analogy in to show how long it takes a computer to do different things if we imagine that one CPU cycle is equivalent to one second. Early JavaScript programs used callback functions to describe asynchronous operations, but as we're about to see, callbacks can be hard to understand even in small programs. In 2015, the language's developers standardized a higher-level tool called promises to make callbacks easier to manage, and more recently they have added new keywords called async and await to make it easier still. We need to understand all three layers in order to debug things when they go wrong, so this chapter explores callbacks, while shows how promises and async/ await work. This chapter also shows how to read and write files and directories with Node's standard libraries, because we're going to be doing that a lot. How can we list a directory? To start, let's try listing the contents of a directory the way we would in Python or Java: import fs from 'fs' const srcDir = process.argv[2] const results = fs.readdir(srcDir) for (const name of results) { console.log(name) } We use import module from 'source' to load the library source and assign its contents to module. After that, we can refer to things in the library using module.component just as we refer to things in any other object. We can use whatever name we want for the module, which allows us to give short nicknames to libraries with long names; we will take advantage of this in future chapters. require versus import In 2015, a new version of JavaScript called ES6 introduced the keyword import for importing modules. It improves on the older require function in several ways, but Node still uses require by default. To tell it to use import, we have added "type": "module" at the top level of our Node package.json file. Our little program uses the fs library which contains functions to create directories, read or delete files, etc. (Its name is short for "filesystem".) We tell the program what to list using command-line arguments, which Node automatically stores in an array called process.argv. process.argv[0] is the name of the program used to run our code (in this case node), while process.argv[1] is the name of our program (in this case list-dir-wrong.js); the rest of process.argv holds whatever arguments we gave at the command line when we ran the program, so process.argv[2] is the first argument after the name of our program (): process.argv. If we run this program with the name of a directory as its argument, fs.readdir returns the names of the things in that directory as an array of strings. The program uses for (const name of results) to loop over the contents of that array. We could use let instead of const, but it's good practice to declare things as const wherever possible so that anyone reading the program knows the variable isn't actually going to vary—doing this reduces the cognitive load on people reading the program. Finally, console.log is JavaScript's equivalent of other languages' Unfortunately, our program doesn't work: node list-dir-wrong.js . internal/process/esm_loader.js:74 internalBinding('errors').triggerUncaughtException( ^ TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received \ undefined at makeCallback (fs.js:168:11) at Object.readdir (fs.js:994:14) at /u/stjs/systems-programming/list-dir-wrong.js:4:20 at ModuleJob.run (internal/modules/esm/module_job.js:152:23) at async Loader.import (internal/modules/esm/loader.js:166:24) at async Object.loadESM (internal/process/esm_loader.js:68:5) { code: 'ERR_INVALID_CALLBACK' } The error message comes from something we didn't write whose source we would struggle to read. If we look for the name of our file ( list-dir-wrong.js) we see the error occurred on line 4; everything above that is inside fs.readdir, while everything below it is Node loading and running our program. The problem is that fs.readdir doesn't return anything. Instead, its documentation says that it needs a callback function that tells it what to do when data is available, so we need to explore those in order to make our program work. A theorem - Every program contains at least one bug. - Every program can be made one line shorter. - Therefore, every program can be reduced to a single statement which is wrong. — variously attributed What is a callback function? JavaScript uses a single-threaded programming model: as the introduction to this lesson said, it splits operations like file I/O into "please do this" and "do this when data is available". fs.readdir is the first part, but we need to write a function that specifies the second part. JavaScript saves a reference to this function and calls with a specific set of parameters when our data is ready (). Those parameters defined a standard protocol for connecting to libraries, just like the USB standard allows us to plug hardware devices together. This corrected program gives fs.readdir a callback function called listContents: import fs from 'fs' const listContents = (err, files) => { console.log('running callback') if (err) { console.error(err) } else { for (const name of files) { console.log(name) } } } const srcDir = process.argv[2] fs.readdir(srcDir, listContents) console.log('last line of program') Node callbacks always get an error (if there is any) as their first argument and the result of a successful function call as their second. The function can tell the difference by checking to see if the error argument is null. If it is, the function lists the directory's contents with console.log, otherwise, it uses console.error to display the error message. Let's run the program with the current working directory (written as '.') as an argument: node list-dir-function-defined.js . last line of program running callback Makefile copy-file-filtered.js copy-file-unfiltered.js copy-file-unfiltered.out copy-file-unfiltered.sh copy-file-unfiltered.txt figures glob-all-files.js ... x-check-arguments x-counting-lines x-destructuring-assignment x-glob-patterns x-rename-files x-significant-entries x-string-interpolation x-trace-anonymous x-trace-callback x-where-is-node Nothing that follows will make sense if we don't understand the order in which Node executes the statements in this program (): Execute the first line to load the fslibrary. Define a function of two parameters and assign it to listContents. (Remember, a function is just another kind of data.) Get the name of the directory from the command-line arguments. Call fs.readdirto start a filesystem operation, telling it what directory we want to read and what function to call when data is available. Print a message to show we're at the end of the file. Wait until the filesystem operation finishes (this step is invisible). Run the callback function, which prints the directory listing. What are anonymous functions? Most JavaScript programmers wouldn't define the function listContents and then pass it as a callback. Instead, since the callback is only used in one place, it is more idiomatic to define it where it is needed as an anonymous function. This makes it easier to see what's going to happen when the operation completes, though it means the order of execution is quite different from the order of reading (). Using an anonymous function gives us the final version of our program: import fs from 'fs' const srcDir = process.argv[2] fs.readdir(srcDir, (err, files) => { if (err) { console.error(err) } else { for (const name of files) { console.log(name) } } }) Functions are data As we noted above, a function is just another kind of data. Instead of being made up of numbers, characters, or pixels, it is made up of instructions, but these are stored in memory like anything else. Defining a function on the fly is no different from defining an array in-place using [1, 3, 5], and passing a function as an argument to another function is no different from passing an array. We are going to rely on this insight over and over again in the coming lessons. How can we select a set of files? Suppose we want to copy some files instead of listing a directory's contents. Depending on the situation we might want to copy only those files given on the command line or all files except some explicitly excluded. What we don't want to have to do is list the files one by one; instead, we want to be able to write patterns like *.js. To find files that match patterns like that, we can use the glob module. (To glob (short for "global") is an old Unix term for matching a set of files by name.) The glob module provides a function that takes a pattern and a callback and does something with every filename that matched the pattern: import glob from 'glob' glob('**/*.*', (err, files) => { if (err) { console.log(err) } else { The leading ** means "recurse into subdirectories", while *.* means "any characters followed by '.' followed by any characters" (). Names that don't match *.* won't be included, and by default, neither are names that start with a '.' character. This is another old Unix convention: files and directories whose names have a leading '.' usually contain configuration information for various programs, so most commands will leave them alone unless told to do otherwise. globpatterns to match filenames. This program works, but we probably don't want to copy Emacs backup files whose names end with ~. We can get rid of them by filtering the list that glob returns: import glob from 'glob' glob('**/*.*', (err, files) => { if (err) { console.log(err) } else { files = files.filter((f) => { return !f.endsWith('~') }) Array.filter creates a new array containing all the items of the original array that pass a test (). The test is specified as a callback function that Array.filter calls once once for each item. This function must return a Boolean that tells Array.filter whether to keep the item in the new array or not. Array.filter does not modify the original array, so we can filter our original list of filenames several times if we want to. Array.filter. We can make our globbing program more idiomatic by removing the parentheses around the single parameter and writing just the expression we want the function to return: import glob from 'glob' glob('**/*.*', (err, files) => { if (err) { console.log(err) } else { files = files.filter(f => !f.endsWith('~')) for (const filename of files) { console.log(filename) } } }) However, it turns out that glob will filter for us. According to its documentation, the function takes an options object full of key-value settings that control its behavior. This is another common pattern in Node libraries: rather than accepting a large number of rarely-used parameters, a function can take a single object full of settings. If we use this, our program becomes: import glob from 'glob' glob('**/*.*', { ignore: '*~' }, (err, files) => { if (err) { console.log(err) } else { for (const filename of files) { console.log(filename) } } }) Notice that we don't quote the key in the options object. The keys in objects are almost always strings, and if a string is simple enough that it won't confuse the parser, we don't need to put quotes around it. Here, "simple enough" means "looks like it could be a variable name", or equivalently "contains only letters, digits, and the underscore". No one knows everything We combined glob.glob and Array.filter in our functions for more than a year before someone pointed out the ignore option for glob.glob. This shows: Life is short, so most of us find a way to solve the problem in front of us and re-use it rather than looking for something better. Code reviews aren't just about finding bugs: they are also the most effective way to transfer knowledge between programmers. Even if someone is much more experienced than you, there's a good chance you might have stumbled over a better way to do something than the one they're using (see point #1 above). To finish off our globbing program, let's specify a source directory on the command line and include that in the pattern: import glob from 'glob' const srcDir = process.argv[2] glob(`${srcDir}/**/*.*`, { ignore: '*~' }, (err, files) => { if (err) { console.log(err) } else { for (const filename of files) { console.log(filename) } } }) This program uses string interpolation to insert the value of srcDir into a string. The template string is written in back quotes, and JavaScript converts every expression written as ${expression} to text. We could create the pattern by concatenating strings using srcDir + '/**/*.*', but most programmers find interpolation easier to read. How can we copy a set of files? If we want to copy a set of files instead of just listing them we need a way to create the paths of the files we are going to create. If our program takes a second argument that specifies the desired output directory, we can construct the full output path by replacing the name of the source directory with that path: import glob from 'glob' const [srcDir, dstDir] = process.argv.slice(2) glob(`${srcDir}/**/*.*`, { ignore: '*~' }, (err, files) => { if (err) { console.log(err) } else { for (const srcName of files) { const dstName = srcName.replace(srcDir, dstDir) console.log(srcName, dstName) } } }) This program uses destructuring assignment to create two variables at once by unpacking the elements of an array (). It only works if the array contains the enough elements, i.e., if both a source and destination are given on the command line; we'll add a check for that in the exercises. A more serious problem is that this program only works if the destination directory already exists: fs and equivalent libraries in other languages usually won't create directories for us automatically. The need to do this comes up so often that there is a function called ensureDir to do) } }) } } }) Notice that we import from fs-extra instead of fs; the fs-extra module provides some useful utilities on top of fs. We also use path to manipulate pathnames rather than concatenating or interpolating strings because there are a lot of tricky edge cases in pathnames that the authors of that module have figured out for us. Using distinct names We are now calling our command-line arguments srcRoot and dstRoot rather than srcDir and dstDir. As we were writing this example we used dstDir as both the name of the top-level destination directory (from the command line) and the name of the particular output directory to create. JavaScript didn't complain because every function creates a new scope for variable definitions, and it's perfectly legal to give a variable inside a function the same name as something outside it. However, "legal" isn't the same thing as "comprehensible"; giving the variables different names makes the program easier for humans to read. Our file copying program currently creates empty destination directories but doesn't actually copy any files. Let's use fs.copy to do) } else { fs.copy(srcName, dstName, (err) => { if (err) { console.error(err) } }) } }) } } }) The program now has three levels of callback (): When globhas data, do things and then call ensureDir. When ensureDircompletes, copy a file. When copyfinishes, check the error status. Our program looks like it should work, but if we try to copy everything in the directory containing these lessons we get an error message: rm -rf /tmp/out mkdir /tmp/out node copy-file-unfiltered.js ../node_modules /tmp/out 2>&1 | head -n 6 [Error: ENOENT: no such file or directory, chmod \ '/tmp/out/@nodelib/fs.stat/package.json'] { errno: -2, code: 'ENOENT', syscall: 'chmod', path: '/tmp/out/@nodelib/fs.stat/package.json' } The problem is that node_modules/fs.stat and node_modules/fs.walk match our globbing expression, but are directories rather than files. To prevent our program from trying to use fs.copy on directories, we must use fs.stat to get the properties of the thing whose name glob has given us and then check if it's a file. The name "stat" is short for "status", and since the status of something in the filesystem can be very complex, fs.stat returns an object with methods that can answer common questions. Here's the final version of our file copying program: import glob from 'glob' import fs from 'fs-extra' import path from 'path' const [srcRoot, dstRoot] = process.argv.slice(2) glob(`${srcRoot}/**/*.*`, { ignore: '*~' }, (err, files) => { if (err) { console.log(err) } else { for (const srcName of files) { fs.stat(srcName, (err, stats) => { if (err) { console.error(err) } else if (stats.isFile()) { const dstName = srcName.replace(srcRoot, dstRoot) const dstDir = path.dirname(dstName) fs.ensureDir(dstDir, (err) => { if (err) { console.error(err) } else { fs.copy(srcName, dstName, (err) => { if (err) { console.error(err) } }) } }) } }) } } }) It works, but four levels of asynchronous callbacks is hard for humans to understand. will introduce a pair of tools that make code like this easier to read. Exercises Where is Node? Write a program called wherenode.js that prints the full path to the version of Node is is run with. Tracing callbacks In what order does the program below print messages? const red = () => { console.log('RED') } const green = (func) => { console.log('GREEN') func() } const blue = (left, right) => { console.log('BLUE') left(right) } blue(green, red) Tracing anonymous callbacks In what order does the program below print messages? const blue = (left, right) => { console.log('BLUE') left(right) } blue( (callback) => { console.log('GREEN') callback() }, () => console.log('RED') ) Checking arguments Modify the file copying program to check that it has been given the right number of command-line arguments and to print a sensible error message (including a usage statement) if it hasn't. Significant entries count-lines-histogram.js displays many zeroes and gives no visual sense of how large entries are. Modify it so that: When it is run with the --nonzeroflag only non-zero values are shown. When it is run with the --graphicalflag the numeric values are replaced with rows of asterisks. If both flags are given the program prints an error message instead of running. Glob patterns What filenames does each of the following glob patterns match? results-[0123456789].csv results.(tsv|csv) results.dat? ./results.data Filtering arrays Fill in the blank in the code below so that it runs correctly. Note: you can compare strings in JavaScript using <, >=, and other operators, so that (for example) person.personal > 'P' is true if someone's personal name starts with a letter that comes after 'P' in the alphabet. const people = [ { personal: 'Jean', family: 'Jennings' }, { personal: 'Marlyn', family: 'Wescoff' }, { personal: 'Ruth', family: 'Lichterman' }, { personal: 'Betty', family: 'Snyder' }, { personal: 'Frances', family: 'Bilas' }, { personal: 'Kay', family: 'McNulty' } ] const result = people.filter(____ => ____) console.log(result) [ { personal: 'Jean', family: 'Jennings' }, { personal: 'Ruth', family: 'Lichterman' }, { personal: 'Frances', family: 'Bilas' } ] String interpolation Fill in the code below so that it prints the message shown. const people = [ { personal: 'Christine', family: 'Darden' }, { personal: 'Mary', family: 'Jackson' }, { personal: 'Katherine', family: 'Johnson' }, { personal: 'Dorothy', family: 'Vaughan' } ] for (const person of people) { console.log(`$____, $____`) } Darden, Christine Jackson, Mary Johnson, Katherine Vaughan, Dorothy Destructuring assignment What is assigned to each named variable in each statement below? const first = [10, 20, 30] const [first, second] = [10, 20, 30] const [first, second, third] = [10, 20, 30] const [first, second, third, fourth] = [10, 20, 30] const {left, right} = {left: 10, right: 30} const {left, middle, right} = {left: 10, middle: 20, right: 30} Counting lines Write a program called lc that counts and reports the number of lines in one or more files and the total number of lines, so that lc a.txt b.txt displays something like: a.txt 475 b.txt 31 total 506 Renaming files Write a program called rename that takes three or more command-line arguments: - A filename extension to match. - An extension to replace it with. - The names of one or more existing files. When it runs, rename renames any files with the first extension to create files with the second extension, but will not overwrite an existing file. For example, suppose a directory contains a.txt, b.txt, and b.bck. The command: rename .txt .bck a.txt b.txt will rename a.txt to a.bck, but will not rename b.txt because b.bck already exists.
https://stjs.tech/systems-programming/
CC-MAIN-2021-39
refinedweb
3,534
57.27
Fluent Bit is a fast and lightweight log processor, stream processor, and forwarder for Linux, OSX, Windows, and BSD family operating systems. Its focus on performance allows the collection of events from different sources and the shipping to multiple destinations without complexity. It is lightweight, allowing it to run on embedded systems as well as complex cloud-based virtual machines. In this post, we will cover the main use cases and configurations for Fluent Bit. Fluent Bit Installation Fluent Bit has simple installations instructions. Coralogix has a straight forward integration but if you’re not using Coralogix, then we also have instructions for Kubernetes installations. Fluent Bit Configuration Configuring Fluent Bit is as simple as changing a single file. You’ll find the configuration file at /fluent-bit/etc/fluent-bit.conf. Concepts in the Fluent Bit Schema The schema for the Fluent Bit configuration is broken down into two concepts: - Sections - Entries: Key/Value – One section may contain many Entries. An entry is a line of text that contains a Key and a Value When writing out these concepts in your configuration file, you must be aware of the indentation requirements. Each configuration file must follow the same pattern of alignment from left to right. The Types of Sections The Fluent Bit configuration file supports four types of sections, each of them has a different set of available options. - The Service section – defines global properties of the service - The Input section – the source from where Fluent Bit can collect data - The Filter section – altering the data before sending it to your destination - The Output section – a destination where Fluent Bit should flush the information Service The Service section defines the global properties of the Fluent Bit service. This is an example of a common Service section that sets Fluent Bit to flush data to the designated output every 5 seconds with the log level set to debug. It also points Fluent Bit to the custom_parsers.conf as a Parser file. [SERVICE] Flush 5 Daemon Off Log_Level debug Parsers_File custom_parsers.conf There are additional parameters you can set in this section. Check the documentation for more details. Input The INPUT section defines a source plugin. You can specify multiple inputs in a Fluent Bit configuration file. Each input is in its own INPUT section with its own configuration keys. The Name is mandatory and it lets Fluent Bit know which input plugin should be loaded. The Tag is mandatory for all plugins except for the input forward plugin (as it provides dynamic tags). [INPUT] Name cpu Tag my_cpu Fluent Bit supports various input plugins options. For example, if you want to tail log files you should use the Tail input plugin. There are a variety of input plugins available. Filter In addition to the Fluent Bit parsers, you may use filters for parsing your data. A filter plugin allows users to alter the incoming data generated by the input plugins before delivering it to the specified destination. You may use multiple filters, each one in its own FILTER section. [FILTER] Name modify Match * Add user coralogix This is a simple example for a filter that adds to each log record, from any input, the key user with the value coralogix. The Name is mandatory and it lets Fluent Bit know which filter plugin should be loaded. The Match or Match_Regex is mandatory for all plugins. If both are specified, Match_Regex takes precedence. There are lots of filter plugins to choose from. Output The OUTPUT section specifies a destination that certain records should follow after a Tag match. The following is a common example of flushing the logs from all the inputs to stdout. [OUTPUT] Name stdout Match * Similar to the INPUT and FILTER sections, the OUTPUT section requires The Name to let Fluent Bit know where to flush the logs generated by the input/s. Match or Match_Regex is mandatory as well. If both are specified, Match_Regex takes precedence. For all available output plugins. Injecting Environment Variables into your Fluent Bit Config Your configuration file supports reading in environment variables using the bash syntax. For example: [OUTPUT] Name ${MY_ENV_VAR} Match * Breaking down your Configuration files The @INCLUDE keyword is used for including configuration files as part of the main config, thus making large configurations more readable. You can create a single configuration file that pulls in many other files. This allows you to organize your configuration by a specific topic or action. All paths that you use will be read as relative from the root configuration file. @INCLUDE somefile.conf @INCLUDE someOtherFile.conf Defining Variables The @SET command is another way of exposing variables to Fluent Bit, used at the root level of each line in the config. This means you can not use the @SET command inside of a section. You can use this command to define variables that are not available as environment variables. They are then accessed in the exact same way. @SET my_input=cpu [SERVICE] Flush 1 [INPUT] Name ${my_input} Parsing Structured and Unstructured Logs Fluent Bit is able to capture data out of both structured and unstructured logs, by leveraging parsers. Parsers are pluggable components that allow you to specify exactly how Fluent Bit will parse your logs. For example, you can use the JSON, Regex, LTSV or Logfmt parsers. There are plenty of common parsers to choose from that come as part of the Fluent Bit installation. Parsers play a special role and must be defined inside the parsers.conf file. [PARSER] Name docker-logs Format json Time_Key time Time_Format %Y-%m-%dT%H:%M:%S %z Parsing Multi-Line Logs If you are using tail input and your log files include multiline log lines, you should set a dedicated parser in the parsers.conf. You are then able to set the multiline configuration parameters in the main Fluent Bit configuration file. Multiline logs are a common problem with Fluent Bit and we have written some documentation to support our users. Fluent Bit Configuration Examples We have included some examples of useful Fluent Bit configuration files that showcase a specific use case. Each file will use the components that have been listed in this article and should serve as concrete examples of how to use these features. Example 1 – Simple Tail Input to Coralogix The Chosen application name is “prod” and the subsystem is “app”, you may later filter logs based on these metadata fields. [SERVICE] # setting application logs level to debug Log_Level debug # setting location for the parsers file Parsers_File parsers.conf # setting location for Coralogix plugin Plugins_File plugins.conf [INPUT] # using tail input to tail log files Name tail # setting the path for the file to tail Path /var/log/fluent-bit/app.log # enabling multiline options Multiline On # using the parser called multiline_pattern for determine first line Parser_Firstline multiline_pattern # Adding a field named filename to be assigned with the path of the tailed file Path_Key filename [OUTPUT] # setting up Coralogix's output plugin to forward logs to Coralogix Name coralogix # here you add your Coralogix account private key Private_Key xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # here you add your Coralogix account company ID company_id xxxx # setting application name as prod App_Name prod # setting subsystem name as app Sub_Name app # forward all logs from all inputs Match * The parsers file includes only one parser, which is used to tell Fluent Bit where the beginning of a line is. It was built to match a beginning of a line as written in our tailed file, e.g. [2020-03-12 14:14:55] ..... [PARSER] Name multiline_pattern Format regex Regex ^\[(?<timestamp>[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2} [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2})\] (?<message>.*) Any other line which does not start similar to the above will be appended to the former line. This parser also divides the text into 2 fields, timestamp and message, to form a JSON entry where the timestamp field will possess the actual log timestamp, e.g. 2020-03-12 14:14:55, and Fluent Bit places the rest of the text into the message field. Example 2 – Kubernetes Integration Here we can see a Kubernetes Integration. This time, rather than editing a file directly, we need to define a ConfigMap to contain our configuration: kind: ConfigMap apiVersion: v1 metadata: name: fluent-bit-coralogix-config namespace: kube-system labels: k8s-app: fluent-bit-coralogix-logger data: fluent-bit.conf: |- [SERVICE] # flush timeout to define when is required to flush the records ingested by input plugins through the defined output plugins Flush 1 # boolean value to set if Fluent Bit should run as a Daemon (background) or not Daemon Off # setting application logs level to warning Log_Level warning # enable built-in HTTP Server HTTP_Server On # setting location for the parsers file Parsers_File parsers.conf # setting location for Coralogix plugin Plugins_File plugins.conf [INPUT] # using tail input to tail log files Name tail # tagging the input Tag kube.* # setting the paths for the kubernetes cluster files to tail Path /var/log/containers/*.log # specify the name of a parser to interpret the entry as a structured message Parser docker # specify the database file to keep track of monitored files and offsets DB /var/log/flb_kube.db # set a limit of memory that Tail plugin can use when appending data to the Engine. # if the limit is reach, it will be paused; when the data is flushed it resumes Mem_Buf_Limit 5MB # when a monitored file reach it buffer capacity due to a very long line (Buffer_Max_Size), the default behavior is to stop monitoring that file. # skip_Long_Lines alter that behavior and instruct Fluent Bit to skip long lines and continue processing other lines that fits into the buffer size Skip_Long_Lines On # the interval of refreshing the list of watched files in seconds Refresh_Interval 10 [FILTER] # name of the filter plugin Name kubernetes # a pattern to match against the tags of incoming records Match kube.* # allow Kubernetes Pods to exclude their logs from the log processor K8S-Logging.Exclude On [OUTPUT] # setting up Coralogix's output plugin to forward logs to Coralogix Name coralogix # a pattern to match against the tags of incoming records Match kube.* # coralogix account private key, which already exists after creating Kubernetes secret with Coralogix credentials Private_Key ${PRIVATE_KEY} # setting kubernetes.namespace_name as the application name in Coralogix, dynamically App_Name_Key kubernetes.namespace_name # setting kubernetes.container_name as the subsystem name in Coralogix, dynamically Sub_Name_Key kubernetes.container_name # using the log time field as timestamp in Coralogix Time_Key time # this option is getting the hostname from field kubernetes.host. If its not present, then hostname will be detected automatically Host_Key kubernetes.host # integer value to set the maximum number of retries allowed Retry_Limit 5 That’s a wrap We’ve gone through the basic concepts involved in Fluent Bit. It is a very powerful and flexible tool, and when combined with Coralogix, you can easily pull your logs from your infrastructure and develop new, actionable insights that will improve your observability and speed up your troubleshooting.
https://coralogix.com/blog/fluent-bit-guide/
CC-MAIN-2021-25
refinedweb
1,842
51.99
Proposed Features/amenity=reception desk Contents Rejection On the second time this has been presented for voting the proposal has been rejected by 7 oppose to 15 approved (68% approval, present rules require 75% for formal approval). Most of those opposed appear to point to the use of 'desk in the name/value and suggest the use of point in its place. There is also one pointing to the use of reception_area. A total of 22 people voted .. compared to some 38 the first time. Does a more controversial proposal attract more participation? I shall put up proposals for reception, reception_point and reception_area and see what happens. Proposal A Reception Desk provides a place where people (visitors, patients, or clients) arrive to be greeted, any information recorded, the relevant person is contacted and the visitor/s, patient/s, or client/s sent on to the relevant person/place. How to Map Map the desk itself - not the waiting/reception area nor the building. As a member of a relation. When a relation is declared you include the node/way/area that contains the tag reception_desk as one member of the relation. Additional Tags - operator=* - phone=* - opening_hours=* - name=* - level=* for multi level indoor tagging Rendering As a desk, represented as a line, with a receptionist, represented as a head and shoulders figure over it, in the amenity colour of brown. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above represents what should appear on the resulting wiki page. Below are presented the explanation of the need for this tag and why this method is used. Rationale (Verbose Explanation) It is particularly useful to know the location of the reception desk when it is located away from the typical place (near a front entry) or where there is only one amongst a number of large buildings. First seen as a suggested extended tag for camp sites, thought to have a wider application to offices, hotels, hospitals and educational features. What key? - Tourism=reception_desk desk is some 600 m from the 'front entry' and is hard to find. It is not a tourist site in any way. - office=reception_desk The office key is used for "a place predominantly selling services". A reception desk does not commonly sell a service, it usually directs to a service. - amenity=reception_desk The amenity key is used for "an assortment of community facilities". You could view the reception_desk as similar to a toilet or telephone (both key:amenity), they are present on tourist sites, businesses/offices and educational institutions. They provide a needed facility to tourists and locals alike. Of these 3 keys, amenity is the 'best' key for reception_desk. What value? (Why desk?) Reception by it self could be confused with GPS reception, radio or TV reception, wedding reception. In order to distinguish it the addition of the word 'desk' was used. I've never encountered this kind of reception that did not have a desk, usually with a telephone, these days with a computer, possibly a sign in book (for Occupational, Health and Safety - to record who enters and if they leave.. any evacuation then enables checking of people). So reception_desk. Association with parent The reception_desk would service some other feature (the 'parent', an office, camp_site etc) and should be associated with it. These may share the operator and/or name tags being the same for both. The relation between the reception_desk and its' parent feature may be indicated by; - the reception_desk being enclosed by the parent feature. - the proximity of the reception_desk and the parent feature. - A site relation. See site This is something that that applies to some features and could be addressed by a wiki page. Indoor Mapping? Many of the present tags in use will need to be considered by any indoor mapping system. The addition of this tag does not add any complexity to that, it is similar to the tags toilet, telephone, all the key:office and key:shop values. A solution to those tag should also work for reception_desk. I see no reason why this tag has to be 'special' in some way for the indoor tagging. See the indoor mapping wiki page. Possibly the most relevant is the level=* tag. This is something that could be addressed by a wiki page, associated with the 'Indoor_Mapping' page above. Relations This can be an element of a relation. But not as a tag on a relation (like a name, operator or contact could be). The relation has a declaration of "type=" .. in that area you cannot have "reception_desk" as it would not identify the location of the reception_desk. The above is true for all amenity values. What relations would it be used with? Those that link it to the thing it services (its 'parent'). Examples Any hotel will have a reception desk, as do many office, industrial, camp and caravan sites. From Taginfo value=reception there are over 900 instances, most of those follow suggested extended tags for camp sites. Many of the rest are names for buildings ... probably where the mapper wants to identify where the reception desk. Presently (April 2015) on the OSM data base there are - 14 amenity=reception_desk (this proposal) related or possibly related - 557 camp_site=reception (previous proposal related to camp sites) - 295 name=Reception - 26 name=reception - 11 name=Main Reception - 11 office=reception - 105 amenity=reception_area At least some of these show a need for the tagging of a 'reception desk'.. Please refrain from publicly commenting on other peoples votes, no matter what the comment is, they are entitled to their ideas. Discussion should have settled any issues and the proposal should have adequately described the feature. Further discussion here is too late. Previous Voting Summary 21 for, 17 against. Most objections to the key amenity. Some about 'indoor mapping'. One about 'desk'. Another how to relate it to the parent feature. And another says it needs more time. I have tried to address these objections by explanations above. Previous votes have been moved to the discussion page to avoid confusion with the new process here. New voting Vote start 2 June 2015, possible end 16 June 2015. I approve this proposal. This is a needed tag, and amenity is just fine. I wish it did not say "desk", as it's not always a "desk", but that's not a fatal problem. Brycenesbitt (talk) 23:43, 1 June 2015 (UTC) I approve this proposal. When I vist Very large corporate campuses and government facilities to see a worker - I have to go to a special place called the reception desk. I have visited more reception desks at government facilities and high security places to gain entry to fix computers - many more than the concierge at a hotel. People who say this is tourism are very narrow minded and very wrong - Or didn't bother to read a wiki page they just voted on (which is my bet). Go to SAIC or General Atomics in San Diego and try to find their reception entrance and reception desk just by looking at a satellite image. it is impossible, and non-obvious from the ground. How about where to check in when visiting Apple? Where do you go at the infinite loop campus to check-in to see Mr Cook? When visiting a Factory with a wide open gate and 50 buildings - Where do visitiors check-in to see the plant manager? All of these are a non-tourism function - it is merely an amenity. *every single place* I would wish to tag a reception desk is in a non-tourist, commercial or industrial (or military) facility. People voting otherwise simply have no life experience outside of hotels - and should be more imaginative. Javbw (talk) 01:21, 2 June 2015 (UTC) I approve this proposal. Polarbear w (talk) 07:46, 2 June 2015 (UTC) I approve this proposal. --Peter Mead (talk) 08:36, 2 June 2015 (UTC) I approve this proposal. I think micromapping in general is the way to go for OSM and this is a part of it. -- Kocio (talk) 09:04, 2 June 2015 (UTC) I oppose this proposal. I was in favour of it until I noticed the instruction "map the desk itself". In my opinion, focussing on the piece of furniture rather than the facility as a whole is a really strange decision. --Tordanik 11:59, 16 June 2015 (UTC) - Selected the desk as a fixed point that can be easily located on the ground. It may not be central to an area, but it is THE place you go to. I approve this proposal. Dr Centerline (talk) 15:45, 2 June 2015 (UTC) I approve this proposal. --Kotya (talk) 22:34, 3 June 2015 (UTC) I approve this proposal. Jojo4u (talk) 09:20, 5 June 2015 (UTC) I approve this proposal. --Mapper999 (talk) 14:54, 6 June 2015 (UTC) I oppose this proposal. Too vague in between tourism, office etc. and needed only in very special cases. Vademecum (talk) 18:42, 10 June 2015 (UTC) - The definitions for tourism, office etc. come from the OSM wiki, you find them vague? They are broad definitions so that all cases of tourism, office etc fit under those definition .. but other cases don't. - You say this is "needed only in special cases" yet you oppose the inclusion? Police Stations too are only needed in special cases! If it is needed or of use then it should be included. Warin61 (talk) 00:40, 11 June 2015 (UTC) - Don't twist my words. First it's "needed only in very special cases" and therefore the definition is too vague and not exact and tries to combine cases which don't belong together. Vademecum (talk) 18:11, 17 June 2015 (UTC) I approve this proposal. Waldhans (talk) 07:29, 16 June 2015 (UTC) I oppose this proposal. I had voted yes, but I'd prefer a different tag like amenity=reception_area which what I noticed now, outnumbers the desk tag in actual use, and which can be more universally applied. This should be a tag about a feature (the spot/area where you should arrive, and where you typically get help, I don't support a tag that is about a piece of furniture --Dieterdreist (talk) 12:34, 16 June 2015 (UTC) - One problem with 'area' is that a large area could be tagged, what is needed is the smaller area where you get help, not a waiting area. - Another problem with reception_area it that the term is used for satellite reception areas, TV reception areas. In other words it is used for other things that I'd rather not have confused with this tag. - The amenity=reception_area has no documentation. Further they are all nodes .. no areas (ways) at all. One of them is a building .. on a node. - Amenity has a few tags about 'furniture' - bench, waste_bin etc. I see nothing wrong with tagging furniture that is of use, and is there on the 'ground'. Warin61 (talk) 00:56, 19 June 2015 (UTC) I oppose this proposal. This proposal is even worse than the previous version. The amenity tag should be for mapping facilities of use to the general public, not for mapping furniture. It is not useful to just map a 'desk', it is useful to map a reception facility. Which might be desk, or it might be several desks (plus chairs and other furniture), or a distinct reception building, or a booth, or a phone or screen etc. So all of those should be mapped as a reception. The "How to map" section is ridiculous micromapping. Why just map the outline of the desk, and not the chair next to it? Instead you should map the whole reception area or building etc. --Vclaw (talk) 10:56, 16 June 2015 (UTC) - The problem with 'area' is that a large area could be tagged, what is needed is the smaller area where you get help, not a waiting area. - Amenity has a few tags about 'furniture' - bench, waste_bin etc. I see nothing wrong with tagging furniture that is of use, and is there on the 'ground'. - Mapping a chair that may be easily moved has not been proposed. Warin61 (talk) 00:56, 19 June 2015 (UTC) I approve this proposal. In my opinion, the reception is always at the main entrance. Even the building with tourism=information. The tagging amenity=porters_lodge would be more important for companies. On campsites would good the node amenity=reception. Reception desk is always for indoor-tagging. RoGer6 (talk) 16:34, 16 June 2015 (UTC) - I'm still not satisfied. Nevertheless, I agree times for it. However, I will not use the tag. RoGer6 (talk) 07:33, 21 June 2015 (UTC) - I know of two places where the reception is a long way from the 'main entrance' in Australia. Someone else knows of a camp site reception that is a long way from the camp site (Africa I think). So the reception is not always at the main entrance! Warin61 (talk) 00:56, 19 June 2015 (UTC) - I have never ever come across a 'porters lodge' in any company, hotel, motel, camp site or office. They do have reception desks. If you want to tag a 'porters lodge' why don't you propose it? Porter = a person who carries luggage. Porters lodge may be found in university accommodation, not something the general public comes across frequently? According to taginfo there are no uses of porter lodge, there are police transporters 16 off, and court reporters 1 ... but no porters. Warin61 (talk) 02:06, 19 June 2015 (UTC) I approve this proposal. this is needed in hospitals and companies (entrance=main does not work there) . I added many in the last weeks. -- Zuse I oppose this proposal. .. with the same reason as Dieterdreist and Vclaw. --Foxxi59 (talk) 04:31, 21 June 2015 (UTC) I approve this proposal. —M!dgard [ talk | projects | current proposal ] 15:36, 21 June 2015 (UTC) I approve this proposal. Janko (talk) 16:01, 21 June 2015 (UTC) I oppose this proposal. Althio (talk) 20:52, 21 June 2015 (UTC) The idea is good, but the emphasis on 'desk' in the key/value and description is rather annoying. Following other votes and comments from Brycenesbitt, Tordanik, Dieterdreist, Vclaw. I would prefer a more generic value (say amenity=reception_point) with potential subtagging and optional mention of furniture and desks. Along the lines of (please mix and match): - amenity=reception_point +[reception_point=customer] +[furniture=booth] - amenity=reception_point +[reception_point=visitor] +[furniture=desk] - amenity=reception_point +[reception_point=delivery] +[furniture=door_phone] I oppose this proposal. Skippern (talk) 03:11, 22 June 2015 (UTC) I objected in the first round because of amenity=*, but I am also against the use of desk. Agree with Althio that reception_point is better, but it should be put in another namespace than amenity. This feature has to do with micro-mapping and indoor mapping, and can take any form, not only a desk. I have seen anything from a small hatch in a wall, to a window, to a large waiting room, to a signed point, to a telephone, so calling it a desk will eventually lead to tags such as reception_room, reception_window, reception_phone, etc. Rename it to reception_point and if needed specify the design and nature of the reception with different sub-tags. TL;DR rename reception_desk to reception_point, no to amenity= I approve this proposal. Warin61 (talk) 10:25, 23 June 2015 (UTC)
https://wiki.openstreetmap.org/wiki/Proposed_Features/amenity%3Dreception_desk
CC-MAIN-2018-34
refinedweb
2,571
65.01
This article is about improvements made for the TextOut GDI function. With the provided text rendering class, one will be able to perform simple text formatting using RTF tags ("\b", "\i", "\u", "\par", "\r", "\n") and also simple text alignment (left, center, right, top, middle, bottom) in a given bounding rectangle. TextOut Please note that you are not restricted in any way to use this class only in MFC applications. There are articles on CodeProject on similar subjects, but this is just a first step in developing an easy-to-use but powerful text-formatting function. To use the code include the header file "TextRender.h" in your project. Then add an instance of the CTextRender class. Call the EnhDrawText method with the provided text and that's it. CTextRender EnhDrawText #include "TextRender.h" // hDC is the device context for text rendering CTextRender m_TextRender; char text[] = "\\b1Hello, World !!!\\b0\\par\\par\\i1Thi" "s is a simple demonstration\\par of new\\i0" " \\ul1EnhDrawText\\ul0 \\i1function...\\i0"; RECT margins = {10, 5, 10, 5}; RECT textRect = {100, 100, 300, 300}; DWORD textAlignment = THA_CENTER | TVA_MIDDLE; m_TextRender.EnhDrawText( hDC, text, strlen(text), &textRect, &margins, textAlignment ); Now, let's see what the other arguments of EnhDrawText are. The first argument is the handle of the device context for text rendering. The second and third arguments are the text with the formatting tags and the length of the text, respectively. The fourth argument is the text bounding rectangle (all word-breaking will be done in this rectangle). The fifth argument is text margins, and finally the last argument is the text alignment flag. It can have the following values for horizontal alignment: THA_LEFT THA_CENTER THA_RIGHT Also, it can take the following values for vertical alignment: TVA_TOP TVA_MIDDLE TVA_BOTTOM Combine these values to achieve different results. The text formatting is performed using basic RTF (Rich Text Format) tags. The following tags are supported in this version of CTextRender class: To calculate the formatted text height use the CalculateTextHeight method of the CTextRender class. See an example below: CalculateTextHeight int textHeight = CalculateTextHeight( hDC, text, strlen(text), textRect, margins, width, height ); // To set width and height arguments do next // width = textRect->right - textRect->left - (margins->right+margins->left); // height = textRect->bottom - textRect->top - (margins->top+margins->bottom); Working on this problem I realised that basic support for text rendering through ExtTextOut or even DrawTextEx is not enough, so I am trying to upgrade these GDI functions to the level they can be used for advanced text rendering. ExtTextOut DrawTextEx In this version of CTextRender class basic text formatting and alignment is supported. For the next upgrade it is planned to extend the list of supported RTF tags and to add text justification, and also a UNICODE text support. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) delete delete [] var KW_NUMBER if ( m_NewLine == TRUE ) if (var == TRUE) if (var) new LPTSTR LPCTSTR CString General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/12020/CTextRender-class
CC-MAIN-2018-22
refinedweb
523
50.87
This page describes how to implement custom DOM events that can be used to pass data. Using this technique you can add extra parameters and query them. For example, if you want Firefox to perform an action whenever something happens (i.e., something other than the standard mouse/keyboard events) and, depending on the data passed along with this event, you want Firefox to react differently. customEvent, which lets you dispatch custom events with arbitrary data from JavaScript. (see bug 427537) Requirements In order to do this you must be able to do all of the following: - Download Mozilla Source Code - Build Mozilla - Creating Custom Firefox Extensions with the Mozilla Build System. This is the foundation for everything we'll do. What's in a name Despite whatever you may have been taught in your English class, there's a lot in a name when it's an event name. As of Gecko 1.8, if your event names do not start with "nsDOM" and their interfaces do not start with "nsIDOM" then you can forget about passing data. You will still be able to throw events, but that's it. The trunk You needed to download (or check out) the trunk source because you will have to modify it in order to implement your event. Be aware that this means your stuff won't work with everyone else's version of Firefox unless you get your patches into the trunk. At the time of writing the author is not aware of a way to do this that doesn't involve modifications to trunk. What follows a list of the files you'll need to modify, as well as a discussion of each change. mozilla/dom/base/nsDOMClassInfoClasses.h The change you make here is really rather small but it is incredibly important. If you peruse nsDOMClassInfoClasses.h you'll see of list of macros of the form DOMCI_CLASS(foo). You'll want to add an entry to it which looks like this: DOMCI_CLASS({truncated name}) Here's the fun part: Above I mentioned that you must name your events as nsDOM. However, here you want to put the other part of the name (e.g. if you have an event named nsDOMMyFirstEvent your nsDOMClassInfoClasses entry would be DOMCI_CLASS(MyFirstEvent)). mozilla/dom/src/base/nsDOMClassInfo.cpp Mozilla contains many convenience macros to make changes like the one you're making easier. Your modification of this file is basically just two macro calls. Try to make sure of two things: - Keep your stuff at the back. You know never know what depends on that enum you modified - Keep your stuff organized. Same reason as above. You need to make the following two modifications: -Dispatcher.cpp Note: In the mozilla 1.8.x branch this code is actually in mozilla/content/events/src/nsEventListenerManager.cpp This is quite an important file since this holds the CreateEvent method which acts as a factory method DOM events. The change you want to make is in nsEventDispatcher::CreateEvent(). You will find that there is a bunch of is important! nsDOMEvent* it = new nsDOMMyEvent(aPresContext, aEvent); if (nsnull == it) { return NS_ERROR_OUT_OF_MEMORY; } return CallQueryInterface(it, aDOMEvent); } In general though I'd strongly recommend using a function the way that everyone else does. You can find the prototypes for the function in nsIPrivateDOMEvent. Your event In order for your event to work you must do the following: - Create a scriptable interface called nsIDOM{YourEventName}inheriting from nsIDOMEvent. A good place to put this .idl is in mozilla/dom/public/idl/events/. #include "nsIDOMEvent.idl" [scriptable, uuid(08bea243-8a7b-4554-9ee9-70d7785d741b)] interface nsIDOMMyEvent: nsIDOMEvent { //put members here! }; - Implement the interface you created with a class that inherits from nsDOMEvent. Use nsDOMEvent.h's NS_FORWARD_TO_NSDOMEVENT macro so that you don't have to forward manually (unless you plan on overriding one of nsDOMEvent's original functions). Example TBP Note for extension developers In order for your event to work the way it is described here it must be derived from nsDOMEvent. The problem that extension developers will hit is that you are not allowed derive from nsDOMEvent in an extension. You can try to rewrite code but it will have to be a lot of code because nsDOMEvent uses a lot of code outside of itself which you, again, cannot access from an extension. This remains true even if you mark you extension code as "internal". Dispatching your event in JavaScript Here is how to dispatch your event in JavaScript. var event = document.createEvent("nsDOMMyEvent"); event.initEvent("nsDOMMyEvent", true, true); window.dispatchEvent(event); Dispatching your event in C++ The following shows how to dispatch your event in(event)); /)
https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Creating_Custom_Events_That_Can_Pass_Data
CC-MAIN-2020-40
refinedweb
779
64.81
You could use a Stage object and link the desired camera? Stage[c4d.STAGEOBJECT_CLINK] = ... Posts made by Cairyn - RE: Rendering with specific camera ? You could use a Stage object and link the desired camera? - RE: What's the state of Ngons in Python? @m_magalhaes said in What's the state of Ngons in Python?: About the bugs on the forum, we have introduce few month ago new tags "Bug report" and "Bug Fixed". We are also adding some tag in our bug database to retrieve faster the post on the forum. I know it's not perfect and sometimes we may forgot to add this tag on the first post of the thread. But it's better than nothing. Yeah, I'll try to use that in the future although it probably won't affect existing threads (a lot of valuable knowledge still resides in the "old forum" parts). @Cairyn said in What's the state of Ngons in Python?: Anyway, I don't think this issue is of huge interest as you said there's a replacement in the new kernel already, which will probably come with a diferent tesselation algorithm, so I present it here as a curiosity. Don't get me wrong, all modeling command have been migrated to the new modeling kernel. If you are using SendModelingCommand, it will use the new kernel. So what you see now in S22 and R23 (ok you will see in R23) IS the new kernel. There will be no better tesselation. I consider this as a bug. As a Perpetual user, I'm still on R21 (as tagged) so is this also the new kernel? AFAIK the new kernel has been working behind the API for a while now, being gradually introduced into the functionality, so it's possible that this bug still persists. I can't test it on a demo of S22 for you, as the current licensing does not allow me to install one. The new modeling kernel isn't exposed yet. But it is used. I understand, it's a bit confusing. We are moving Cinema4D to the new core. But as long as some part of Cinema4D are using the old system (object manager for exemple), the new core need to "translate" that to the classic API. (...) I hope it's clear. Sure, I have a few decades of programming under the belt. It's just a bit difficult as non-Maxon developer to see the details. Seeing only the API (and therefore the user-side of the translation layer), I can't always tell what the underlying data model really is; what's stored as attribute, what's calculated on the fly, what's internally cached for fast access, what's abstracted and what's plainly stored... I may make wrong assumptions on the internal workings. this look like a valid ngon but i will ask :) It probably is valid - I don't see a reason why it should be forbidden. I just notice that the tesselation algorithm tends to avoid such "inner polygons". That may not be intentional (based on a rule) though, but just a consequence of how the algorithm works. Thanks again, -- Cairyn -- - RE: What's the state of Ngons in Python? @m_magalhaes Thanks again. I really should look into the C++ New Maxon API documentation, but I find it hard to get access to it. I am under the impression that the Maxon API does not really cover all aspects of the Classic API yet, and we still have to use BaseDocument, BaseObject etc for access. Which means that I cannot see the Ngons of the new kernel exposed (?) Just two remarks: Corollary: Any two polygons in an Ngon must transitively share an edge Not correct. The polygons are an arbitrary valid tessellation of the polygon, and 2 polygons of that tessellation must not necessarily share an edge. There are however always two polygon that will share an internal edge. I need to work on my wording, the "transitively sharing" was apparently not a wise choice (see above) . What I meant was: a polygon must be connected to the rest of the Ngon by a shared edge; all polygons share at least one edge with another polygon within the Ngon. It's only a corollary though from the previous two statements. A polygon of an Ngon may have only inner Ngon edges (but its points still must be border points) Not correct. Some polygons of the tessellation of an Ngon must make up the border edges and the hole edges of the Ngon and those are not inner ngon edges. All points must be part of the outline or a hole (no inner points) is Correct I fell for a Germanism here in the usage of "may"; what I was trying to say was "can possibly". The situation I thought of was the following: The innermost polygon (central triangle) contains only inner edges of the Ngon; it has no outer edges. I was actually surprised that this is possible since the tesselation algorithm seems to avoid such situations. This is not a C++ coded construct though; I only used onboard tools. It took me quite a few knife cuts and Melt calls before the tesselation finally came up with this. - RE: What's the state of Ngons in Python? @m_magalhaes Thank you for the answers! Q1: ok, so the C++ functions are close to deprecation too... I thought these were already using the new kernel, but when looking at the timeframe, I notice that the Ngons have been around for a while... Q2: I don't know, this is information found on a thread here, stating that the function is broken and will be fixed. I was unable to find a similar statement that it actually has been fixed. The corresponding thread peters out without saying so. This is a general issue; I often browse old posts where something or the other doesn't work but I can't find information on the fix (if there even was a fix). Naturally, I understand that it's impossible to follow up on all old threads with fix information, but I wished there was a searchable list with all the fixes (that are announced with a release anyway, but often lacking the precise information) where I could look up what function was fixed when. Or a list of known errors, so any problems will not come as a surprise. I assume this special error has already been fixed as I can't provoke a problem either today, but it's guesswork. The file: ok, here's what I do: I start with an octagon There I delete some polys to create holes, and then I melt the whole object into one Ngon. Note that the tesselation is pretty confusing even in parts of the octagon where the original polys would have made a perfectly legal tesselation of the Ngon, but that's another thing. Now I cut an edge between two holes: You can already see that this is going wrong... Looking at the result (highlighting the Ngon) I see that the hole is gone and actually the tesselation has created coincident polygons on top of each other: The marked point in the following screenshot is the end of... well, it's partly an inner edge and partly an outer edge that ends in a... somewhat inner point. It's hard to describe because the result is not even a proper manifold any more; when I lift the two edge points it becomes visible: The foot edge of that polygon (opposite the two selected points, inner edge) is actually used by three polygons. This is still all just one single Ngon (and it doesn't lead to crashes even inside of an SDS). The behavior is easily repeatable. Anyway, I don't think this issue is of huge interest as you said there's a replacement in the new kernel already, which will probably come with a diferent tesselation algorithm, so I present it here as a curiosity. - RE: What's the state of Ngons in Python? @zipit Yes, it's heavy lifting. Ngons are fairly nasty as far as side conditions are concerned. I must admit, I never did anything with them on the C++ side. But nevertheless I am surprised that they are practically missing from the Python API, with the exception of a few read-only functions. The corollary is correct - it says "transitively share", so if you have polygons 1 and 2 sharing an edge, and 2 and 3 sharing an edge, then 1 and 3 are sharing an edge via 2. Okay, "share" may not be proper terminology, I could invent a new relationship operator, but people are already complaining about my overlong posts, so I try to suppress my inner mathematician - What's the state of Ngons in Python? Hello again, as Ngons seem to pop up once again in the questions, I'm doing some investigations on them, and... well, they are still not very Python friendly. Question 1: Is anybody currently working on expanding the Ngon handling in the Python API? (Status August 2020, comparing the newest Python and C++ documentation) Python is missing the classes Ngonand NgonBaseand the struct NgonNeighbor. The PolygonObjectdoes not have the functions GetNgonBaseand GetAndBuildNgon. The modeling interface is missing AddNgon, SetNgon, FindNgon, GetNgon, NewNgon, and more. In total, that means Ngons cannot be created in Python (sure, we can use SendModelingCommandto send a Melt command, but that is not practical and only feasible at all in certain threading situations.) This seems to be the case since a long time, and I wonder if the Python API will ever be amended to enable Ngon generation, or whether that's not even planned (as Ngon handling is fairly complicated and may not be suitable for the targeted Python audience) (Edit: I am aware that there are functions in the PolygonObject that allow inferring the Ngons - returning the relationship lists between Ngons and polygons. But these are read-only: GetPolygonTranslationMap()and GetNGonTranslationMap().) Question 2: Browsing the PluginCafé history, I found the mention that GetPolygonTranslationMap()is broken (2017). Is that still the case? It was also mentioned that the error is known and it's being worked on, but in lack of a complete error history I can't find a confirmation that it has been fixed. The thread ends shortly after without mentioning the issue again. Question 3: Is there any documentation on permitted Ngon constructs? An Ngon is ultimately just a collection of polygons, but not every arbitrary collection of polygons can be an Ngon. This is normally ensured by C4D functions that generate the Ngons. But if we could create Ngons ourselves (let's pretend we have the needed C++ functionality), what are the rules? From the behavior of the Melt command, I can only infer: - Disjunct polygons cannot make an Ngon - Polygons that meet only in a point cannot make an Ngon - Corollary: Any two polygons in an Ngon must transitively share an edge - All points of an Ngon are border points. An Ngon cannot contain "inner" points (points that are only part of "inner" Ngon edges). - An Ngon may not have edges that "cut into" the Ngon and end on an isolated point (an edge that is technically a border edge but neighbors only Ngon polygons) - Ngons can contain holes, even multiple ones - Ngons can be non-planar and have concave borders - A polygon of an Ngon may have only inner Ngon edges (but its points still must be border points) Also: Melt may completely change the polygon selection and create triangles and poles with inner Ngon edges even if the original polygon selection in my opinion would have made a perfectly valid Ngon. -- I am fairly sure that this is just a weakness of the algorithm but I cannot be totally sure that there are more rules behind it that I simply don't know. By cutting a line between two holes in an Ngon, I was able to create an Ngon that is invalid - it's not an open manifold, and it contains an edge that cuts into the Ngon. Apparently a bug, since the algorithm also closed one of the holes. Just for fun: 20200823__02__NgonInvalid.c4d - RE: What is the max parameter in BaseSelect.GetRange() really for? yupyup, BaseSelecthas no connection to the original object it actually selects from, not even in the cases where you get a pointer to the BaseSelectreturned and change the selection directly through it. That's why we need the max parameter for SelectAll and ToggleAll -- the BaseSelectdoesn't know what "all" even is. (Not GetLastElement()!) For GetRange()though, that reasoning does not apply. Now let's see whether I can crash C4D with inconsistent edge selections... - RE: Get Point Positions of Selected N-Gon or Polygon. (Newest online docs, tested with R21) - RE: What is the max parameter in BaseSelect.GetRange() really for? @zipit said in What is the max parameter in BaseSelect.GetRange() really for?: About your error, are sure that actually the method is raising the error and not your surrounding code with an unpacking or indexing operation for example? When the return value is None, that would give you exactly that error. E.g. this will fail when the method fails, i.e. returns None: a, b = selection.GetRange(*data) Aha, good thinking! Yes, that's exactly the error. The doc for the parameter doesn't say that the function completely fails when the max condition is not met - it just states The method makes sure they are < max. That of course also answers my question what happens when a and b both are < max. It makes the existence of the parameter even more mysterious, but it explains why I get this error. I definitely need to be more careful with return value checking... thanks! - RE: What is the max parameter in BaseSelect.GetRange() really for? @PluginStudent But the indices in the segment in the BaseSelect are automatically valid if the BaseSelect was built by a valid source. The only way to get invalid values would be to apply the same BaseSelect to a different object with less polys/points, and in that case the function GetRange() is of lower priority - you'd get out of range errors much earlier. If you really have an arbitrary BaseSelect to store indices from a list, and the BaseSelect contains indices that are not in the list at all, then your code is buggy, and limiting the output of GetRange() would be just covering up that bug. It's confusing. Maybe it's just a relic from some older code, grandfathered into the current API. - What is the max parameter in BaseSelect.GetRange() really for? As the headline says... BaseSelect.GetRange()returns the min and max values for a segment in a selection. But it has a second parameter (besides the segment), called max. Now, maxis not needed from a structural point of view. The selection contains a known number of segments, which contain one tuple each. Other than e.g. BaseSelect.SelectAll(), where we actually need to pass a max value because the BaseSelect does not know the total number of elements that may possibly selected, GetRange()does not deal with unknowns. The documentation says about this parameter: max (int) – The maximum value for the returned elements numbers. Usually pass PolygonObject.GetPolygonCount() or PointObject.GetPointCount() or the edge count of the object. The method makes sure they are < max. I would interpret that as assurance that any value we get returned is smaller than max. So if there is a segment (1,5) and max = 3, then we'd get (1,3) back. (I can't for the life of me think of a reason why I would want that, but hey.) That is, however, not what I really get. If I use a value for maxthat is smaller than the value GetRange tries to return, I receive TypeError: 'NoneType' object is not iterable. If I use a ridiculous large value for max, no apparent effects happen at all, not even a perceivable increase in runtime. So, I have a parameter that at best does nothing, and at worst throws an error. I don't know whether this is a bug (R21) or whether I just don't understand the function. The C++ doc says about the same parameter: The maximum value for a and b. Makes sure a and b are < maxElements. Pass LIMIT<Int32>::MAX for no additional checks. That supports my understanding of the parameter, but does not explain why I get a TypeErrorinstead. (It also doesn't explain why a limit on the selection is so important that it justifies an additional parameter when the check could easily be done on the returned values. Or: what happens, if both returned limits of the segment are larger than max.) btw, it would be nice if the Python docs also contained the additional info from the C++ doc: The spans are always sorted (spans with higher index have higher numbers for a/b), also b is always >= a. - RE: Controlling tessellation of c4d.SplineObject in python @android Here's a thread for reference regarding the limitation of a Generator spline: - RE: Python, tool attributes and hotkeys @John_Do said in Python, tool attributes and hotkeys: @Cairyn Sorry for the misunderstanding, in my mind hotkeys = shortcuts, I didn't want to make any particular distinction. What you described is also called Sticky Keys in some softwares. Yeah, the nomenclature for keyboard shortcuts is unfortunately all over the place. I know Sticky Keys as the type of behaviour where you type a key and release it, but the key still registers as pressed, until it is pressed a second time. This is the case for e.g. Windows' "easy access" for qualifier keys. (No idea whether this is still called that; I'm on a German system.) But sadly every system, every application, and every user uses the terms as they just come to mind, so it's fairly worthless now without an explanatio every time. I was just pointing out the "hotkey" as Cinema 4D actually uses this term in its API. To answer your questions : I want to be able to modify tool settings / attributes while the tool is enabled AND in interactive mode. Since I don't want to bother with gazillions of shortcuts and multiple keyboards, it has to be context sensitive so I can use the same set of keys with many tools. But a picture is worth a thousand words, so I made a little demo of what I want to achieve in C4D : Modal Bevel Shortcuts demo I understand what you want to do... I suppose as long as you reserve the necessary keys for your scripts/tools, it's possible to get the effect. I was actually thinking along the lines "if you want these keys to work only when the tools are active, and have their original meaning if something else is active" which is a much more difficult goal - it would force you to remember the original function in some way, and jump there if your target tools are not active. I actually have no solution for that, as Cinema does not have an additional context sensitive layer for keyboard shortcuts that depends on tools. (I often wish for that.) I might offer the functions to swap out the keyboard shortcuts dynamically, but you probably don't want that and have found these already anyway ;-) - Is there is a way to gather all the commands in one file / script but output as many commands as shortcuts needed ? Right now I have one script per command, it's a bit clunky. I guess plugin and command registering is the answer ? You can create one file that registers several command plugins. You need a separate ID from the PluginCafé for each, but it's easy to achieve. The plugin needs to go into the plugin directory then, naturally. - RE: Controlling tessellation of c4d.SplineObject in python Doesn't look coarse to me, neither as script nor as generator Generator: import c4d def main(): obj = c4d.SplineObject(4, c4d.SPLINETYPE_BSPLINE) p1 = c4d.Vector(0.0, 0.0, 0.0) p2 = c4d.Vector(100.0, 0.0, 0.0) p3 = c4d.Vector(100.0, 100.0, 0.0) p4 = c4d.Vector(0.0, 100.0, 0.0) obj.SetAllPoints([p1, p2, p3, p4]) obj[c4d.SPLINEOBJECT_INTERPOLATION] = 2 # here: uniform obj[c4d.SPLINEOBJECT_SUB] = 20 # number of subdiv points obj.Message (c4d.MSG_UPDATE) return obj Did you use enough points? set the interpolation and subdivision? There is not much room for settings here... Note that a Python generator cannot act as spline itself (see some other threads for that), even if it can contain a spline. There is currently no Python Spline Generator in C4D. - RE: How to use GetPolygonW/R under Python? ...if at. - How...) - RE: Python, tool attributes and hotkeys (It just came to mind that you may not mean "hotkey" but "keyboard shortcut". A hotkey is a special kind of keyboard shortcut that takes effect while it is pressed, so it switches on when you press and keep pressing, and switches off when released. The hotkeys are the ones that require the PLUGINFLAG_COMMAND_HOTKEYflag. For other keyboard shortcuts that trigger an action on release only you can use a simple script where applicable and don't necessarily require a command plugin.) - RE: Python, tool attributes and hotkeys I'm not quite sure what you are looking for... the code does change the settings in the tool, not just "the UI", provided you define the function tool()which the script log automatically does. If you expect the default tool settings to change: no, that is not what the script does. If you expect the script to trigger the tool (cause the tool to execute): no, the script only changes the settings, you still have to click Applyor New Transform. To execute the Bevel tool, you can use SendModelingCommandinstead of the stuff the Script Log recommends: import c4d from c4d import gui, utils def main(): doc.SetMode(c4d.Mpolygons) doc.StartUndo() doc.AddUndo(c4d.UNDOTYPE_CHANGE, op) settings = c4d.BaseContainer() # Settings settings[c4d.MDATA_BEVEL_MASTER_MODE] = c4d.MDATA_BEVEL_MASTER_MODE_CHAMFER settings[c4d.MDATA_BEVEL_OFFSET_MODE] = c4d.MDATA_BEVEL_OFFSET_MODE_FIXED settings[c4d.MDATA_BEVEL_RADIUS] = 10.0 res = utils.SendModelingCommand(command = c4d.ID_XBEVELTOOL, list = [op], mode = c4d.MODELINGCOMMANDMODE_POLYGONSELECTION, bc = settings, doc = doc) doc.SetAction(c4d.ID_MODELING_MOVE) doc.EndUndo() c4d.EventAdd() if res is False: print "Something went wrong." elif res is True: print "Command successful." elif isinstance(res, list): print "Oops, you got new objects?" # Execute main() if __name__=='__main__': main() Regarding the hotkeys: I have a hunch that you want to use C4D in a way that is not really supported. A keyboard shortcut triggers a script or a tool or a command - hotkeys are global and depend on the command behind it. You can make them context sensitive by checking the current tool in the called script, and then react accordingly, but that still requires that you bind that key to that command, not the other way round. You may be able to catch key press events from the messaging system and evaluate them yourself, but that would require much programming experience and API knowledge, and you will probably break the shortcut system. If you just want to define your own hotkeys, you will need to program a command plugin with the flag PLUGINFLAG_COMMAND_HOTKEYset. That's not context sensitive, again, you would have to program any context dependencies yourself. At least you wouldn't need to have a preferences plugin to assign them; any script or plugin can have its keyboard shortcut assigned on the Customize Command window. Provided I even understand correctly what you want... if you could describe an actual usecase...? Learn more about Python for C4D scripting: - RE: How to work with LoadFile from content browser. - RE: Add and Remove Edge Loops Poly Object Does your setup react to the global Level of Detail controls? If not, could you use a local LOD object with differently subdivided children?
https://plugincafe.maxon.net/user/cairyn/posts
CC-MAIN-2020-40
refinedweb
4,027
62.68
24 April 2008 16:12 [Source: ICIS news] SINGAPORE (ICIS news)--Could the Middle East one day no longer be the choice destination for building petrochemical capacity? This might seem a bizarre question to ask in the midst of the biggest capacity build-up in the history of the region. For example, ?xml:namespace> But the question is being asked by senior western industry executives who see an opportunity to add basic petrochemical capacity via non-gas routes beyond 2012. Perhaps the first task might be, though, to get through the looming oversupply crisis which could last far longer than many people expect. That aside, though, anybody with a long-term vision needs to examine whether there will be sufficient gas feedstock in the Gulf Cooperation Council (GCC) for another big wave of investment. Allen Kirkley, vice-president of strategy and portfolio for Shell Chemicals, raised this very important point in a recent presentation. “Higher engineering and procurement costs and labour issues are already impacting the competitiveness of new “It is increasingly clear that there are limits to the availability of low-cost ethane in the Kirkley talks about the Countries such as But these are very uncertain investment plays because of bureaucracy in The big issue - along with tightness of supply - is the emergence of alternative values for gas which didn’t exist a few years ago. In its June 2007 issue, the ICIS/International e-Chem “Your comments about oil price parity were interesting because this has occurred over the last two months,” said Helena Wisden, editor, Heren LNG Markets*. “A supply deal was struck between Qatargas 4 and PetroChina, which equates to $16/million metric British thermal units (mmBtu) at a crude price of just below $90/bbl. The price is based on a formula linked to the cost of oil,” she added. The deal - announced earlier this month - will run for 25 years with supply at 3m tonne/year. Qatargas (Qatar Liquefied Gas Co) 4 is a joint venture of Qatar Petroleum and Shell. Wisden added a similar contract was recently struck between The shift in LNG markets has occurred partly because the start-up of liquefaction facilities has been delayed due to engineering, labour and raw material shortages. Meanwhile, many of the receiving or import terminals designed to receive this new capacity are already in place and demand is surging, in If industry forecasts from two or three years ago were to be believed, more liquefaction capacity should soon have been on stream in “The Iranians, currently net gas importers, are being held back by political instability and sanctions which limit their ability to buy the necessary equipment,” said Wisden. “If “However, I suspect that such pipelines are at least 20 years away." The less pipeline gas there is available the tighter LNG markets might remain. Wisden said that further delays to new liquefaction capacity were also possible. “High pricing in long-term contracts is here to stay, for the medium-term at least. More immediately, spot prices could easily spike to as high as $23-24/mmbtu this winter - the traditional peak demand season,” she said. Demand is being boosted by ongoing safety scares at Japanese nuclear power plants. Some 10% of nuclear-based generating capacity has been closed down, forcing LNG-fed stations to run flat out. Building further nuclear capacity in “This is a long-term shift in the Japanese market. Traditionally, summer prices fall because of lower demand for heating. What we have seen this summer for the first time is pricing in Asia holding up, largely because of the Japanese factor but also due to ongoing problems with LNG storage tanks in The Iranians decided to renegotiate the deal when crude increased to around $70/bbl, but now the LNG plants that would have supplied The steep rise in LNG prices has already put paid to Gas Authority of India’s plans for a cracker based on imported LNG at Kerala. The Oil and Natural Gas Corp mixed-feed cracker, based on imported LNG from Crackers based on imported LNG are in general off the cards, though - no matter where they are located. Even In The milestone LNG deal between Qatargas 4 and PetroChina is an indication of the tremendous rise in demand for LNG in “Two terminals have been built in “The Qatargas and PetroChina deal is the first time oil-price parity has been achieved with a Chinese buyer and signals the seriousness of the country’s ambitions as a major importer,” she said. So, has a global market emerged for LNG? “Trade is thin because of the delays in liquefaction plants and so some argue that a global LNG market doesn’t exist,” said Wisden. “I would disagree as the price for big contract deals, such as the one between Here’s a further scary thought: sellers in the LNG industry are trying to talk up the prospect of pricing eventually being above crude because of the environmental benefits of switching from oil to natural gas consumption. “If a global carbon-credit trading market takes off this could happen. Using LNG instead of oil would become a good means of gaining credits,” said Wisden. Rising oil prices, a possible global recession and the biggest capacity surge in the history of the petrochemicals industry are big enough problems by themselves. Yet another headache is the growing uncertainties over future feedstock supply. There must, surely, be easier ways of making a living than working in petrochemicals. * Heren Energy
http://www.icis.com/Articles/2008/04/24/1120369/insight-lng-changing-mideast-petchem-patterns.html
CC-MAIN-2014-35
refinedweb
919
53.44
SC_ScoresController_Release() Decrements the object's reference count, and deletes the object if the counter reaches 0. Synopsis: #include <scoreloop/sc_scores_controller.h> SC_DEPRECATED SC_PUBLISHED void SC_ScoresController_Release(SC_ScoresController_h self) Since: BlackBerry 10.0.0 Deprecated in BlackBerry 10.3.0 Arguments: - self An opaque handle for the current controller instance. Library:libscoreloopcore (For the qcc command, use the -l scoreloopcore option to link against this library) Description: This method decrements the reference count for the current instance by 1. The current controller instance will be automatically deleted when the reference count equals 0. Please note that this method is NULL pointer safe. That is, NULL as an argument will not cause an exception. Returns: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.scoreloop.lib_ref/topic/sc_scorescontroller_release.html
CC-MAIN-2014-35
refinedweb
133
52.76
Hi, I am a quite intensive equation (sin/cos double) which is taking about 40ms at 1MHz on a Mega328. Compiler is WinAVR 20090313. Changing the compiler options from -Os to -O3 or even -O0 does not change the execution time at all. Do these options affect the execution time of the math.h functions or is the library precompiled? #include <avr/io.h> #include <math.h> int main(void){ volatile double distance; volatile double a1; volatile double a2; volatile double b1; volatile double b2; volatile double rearth; a1 = 1.2; a2 = 1.1; b1 = 2.2; b2 = 2.3; rearth = 6378.137; DDRB = 0xFF; while(1) { PORTB = PORTB ^ 0xFF; //led on pb5 distance = rearth * acos( sin(a1) * sin(a2) + cos(a1) * cos(a2) * cos(b2 - b1) ); } } aaaaahhh, I am of course not an equation, I am computing an equation :-) Execution time of library functions would only change if the compiler is able to inline a specific function (eg. the family of str... functions is a good candidate for this). In the case of math functions, those functions are precompiled and there is very little you can do about it. Your best option would be to find a simpler solution to your problem, if such a thing is mathematicaly possible, of course. use the function sincos, or if not available, usa a library/source of it. This removes two instances of sin/cos call, probably 13 milliseconds. Further, if you want speed up things, use this or a lookuptable+intepolation. If your variables are volatile, your optimizer has no chance to speed your code up! Be careful with volatile. If you don´t need it, change the variables to normal ones. The math-Functions are pre-compiled, because they´re located in libm.a. To change the optimization of this functions, you have to re-compile the library or you can compile your own version of sin(), cos(),... in the way you look for the GNU source files (GPL) and compile it with your own compiler flags. I realy hate to say that, but > taking about 40ms at 1MHz on a Mega328. There ist a relatively easy 'solution'. Remove the CKDIV8 Fuse, your processor runs at 8Mhz instead of just 1 und the calculation is done in 5ms instead of 40. Karl Heinz Buchegger wrote: > Remove the CKDIV8 Fuse, your > processor runs at 8Mhz instead of just 1 und the calculation is done in > 5ms instead of 40. However, that's only possible of Vcc is high enough. (That's the main reason why the devices ship with CKDIV8 programmed.) Also, if the device does have a CKDIV8 fuse (rather than four different RC oscillators, as it's been the case on older AVRs), you can use #include <avr/power.h> ... clock_prescale_set(clock_div_1); in order to achieve the same effect at run-time as unprogramming the CKDIV8 fuse would. Thanks for your replies! @Karl Heinz: I had the impression that the stuff is precompiled... I am still in a very early phase in the design and don't know yet how much precision I need. So I'm starting with the highest complexity and if the system works I'll try to reduce it. @Guest: Thanks for pointing that out, I was afraid the compiler might optimise my completely useless calculation away and therefore declared them as volatile. I'll have a try without tonight. The final system will run at 16MHz. I just wrote the code yesterday to get an impression how long it would take to compute the equation. The scope on PORTB shows an execution time of about 2.5ms at 16MHz, the 40ms figure was taken from the instruction set simulator at 1MHz. Anyway, I'm doing the calculation 10 times per second so there's still some margin. Guest wrote: > @Guest: Thanks for pointing that out, I was afraid the compiler might > optimise my completely useless calculation away It will, yes. But to prevent this, you have to do a little more. Placing the entire function into a separate compilation unit might be a good starting point. As the earth's radius seldom changes :), make that a "const". Make a1, a2, b1, b2 parameters to the function, and return the result. If you call it from main() (without using the option -combine when compiling), it should make a real CALL to the function, so you can debug it. Inside main, you can still place the result into a global (and maybe even volatile) variable to prevent the compiler from throwing the unused result away. Ok, I tried it without the volatiles. The calculation is now in a function as Joerg suggested. The execution time is still not depending on the optimisation settings. Seems that there will be no gain without recompiling the library. I'll just leave it like that now and once I run into performance problems start asking questions how to recompile the lib :-) Thanks! Guest wrote: > The execution time is still not depending > on the optimisation settings. Sure, because the major time is spent inside library functions. > Seems that there will be no gain without recompiling the library. That won't help. The library is already using hand-optimized assembly code. No one has yet pointed out that this is an ARM forum, not an AVR forum! ;) Are you lost? However, firstly the library is provided as object code, and will have already been optimised when it was compiled, so compiler optimisations will not have any effect. Second, the part has no hardware FPU, and 1MHz is very slow. I'd say that 40ms is pretty good going under those circumstances, and wonder that you are at all surprised. Arguably you have the wrong part for your application (depending on the application). However it is probably possible to speed things up considerably using fixed-point arithmetic and the CORDIC algorithm. Here's an article on exactly that: with a source code library you can download and adapt too. Another way to speed this up at the expense of a perhaps significant chunk of Flash is to use a look-up table. The larger the lookup table, the better the resolution you might achieve. You could reduce the table size at the expense of processing time by using interpolation for intermediate values. And remember that you only need a lookup table for a single quadrant (pi/2 radians), the other quadrants can easily be determined from that. Clifford
https://embdev.net/topic/153896
CC-MAIN-2018-26
refinedweb
1,075
74.08
Needless to say that Docker is pretty awesome. This blog itself is now powered by Docker + Capistrano and I can deploy a new post simply by doing bundle exec cap deploy. What's more with Docker, I can move to any hosting provider and setup everything in 10 minutes. Also, gone are the days when I had to fiddle to Chef/Puppet scripts to try and setup servers only to find a new Ruby/JDK/Node.js version is out so I need to modify those scripts again. With Docker all you need to install on a new server is probably - - Git and - Docker And maybe setup a user with whom you will deploy the application. If your mind is not blown already, allow me to demonstrate with an application. Let's say we have a web application, maybe it is a Rails application, all we need is a Dockerfile (for example) - # Dockerfile FROM phusion/passenger-ruby22:0.9.17 MAINTAINER Rocky Jaiswal "rocky.jaiswal #Enable env vars ADD ./app-env.conf /etc/nginx/main.d/app-env.conf # Add the nginx site and config ADD ./webapp.conf /etc/nginx/sites-enabled/lehrer_webapp.conf # Add the Rails app RUN mkdir /home/app/lehrer WORKDIR /home/app/lehrer ADD . /home/app/lehrer RUN bundle install --binstubs --deployment --without test development RUN bundle exec rake assets:precompile RUN chown -R app:app /home/app # Clean up APT and bundler when done. RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* And a capistrano deploy script - #production.rb server 'AA.BB.CC.DD', user: 'app', roles: %w{docker} namespace :custom do task :setup_container do on roles(:docker) do |host| image_name = "lehrer" #we use this for container name also puts "================Starting Docker setup====================" execute "cp /home/app/database.yml #{deploy_to}/current/config/database.yml" execute "cp /home/app/secrets.yml #{deploy_to}/current/config/secrets.yml" execute "cd #{deploy_to}/current && docker build --rm=true --no-cache=false -t rockyj/#{image_name} ." execute "docker stop #{image_name}; echo 0" execute "docker rm -fv #{image_name}; echo 0" execute 'docker run -tid -p 80:80 -e "PASSENGER_APP_ENV=production" -e "RAILS_ENV=production" --name lehrer rockyj/lehrer' execute "docker exec -it lehrer bundle exec rake db:migrate" end end end after "deploy:finishing", "custom:setup_container" For the Dockerfile, the base image (phusion-passenger-docker) does a lot of groundwork for us so all we need to is setup the code and some configuration. You can test the image build and container locally to your heart's content before deploying. The capistrano script in the end Git clones our code, builds the docker image for our code and runs a container based on the image. All with one command - bundle exec cap production deploy Once your deployment finishes, you have a working application and all you installed on your server was Docker and Git. That is pretty awesome IMHO! Code for this sample application is available on Github. Database Setup Some of you might say, I pulled a fast one and did not talk about the database. I think there are two options for that - - Run the database itself as a container. In this case you need to install docker-compose for the two containers to talk to each other. - Run the database on the host / separate machine on the network. I like this option personally since unlike the application code, the database is a pretty static and stable piece of software. In this case you need to install PostgreSQL as usual and configure it so that it allows access from the Docker container. This is pretty standard for any application. Database on the Docker host Simple applications / test setup usually has the application server and the database server running on the same machine. To enable a Docker container to connect to the PostgreSQL instance on the Docker host you will need to change two files. - sudo vim /etc/postgresql/9.3/main/postgresql.conf Add the line - listen_addresses = 'localhost, 172.17.42.1' - sudo vim /etc/postgresql/9.3/main/pg_hba.conf Add the line - host all all 172.17.0.0/24 md5 Then restart PostgreSQL. These two changes allow connections to PostgreSQL from the Docker container. Basically we allow the Docker's internal network's bridge and IP to connect to PostgreSQL. If your container's bridge and IP differ, please update the two files. You can find these two by running ifconfig inside the container and on the host machine.
http://rockyj.in/2015/09/06/docker_capistrano.html
CC-MAIN-2017-09
refinedweb
745
55.84
What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added. Note that I also have a list Coordinates that stores the same information. The list works as no repeats are added.(By checking) However, the text file has the same coordinates appended over and over again even though it theoretically shouldn't as it is contained within the same if-block as the list. import requests pokemon_url = '' while True: response = requests.get(pokemon_url) response.raise_for_status() pokemon = response.json()[0:] Sighting = 0 Coordinates = [None] * 100 for num in range(len(pokemon)): if pokemon[num]['pokemon_name'] == 'Aerodactyl': Lat = pokemon[num]['latitude'] Long = pokemon[num]['longitude'] if (Lat, Long) not in Coordinates: Coordinates[Sighting] = (Lat, Long) file = open("aerodactyl.txt", "a") file.write(str(Lat) + "," + str(Long) + "\n") file.close Sighting += 1 You need to put your Sighting and Coordinates variables outside of the while loop if you do not want them to reset on every iteration. However, there are a lot more things wrong with the code. Without trying it, here's what I spot: whileloop. Please don't do this to the poor website. You'll essentially be spamming requests. file.closeshould be file.close(), but overall you should only need to open the file once, not on every single iteration of the loop. Open it once, and close once you're done (assuming you will add an exit condition). 0( response.json()[0:]) is unnecessary. By default the list starts at index 0. This may be a convoluted way to get a new list, but that seems unnecessary here. Coordinatesshould not be a hard-coded list of 100 Nones. Just use a setto track existing coordinates. Sightingaltogether. It doesn't make sense if you're re-issuing the request over and over again. If you want to iterate through the pokémon from one response, use enumerateif you need the index.
https://codedump.io/share/WSpCshzRriOX/1/if-statement-seemingly-ignored-by-write-operation
CC-MAIN-2016-44
refinedweb
352
58.69
3 Subjects Written by Scott Gardner At this point, you know what an observable is, how to create one, how to subscribe to it, and how to dispose of things when you’re done. Observables are a fundamental part of RxSwift, but they’re essentially read-only. You may only subscribe to them to get notified of new events they produce. A common need when developing apps is to manually add new values onto an observable during runtime to emit to subscribers. What you want is something that can act as both an observable and as an observer. That something is called a Subject. In this chapter, you’ll learn about the different types of subjects in RxSwift, see how to work with each one and why you might choose one over another based on some common use cases. You’ll also learn about relays, which are wrappers around subjects. We’ll unwrap that later! Getting started Run ./bootstrap.sh in the starter project folder RxPlayground, which will open the project for this chapter, and select RxSwiftPlayground in the Project navigator. You’ll start out with a quick example to prime the pump. Add the following code to your playground: example(of: "PublishSubject") { let subject = PublishSubject<String>() } You just created a PublishSubject. It’s aptly named, because, like a newspaper publisher, it will receive information and then publish it to subscribers. It’s of type String, so it can only receive and publish strings. After being initialized, it’s ready to receive strings. Add the following code to your example: subject.on(.next("Is anyone listening?")) This puts a new string onto the subject. Nothing is printed out yet, because there are no observers. Create one by subscribing to the subject. Add the following code to the example: let subscriptionOne = subject .subscribe(onNext: { string in print(string) }) You created a subscription to subject just like in the last chapter, printing next events. But still, nothing shows up in Xcode’s output console. What gives? What’s happening here is that a PublishSubject only emits to current subscribers. So if you weren’t subscribed to it when an event was added to it, you won’t get it when you do subscribe. Think of the tree-falling-in-the-woods analogy. If a tree falls and no one’s there to hear it, does that make your illegal logging business a success? :] To fix things, add this code to the end of the example: subject.on(.next("1")) Notice that, because you defined the publish subject to be of type String, only strings may be added to it. Now, because subject has a subscriber, it will emit the added value: --- Example of: PublishSubject --- 1 In a similar fashion to the subscribe operators, on(.next(_:)) is how you add a new next event onto a subject, passing the element as the parameter. And just like subscribe, there’s shortcut syntax for subjects. Add the following code to the example: subject.onNext("2") onNext(_:) does the same thing as on(.next(_)). It’s just a bit easier on the eyes. And now the 2 is also printed: --- Example of: PublishSubject --- 1 2 With that gentle intro, now it’s time to dig in and learn all about subjects. What are subjects? Subjects act as both an observable and an observer. You saw earlier how they can receive events and also be subscribed to. In the above example, the subject received next events, and for each of them, it turned around and emitted it to its subscriber. There are four subject types in RxSwift: PublishSubject: Starts empty and only emits new elements to subscribers. BehaviorSubject: Starts with an initial value and replays it or the latest element to new subscribers. ReplaySubject: Initialized with a buffer size and will maintain a buffer of elements up to that size and replay it to new subscribers. AsyncSubject: Emits only the last nextevent in the sequence, and only when the subject receives a completedevent. This is a seldom used kind of subject, and you won’t use it in this book. It’s listed here for the sake of completeness. RxSwift also provides a concept called Relays. RxSwift provides two of these, named PublishRelay and BehaviorRelay. These wrap their respective subjects, but only accept and relay next events. You cannot add a completed or error event onto relays at all, so they’re great for non-terminating sequences. Note: Did you notice the additional import RxRelayin this chapter’s playground? Originally, relays were part of RxCocoa, RxSwift’s suite of reactive Cocoa extensions and utilities. However, relays are a general-use concept that are also useful in non-Cocoa development environments such as Linux and command line tools. So it was split into its own consumable module, which RxCocoa depends on. Next, you’ll learn more about these subjects and relays and how to work with them, starting with publish subjects. Working with publish subjects Publish subjects come in handy when you simply want subscribers to be notified of new events from the point at which they subscribed, until either they unsubscribe, or the subject has terminated with a completed or error event. In the following marble diagram, the top line is the publish subject and the second and third lines are subscribers. The upward-pointing arrows indicate subscriptions, and the downward-pointing arrows represent emitted events. The first subscriber subscribes after 1 is added to the subject, so it doesn’t receive that event. It does get 2 and 3, though. And because the second subscriber doesn’t join in until after 2 is added, it only gets 3. Returning to the playground, add this code to the bottom of the same example: let subscriptionTwo = subject .subscribe { event in print("2)", event.element ?? event) } Events have an optional element property that contains the emitted element for next events. You use the nil-coalescing operator here to print the element if there is one; otherwise, you print the event. As expected, subscriptionTwo doesn’t print anything out yet because it subscribed after the 1 and 2 were emitted. Now add this code: subject.onNext("3") The 3 is printed twice, once for subscriptionOne and once for subscriptionTwo. 3 2) 3 Add this code to terminate subscriptionOne and then add another next event onto the subject: subscriptionOne.dispose() subject.onNext("4") The value 4 is only printed for subscription 2), because subscriptionOne was disposed. 2) 4 When a publish subject receives a completed or error event, also known as a stop event, it will emit that stop event to new subscribers and it will no longer emit next events. However, it will re-emit its stop event to future subscribers. Add this code to the example: // 1 subject.onCompleted() // 2 subject.onNext("5") // 3 subscriptionTwo.dispose() let disposeBag = DisposeBag() // 4 subject .subscribe { print("3)", $0.element ?? $0) } .disposed(by: disposeBag) subject.onNext("?") From the top, you: - Add a completedevent onto the subject, using the convenience method for on(.completed). This terminates the subject’s observable sequence. - Add another element onto the subject. This won’t be emitted and printed, though, because the subject has already terminated. - Dispose of the subscription. - Subscribe to the subject, this time adding its disposable to a dispose bag. Maybe the new subscriber 3) will kickstart the subject back into action? Nope, but you do still get the completed event replayed. 2) completed 3) completed Actually, subjects, once terminated, will re-emit their stop event to future subscribers. So it’s a good idea to include handlers for stop events in your code, not just to be notified when it terminates, but also in case it is already terminated when you subscribe to it. This can sometimes be the cause of subtle bugs, so watch out! You might use a publish subject when you’re modeling time-sensitive data, such as in an online bidding app. It wouldn’t make sense to alert the user who joined at 10:01 am that at 9:59 am there was only 1 minute left in the auction. That is, of course, unless you like 1-star reviews of your bidding app. Sometimes you want to let new subscribers know what was the latest emitted element, even though that element was emitted before the subscription. For that, you’ve got some options. Publish subjects don’t replay values to new subscribers. This makes them a good choice to model events such as “user tapped something” or “notification just arrived.” Working with behavior subjects Behavior subjects work similarly to publish subjects, except they will replay the latest next event to new subscribers. Check out this marble diagram: The first line at the top is the subject. The first subscriber on the second line down subscribes after 1 but before 2, so it receives 1 immediately upon subscription, and then 2 and 3 when they’re emitted by the subject. Similarly, the second subscriber subscribes after 2 but before 3, so it receives 2 immediately and then 3 when it’s emitted. Add this code to your playground, after the last example: // 1 enum MyError: Error { case anError } // 2 func print<T: CustomStringConvertible>(label: String, event: Event<T>) { print(label, (event.element ?? event.error) ?? event) } // 3 example(of: "BehaviorSubject") { // 4 let subject = BehaviorSubject(value: "Initial value") let disposeBag = DisposeBag() } Here’s the play-by-play: - Define an error type to use in upcoming examples. - Expanding upon the use of the ternary operator in the previous example, you create a helper function to print the element if there is one, an error if there is one, or else the event itself. How convenient! - Start a new example. - Create a new BehaviorSubjectinstance. Its initializer takes an initial value. Note: Because BehaviorSubjectalways emits its latest element, you can’t create one without providing an initial value. If you can’t provide an initial value at creation time, that probably means you need to use a PublishSubjectinstead, or model your element as an Optional. Next, add the following code to the example: subject .subscribe { print(label: "1)", event: $0) } .disposed(by: disposeBag) You subscribe to the subject immediately after it was created. Because no other elements have been added to the subject, it replays its initial value to the subscriber. --- Example of: BehaviorSubject --- 1) Initial value Now, insert the following code right before the previous subscription code, but after the definition of the subject: subject.onNext("X") The X is printed, because now it’s the latest element when the subscription is made. --- Example of: BehaviorSubject --- 1) X Add the following code to the end of the example. But first, look it over and see if you can determine what will be printed: // 1 subject.onError(MyError.anError) // 2 subject .subscribe { print(label: "2)", event: $0) } .disposed(by: disposeBag) With this code, you: - Add an error event onto the subject. - Create a new subscription to the subject. This prints: 1) anError 2) anError Did you figure out that the error event will be printed twice, once for each subscription? If so, right on! Behavior subjects are useful when you want to pre-populate a view with the most recent data. For example, you could bind controls in a user profile screen to a behavior subject, so that the latest values can be used to pre-populate the display while the app fetches fresh data. Behavior subjects replay their latest value to new subscribers. This makes them a good choice to model state such as “request is currently loading,” or “the time is now 9:41.” What if you wanted to show more than the latest value? For example, on a search screen, you may want to show the most recent five search terms used. This is where replay subjects come in. Working with replay subjects Replay subjects will temporarily cache, or buffer, the latest elements they emit, up to a specified size of your choosing. They will then replay that buffer to new subscribers. The following marble diagram depicts a replay subject with a buffer size of 2. The first subscriber (middle line) is already subscribed to the replay subject (top line) so it gets elements as they’re emitted. The second subscriber (bottom line) subscribes after 2, so it gets 1 and 2 replayed to it. Keep in mind, when using a replay subject, that this buffer is held in memory. You can definitely shoot yourself in the foot here, such as if you set a large buffer size for a replay subject of some type whose instances each take up a lot of memory, like images. Another thing to watch out for is creating a replay subject of an array of items. Each emitted element will be an array, so the buffer size will buffer that many arrays. It would be easy to create memory pressure here if you’re not careful. Add this new example to your playground: example(of: "ReplaySubject") { // 1 let subject = ReplaySubject<String>.create(bufferSize: 2) let disposeBag = DisposeBag() // 2 subject.onNext("1") subject.onNext("2") subject.onNext("3") // 3 subject .subscribe { print(label: "1)", event: $0) } .disposed(by: disposeBag) subject .subscribe { print(label: "2)", event: $0) } .disposed(by: disposeBag) } From the top, you: - Create a new replay subject with a buffer size of 2. Replay subjects are initialized using the type method create(bufferSize:). - Add three elements onto the subject. - Create two subscriptions to the subject. The latest two elements are replayed to both subscribers; 1 never gets emitted, because 2 and 3 are added onto the replay subject with a buffer size of 2 before anything subscribed to it. --- Example of: ReplaySubject --- 1) 2 1) 3 2) 2 2) 3 Next, add the following code to the example: subject.onNext("4") subject .subscribe { print(label: "3)", event: $0) } .disposed(by: disposeBag) With this code, you add another element onto the subject, and then create a new subscription to it. The first two subscriptions will receive that element as normal because they were already subscribed when the new element was added to the subject, while the new third subscriber will get the last two buffered elements replayed to it. 1) 4 2) 4 3) 3 3) 4 You’re getting pretty good at this stuff by now, so there should be no surprises, here. But what would happen if you threw a wrench into the works? Add this line of code right after adding 4 onto the subject, before creating the third subscription: subject.onError(MyError.anError) This may surprise you. And if so, that’s OK. Life’s full of surprises. :] 1) 4 2) 4 1) anError 2) anError 3) 3 3) 4 3) anError What’s going on, here? The replay subject is terminated with an error, which it will re-emit to new subscribers — you learned this earlier. But the buffer is also still hanging around, so it gets replayed to new subscribers as well, before the stop event is re-emitted. Add this line of code immediately after adding the error: subject.dispose() By explicitly calling dispose() on the replay subject beforehand, new subscribers will only receive an error event indicating that the subject was already disposed. 3) Object `RxSwift...ReplayMany<Swift.String>` was already disposed. Explicitly calling dispose() on a replay subject like this isn’t something you generally need to do. If you’ve added your subscriptions to a dispose bag, then everything will be disposed of and deallocated when the owner — such as a view controller or view model — is deallocated. It’s just good to be aware of this little gotcha for those edge cases. Note: In case you’re wondering what is a ReplayMany, it’s an internal type that is used to create replay subjects. By using a publish, behavior, or replay subject, you should be able to model almost any need. There may be times, though, when you simply want to go old-school and ask an observable type, “Hey, what’s your current value?” Relays FTW here! Working with relays You learned earlier that a relay wraps a subject while maintaining its replay behavior. Unlike other subjects — and observables in general — you add a value onto a relay by using the accept(_:) method. In other words, you don’t use onNext(_:). This is because relays can only accept values, i.e., you cannot add an error or completed event onto them. A PublishRelay wraps a PublishSubject and a BehaviorRelay wraps a BehaviorSubject. What sets relays apart from their wrapped subjects is that they are guaranteed to never terminate. Add this new example to your playground: example(of: "PublishRelay") { let relay = PublishRelay<String>() let disposeBag = DisposeBag() } Nothing new here versus creating a PublishSubject, except the name. However, in order to add a new value onto a publish relay, you use the accept(_:) method. Add this code to your example: relay.accept("Knock knock, anyone home?") There are no subscribers yet, so nothing is emitted. Create a subscriber and then add another value onto relay: relay .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) relay.accept("1") The output is the same as if you’d created a publish subject instead of a relay: --- Example of: PublishRelay --- 1 There is no way to add an error or completed event onto a relay. Any attempt to do so such as the following will generate a compiler error (don’t add this code to your playground, it won’t work): relay.accept(MyError.anError) relay.onCompleted() Remember that publish relays wrap a publish subject and work just like them, except the accept part and that they will not terminate. How about something a little more interesting? Say hello to my little friend, BehaviorRelay. Behavior relays also will not terminate with a completed or error event. Because it wraps a behavior subject, a behavior relay is created with an initial value, and it will replay its latest or initial value to new subscribers. A behavior relay’s special power is that you can ask it for its current value at any time. This feature bridges the imperative and reactive worlds in a useful way. Add this new example to your playground: example(of: "BehaviorRelay") { // 1 let relay = BehaviorRelay(value: "Initial value") let disposeBag = DisposeBag() // 2 relay.accept("New initial value") // 3 relay .subscribe { print(label: "1)", event: $0) } .disposed(by: disposeBag) } Here’s what you’re doing this time: - You create a behavior relay with an initial value. The relay’s type is inferred, but you could also explicitly declare the type as BehaviorRelay<String>(value: "Initial value"). - Add a new element onto the relay. The subscription receives the latest value. --- Example of: BehaviorRelay --- 1) New initial value Next, add this code to the same example: // 1 relay.accept("1") // 2 relay .subscribe { print(label: "2)", event: $0) } .disposed(by: disposeBag) // 3 relay.accept("2") From the top: - Add a new element onto the relay. - Create a new subscription to the relay. - Add another new element onto the relay. The existing subscription 1) receives the new value 1 added onto the relay. The new subscription receives that same value when it subscribes, because it’s the latest value. And both subscriptions receive the 2 when it’s added onto the relay. 1) 1 2) 1 1) 2 2) 2 Finally, add the following piece of code to the last example: print(relay.value) Remember, behavior relays let you directly access their current value. In this case, the latest value added onto the relay is 2, so that’s what is printed to the console. 2 This is very helpful when bridging the imperative world with the reactive world. You’ll try this in the second challenge of this chapter. Behavior relays are versatile. You can subscribe to them to be able to react whenever a new next event is emitted, just like any other subject. And they can accommodate one-off needs, such as when you just need to check the current value without subscribing to receive updates. Challenges Put your new super subject skills to the test by completing these challenges. There are starter and finished versions for each challenge in the exercise files. Challenge 1: Create a blackjack card dealer using a publish subject In the starter project, twist down the playground page and Sources folder in the Project navigator, and select the SupportCode.swift file. Review the helper code for this challenge, including a cards array that contains 52 tuples representing a standard deck of cards, cardString(for:) and point(for:) helper functions, and a HandError enumeration. In the main playground page, add code right below the comment // Add code to update dealtHand here that will evaluate the result returned from calling points(for:), passing the hand array. If the result is greater than 21, add the error HandError.busted onto dealtHand with the points that caused the hand to bust. Otherwise, add hand onto dealtHand as a next event. Also in the main playground page, add code right after the comment // Add subscription to dealtHand here to subscribe to dealtHand and handle next and error events. For next events, print a string containing the results returned from calling cardString(for:) and points(for:). For an error event, just print the error. The call to deal(_:) currently passes 3, so three cards will be dealt each time you press the Execute Playground button in the bottom-left corner of Xcode. See how many times you go bust versus how many times you stay in the game. Are the odds stacked up against you at the casino or what? The card emoji characters are pretty small when printed in the console. If you want to be able to make out what cards were dealt, you can temporarily increase the font size of the Executable Console Output for this challenge. To do so, select Xcode/Preferences…/Fonts & Colors/Console, select Executable Console Output, and click the T button in the bottom-right to change it to a larger font, such as 48. Challenge 2: Observe and check user session state using a behavior relay Most apps involve keeping track of a user session, and a behavior relay can come in handy for such a need. You can subscribe to react to changes to the user session such as log in or log out, or just check the current value for one-off needs. In this challenge, you’re going to implement examples of both. Review the setup code in the starter project. There are a couple enumerations to model UserSession and LoginError, and functions to logInWith(username:password:completion:), logOut(), and performActionRequiringLoggedInUser(_:). There is also a for-in loop that attempts to log in and perform an action using invalid and then valid login credentials. There are four comments indicating where you should add the necessary code in order to complete this challenge. Good luck!
https://www.raywenderlich.com/books/rxswift-reactive-programming-with-swift/v4.0/chapters/3-subjects
CC-MAIN-2021-04
refinedweb
3,823
65.12
Related link: No sales pitch here, but I just have to announce the launch of something I’ve spent over two years making: the HostBaby Wizard Related link: No sales pitch here, but I just have to announce the launch of something I’ve spent over two years making: the HostBaby Wizard Related link: I’ve been reading about viral marketing recently, so I tried to fit the phenomemon in with trends in social networks and Web Services. Here’s a short script to remove multiple ip6fw rules sharing the same number. for a in `ip6fw list $1 | cut –d ' ' –f 1` do ip6fw delete $1; echo "ip6fw: deleted rule $1"; done Usage: # sh rmrules.sh 123 Today’s post is a one-liner that saves me a few lines of PHP every time I do a people query. I used to always select my clients’ or customers’ names from the database, then use PHP/Ruby/something to grab just the first word of the name. From now on I’m doing it in the database directly, though it took a while to figure out how. SELECT name, INITCAP(SPLIT_PART(name, ‘ ‘, 1)) AS firstname FROM clients (Ok so it only took like 3 minutes to figure out but I’m posting it here so I don’t lose it.) :-) Related link: This Bugtraq post questions if a 16-bit counter overflow was the cause of Comair’s recent computer failure that caused the cancellation of 1,100 flights on Christmas day. Quote from the post: “…”. And while we are at it, can someone please explain to me what a “worker keystroke error” is?! Here’s a quote from the article: “A worker keystroke error grounded or delayed some American and US Airways flights for several hours in August.” Give me a break! Sounds more like an “input validation” flaw in the software. IPFW, IPFW2, and IP6FW allow the ruleset writer to add more than one rule with the same number. Here’s a command that lists rules with the same numbers: IPFW/IPFW2: $ ipfw show | cut -f 1 -d ’ ’ | uniq –d 00100 00243 IP6FW: $ ip6fw show | cut -f 1 -d ’ ’ | uniq –d 00100 00243 In recent years, Open Source has become a relevant and strangely addictive force in IT. As the Internet age has dominated businesses and consumers with the same well oiled, yet clunky machine, Open Source has crept out of the dimly lit bedrooms occupied by toiling hackers and into the network rooms and ‘enterprise centric strategies’ of todays businesses. Open Source has not just become more acceptable, it has become more relevant. Despite the over-production of rubber penguins and increasing technorati blogging about Open Source across the net, Open Source still has a long way to go in achieving the kind of acceptance and use we as enthusiasts optimistically predict. As bods familiar with the workings of an Open Source community, it makes reverent sense why one should use the software; freedom, stability, security, quality etc. The real challenge that faces us is that although you may have a clear view of why Open Source may be the right solution, expressing and communicating this message can be difficult at best. Advocacy is a concept riddled with theories, beliefs and opinions on how it should be practiced - how can you best advocate Open Source software? I am going to be writing a series of new articles about advocacy. In these features, I am going to write about the different issues involved in advocating Open Source software, and attempt to beat a path towards best practice. For quite some time, I have been advocating how Open Source can be right for some people. This evangelism was first expressed through my efforts creating Linux UK (one of the first UK editorial sites about Linux), on through my work as a journalist and resulting in my current full time position at OpenAdvantage () as a professional Open Source evangelist. Although there is still much to learn, the body of experience I have collated myself and from other people can act as a useful map when choosing which path to head down. The goal in this game is to be as productive as possible with your advocacy; anyone can randomly advocate, but here you want results. Before you set forth and explore the different avenues of advocacy, you need to step back and evaluate exactly what you are aiming to do. Sure, this nugget of advice sounds like one of those self-help audio cassette courses, but it is particularly important in the context of Open Source. The reason for this is that Open Source is first and foremost a culture, and like any other culture, it can be perceived and understood in inherently different ways. As an example, some people are inspired by Open Source due to the ethical and philosophical concepts, some are inspired by the technical benefits and some are plainly in it financial benefits. Even within these three loose groups, there are variations in tone and colour. If you support Open Source due to its ethical nature, you may approve of certain rights (such as access to source code and freedom of innovation), but not approve of other rights (such as selling Open Source, or including closed source components). What do you feel about free media - do you believe Open Source should be applied to sound/video? What is your take on software patents? Do you feel that Open Source should be advocated to businesses who will use it for closed source solutions? Are you happy running closed source software on Linux? Each of these questions has a variety of distinct answers that vary among members of the same Open Source community. In marketing parlors there is a general rule that you should know your product inside out. This common-held view preaches that if you don’t understand part of your product, you won’t be able to answer *every* question and query about it. Open Source advocacy has a similar, albeit, less critical rule of thumb; “to help Open Source, you need to know Open Source”. With such a range in views of Open Source, you need to firmly understand your own position, and more importantly, understand how flexible you are in promoting Open Source in areas that you are not personally familiar with. Throughout your experiences advocating, it is likely that you will face challenges that will test your ethical and technical views, and it is advisable to set yourself a policy regarding how far you can bend on these issues. With the policy set early, you will gain more confidence in pushing forward. While you are sat back, re-evaluating your perspective on Open Source, you should also re-evaluate your perspective on facts. Although we can be safe in knowledge that the O’Reilly Network does not resort to ridiculous headlines that mis-represent a story, it is likely that you will hear stories that may be perceived one way, but are entirely wrong in how the story was actually played out. As an example, a while back I was at a conference in London designed to help public sector organisations and schools understand what Open Source is, and a number of councils and schools gave a presentation at the event. One such school, Orwell High School, a specialist school for technology, made the leap over to Open Source. With over 1000 students, the school found upgrade costs quite prohibitive due to expensive hardware requirements for Windows XP, as well as high administrative costs. The school made the move to a LTSP thin-client setup, and this resulted in cheaper hardware, less landfill and a centrally administered system. This solution was by its very nature, a standard cut n’shut case; the need was there, and a solution was proposed. The result of this case was a saving of £13,000 a year in license fees; a worthwhile but not exactly ground shattering figure, given the millions saved in cases such as that at Beaumont Hospital where they saved over EU4million with Open Source. What is interesting with the Orwell High School case is how that saving is relevant to their context. A teacher in the English department stated that each child in the department had a budget of £1 per head. When you are dealing with such low figures, £13,000 can seem like an awful lot of money being saved each year. The key point here is that information is relative to context, and context is relative to information. Before you even begin discussing how to push the merits of advocacy in different ways, you need to be prepared to sit back and think about the information you receive, and how that information is relevant to the bigger picture. The goal here is not to con people into using Open Source, neither is it to suppress some elements of Open Source. The goal is to be as honest and up front as possible, and to try and dispel some of the large quantities of hype. The new series of articles will be online soon on the O’Reilly Network. Thoughts and ideas? Scribe them below… In most of the articles and forum entries everyone always mentions that installing Mono is greatly simplified by using Red Carpet. Now that I’ve done it, I’d have to agree. Getting there was, however, not as easy as I would have liked. In this article I’ll provide the step by step instructions for installing Mono on SuSE Linux Professional 9.1 using Red Carpet 2.2.3. After reading, you should have a clear idea of how to get through the installation, and hopefully avoid some of the snags I ran into. In the end, with this article, setting up Red Carpet will be as easy as using it to install Mono. This article will not provide any explanation about Mono itself. It assumes that the reader knows what Mono is, otherwise, why would you be interested in completing the installation? Well the first thing to understand is that since Novell’s purchase of Ximian, Red Carpet is no longer available as a separate download. As mentioned on the Mono Project download project, it is now available as the ZENWorks Suite 6.5. Once you get to the ZENWorks download page from Novell, the file required is ZEN65_LinuxMgmt.iso. This provides management for Linux desktops and servers, but it is essentially Red Carpet Enterprise. Be forewarned, the only way to get the necessary installation RPMs are from a 474.2 MB iso image. In addition, according to the Novell web site, this is a 90-day evaluation license of Red Carpet. I believe that Novell is well positioned to benefit from the growth of LInux and open source software. However, I question their restrictive licensing of a technology that is necessary to download and install what may become the predominant open source software development platform. I’m really not sure if this license will apply to Red Carpet, so I’ll let you know in 88 days. In addition, why not break up the iso image into the individual components? Why should I have to download 474 MB when I only need 3 files that are less than 2 MB? Once you have downloaded the iso image and have burned it onto a CD, then mount the CD and look for the redcarpet2 directory. For SuSE Linux Professional 9.1, the RPMs necessary were found in the suse-91-i586 subdirectory. The critical files are: This is the Red Carpet Daemon. It is absolutely necessary for getting Red Carpet to work correctly as I’ll explain later. This package contains the graphical user interface for Red Carpet. This package contains the command graphical user interface for Red Carpet. Install these packages and we are almost done. First, the GUI application should appear in the KMenu in the System -> Configuration folder as Red Carpet. You can further verify the successful installation by using YaST. Check in the Install and Remove Software -> Package Groups -> System Environment where you will find the newly installed software in the the Applications and Deamons groups. With the software installed, the next step requires starting the Red Carpet Deamon. To start the deamon from the graphical user interface, you need to return to YaST. Select System -> Runlevel Editor, and then click on the rcd service. Click on the Enable button and the service should change status and show Enabled is now equal to Yes. To start the Red Carpet Deamon from the command line, use the following quick command. Enter: sudo /etc/init.d/rcd start You will need the root password, in order to complete this transaction. Once complete, you should receive the prompt “Starting Red Carpet Daemon.” Now that the deamon is running you are ready to begin the Mono installation. I’ll assume that you are not currently using the root account, so the first thing to do is be sure and start the Red Carpet GUI application using the root account. Enter: sudo /usr/bin/red-carpet If the connect to deamon dialog appears as illustrated in Figure 1, then the red carpet deamon is not currently enable. Return to the previous step and start the rcd deamon. Click on the Available Software tab, then click on the Channel drop down list selection button. This should produce a list of available channels. Select the mono-1.1 channel and then all available packages from the channel should appear. Slect Edit -> Select All or press Ctrl A to select all of the available packages. Select Actions -> Mark for Installation or right click the selected packages and select Mark for Installation. Click on the Run Now icon from the tool bar, select Actions -> Run Now, or press Ctrl X. This will start the installation process. Issue the following commands as root: rug refresh This will download the most current channel information. Next in order to confirm connectivity with the redcarpet servers run: rug channels This should present a list of available channels. The list will also present whether you are currently subscribed to them. The output should resemble the following listing: To complete the installation, then run the following commands: sudo rug sub mono-1.1 sudo rug update -y The -y option will permit all actions without confirmations. Since there are approximately 50 different packages required for Mono, including all of the dependencies, this option should prove helpful. After installing Mono, confirm the installation with a simple test. Using a text editor, enter the simple C# program shown in Lilsting 1. using System; namespace HelloNameSpace { public class Hello { static void Main() { Console.WriteLine("Hello, from Gurabo, Puerto Rico"); } } } To compile the program, enter: mcs hellopr This should produce a response of “Compilation succeeded.” If the compilation fails, then check whether the system class starts with a capital “S”, the console class starts with a capital “C”, and the write line method uses a capital letter for both write and line. Remember, that in C#, classes and all methods and properties are case sensitive. Successfully compiling the hellopr program should produce a hellopr.exe executable. To run the program, enter mono hellopr.exe This should produce the output “Hello, from Gurabo, Puerto Rico”. In this article you have seen how to install and verify Mono. This process includes obtaining Red Carpet Enterprise, installing Mono, and finally creating, compiling and running a simple test program. I hope this provides a simple to follow procedure and eases your way on the road to developing Mono applications. Do any of your development plans include Mono in 2005? I’ll start with the thanks. I’ve received bundles of blog comments and personal e-mail messages with helpful ideas and very patient tutoring regarding my OS X problems. I’ve always been lucky to roll in congenial ‘Net company. From the early C++ community (before eventual insanity set in) to the early Linux community to the early Python community, I’ve seen the best that brilliant and dedicated interest groups can offer a newbie willing to do some homework. My experiences so far with OS X folks matches up against all the above. Thanks guys. So I hope you don’t take it the wrong way when I say that as for the issue at hand, I tried as much was was practical from your suggestions with no luck. I had just decided: No mas. I surrender. Time to reinstall. I was in the middle of a glacial job of backing up by tarring to our household backup server before a reinstall. using tar. Then I heard of the OS X 10.3.7 release. I have always suspected 10.3.6. I know many of you run it without problems but the timing for me and for many others I’ve seen on the Net is just too much coincidence for my skeptic taste. So I upgraded to 10.3.7 and the problem has vanished. Everythign is snapy again. Lori has stopped abusing me for buying her a Mac (easy now, she likes the computer, but she became very frustrated when it became unusable). My opinion is that OS X 10.3.6 had a bug that only affected some users, and that we were among the unlucky, and that they fixed it in 10.3.7. That’s cool and all, but I must say that I wish such breaks and fixes wouldn’t come and go in such mystery. I think Apple has a lot of opening up todo, but that’s the subject of another blog. For now, it’s all love. Before I put this issue behind me (I hope), here are some brief notes in response to the many thoughtful suggestions: A lot of people mentioned disk damage as a likely culprit. Some pointed me to this helpful article about running Disk Utility (or fsck). This seemed reasonable, since my one brief reprieve from the problem had come after running repair permissions. I dutifully tried both Disk Utility and fsck, neither found anything wrong, and I was right back to the problem upon full boot. I think Apple tech support also instructed Lori to do this when she first reported the problem, but it was worth my trying personally. One note is that in safe mode everything was nice and fast, but back in regular start-up (regardless of the user) it was dog slow. Perhaps it was a kernel extenson in that case, but I had no idea how to start narrowing down which was the culprit. Some suggested DiskWarrior, a third-party tool, but one that has received an impressive shelf of accolades. Apparently it can fix some problems that elude all other tools, including those built into OS X. Problem 1 is that it costs $80, but that’s a bargain if I were confident that it would do the trick. Problem 2 is that it is not even really advertized as a performance elixir. It’s advertized more as a wicked sharp disk error recovery tool. A bit more lumber than we need overall, and not an obvious enticement to spend a speculative $80. Some suggested DNS issues. This doesn’t seem at all likely. The slowdown affects launch of applications that have nothing to do with networking, yet networking applications such as Safari don’t seem in any more distress than any other counterparts. What’s more, if I do basic lookups on the command line, once the command line applet itself has taken ages to start up, network responses are immediate. Apparently HP printer drivers, have been the source of some reported problems, but these problems are a matter of chewing up CPU. Once again, Activity monitor shows plenty of CPU idle left. CPU utilization is not the problem here (nor is memory). I checked for third-party extensions and all that. /System/Library/Extensions has tons of “.kext” file (kernel extensions, I presume) but I can’t tell which would be 3rd-party, nor did I feel confident just deleting the lot. In /Library/StartupItems I did find a file “Wacom” which might correspond to an old Wacom tablet which I’d forgotten we’d installed (we hardly used it). Deleting that file didn’t make a difference. Some thought that the fact that we’d made incremental updates from 10.3.0 to 10.3.6 caused a few gaps and fissures in things and that we should just use the “combo updater” (new concept for me) to go back to 10.3.0 and make the leap back to 10.3.6 in one go. Sounded plausible and all, but if it were the problem wouldnit it have got worse with 10.3.7, rather than better? Here is a quote from one sugghestion: [T]he Jan 2005 issue of MacAddict addresses the “lazy Mac” (p.20: “your Mac isn’t as snappy as it used to be”). They start by recommending a reboot and then checking Activity Monitor, but eventually they recommend running the $15 shareware Cocktail, which would have worked (as “repair permissions” is one of its options). Seems like useful into to keep in mind, though I don’t know how Cocktail would compare to DiskWarrior and other similar packages. Bottom line now: my wife is happy so I’m happy. Thanks to Apple for the fix, and thanks to the OS X community for such solid support. Related link: It looks like the first quarter of 2005 is going to be a busy time for your humble weblogger. I will spend most of the January and February working on a book for O’Reilly. Then, the last week of February I’m going to Sheffield to speak about Open Source firewals at the ShefLUG 2005 Seminar (23rd February 2005) and immediately after that I’m off to Fosdem 2005. (I won’t be one of the speakers at Fosdem, just a regular attendee, look for me near the OpenBSD booth.) Then, in March, I’ll be teaching BSD Firewalls classes in Krakow (Cracow), Poland. Fingers crossed, my health will keep up with my schedule. A? Related link: Rogue Amoeba, the makers of the insanely cool Audio Hijack, will release Slipstream in January 2005. In an email they sent to registered users of their other products, they say: Now, audio from any program can be played through it. With Slipstream, the AirPort Express isn’t just for iTunes any more. Very cool: I can’t seem to give these guys money fast enough for all the cool stuff they have. At some point I’d like to have RealPlayer on all the speakers in my house so I can keep listening no matter which room I move to. Related: Kudos to all the Thunderbird developers for making such a great app. Related link:×087h29ub This week the web analytics software company WebSideStory reported that the Mozilla Firefox browser now has an estimated 4% share of U.S. Browser Usage Share. Most of this new found usage has come at the expense of the Microsoft Internet Explorer, which is now down to 91.8%. I can only imagine that this number will continue to drop. I’m even now more excited about giving all my relatives copies of the OpenCD for Christmas. I’m mostly just giving it to them just to encourage their use of Firefox, but who knows? Maybe they’ll get curious and give some of the other fine apps a spin. Looking to impress your friends and relatives, give’m Firefox. They’ll thank you all next year. Related link: NetFlix uses RSS to tell me which movies they’ve gotten back from me and which ones they have shipped. It’s been handy. I’ve been curious when they get the movies back, and now I know. I? Of all of the companies that are playing the open source card, the one I least understand is Oracle. HP, IBM, and even to some degree Sun Microsystems are easy to understand. Promoting open source helps them sell more hardware, like I said easy. Fundamentally, Oracle’s interest in Linux is the same, by promoting open source it helps them sell more software licenses. However, that’s the kicker. Until Bill Gates’ prediction comes true and hardware is essentially free, there is a big difference between these two positions. Hardware manufacturers are not on a collision course with open source. Computer hardware and open source are complimentary markets. On the contrary, database management servers, middleware, web servers, finance and accounting software, and customer relationship management software are dead center the target of some of the most aggressive and successful open source companies. A simple example is MySQL AB, that competes, or will compete, directly with Oracle in the database market. I’ve been confused by this for a while, but this week I was stunned. After a relentless pursuit, Peoplesoft Corporation surrendered to Larry Ellison and Oracle Corporation. This week the Peoplesoft Board of Directors took the advice of the “Transaction Committee” and accepted a cash bid from Oracle of $26.50 per Peoplesoft share, for an estimated total transaction value of $10.3 Billion. As I’ll break this transaction down later, it is my opinion that this purchase may be a serious mistake by Oracle Corporation. I’ll show through a very brief review of their finances, that with the growing credibility of open source software in the server room, both Oracle and Peoplesoft will be directly threatened by a strong contender in some of their most successful product areas. This threat will drain new software licenses faster than they expect and they will be slow to respond to this threat. In the end, I commend the Peoplesoft share owners in successfully raising Oracle’s offer price per share from $19 per share to $26.50. If completed, this will be a huge financial windfall for all Peoplesoft share owners. Although their 2003 annual report does not even mention a threat from open source it is curious to note that one of their key ex-executives believes differently. As we have already seen in the attempt from Novell to hire ex- PeopleSoft exec Ram Gupta to replace departed vice-chairman Chris Stone, it seems the executives at Peoplesoft know where the future lies. I predict that some of the biggest Peoplesoft shareholders, those who will reap the most from a successful sale, will head into open source. More and more to get a sense of how little this makes sense, we only need to examine the numbers. The best place to go for any public company are the federally mandated Security and Exchange Commission reports. Let’s first check out the basic numbers from Oracle Corporation (ORCL). First, according to the Oracle Corporation 2004 10Q, Year End Report they claim that “We are the world’s largest enterprise software company.” They are most definitely somewhere in the top five of all proprietary software companies in the world. In 2004 they generated a total of $10B revenue, with $8B in software licensing (79%) and $2B from services (21%). 44% of those software revenues were from new software sales, while the remainder comes from license renewals and upgrades. Due to the well deserved reputation of their marque product, the Oracle database, they seem rock solid. It is worth mentioning though, they do have open source on their radar. I guess they believe, as many of us do, that open source is important to watch but it is anyone’s guess when it might actually have any material impact on their revenue. Oracle admits: “We may also face competition in the open source software initiatives, in which companies such as JBoss and MySQL provide software and intellectual property free over the internet.” and “We may also face increasing competition from open source software initiatives, in which competitors may provide software and intellectual property free over the internet. If existing or new competitors gain market share in any of these markets, at our expense, our business and operating results could be adversely affected.” I say that when a risk finally makes it into the management discussion, it is probably too late to do anything to stop that threat from becoming an issue. So the risk is there, fine. So let’s take a look at Peoplesoft. Reading from Peoplesoft Corporation’s 10Q Quarterly statement for the third quarter, they have booked $1.9B in revenue in the first 3 quarters of 2004. They are on track to surpass the annual numbers from 2003. Digging a little deeper, they have $1.3B in software license related revenue and $0.6B in service revenue. We see less of an emphasis on software licensing, but it is still heavily dependent on software licensing. It is also very important to look at what it would take to see a return on investment for Oracle’s $10.3B. With $61 Million in net income in the first nine months of 2004, it would take approximately 384 years to earn back the investment based only on profit. Maybe it makes more sense to look at the almost 4 years it will take to have the Peoplesoft annual revenue to cover the sale price. Now I realize this freshman business school student’s analysis of this transaction is way off, but I stand by my analysis that this is a fantastic deal for Peoplesoft’s shareholders and an anchor around the neck of Oracle. Companies are bought and sold for many reasons, and I’m sure we may learn why Larry Elison pushed so hard to get Peoplesoft. In the meantime, let me elaborate on some of the open source projects that I hope, err I mean “may”, represent some of the biggest risks to Oracle and Peoplesoft. In no particular order, here are some companies and projects that should be giving the Oracle sales staff nightmares before too long: Anyone, or maybe several, of these companies or projects may rise to be a serious threat to Oracle’s future software revenue. Only time will tell, however, I know that if I had $10 Billion dollars burning a hole in my pocket, I imagine there are better ways to invest it. To obtain copies of the financial data reviewed for this, please visit: What do you think Oracle’s purchase of Peoplesoft means for the software industry? Related link: That. Related link:… This inspiring phrase from Kent Beck’s book Test-Driven Development By Example: “When we write a test, we imagine the perfect interface for our operation. We are telling ourselves a story about how the operation will look from the outside. Our story won’t always come true, but it’s better to start from the best-possible application program interface (API) and work backward than to make things complicated, ugly, and “realistic” from the get-go.” The following example test is just a little simple one-method thing, but I realized this same approach could be used to design an entire system! You can just start typing some pseudocode the way you *wish* you could type *if* your class/system was “just that easy”. Then, when done, break it down into bits, and try test-driven development to see if you can make it so! Just a 1-hour-old idea. Feel free to rip it apart…. Related link: I am pleased to announce that starting next month, the start of the Spring semester at Tufts University, I will be teaching a course entitled Security, Privacy, and Politics in the Computer Age. The course will be offered by the Experimental College at Tufts University. The following is a brief description of my course: Computer viruses, worms, Trojan Horses, spyware, exploits, poorly designed software, inadequate technology laws, and terrorism: these issues have a profound affect on our daily computing operations and habits. New technological innovations such as file-sharing software and location-based tracking tools also have major political and social implications. Unfortunately, basic knowledge and understanding of the security, political, and social issues concerning the use of technologies is lax, and is a major reason why people are continually affected by computer security breaches and technology misuse. Granted, the problems are only getting worse. Issues including electronic voting, Radio Frequency Identification (RFID) tags, location-based tracking technologies, and the Digital Millennium Copyright Act (DMCA) will be discussed. This course will also delve into reverse engineering of software, understanding exploits (e.g. buffer overflow, Denial of Service, rootkits, spoofing) and intrusion detection, and how to protect yourself from malicious computer activities. Then, the issues will be put into a global context to answer the question: we have dug ourselves into a deep hole; how do we dig out of it? This course is open to all, regardless of area of study. No software development or computer programming knowledge is required. Basic knowledge on computer technology and concepts is sufficient. The only requirement is that you are curious on the security, privacy, political, and legal issues in computer technology, and why they are important in society. I do understand that only Tufts students and neighboring community members can enroll in the class (EDIT, 1/5/2005: ON A SPACE AVAILABLE BASIS). However, I endear to make this course accessible to the general public. Therefore, all lecture notes, news, examples, and assignments will be published to the course’s website as soon as they become available. I also envision having a message board for the course, and possibly videos or audio recordings for some lectures –all available to the general public’s use. I am honored to have the opportunity to teach this course not only because of my passion for this complex matter, but to contribute back to my alma mater and to the Computer Science community. In addition, there is a lack of ownership of the subject matter that I will be presenting, a major reason why there is a lack of basic understanding of the security, legal, political issues in using technology. For more information, please visit the course’s (tentative) website at. Once in a while someone asks for a graphical installer for BSD, similar to Fedora Core. Wouldn’t it be cool if we could see the daemon or Puffy in full color? No, it wouldn’t. As someone who just finished a chapter on BSD and Linux installation procedures, I must say that I like BSD installers much better than their Linux counterparts and that I don’t see a reason to ask the developers to spend their time on something that’s pure eye candy. This is 2004, soon to be 2005, and the odd graphical Linux installer can still have problems talking to some monitors and video cards. Related link: A long time ago in a publishing world far, far away, Brian Richard started Py, an independent Zine for Python developers. I still have several copies of the first issue I picked up at OSCON 2002. That was about the same time I was thinking about going into print with The Perl Review. Brian and I had chatted over email a couple times, and he had moved on to Linux Magazine. I thought that was the end of Py. Mark Pratt, the new publisher of PyZine, called me tonight (all the way from Barcelona) and we talked about what each of us is doing and what we have planned. I certainly don’t want to compete with PyZine, so my idea for a Python magazine (I wanted to call it MagPy) is dead. There might be some ways we can help each other, but mostly we just talked about how we do things and exchanged some ideas. Now I’ll have to find another idea for a new magazine, but that’s okay. :) Someone, somewhere on the Internet claimed recently that the hama USB 2.0 Card Reader 9in1 doesn’t work with OpenBSD 3.6. This is not true, the system detects the card reader and the flash cards you plug into the reader.. Related link: Google just keeps doing amazing things. Google for “War and Peace”. One of the top links should be “Book results for war and peace” with a rainbow colored collection of book spines next to it. Follow that result and you’re in Google Print, which shows you the Penguin edition of the book, and it’s fully searchable!. I’ve had this dream of creating concordances for my favorite books, but Google Print would virtually do that for me. Go on Google, take it off my to-do list!? Tonight I had some time to update Busines::ISBN::Data, which is the data pack for Business::ISBN. It exists separately so I can update them separately. The ISBN folks have added several country prefixes and updated the publisher ranges in a lot of the prefixes: space for new publishers is getting short. The task was much easier this time. Previously, I got the data from the HTML pages on their web site. They’ve done away with that in favor of a PDF file. Things would have been much easier if it was just a text file. There isn’t anything fancy in the PDF: no images, no fancy text effects: just the data. Oh well. Updates are infrequent, and it was easy to extract the text from the PDF, even if the data was a bit dirty. Still, text wants to be text. Updated. Thanks to “david_given” for pointing out a typo, which is now corrected. Much of my current late-night hacking (I should be making a couple of big announcements soon) involves pushing the art of XML/SAX processing in Python by using its ever more powerful functional features. In doing so, I’ve been making more and more use of nested (AKA inner) functions for modularity and some neat approaches to dynamic dispatch. This has also brought me several times into the grey areas of nested scopes. I’ve come to know the PEP pretty well, but in case it saves anyone time spent probing Python legalese, here is an example that illustrates the behavior of nested scopes. The code can be run as is in Python 2.2 or later. For Python 2.1, add from __future__ import nested_scopes to the top. g_a = 1 #global scope def f1(): a = 2 def g(): print "f1/g", a #a is 2 return g() def f2(): a = 3 def g(): print "f2/g", a #UnboundLocalError (at runtime) a = 4 return g() def f3(): def g(): global g_a print "f3/g A", g_a #a is 1 g_a = 5 #Modifying the global print "f3/g B", g_a #g_a is 5 return g() print "f3/g C", g_a #g_a still 5 def f4(): a = 6 def g(a=a): #Yuck. Cumbersome print "f4/g A", a #No problem. a is 6 a = 7 print "f5/g B", a #Now a is 7 g() print "f4", a #Back to 6, since int is immutable and def f5(): a = 8 def g(a): print "f5/g A", a #No problem. a is 8 a = 9 print "f5/g B", a #Now a is 9 return a a = g(a) print "f5", a #a is still 9 f1() #f2() #Commented out to avoid Exception f3() f4() f5() When I first ran into the UnboundLocalError problem demoed in f2 I started with the fall-back solution in f4, but 2 considerations turned me off that solution. The main one was ugliness of the keyword stuffing, especially when I wanted several variables in the shared scope. A more minor issue was a need to mutate such variables within the nested function. This is a minor issue because such mutation is rather inelegant and runs counter to the very functional principles underlying nested scopes. Nevertheless, I did have a couple of cases where I wanted to hack in mutation temporarily for some quick and dirtypurpose. It turns out that the f5 approach deals with both issues, with a bonus that mutation is replaced by functional transform. I use tuples to pass back multiple values from the inner function, of course. I did not show in the listing how using exec or from foo import * can lead to syntax errors, a situation I ran into once, to my great confusion. See the PEP for a terse listing of syntax gotchas. Andrew Kuchling’s document mentions the exec gotcha. The usual solution is to use the form exec cmd in globals(), locals(). See the Python Library Ref exec documentation for details (notice: Python 2.4 relaxes the rules a bit on what can be used with exec ... in ...). This slide mentions the exec gotcha as well as a possible problem with eval. Side note: in Andrew Kuchling’s brief on nested scopes he introduces them by saying:?) I read this bit after I’d already used recursive inner functions in several cases, and had been impressed at their expressive power. Just goes to show that the human imagination is not fit to find limits to the usefulness of recursion. Overall, nested scopes in Python are not as clean as a language purist might wish, but like so much in Python’s evolution, they find a comfortable niche between cleanliness and practicality. Related link: Here are some BSD and firewall sticker designs: DragonFly BSD — Because There Are Other Alternatives FreeBSD — Because There Are Other Alternatives NetBSD — Because There Are Other Alternatives OpenBSD — Because There Are Other Alternatives OpenBSD — Painted Puffy IPFW — Building a Better Firewall IPFilter — Building a Better Firewall IPTables — Building a Better Firewall PF — Building a Better Firewall Copyright? You are free to print and sell/give away these designs as long as they are used to promote DragonFly BSD, FreeBSD, NetBSD, OpenBSD, IPFW, IPFilter, PF, and IPTables in a positive manner. The Puffy image is copyright Theo de Raadt Have fun. I
http://www.oreillynet.com/onlamp/blog/2004/12/
crawl-001
refinedweb
7,020
61.06
If you are an applications developer for embedded systems, sending your solutions to remote locations where they can’t be reached for reset or service, this update is for you. The LiFePO4wered/Pi+ has many helpful features for different use cases. Some people like to use the on/off button to boot and shut down their Pi, while others turn on auto-boot and/or auto-shutdown to get on/off behavior based on external power for their application. The wake-up timer feature is really cool and helpful in low power, low duty cycle applications, and it’s pretty easy to understand what it does and how to use it. One feature that people have more trouble with is the application watchdog. Unless you come from an electronics or embedded systems background, you may not be familiar with what a watchdog is or does. So in this update, I’ll explain what it is, why you want it, and how you can use the one provided by the LiFePO4wered/Pi+ to make your Raspberry Pi-based project more reliable. The Wikipedia article on watchdog timers explains that a watchdog timer is "an electronic timer that is used to detect and recover from computer malfunctions." Let’s face it: computers are complicated beasts with many moving parts that all need to work correctly. There will always be bugs (or cosmic rays) that will cause something to act up at some point. If your computer is on your desk, you can reboot it when this happens, but what if you are using a computer like a Raspberry Pi in an embedded system? What about in something that needs to run automatically and reliably, may be hard to reach inside a machine, or is located far away in a remote location? The Wikipedia article notes that "watchdog timers are essential in remote, automated systems," giving the example of a Mars rover. If your Mars rover’s computer crashed, who would go reboot it? Watchdog timers are usually extremely simple, and this is a good thing. It’s the complexity of computers that makes them susceptible to crashes and hangups, so it makes sense that the system that watches over them should be less susceptible to these issues, hence simpler. Ideally, watchdog timers are implemented in hardware. In the LiFePO4wered/Pi+, the watchdog is implemented in firmware. Not quite as desirable as hardware, but if you compare the complexity of the firmware on the LiFePO4wered/Pi+ (4 kB) with that of the Linux system running on the Pi (4 GB), it’s orders of magnitude simpler. The basic concept of a watchdog timer is that the software running on the system needs to regularly reset the timer (commonly referred to as "kicking" or "feeding" the dog, depending on how you feel toward dogs), because if you fail to do so, it will reset you instead (the dog will "bite" you) when the time runs out. This ensures that if your system hangs, it can be reset and brought back to a responsive state. In the LiFePO4wered/Pi+ implementation, by default the watchdog is off ( WATCHDOG_OFF or 0). This is because it’s conceived as an application watchdog: it’s not just there to ensure the Linux system is up, but also to ensure that whatever application you are running is behaving as it should. So how you implement this is up to you as a developer and depends on what functionality is critical to your application. The watchdog can be set to two levels by writing to the WATCHDOG_CFG register. The first level, WATCHDOG_ALERT ( 1), is useful during development or when the Pi system is within view of an operator who can take action. At this level, the PWR LED will start flashing the fast error flash when the timer expires. The second level WATCHDOG_SHDN ( 2) will trigger a Raspberry Pi shutdown when the timer expires, and is most likely what you want in production systems. Note that all it does is trigger a shutdown — nothing more. This means you still benefit from the nice shutdown behavior you expect from the LiFePO4wered/Pi+: it will always try to do a clean shutdown first (your application may have crashed but the Linux system may still be running, so why risk corrupting it by doing a hard reset if you don’t have to?). If the clean shutdown doesn’t succeed though, power will be forced off after the settable shutdown timeout (in case the whole system was locked up). Unless the proper response to a watchdog timeout for your application is to turn completely off and stay off, you should use one of the auto-boot settings to turn the shutdown into a reboot instead so you get the system back up. To prevent the watchdog from biting you, your application needs to write a timeout value to the WATCHDOG_TIMER register, and keep doing so before the time that was written last expires. The register can also be read to see how much time is left and counts down with ten-second resolution. The timeout value you want depends on your application, or even the specific thing you are doing in your application. You need to find the balance between how long you can allow your system to stay unresponsive if something is wrong, and how long you can expect certain operations to take if everything is working. The simplest watchdog example application in Python would be something like this: from lifepo4wered import write_lifepo4wered, WATCHDOG_TIMER from time import sleep while True: write_lifepo4wered(WATCHDOG_TIMER, 10) sleep(5) Of course, this example would have limited use in the real world. It only ensures the Linux system is alive, your Python installation is working and the Raspberry Pi and LiFePO4wered/Pi+ can communicate. Please resist the urge to just add a process like this to your system and think the watchdog is now guarding your application. To be really effective, the watchdog reset calls need to be intertwined with your application logic, and depend on its correct behavior. Here’s a better example. Imagine you have a Raspberry Pi-based system that reads sensor data and sends it to a cloud server over a cellular modem. Without getting lost in implementation details, this would be an effective use of the watchdog: from lifepo4wered import write_lifepo4wered, WATCHDOG_TIMER from time import sleep from sensor import read_sensor # Part of your app from cloud import send_to_cloud # Part of your app while True: data = read_sensor() if data.read_success: if send_to_cloud(data): write_lifepo4wered(WATCHDOG_TIMER, 120) sleep(10) Here the watchdog guards many more potential error conditions. First of all, the watchdog will never be reset and will therefore reboot the system if for some reason we can’t talk to the sensor. The sensor itself may contain firmware that could have crashed, so by powering down the system and restarting, the sensor might be returned to a working condition. The same for the cellular modem. If we fail to send data to the cloud because the modem has locked up, we may recover by powering down and back up again. Note that the watchdog timer value is set much higher than the expected loop time. This allows the system some time to work through adverse conditions without getting rebooted all the time. For instance, if the cellular modem suffers from a bad connection, it may take a while to get the data out. In this case, we’ve decided that if the system isn’t responsive for two minutes, something must be wrong and we let the watchdog reboot us. There is one last register related to the watchdog that I want to touch on: WATCHDOG_GRACE. This provides a grace period after the system has booted until your application has the chance to write to the WATCHDOG_TIMER register for the first time. You can think of it as the initial value for the WATCHDOG_TIMER register after boot. Depending on how heavy your application is, it may take a while to start and you wouldn’t want the watchdog to reboot the system before your application is ready to go. The WATCHDOG_TIMER register is the only one your app should have to deal with. The WATCHDOG_CFG and WATCHDOG_GRACE registers are supposed to be configured and written to flash with CFG_WRITE before deployment. This ensures the watchdog is always active with the right configuration so you don’t depend on the system you’re trying to protect to launch the thing that’s supposed to protect it… which might not happen if something is wrong. Full details on how to use the watchdog registers (or any register for that matter) can be found in the LiFePO4wered/Pi+ Product Brief. I hope this guide can help you build reliable Raspberry Pi-based systems by using the watchdog! Designer Product Delivery Recommended PCB Assembler An open-source, multi-parameter, full fledged human body vital sign monitoring HAT for Raspberry Pi as well as standalone use. Make your Raspberry Pi bright and shiny with an RGB LED strip and ANAVI Light pHAT! An open source stereoscopic camera based on Raspberry Pi
https://www.crowdsupply.com/silicognition/lifepo4wered-pi-plus/updates/watchdog-feature
CC-MAIN-2021-17
refinedweb
1,523
56.49
Java basics In this part of the Java tutorial, we will cover some basic programming concepts of the Java language. We begin with some simple programs. We will work with variables, constants, and basic data types. We will read and write to console. We will also mention string formatting. Java simple example We start with a very simple code example. The following code is placed into the Simple.java file. The naming is important here. A public class of a Java program must match the name of the file. package com.zetcode; public class Simple { public static void main(String[] args) { System.out.println("This is Java"); } } Java code is strictly organized from the very beginning. A file of a Java code may have one or more classes, out of which only one can be declared public. package com.zetcode; Packages are used to organize Java classes into groups, which usually share similar functionality. Packages are similar to namespaces and modules in other programming languages. For a simple code example, a package declaration may be omitted. This will create a so called default package. However, in this tutorial we will use a package for all examples. Another important thing is that a directory structure must reflect the package name. In our case the source file Simple.java with a package com.zetcode must be placed into a directory named com/zetcode/. The package statement must be the first line in the source file. public class Simple { ... } A class is a basic building block of a Java program. The public keyword gives unrestricted access to this class. The above code is a class definition. The definition has a body that starts with a left curly brace { and ends with a right curly brace }. Only one class can be declared public in a source file. Also note the name of the class. Its name must match the file name. The source file is called Simple.java and the class Simple. It is a convention that the names of classes start with an uppercase letter. public static void main(String[] args) { ... } The main() is a method. A method is a piece of code created to do a specific job. Instead of putting all code into one place, we divide it into pieces called methods. This brings modularity to our application. Each method has a body in which we place statements. The body of a method is enclosed by curly brackets. The specific job for the main() method is to start the application. It is the entry point to each console Java program. The method is declared to be static. This static method can be called without the need to create an instance of the Java class. First we need to start the application and after that we are able to create instances of classes. The void keyword states that the method does not return a value. Finally, the public keyword makes the main() method available to the outer world without restrictions. These topics will be later explained in more detail. System.out.println("This is Java"); In the main() method, we put one statement. The statement prints the "This is Java", which is a string literal, to the console. Each statement must be finished with a semicolon ; character. This statement is a method call. We call the println() method of the System class. The class represents the standard input, output, and error streams for console applications. We specify the fully qualified name of the println() method. $ pwd /home/janbodnar/programming/java/basics/simple $ javac com/zetcode/Simple.java Java source code is placed into files with the .java extension. The javac tool is the Java compiler. We compile the Java source into Java classes. Note the directory structure. The structure must match the Java package. $ ls com/zetcode/ Simple.class Simple.java Simple.java~ After we compile the source, we get a Java class file with the .class extension. It contains a Java bytecode which can be executed on the Java Virtual Machine (JVM). Simple.class is a Java program which can be executed with the java tool. $ java com.zetcode.Simple This is Java We execute the program with the java tool. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method. The parameter to the java tool is the fully qualified name of the Java class. Note that the .class extension is omitted. Java console reading values The second example will show, how to read a value from a console. package com.zetcode; import java.util.Scanner; public class ReadLine { public static void main(String[] args) { System.out.print("Write your name:"); Scanner sc = new Scanner(System.in); String name = sc.nextLine(); System.out.println("Hello " + name); } } A prompt is shown on the terminal window. The user writes his name on the terminal and the value is read and printed back to the terminal. import java.util.Scanner; The Java standard library has a huge collection of classes available for programmers. They are organized inside packages. The Scanner class is one of them. When we import a class with the import keyword, we can refer later to the class without the full package name. Otherwise, we must use the fully qualified name. The import allows a shorthand referring for classes. This is different from some other languages. For instance in Python, the import keyword imports objects into the namespace of a script. In Java, the import keyword only saves typing by allowing to refer to types without specifying the full name. System.out.print("Write your name:"); We print a message to the user. We use the print() method which does not start a new line. The user then types his response next to the message. Scanner sc = new Scanner(System.in); A new instance of the Scanner class is created. New objects are created with the new keyword. The constructor of the object follows the new keyword. We put one parameter to the constructor of the Scanner object. It is the standard input stream. This way we are ready to read from the terminal. The Scanner is a simple text scanner which can parse primitive types and strings. String name = sc.nextLine(); Objects have methods which perform certain tasks. The nextLine() method reads the next line from the terminal. It returns the result in a String data type. The returned value is stored in the name variable which we declare to be of String type. System.out.println("Hello " + name); We print a message to the terminal. The message consists of two parts. The "Hello " string and the name variable. We concatenate these two values into one string using the + operator. This operator can concatenate two or more strings. $ java com.zetcode.ReadLine Write your name:Jan Bodnar Hello Jan Bodnar This is a sample execution of the second program. Java command line arguments Java programs can receive command line arguments. They follow the name of the program when we run it. package com.zetcode; public class CommandLineArgs { public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } } } Command line arguments can be passed to the main() method. public static void main(String[] args) The main() method receives a string array of command line arguments. Arrays are collections of data. An array is declared by a type followed by a pair of square brackets []. So the String[] args construct declares an array of strings. The args is an parameter to the main() method. The method then can work with parameters which are passed to it. for (String arg : args) { System.out.println(arg); } We go through the array of these arguments with a for loop and print them to the console. The for loop consists of cycles. In this case, the number of cycles equals to the number of parameters in the array. In each cycle, a new element is passed to the arg variable from the args array. The loop ends when all elements of the array were passed. The for statement has a body enclosed by curly brackets {}. In this body, we place statements that we want to be executed in each cycle. In our case, we simply print the value of the arg variable to the terminal. Loops and arrays will be described in more detail later. $ java com.zetcode.CommandLineArgs 1 2 3 4 5 1 2 3 4 5 We provide four numbers as command line arguments and these are printed to the console. When we launch programs from the command line, we specify the arguments right after the name of the program. In Integraged Development Environments (IDE) like NetBeans, we specify these parameters in a dialog. In NetBeans, we right click on the project and select Properties. From the Categories list, we select the Run option. In the Arguments edit control, we write our arguments. Java variables A variable is a place to store data. A variable has a name and a data type. A data type determines what values can be assigned to the variable. Integers, strings, boolean values etc. Over the time of the program, variables can obtain various values of the same data type. Variables in Java are always initialized to the default value of their type before any reference to the variable can be made. package com.zetcode; public class Variables { public static void main(String[] args) { String city = "New York"; String name = "Paul"; int age = 34; String nationality = "American"; System.out.println(city); System.out.println(name); System.out.println(age); System.out.println(nationality); city = "London"; System.out.println(city); } } In the above example, we work with four variables. Three of the variables are strings. The age variable is an integer. The int keyword is used to declare an integer variable. String city = "New York"; We declare a city variable of the string type and initialize it to the "New York" value. String name = "Paul"; int age = 34; We declare and initialize two variables. We can put two statements into one line. Since each statement is finished with a semicolon, the Java compiler knows that there are two statements in one line. But for readability reasons, each statement should be on a separate line. System.out.println(city); System.out.println(name); System.out.println(age); System.out.println(nationality); We print the values of the variables to the terminal. city = "London"; System.out.println(city); We assign a new value to the city variable and later print it. $ java com.zetcode.Variables New York Paul 34 American London This is the output of the example. Java constants Unlike variables, constants cannot change their initial values. Once initialized, they cannot be modified. Constants are created with the final keyword. package com.zetcode; public class Constants { public static void main(String[] args) { final int WIDTH = 100; final int HEIGHT = 150; int var = 40; var = 50; //WIDTH = 110; } } In this example, we declare two constants and one variable. final int WIDTH = 100; final int HEIGHT = 150; We use the final keyword to inform the compiler that we declare a constant. It is a convention to write constants in uppercase letters. int var = 40; var = 50; We declare and initialize a variable. Later, we assign a new value to the variable. It is legal. // WIDTH = 110; Assigning new values to constants is not possible. If we uncomment this line, we will get a compilation error: "Uncompilable source code - cannot assign a value to final variable WIDTH". Java string formatting Building strings from variables is a very common task in programming. Java language has the String.format() method to format strings. Some dynamic languages like Perl, PHP, or Ruby support variable interpolation. Variable interpolation is replacing variables with their values inside string literals. Java language does not allow this. It has string formatting instead. package com.zetcode; public class StringFormatting { public static void main(String[] args) { int age = 34; String name = "William"; String output = String.format("%s is %d years old.", name, age); System.out.println(output); } } In Java, strings are immutable. We cannot modify an existing string. We must create a new string from existing strings and other types. In the code example, we create a new string. We also use values from two variables. int age = 34; String name = "William"; Here we have two variables, one integer and one string. String output = String.format("%s is %d years old.", name, age); We use the format() method of the built-in String class. The %s and %d are control characters which are later evaluated. The %s accepts string values, the %d integer values. $ java com.zetcode.StringFormatting William is 34 years old. This is the output of the example. This chapter covered some basics of the Java language.
http://zetcode.com/lang/java/basics/
CC-MAIN-2019-26
refinedweb
2,138
69.18
User:Laubersm/wiki cleanup notes From FedoraProject A number of groups are just beginning the process of going through wiki pages and renaming them so that they work better with the MediaWiki search engine and adding categories to help group them together by topics. Here are the resources I have used to work through this process with Docs Project and Package Maintainers. The official instructions Read these pages first! Everything else on this page is just another way of saying some of the same thing again. - Help:Wiki_structure describes the overall structure for page names, categories, and special namespaces. - FedoraProject:Deletion describes the very few cases where a page may be deleted. The general rule is to use a redirect or the Archive namespace. - Category:Wiki_policy is a category which contains the above pages and a few more. Using categories In some instances page naming is easier, in some instances assigning categories is easier, in most cases you need to think about both at the same time. Also when choosing category names, be sure to follow the same guidelines as page naming concerning natural language and case. Examples Category:Fonts has been the poster page for using categories. Notice that this category has no pages but only subcategories. There is a brief description at the top of the category. A category page can have more than a brief description, in fact it can be used as the process page for a number of pages. Category:In-progress fonts and Category:Packaging guidelines drafts are simple examples and Category:Package Maintainers is an example where what was originally a manually updated page of links to pages is now a category page where outside resources are still manually linked, but pages in the category are added dynamically at the bottom. Category:Ambassadors and Category:Events should end up with few (if any) pages but instead be collections of subcategories. Events can be a subcategory to marketing as well as ambassadors. Events can have subcategories by region North America events or year Events 2009 or both. Recurring events such as OpenExpo might have their own category and large events with lots of separate pages such as LinuxTag should have their own category. Tools Make use of the special pages. Special:SpecialPages has a list of useful lists. [Hint: there is a link to Special Pages on the left of every wiki page]]. - All pages lists all pages starting for a specific point. For example, to list all pages currently names Events/ which should be renamed and added to an events subcategory. - Categories lists all the currently used categories. If your page fits into one of these, use it. If not, create a new one. - Uncategorized categories and Uncategorized pages show categories and pages that should be put into categories. Question: It doesn't let me add the page to a category. The category name shows up at the bottom but is red as if it does not exist. What am I doing wrong? Answer: Nothing. A category that does not have any description or is not a subcategory to another category will show up as red even if there are 100 pages in the category. Click on the link to edit the category and add some description or make it a subcategory and the red will go away. Question: There are 50 pages in category FooBar and I want them to be in Foo at bar to follow the naming guidelines. Is this a manual process of editing each page? Answer: Yes, at least at the moment. There has been a script to rename pages but it too still requires a person to go through an list the old name and then the new name in a file. The script cannot (yet) add or change categories even if the person had manually decided what categories and added them to the file. Question: What if there are multiple categories for the same thing? Such as Events 2009 and Events in 2009 or FAD and Fedora Activity Day? Which should I use?Answer: The best end result is that all the pages are in one category (see previous question about changing each page). Your team (in this case Marketing or Ambassadors) should decide which one works bests and move all the pages to that category. Then the empty category is no longer needed. Since we rarely delete anything and there is not a move button on a category page, the solution here is to edit the category page and add a #REDIRECTline. In this case, Events in 2009 is empty (even though it is the better name) so edit that category page and add #REDIRECT [[:Category:Events 2009]]Note the colon in front of Category so that it links to the category and does not just make it a subcategory. Example of choosing a page name Help:Wiki_structure has several good examples [I know you read that page], but here are a few more things to think about: - Use a natural language name. - Do not use upper case except to start the first word or for proper names - How would you describe the page? - Think about the first line in the page. - Do not use level 1 headers - if you normally would use one, then that is probably your title. - Does it translate easily? Here are a few more examples: LUCI should be moved to Linux UC Irvine or even better to Linux UC Irvine (LUCI) This way a search for Irvine will find the page. Since many people who are familiar with the event would likely search on the acronym than it can also be included in the title. Here is a harder one: LinuxTag 2007 Social Event As it is, this should be LinuxTag 2007 social event (note the lower case for social event) but there are other options as well such as Social event at LinuxTag 2007 This is where we need to think about categories where the pages are sorted lexicographically. If the page is in Events in 2007 then I want it sorted on the L of LinuxTag but if it is in its own category of LinuxTag then perhaps I want it listed under S for Social event. No, you cannot have it both ways, if the page is to be in both categories someone will need to decided which makes more sense to more people. For public facing pages (rather than sub project status pages) you are encouraged to think about how to help a new user or contributor find the page. Most likely for an event page it will be best to use the name that will best represent the event and do not worry about where it appears in a category listing. To move a page, use the Move tab at the top of the pages. For more details check out the User:Ianweller/Wiki_tip_of_the_week for moving pages. How to use the Archive: namespace The Archive space allows a page to still exist if someone looks for it including with an advanced search, but is not searched by default. This means that a new user or contributor to Fedora Project would not find Archive:Marketing rewards in a default search at the same time that some other page that gives the history of the marketing team might still link to the page. Here is an example I gave in an email to actually archive a page: Take the page: Which is known to mediawiki as Marketing rewards Use the move tab and make the new name Archive:Marketing rewards this will set up the redirects. If you go to Marketing rewards you should end up at the archived page. [Note: the URL in the browser will not change, but look just below in the page itself where it will have the Archive: title and it will say "redirected from"] Help:Wiki_structure says to also use an archive category. Some groups are putting these files in a Category:<Group> archive others are not bothering. Archive: is not searched by default but can easily be searched if you need to find something. If you think you will reference them some, but don't want them in a default search for users, you will want a category as a shortcut to finding them all at once. Archive and redirection are strongly preferred over deletion. How to use the Meeting: namespace There is also a Meeting: namespace so that, like the Archive space mentioned above, meeting logs do not show up in a default search that a new user might initiate. In addition you can then put them in a sub category. If you look at Category:Docs_Project You will see under subcategories both Docs Project meetings where we have summaries and agendas and such and Docs Project meeting logs which have the IRC logs. All of the Ambassadors/Meetings/* pages should be moved and categorized such as moving Ambassadors/Meetings/2006-11-16 to Meeting:Ambassador meeting 2006-11-16 and putting it in a Category:Ambassador meetings 2006 which would be in Category:Ambassador meetings which would be in Category:Ambassadors
https://fedoraproject.org/wiki/User:Laubersm/wiki_cleanup_notes
CC-MAIN-2015-48
refinedweb
1,523
67.69
Pen Tablet Support/GTK Widget From OLPC This GTK widget is intended for applications that want to map tablet input to an on-screen widget that is the same shape and aspect ratio as the physical tablet. At its largest size, this would take up the full width of the screen and approximately 1/3 of the height of the screen. Note: As of April 12, 2008, this is being developed in Patrick Dubroy's git branch at git://dev.laptop.org/users/pdubroy/sugar-toolkit or on gitweb. Comments are welcome -- please leave them on the Talk page. Usage Using this widget is as simple as: from sugar.graphics.tabletarea import TabletArea tablet_area = TabletArea() This will create a gtk.DrawingArea on-screen. Whenever a stroke is detected on the tablet, a corresponding stroke will appear inside the widget. Some useful API: # Returns a list of strokes that have been made inside the tablet area tablet_area.get_strokes() # Returns a copy of the gtk.gdk.Pixmap displayed on the tablet area tablet_area.get_pixmap() # Clears the tablet area -- both the pixmap and the list of strokes. tablet_area.clear() Full API documentation (subject to change) can be found here. Sample Activity For more information, please see the sample activity: source is in git://dev.laptop.org/users/pdubroy/TabletAreaTest or on gitweb. Alternatively, you can just grab the bundle: TabletAreaTest.
http://wiki.laptop.org/index.php?title=Pen_Tablet_Support/GTK_Widget&oldid=125666
CC-MAIN-2015-40
refinedweb
227
67.15
a(); b(); print "$var\n"; sub a { local $var = "a\n"; c(); } sub b { local $var = "b\n"; c(); } sub c { # i'm pleasing you to print a or b print "var: $var"; } [download] Is there a hack to do the above? If not, here is my next best choice... the sub c() is actually spit out by a class and evaled in the callers package, is it possible to have the eval happen in the callers namespace? That is: $b = new SubMaker(); sub a { my $var; $b->make_sub("subname"); subname(); } [download] thanks. use strict; # ALWAYS! $a = LetterPrinter( "a" ); $b = LetterPrinter( "b" ); $a->(); # these can also be called with ampersand $b->(); # ie: &$b; sub LetterPrinter { my $letter = shift; return sub{ print $letter, $/ }; } [download] Yes, local would probably be the trick, but I don't have that luxury. This thing is supposed to plug into a lot of existing code that uses "my" variables. It will work if I eval the manufactured sub each time, I was just trying to find a way around that because it is such a performance hit. I'm becoming convinced that what I want to do is impossible, and for all I know, it's impossible for a good reason :-) From what I've been reading, the "my" variables live on what is known as a "scratchpad", what I was looking for was a way for the manufactured sub to get access to that scratchpad. Of course the scratchpad changes each time the parent sub is called, so the pointer to it in the manufactured sub would have to change with each invocation. I wonder if the rfc period for perl 6 is closed :-) Hopefully merlyn will chime in here and tell me why it's such a bad idea to try and do what I am trying to do, because there is probably a good reason not to allow it, I just don't know what that is yet. :-) What you are trying to do has serious conceptual problems for reasons I tried to explain in RE (3): BrainPain-Help. However instead of saying what it is you want to do, why don't you explain what it is that you are trying to do? Then instead of trying to fight the design of the language we might be able to tell you how to get it done working with the language. For instance you could always pass the variables you want access to in as arguments to the function. Or if it is more convenient, pass in references to the variables instead. (Not strictly needed, but it tends to warn the caller that you may intend to do stuff to the variable.) I am trying to figure out what you need direct access to your caller's lexical variables for or why providing that wouldn't ruin the entire point of having them - and I am failing... So, what am I trying to do? I am trying to provide an easy to use output functionality to perl programmers, ala Template::Toolkit, embperl, etc... I do understand how to do it by passing variables or eval-ing the sub each time. Both have drawbacks in my mind. The drawback to the passing the variables is that is no longer quite as easy as envisioned: If you decide to display a new variable, you can't just change your template and be done, you now must change the code that passes in the hash or hashref to the display function. Eval-ing each time works ok, but it is molasses slow. As for ruining the point of having lexicals, I hope I'm not quite proposing that... The lexicals would only be accessible to the sub that made them, and to subs that were created by the sub that made them. I'd say they'd still be pretty safe from falling into the soup. Now I don't know anything about perl internals except from what I read in Advanced Perl Programming but it tells me that lexicals live on a scratchpad for each sub. I think it would be useful if subs created in a sub had access to it's parent's scratchpad, and if the parent that created it is no more, then the last instance of the parent sub that was created. I'd even accede that the created sub must be called from within the parent sub -- but with access to the scratchpad of the current instance of the parent sub, not the scratchpad of the instance of the parent sub that did the actual creation (which may be long gone...). I know this is confusing, and I'm probably not explaining myself well, but if you get what I'm saying... what do you think of it? thanks use strict; my $evaled = 0; # very simplified... sub makesub { my($name) = @_; return "sub $name { print \"\$var \"; }"; } sub a { my($var) = @_; if(!$evaled) { eval(makesub("somesub")); $evaled=1; } } a("what"); somesub(); a("the"); somesub(); [download] prints: what what sub a { my($var) = @_; if(!$evaled) { eval(makesub("somesub")); $evaled=1; } somesub(); # only place I call it from. # only want to eval once per # program execution, but have # access to the my variables for # each calling of "a" } [download] #!perl -w use strict; # ALWAYS! a("what"); somesub(); a("the"); somesub(); { my $var; # shared only between a() and somesub() sub a { $var = shift } sub somesub { print $var, $/ } } # proof that $var is scoped correctly: my $var = 'global'; print $var, $/; somesub(); print $var, $/; [download] Update: I'm looking at this, and it doesn't look like your original question. It seems you wanted named routines that came from the same code but did different stuff based on some third party manipulator function... let me think on that. #!perl -w use strict; # ALWAYS! a("what"); b("the"); { use vars ('$var'); local $var; # shared only between a() and somesub() sub a { local $var = shift; _somesub() } sub b { local $var = shift; _somesub() } # sub routines with a leading _ usually denotes a private func. sub _somesub { print $var, $/ } } [download] &a; &b; sub a { my $var = 1; &c($var); } sub b { my $var = 2; &c($var); } sub c { my $var = shift; print "var=$var\n"; } [download] 1. Keep it simple 2. Just remember to pull out 3 in the morning 3. A good puzzle will wake me up Many. I like to torture myself 0. Socks just get in the way Results (284 votes). Check out past polls.
http://www.perlmonks.org/index.pl?node_id=37758
CC-MAIN-2016-44
refinedweb
1,080
75.95
It's a very different world when a program is an algebraic structure rather than a bag of characters, when you can actually do algebra on programs rather than just swizzling characters around. A lot of things become possible. --James Gosling Read the rest in Analyze this! Two years from now, spam will be solved, --Bill Gates, January, 2004 Read the rest in Spam Will Be 'Solved' In 2 Years--Gates. --Vinod Khosla Read the rest in Wired 14.10: My Big Biofuels Bet Read the rest in An Atheist Can Believe in Christmas I have made it my life’s work to rid my brain of recursive thinking: it simply does not gel well with text processing under a fixed-stack system like Java. For text processing, the recursive solution is always the wrong solution…unless your system implements the tail recursion optimization of course --Rick Jelliffe Read the rest in Fake real-time blog from XML 2006: day one...some more. --Scott Adams Read the rest in The Dilbert Blog: Electronic Voting Machines I understand the philosophy that developer cycles are more important than cpu cycles, but frankly that's just a bumper-sticker slogan and not fair to the people who are complaining about performance. --Joel Spolsky Read the rest in Joel on Software Implementation inheritance causes the same intertwining and brittleness that have been observed when goto statements are overused. As a result, OO systems often suffer from complexity and lack of reuse. --John Ousterhout Read the rest in Scripting, IEEE Computer, March 1998 Last year, a Republican Congress passed a highway bill with 6,371 special projects costing the taxpayers 24 billion dollars. Those and other earmarks passed by a Republican Congress included $50 million for an indoor rainforest, $500,000 for a teapot museum; $350,000 for an Inner Harmony Foundation and Wellness Center; and of course, as you all know, $223 million for a bridge to nowhere. I didn’t see these projects in the fine print of the Contract with America, and neither did the voters. --Sen. John McCain, R-Arizona Read the rest in McCain Tells Conservatives G.O.P.’s Defeat Was Payback for Losing ‘Our Principles’ mailing list, Wednesday, 17 Aug 2005 08:25:54 Did you every try to get a bunch of freshmen to add a JAR to their class path? It's not a pretty sight. --Cay Horstmann Read the rest in Cay Horstmann's Blog: The World's Simplest Unit Testing Framework GPL version 2 is the proper forcing function. By keeping all the industry innovations viewed and shareable, it pushes everyone toward compatibility." --Rich Green, Sun Read the rest in Sun picks GPL license for Java code | Tech News on ZDNet. --Ron Garrett Read the rest in Rondam Ramblings: Top ten geek business myths. --Tim Bray Read the rest in ongoing · Java Is Free The Republican Party is not now, never was and never will be a conservative party. It is what it has always been – a representative of the rich and of big business. --Charley Reese Read the rest in No Conservative Party by Charley Reese What. --Roland Turner Read the rest in Armadillo Reticence: Sun, Java and GPLv2 There’s class warfare, all right; but it’s my class, the rich class, that’s making war, and we’re winning. --Warren Buffett Read the rest in In Class Warfare, Guess Which Class Is Winning. --Sam Harris Read the rest in RichardDawkins.net. --Dalibor Topic Read the rest in Cutting Free? --Ben Stein Read the rest in In Class Warfare, Guess Which Class Is Winning Just because you buy a DVD to watch at home doesn't give you the right to invite friends over to watch it too. That's a violation of copyright and denies us the revenue that would be generated from DVD sales to your friends. --Dan Glickman, MPAA Read the rest in BBspot Java Standard Edition contains about 6 million lines of code. Our legal team had to go over it, line by line, and look for all copyright marks and third-party involvements. Where Sun didn't have the correct licenses, we had to contact the owners, one by one, and determine the rights. --Mike Dillon, Sun General Counsel Read the rest in Sun Pours Out Java Cup Anything that we scientists can do to weaken the hold of religion should be done and may in the end be our greatest contribution to civilization. --Dr. Stephen Weinberg Read the rest in A Free-for-All on Science and Religion. --Mark D. Rasch, J.D. Read the rest in Vista's EULA Product Activation Worries First let’s get something straight. The real Jean Grey committed suicide in “The Uncanny X-Men” #137 in 1980. Every issue since then with “Jean Grey” in it is a PACK OF LIES. --Erik Even Read the rest in Furinkan High School Kendo Club: The 20 Sexiest Sci.) --Ian Hickson Read the rest in Hixie's Natural Log People have been hesitant to distribute Java worldwide with Linux because of license alignment. This is the last gate to ensure that Java will be distributed worldwide. --Rich Green, Sun Microsystems Read the rest in Sun picks GPL license for Java code | Tech News on ZDNet --Tim Bray Read the rest in ongoing · Java Is Free If Java was an open standard, technologies like C# and the technologies it works with might not exist today. --Bob Sutor, IBM Read the rest in IBM pressures Sun to free Java - TechUpdate Over the last 7 years I have come to the following conclusions: - There are no instances in which TDD is impossible. - There are no instances in which TDD is not advantageous. - The impediments to TDD are human, not technical. - The alternative to TDD is code that is not repeatably testable. --Robert Martin on the junit mailing list, Sunday, 17 Aug 2006 10:53:39 The JRE+JDK was a loss-leader from the outset; the intent was to get adoption as widespread as possible so that they could sell related products and services. Sadly, they were obsessively focussed on preventing forks, which meant no open-source licensing, which severely curtailed reach amongst their largest natural constituency (developers with horizons wider than "we use it because it comes from Microsoft"). Sun has at last realised this error, realised that trademark law makes it possible to prevent forks from creating confusion, perhaps even realised that the ability to fork is a good thing, not a bad thing. --Roland Turner Read the rest in Armadillo Reticence: Sun, Java and GPLv2 As a rule of thumb, whenever multiple threads share data, you must make sure the relevant threads exchange monitor locks to ensure consistent memory views. --Vladimir Roubtsov Read the rest in The thread threat"? --Alan Hargreaves Read the rest in Alan Hargreaves' Weblog : Weblog. --Eben Moglen Read the rest in Alan Hargreaves' Weblog : Weblog I think Sun has well, with this contribution have contributed more than any other company to the free software community in the form of software. It shows leadership. It's an example I hope others will follow --Richard M. Stallman, Free Software Foundation Read the rest in Alan Hargreaves' Weblog : Weblog. --Joel Spolsky Read the rest in Joel on Software The war is over and Linux won. --Dana Blankenhorn Read the rest in Open Source | ZDNet.com. --James Gosling Read the rest in James Gosling Q & A: Builder AU: Program: At See the rest in Colbert calls it quits Extending a class that you don't have source code for is always risky; the documentation may be incomplete in ways you can't foresee. --Peter Norvig Read the rest in Java IAQ: Infrequently Answered Questions. --Michael Moore Read the rest in MichaelMoore.com : 5 Good Reasons to Vote Today ... a letter from Michael Mo. --Paul Krugman Read the rest in Limiting the Damage. --Charley Reese Read the rest in No Conservative Party by Charley Reese. --Shannon Hickey Read the rest in Meet Shannon Hickey, Technical Lead for the Swing Toolkit Team at Sun Microsystems. --Paul Graham Read the rest in The 18 Mistakes That Kill Startups. --Bruce Schneier Read the rest in Wired News: The Boarding Pass Brouhaha?” --John Cole Read the rest in Balloon Juice Java EE's days have been numbered for a while now. Clearly, every time a new version comes out or module gets added, it only adds to the complexity. Eventually, it'll simply collapse under its own weight. It's not like there will be a future version of Java EE that's more lightweight than its predecessor. --Jason Bloomberg, ZapThink Read the rest in Analysts see Java EE dying in an SOA world." --Pete Ashdown Read the rest in Wired News: Techie Faces Orrin Hatch Nov. 7 Read the rest in Wired News: Battle of the New Atheism Right now, there are two main groups, the Alliance and the Horde, which roughly correspond to "good" and "evil," although when most of your quests involve committing murder for a bribe, the moral distinction becomes tricky. I suggest they give us a third faction, the "apathetic" faction. The group's quests will all involve posting on message boards about how both sides are equally stupid and there's no point in trying because frankly demons are going to invade our dimension whether or not we do anything so everyone should just quit whining, except for people who are whining about how everyone's whining. When you get to 70th level, someone creates a Wikipedia article about you. --Lore Sjöberg Read the rest in Wired News: Warcraft Wonders of Tomorrow I am quite convinced that test-first is a good approach to a huge majority of software situations. It is my default position. When, as very rarely happens, this approach leads to an apparent impasse, I will expend significant energy to find a way through before abandoning the test-first approach. --Robert Martin on the junit mailing list, Sunday, 1 Jun 2006 08:41:34 One of the basic rules of debugging applies: any given bug is far more likely to be in your code than in the library. (Not "must be", but definitely "far more likely to be".) Can you create a *simple* program that demonstrates the problem? --Glen Fisher Read the rest in Re: Java Spelling Framework bugs don’t be shocked when our grandkids bury much of this generation as traitors to the nation, to the world and to humanity. --Kevin Tillman Read the rest in Truthdig - Reports." --Bruce Eckel Read the rest in Testing vs. Reviews. --Steve Yegge Read the rest in Stevey's Blog Rants: Blogger's Block #4: Ruby and Java and Stuff Mostly, in the end, it appears that Java on the client lost out to Flash of all things! This must be embarrassing for Sun, but it puts Java in its place. It couldn't even be competitive in the most inessential of tasks. --Larry Seltzer Read the rest in Java's Momentum Is Running Low Read the rest in The 18 Mistakes That Kill Startups. --Brian Goetz Read the rest in Testing Concurrent Programs. --Marcus Ranum Read the rest in Interview with Marcus Ranum That reminds me of when I started out as a programmer and I was very intimidated by the fact that I knew so little and everyone else must know so much. After a while I got some experience but it was not "real" experience, we didn't have really good control over what we were doing so I dreamt of working on a "real" team, you know the kind they must have in banks and when developing medical equipment and such... Later I have been working at a bank and I know more than I would like to know about development of medical equipment. --Joakim Ohlrogge on the junit mailing list, Friday, 4 Aug 2006 12:54:46. --Bruce Schneier Read the rest in Wired News: Why Everyone Must Be Screened why does everyone use ArrayList and hate Vectors these days? Because Vector is synchronized and is slower (or because it's trendy to use the later collection APIs to show how superior you are?) Try it sometime. Add a million objects to a collection and get them out again. Which is faster? The winner is... Vector. --Rolf Howarth on the java-dev mailing list, Friday, 4 Feb 2005 07:44:53 It's an urban myth that final actually speeds up anything in Java, just like it's an urban myth that synchronized blocks slow it down. Both may have been true in Java 1.0 but ain't any longer. A modern JIT compiler is almost certainly waaaay cleverer than you, so don't try and second guess it. Just write code that does what it's supposed to and is easy to read and let the compiler worry about low level optimisations. --Rolf Howarth on the java-dev mailing list, Friday, 4 Feb 2005 07:44:53. --Adrian Kingsley-Hughes Read the rest in » Protect DVD-Video. --James Gosling Read the rest in James Gosling: For Ruby or Ajax or SOA, it's NetBeans Dynamic code feels great to program in. After the first day you have half the system built. I did a huge portion of my thesis work in Python and it was a life saver. Thesis work doesn’t need to be bug free, it is the quintessential proof-of-concept (and yet so many CS students, when faced with a problem, break out the C++). But I have also worked on a large, multi-programmer, multi-year project, and this was not so pleasent. A large dynamically typed code base exhibits all the problems you would expect: interfaces are poorly documented and ever changing, uncommon code paths produce errors that would be caught by type checking, and IDE support is weak. The saving grace is that one person can do so much more in Python or Ruby that maybe you can turn your 10 programmer program into three one programmer programs and win out big, but this isn’t possible in a lot of domains. It is odd that evangelists for dynamic languages (many of whom have never worked on a large, dynamically-typed project) seem to want to deny that static type-checking finds errors, rather than just saying that type-checking isn’t worth the trouble when you are writing code trapped between a dynamically typed database interface and a string-only web interface. --Jay Kreps Read the rest in Empathy Box :: 5 Principles For Programming If you copy-n-paste a handler half a dozen times, each time making minor changes, it's a good bet that the resulting code can be rearranged to separate the bits that stay the same from the bits that changed; the former become a generic handler and the latter into additional parameters to that handler. Bloat and complexity are reduced, which makes for better code, plus you've also now got a nice reusable handler you can use the next time. --Hamish Sanderson on the applescript-users mailing list, Sunday, 29 Sep 2005 23:05:39 Programmers have very well-honed senses of justice. Code either works, or it doesn’t. There’s no sense in arguing whether a bug exists, since you can test the code and find out. The Read the rest in A Field Guide to Developers C/C++ datatypes were based on the pysical host architecture and not on the effective data model that people want when developing portable applications; this is the major cause of the complexity of porting C/C++ applications across platforms, and even the most "portable" libaries are in fact "ported" by adding lots of modifications and conditional macros that are alien to the effective semantics of the language. --Philippe Verdy on the unicode mailing list, Sunday, 21 Sep 2006 23:38:54. --Vinod Khosla Read the rest in Wired 14.10: My Big Biofuels Bet. --Ron Garrett Read the rest in Rondam Ramblings: Top ten geek business myths secrecy is the essence of evil. --Len Bullard on the xml-dev mailing list, Friday, 29 Sep 2006 10:47:43 I think that conspiracy-mongering on 9/11 is a waste of time. The far greater conspiracy occurred after 9/11 when basically a neo-cabal inside our government hijacked policy and went to war. That was as broad a conspiracy as we can get and it was about 20, 30 people. That's all, they took over --Oliver Stone Read the rest in CNN.com - Oliver Stone: 'I'm ashamed for my country' people always say static typing catches more errors at compile time. It is true, but these are the sort of errors that raraly occur anyhow and are usually trivial to notice, find and fix (if you have tests). And static typing makes you pay a high price for preventing these trivial errors - it's not just the type declarations for the vars, the impact goes a lot deeper. --Antti Karanta on the junit mailing list, Friday, 3 Feb 2006 13:07:17 Eclipse development is far out-pacing its open source rival. This is likely because Eclipse benefits from a huge and growing ecosystem of contributors around the world, many of whom work on commercial software based on Eclipse RCP. Despite intense marketing and bundling efforts, and breaking down the barriers between the NetBeans and JDK teams, Sun has so far failed to put a dent in Eclipse's momentum. If you can't beat 'em… --Ed Burnette Read the rest in » NetBeans 6.0M3 vs. Eclipse 3.3M2 | Ed Burnette's Dev Connection | ZDNet.com I'm not in the business of using code to protect people from their own carelessness. I provide good documentation in the form of a roadmap, some Javadoc and tests. If, after all that, they insist on being careless or lazy, then they deserve whatever they get. --J. B. Rainsberger on the junit mailing list, Friday, 02 Sep 2005 08:35:49 People no longer necessarily install Java, and they don't notice it missing when it's. --Larry Seltzer Read the rest in Java's Momentum Is Running Low My big complaint with Mac OS security is that things like FileVault and secure virtual memory shouldn't be options -- they should be defaults. I believe that it's unethical for the computer to give the appearance of deleting information while actually leaving that information on the disk; computers shouldn't lie (explicitly or implicitly) to their users. --Simson Garfinkel Read the rest in Safe storage, Mac style. --Christopher Griffith Read the rest in How Many Lightbulbs Does it Take to Change the World? One. And You're Looking At It. In five years, Java EE will be the CORBA of the 21st Century. People will look at it and say, "It had its time but nobody uses it any more because it was too complicated." --Richard Monson-Haefel Read the rest in Analysts see Java EE dying in an SOA world What has to be especially satisfying about this plan for Apple is that there is literally no response even possible from its greatest competitor -- Microsoft. The. --Mark Stephens Read the rest in PBS | I, Cringely . September 22, 2006. --Charlie Demerjian Read the rest in Microsoft Media Player shreds your rights. --President Hugo Chavez (translated) Read the rest in President Hugo Chavez Delivers Remarks at the U.N. General Assembly Everyone in Iraq knows Bush is a dickhead. He's the boss' kid. Everybody I know who has a successful business who has a kid - the kid is always a fuckhead. Have you ever noticed that? --Jesse James Read the rest in BULLOCK'S HUSBAND IN BUSH RANT I've always been a big fan of diversity and diversity certainly has its dark sides and it's like it's really confusing. The. --James Gosling Read the rest in James Gosling: For Ruby or Ajax or SOA, it's NetBeans Software development is, ultimately, controlled innovation - a software developer (unlike nearly all other professionals) is typically required to innovate on a daily basis. In only comparatively rare cases do software developers get to keep the fruits of their innovation; far more often they will receive wages that, when actual time versus "in-seat" time is calculated, place them fairly low down the totem pole in comparison to most other professionals. I'd argue that for most of the programmers working today on Longhorn, Microsoft will likely be making $100 return on investment for every $1 spent on compensation - with the resulting IP owned by Microsoft to boot. Not a bad return for a shared office, a few cola machines and strategically placed foosball games. --Kurt Cagle on the xml-dev mailing list, Monday, 6 Jun 2005 16:41:24 At one time, the term alpha test meant something that was feature complete but had known bugs, and the term beta test was likewise feature complete and had no known bugs. The purpose of an alpha test was to find out whether the feature set was what the users needed, and a beta would be the version shipped to manufacturing if the test showed no significant issues. With XP, this sequence has reversed: an iteration test version should be defect free but be feature incomplete. --John Roth on the fitnesse mailing list, Monday, 11 Sep 2006 16:05:20. --Mark Shuttleworth Read the rest in Mark Shuttleworth » Blog Archive » Conflicting goals create tension in communities It is always possible to write tests first. The question is whether it is always practical. There are some situations, specifically having to do with untested legacy code, in which the cost to write tests is so high that manual testing might be cheaper; at least in the short term. But over time those situations can be mitigated to make testing easier. --Robert Martin on the junit mailing list, Sunday, 1 Jun 2006 20:46:33 Remember the ASSSSS principle - A Simple Site Saves Stress Sometimes. --David Matusiak on the webgroup mailing list, Monday, 11 Sep 2006 11:26:30 Today, in the West, there are no good excuses for religious belief - unless we think that ignorance, reaction and sentimentality are good excuses. --Martin Amis Read the rest in The Observer | Review | The age of horrorism (part one) trying to make digital files uncopyable is like trying to make water not wet. --Bruce Schneier Read the rest in Wired News: Quickest Patch Ever What kind of contract includes a provision that one of the parties has the right to violate the contract with impunity? Well, the Windows XP EULA for one, as an interesting analysis of Microsoft's legalese points out. --Ed Foster Read the rest in InfoWorld GripeLine by Ed Foster | InfoWorld | A Contract Only Microsoft Can Break | September 5, 2006 12:08 AM | By Ed Foster When Java was first released, performance was that of a middling interpreted language - now it is as fast as any compiled language (including C) and only the design of your application holds back performance, --Jack Shirazi on the Java Performance Tuning Newsletter mailing list, Sunday, 31 Mar 2005 14:34:42 Some people want the future of desktop Java to lie in rebuilding existing Java apps. This was the vision in the late '90s. Today some think Java apps have failed on the desktop because they don't see lots of Java technology-based word processors, spreadsheets, or graphics apps. It was shortsighted of us to think that developers would rewrite all of their old apps to run in the Java programming language. Existing apps aren't written in Java software or Perl or Ruby or .NET or anything else new simply because they haven't been rewritten at all. Existing apps are still in C++ and always will be. The future of desktop Java technology -- and the future of other new languages and runtimes -- is in new kinds of applications, often talking to web-based services. I'm thinking of something like iTunes, where a web service, the music store, is as much a part of the application as the local app itself. --Joshua Marinacci Read the rest in Meet Josh Marinacci of the Swing Toolkit Team at Sun Microsystems). --Joel Spolsky Read the rest in Joel on Software It's interesting how many bugs you can find in ancient code that thousands of people use every day --Jeremias Maerki on the fop-dev mailing list, Tuesday, 30 Aug 2005 21:22:01 A good programmer can write a better program in a more appropriate language. --Dan Saks Test your multi-threaded code on an unusually slow system. We developed a bunch of code that passed its unit tests just fine when run from our desktops (fast single processor WinXP machines) and on our CruiseControl server (fast dual processor Linux machine). But when we tried running it on a quad processor PIII, stuff failed that we thought for months was safe and sound. --Todd Bradley on the junit mailing list, Friday, 25 Aug 2006 09:02:09 Third World lives are worth much less than the European lives. That is what colonialism was all about. --Srirupa Prasad, University of Wisconsin-Madison. Read the rest in Wired News: Testing Drugs on India's Poor That's one of the nice things about living in Cleveland: visiting just about any other city in the US a really cool experience. --Alex Papadimoulis Read the rest in The Daily WTF Any programmer that cannot follow rule N cannot follow rule M. My experience is that refusal to follow coding conventions is a warning flag, and that more serious problems will eventually appear. This is especially true for rules where the intent is to produce code that can be manipulated by others. A programmer that refuses to do this is costing money, and very likely doing so deliberately (with job security in mind). --Andrew Gideon on the wwwac mailing list, Sunday, Fri, 11 Aug 2006 14:18:15. --Geert Bevin Read the rest in The Philosophy of RIFE --Dan Roberts, director of marketing for developer tools, Sun Read the rest in Sun: We're happy with Eclipse, honest... | The? --Ben Stein Read the rest in Looking for the Will Beyond the Battlefield I'd like to make two quick points in favor of static typing: - The value is not so much about robustness (I agree that mis-casts are rare) but about documentation. I do a lot of code reviews every day and I can tell you that reviewing Python or Ruby is an order of magnitude harder than reviewing Java because I can never tell what types are expected from method signatures. - Refactoring in dynamically typed languages is inherently unsafe. You can't even rename a method reliably. I'm glad it worked for you, but you need to keep in mind that renaming in a dynamically typed language is nothing more than a string replace. Use with caution. --Cédric Beust on the junit mailing list, Monday, 6 Feb 2006 08:40:05. --Weiqi Gao Read the rest in The First Thing I Would Do When I Get My Hands On Open Source Sun-Java ... Despite what some parts of the media industry would like us to believe, copyright does not and is not intended to give authors complete control over all use of anything someone might have written. --John Levine on the cbp mailing list, Sunday, Aug 2006 01:02:04 Smalltalk was more of a conceptual breakthrough than Java, but Smalltalk itself had several important predecessors from which it borrowed programming concepts. Java is a broadly successful synthesis of predecessor ideas plus its own unique networking-oriented innovations--just right for the Internet. Java will still be broadly used long after Smalltalk has contracted to a smaller and smaller niche. --Charles Babcock Read the rest in InformationWeek Weblog: 5 That Almost Made The List Of Greatest Software Ever While you may think you (or your colleague) couldn't possibly get used to a different format, empirical evidence otherwise. Whether it's Hungarian notation, K&R vs. ANSI C, underscores_in_names vs. midCaps, whatever, people quickly get used to whatever they're dealing with day to day. Style /consistency/ is far more important than the particulars of the style itself. --Colin Strasser on the wwwac mailing list, Friday, 11 Aug 2006 11:03:25 How many buttons do you need to click? This was the excellent question asked during a demo I recently saw. What was so good about that question? It is one of the better metrics for measuring user-interface productivity, which is in turn a key metric for perceived performance of user interfaces. --Jack Shirazi in the Java Performance Tuning Newsletter, Sunday, 31 Jul 2005 15:42:45 Operation Iraqi Freedom has been exposed as a gruesome travesty. An old-fashioned colonial war, built on lies, greed and geopolitical fantasies, it has nothing to do with 'disarming' Iraq or 'liberating' the Iraqi people. Iraq is a threat to no one. No connection has been found between Iraq and the terrorist attacks of September 11, and no evidence has been provided that Iraq has continued to manufacture chemical, biological and nuclear weapons and might pass them on to terrorist groups. All this is malicious propaganda to mask the real war aims which are what they have been since 1991: to affirm America's global supremacy in a strategically vital, oil-rich part of the world, and to protect Israel's regional supremacy and its monopoly of weapons of mass destruction. --Patrick Seale Read the rest in Dar Al Hayat. --Ron Goldman Read the rest in Innovation Happens Elsewhere: Part Two of a Conversation With Sun Microsystems Laboratories' Ron Goldman When I think that things around me works good enough and I can't see any problems that needs to be solved I will be really scared since it probably means that: - a) I have given up - b) I have stopped learning and trying new things. - c) there is probably a c... --Joakim Ohlrogge on the junit mailing list, Friday, 4 Aug 2006 12:54:46. --Bruce Schneier on the CRYPTO-GRAM-LIST mailing list, Sunday, Wed, 15 Jun 2005 03:00:49 Today is yet another Big LayoffReduction-in-Force Day at Sun Microsystems. Between 4,000 and 5,000 jobs are expected to be cut this year, and today 311 jobs were cut from my local Sun Colorado campus. I have only a few friends left there... most of us got the boot one way or another over the last 4 years. But what I think is worse than the layoffs is the anticipation of layoffs. Ever since the first cuts began (the first one was supposed to be the only one, but there have been a gazillion since then), most of the employees who made each successive cut became more and more anxious, and less and less focused on whatever it is we were supposed to be doing to help the company turn things around (after the whole "we're the dot in dot com" thing stopped being Good Positioning). --Kathy Sierra Read the rest in Creating Passionate Users: Silver lining on Sun layoffs? It's all about the frameworks. People talk about Java vs. Objective-C vs. Python vs. whatever, and I think the discussions are just idiotic. It's like arguing what kind of needle you want to use on a syringe and not paying any attention to what substance you're actually injecting yourself with. Frameworks are the substance of programming. You build on top of a good one, your program is solid and fast and comes together beautifully. You build on top of a bad one, your life is miserable, brutish, and short. I have much respect for my homies running Linux, but I just don't care for the frameworks. I programmed X11 in college and it sucked rats. I'm not going back to that, ever. --Wil Shipley Read the rest in On Being and Deliciousness, with Wil Shipley. --Robert Fisk Read the rest in Democracy Now! | Robert Fisk Reports From Lebanon on the Israeli Bombing of Qana That Killed 57, Including 37 Children I've said it before, I'll say it again: the real problem is LACK OF DOCUMENTATION. Those who describe application interfaces as 'frustratingly inconsistent' merely misdiagnose a symptom and miss the cause completely. Application developers who do not provide comprehensive interface documentation need to be held accountable by their users, because without accurate, detailed documentation users are left to figure out mystery meat APIs with nothing more than intelligent guesswork and random attempts at applying what's already been found to work on other applications to see if anything sticks on this one as well (where the 'inconsistent' misdiagnosis comes from). --Hamish Sanderson on the applescript-users mailing list, Sunday, 29 Sep 2005 09:33:27 A common view of the schema or DTD is as a means to validate the instance for acceptance. However, it is perfectly useful as a means to validate an instance for rejection. You can have anti-schemas, anti-anti-schemas and so forth given some dynamic exchange such as messages which are themselves, evolving (the schema is a kind of message). --Claude L (Len) Bullard, on the xml-dev mailing list, Sunday, 10 Feb 2005 10:46:05 America wasn’t founded as a theocracy. that America is not the light of the world and the hope of the world. The light of the world and the hope of the world is Jesus Christ. --Rev. Gregory A. Boyd Read the rest in Disowning Conservative Politics, Evangelical Pastor Rattles Flock I used to have a blog, a wiki and forum software on my web server. But I got fed up with the never-ending job of staying on top of the latest "oops!" exploit. --Steve Manes on the WWWAC mailing list, Tuesday, 09 May 2006 10:12:45 In almost every successful IT project I've ever been involved with it's been a nuts-and-bolts techie that's had the most important impact. More often than not, the "business skills" types were more hindrance than help. Many times their superiority and arrogance led to project failure. For as long as I've been following IT, it's been the dream of business people and others to banish hard-core techies from such an important industry. There's always some prediction about how some new tool or methodology will finally make us irrelevant. Five years down the line, we'll have built thousands of new successful products, while those new tools and methodologies will be long forgotten. You need us guys, get over it. --Paul Knapp Read the rest in Sorry businesspeople, but you need techies to build technology. --Ted Neward Read the rest in The Blog Ride. --Norm Walsh Read the rest in Working with JAXP namespace contexts Regulatory compliance (BASEL II, Sarbanes-Oxley, HIPPA) will be an influence. If you have to be able to defend how you arrived at some numbers seven years ago, you're probably going to want a repository that supports versioning for XML schemas, source libraries, executables, XML documents, specifications, e-mails, diagrams, spreadsheets, and more. --Ken North on the xml-dev mailing list, Monday, 3 May 2004 a program that is 10 times longer is 32 times harder to write.Or put another way: a program that is 10 times smaller needs only 3% of the effort. --Stephen Pemberton, XTech 2006 Read the rest in The Right Way to do Ajax is Declaratively | What Not How |. --Patrick Cockburn Read the rest in Independent Online Edition > World Politics. --Jeff Jarvis Read the rest in BuzzMachine » Blog Archive » Some friendly advice from Dell We don't allow doctors to perform surgery before washing their hands. It took a lot of effort and angst to get doctors to agree to this procedure when it was first discovered as beneficial. I think the effort was noble, and certainly not pointless. I look at TDD in exactly the same way. It is a minimum standard of professionalism. You wash your hands before you cut, or you don't cut. Period. --Robert Martin on the junit mailing list, Sunday, 1 Jun 2006 08:41:34 --Kathy Sierra Read the rest in Creating Passionate Users: Do your graphics say the wrong thing?. --Steve Wozniak Read the rest in The Great Woz Tells All The odds are zero that RFID passport technology won't be hackable." --Bruce Schneier , Counterpane Internet Security Read the rest in Technologists object to U.S. RFID passports. --Larry C Johnson Read the rest in NO QUARTER: Israel Takes A Stupid Pill If you are a member of AT&T (including Cingular and SBC), Bell South or Verizon, your telecom company willingly sold the private telephone records of American citizens to the Bush administration’s illegal domestic spying operation. -- Michael Kieschnick, Working Assets Read the rest in WorkingForChange The goal of the virtual machine is to provide for code portability, while in SOA, interoperability is far more important.. --Jason Bloomberg, ZapThink Read the rest in Analysts see Java EE dying in an SOA world Let’s review what led up to me receiving this comment. 1.) I spend hard earned dollars on a Dell computer. 2.) I detect unwanted software on my computer 3.) I try to remove unwanted software on my own, only to discover it doesn’t easily uninstall. 4.) I ask Dell customer service for support and am asked to pay $49 to have it removed. 5.) I exercise my freedom of speech by truthfully complaining about my experience on my web site. 6.) Dell calls me a dipshit. Wow, what a way to win back your customers, Dell. --Michael Righi Read the rest in www. Michael Righi .com. --Joshua Bloch Read the rest in Official Google Research Blog: Extra, Extra The challenge isn't from the government alone, from industry alone or from technology alone. In different moments, each of these are friends of civil liberties. Sometimes they conspire in some combination of the three to be a challenge to civil liberties. --Jennifer Granick, Center for Internet and Society Read the rest in CHAMPION OF CYBERSPACE FACES ITS BIGGEST CASE YET / Listening in? Electronic Frontier Foundation accuses AT&T of violating users' digital privacy The DB and the middle tier are merging, clearly. The current situation of having to deeply understand programming objects (top tier), XML etc. (mid-tier) and SQL (back-end) AND somehow keep track of which knows the state of what in order to work effectively does not make people happy. --Michael Champion on the xml-dev mailing list, Wednesday, 4 May 2005 14:47:57 MacOS X is an inconsistent mess. Yes, it really is. Graphically, that is. OSX now has, what, 7 or 8 different themes, and as far as I'm concerned, that's 6 or 7 too many. Some people say Apple is experimenting with all these themes; that's fine, but please keep that reserved for testers, and not for people like me who do not like to spend 130 Euros every 18 months on a piece of software that is only getting more inconsistent instead of less. If you like graphical consistency, stick with BeOS/Zeta or GNOME. --Thom Holwerda Read the rest in What Sucks About DEs, pt. II: Apple, MacOS X If you bring somebody in and they have problems, it's not because they're dumb, but we were dumb with the design. --Robert Moritz, Sprint Nextel Read the rest in iWon News It's usually considered better engineering practice to assume that a building, a bridge, or a standard will be in existence for a long time, and to build it so as to allow incremental upgrades such as earthquake retrofitting, than to assume its imminent obsolescence and underengineer it. --Doug Ewell on the Unicode mailing list, Tuesday, 17 May 2005 06:56:15 . --Guy Kawasaki Read the rest in Signum sine tinnitu-. --Adam Bosworth Read the rest in ACM Queue - Learning from THE WEB Code coverage is the perfect example of the old maxim that "things get worse before they get better". Everyone's experience with code coverage is basically the same. The first time you run code coverage, you are horrified because no matter how comprehensive you think your test suite is, the initial percent coverage is surprisingly low. That's the beauty of using code coverage -- it gives you a useful quantitative result to replace a qualitative guess which is almost always wildly optimistic. --Eric Sink Read the rest in My life as a Code Economist The one place where Java does have a legitimate remaining performance issue is startup time. But these days it's down small enough to where anything that runs more than a few seconds has a hard time noticing it. Most startup time in modern Java apps goes to the app itself, not the VM. --James Gosling Read the rest in Java Urban Performance Legends One of the things that is often not well appreciated is that Java is really a two-level language: It's the virtual machine and it's the sort of ASCII syntax…all the other really interesting magic is in the virtual machine, the things that people never actually see. There are many, many, many scripting languages that have been put on top of that virtual machine. --James Gosling Read the rest in Is Java getting better with age?, - We throw up a confirmation dialog - The user confirms - We delete the file - We tell the user we deleted it.. --Bruce Tognazzini Read the rest in The Scott Adams Meltdown: Anatomy of a Disast). --Tim Boudreau Read the rest in Tim Boudreau's Blog: Of saxophones, westerns and the sense of beauty in programming. --Tim Bray, Read the rest in LAMP and Java If Share Your OPML was a Java project I would've been heartsick to destroy it, but I coded the application in PHP. I've never written anything in PHP I didn't want to completely rewrite six months later. --Rogers Cadenhead Read the rest in Workbench: Settlement Reached with Dave Winer Developers are renowned for underestimating effort, and I don't think that test-effort estimation is any different. In fact, given the disregard many developers have for testing, I think they would be more likely to underestimate the effort required to test their code than they would be to underestimate anything else. The main cause of this test-effort blow-out is not that executing the test cycle in itself takes longer than expected, but that the number of test cycles that need to be executed over the life of the software is greater than expected. In my experience, it seems that most developers think they'll only test their code a couple of times at most. To such a developer I ask this question: "Have you ever had to test anything just a couple of times?" I certainly haven't. --Ben Teese Read the rest in Should we be doing more automated testing? There are two kinds of legal departments in large companies: (a) the kind that automatically says, “No,” when asked, “Can we do this?” (b) and the kind that automatically says, “No,” when asked, “Can we do this? --Guy Kawasaki, Read the rest in The Top Ten Lies of Corporate Partners Testing everything is a good thing. An important difference between TDD and double entry bookkeeping is that it /does/ matter whether we do the test or the code first. The most apparent reason is that the test is a /user/ of the code and the code is an /implementer/ of the usage. So when we write the test first, we are designing the interface to our code from the viewpoint of a user and when we write the code first, we have (more) the viewpoint of the implementer. --Ron Jeffries on the junit mailing list, Friday, 2 Jun 2006 19:47:28 I’m not writing shitty code; I’m creating refactoring opportunities. --Steven R. Baker Read the rest in Always the Optimist. literacy is so bad, that those few of us who can read can make a lot of money just by reading the manuals noone else can read... --Rick Marshall on the xml-dev mailing list, Saturday, 10 Jun 2006 13:28:08. --Martin Fowler Read the rest in Inversion of Control Containers and the Dependency Injection pattern Mac OS X may be only a small percentage of the PC installed base, but it's a HUGE percentage of the installed base of leading-edge developers. --Tim O'Reilly Read the rest in O'Reilly Radar > Tim O'Reilly My thought on the rise in fundamentalism is that it’s a reaction to what’s becoming increasingly obvious–the Enlightenment was no lark, but in fact was the beginning of a profound shift in society that shows no signs of slowing down any time soon. One thing that really sticks out to me is that the authoritarians have to reference Enlightenment principles when trying to argue for their side–creationists try to tear at science by saying scientists don’t have enough evidence, sexists trying to bolster their arguments by saying women have it worse elsewhere (i.e., we suck, they suck more), and conservatives in general are infatuated with the Founding Fathers, though I notice the praise is often less for the groundwork they laid for future generations to push for progress than for the ways their vision was incomplete. That authoritarians have to dress up their anti-progress arguments in progressive language demonstrates how entrenched the Enlightenment has become. It’s a mirror image of the way that early thinkers had to justify themselves by leaning on the authoritative ways–the Founding Fathers had to reject the king’s authority by invoking a higher one, after all. That shift means that progressives have an extra card in our hands, and that’s why fundamentalism is getting louder and more violent–they’re desperate. --Amanda Marcotte Read the rest in Freedom from choice is what you want at Pandagon. --Mark Stephens Read the rest in PBS | I, Cringely . May 11, 2006 - Google the best user interface is no user interface at all. Self configuration, self diagnosis, automatic assembly are all better than interfaces that require human interaction. --John Loiacono Read the rest in JohnnyL's Blog In my experience the Indian outsourcers have a harder time keeping their best talent than outsourcers in other countries. (Granted, my experience is with software development, not customer service.) First of all, demand is so high in India right now that good people jump from firm to firm to work on more interesting projects for more money. And second of all, many of these folks follow the /real/ money right back to the countries doing the outsourcing, where they can easily get high-paying jobs. In the US, they're here on H1-B visas. This leads to a spiral: A big outsourcing firm hires large numbers of programmers to meet demand. Most of the new hires suck. The relatively few good ones leave. The firm hires more programmers to replace them and the percentage of sucky programmers goes up. (Either that, or they poach their competitors' best people and contribute to the rising cost of quality in their market.) --Colin Strasser on the wwwac mailing list, Friday, 10 Mar 2006 12:46:57 A developer should not release code that they haven't tested. They should not release a line of code that they have not tested. Every line, every statement, every condition should be tested before the developer releases the code. It seems to me that's a minimum professional standard. Releasing code that you have not thoroughly tested is, simply, unprofessional. --Robert Martin on the junit mailing list, Sunday, 1 Jun 2006 20:50:49 My first exposure to Object-Oriented Programming (OOP) was circa 1989. First with C++ and shortly thereafter, Eiffel. It's an interesting way to enter this complex domain, probably akin to being punched in the nose and in the stomach at the same time. It wasn't always pretty but I did gain some interesting insight on how radically different languages can tackle a programming idiom. Another good thing about it is that people feel sorry for me when they read my resume. At least, I think that's the reason. --Cedric Beust Read the rest in Otaku, Cedric's weblog. --Glenn Greenwald Read the rest in Unclaimed Territory As the virtualization of the movie experience (and secondarily the TV experience) continues unabated, DRM becomes an increasing rallying cry - largely along with the argument that because the studios control the "best" talent, that they should be able to gate that talent, and get a fee for being the gatekeeper. The problem here is that this assumes that in fact it is in the best interests of the actual creators of that content to do so. If that talent is largely made up of heavily promoted divas, I suspect that this may serve the studios but not the independent producers, which actually now make up, in aggregate, the bulk of the actual production of television and theatrical content worldwide. One telling example is the recent Battlestar Galactica. Produced largely independently, it would have been cancelled because the Nielsons indicated that no one was watching it. The web told a very different situation, however, with BG episodes becoming some of the most heavily watched on the Internet, with numbers that rivalled blockbuster shows. If these episodes had been DRMed, the show would have died an early death, because people would not have wanted to pay money for a show that came from one of the most campy of vintage 1970s campiness. If ads had been placed in, either as trailors or discretely, chances are that the ads would have remained. The value proposition of having the ads to support the product is a reasonable one to the "community", whereas the individual per-play costs are generally less so. --Kurt Cagle, Read the rest in Scarcity vs. Abundance The problem with blogging is that sometimes it is so easy to publish your thoughts that you don't stop to think about what you are writing. --Dare Obasanjo Read the rest in Dare Obasanjo aka Carnage4Life. --Andrew Purvis Read the rest in The Observer | Food monthly | How a £1.50 chocolate bar saved a Mayan community from destruction. And these are people who call themselves pro-life. --Tony Hendra Read the rest in The Blog | Tony Hendra: The Christian Right? Their Christ Is No Christian | The Huffington Post? --Molly Ivins Read the rest in CNN.com - Molly Ivins: Not. backing. Hillary.. --Steve Wozniak Read the rest in The Great Woz Tells All. --Jennifer Granick, Center for Internet and Society Read the rest in Wired News: Security vs. Privacy: The Rematch People didn't die because the storm was bigger than the system could handle, and people didn't die because the levees were overtopped. People died because mistakes were made, and because safety was exchanged for efficiency and reduced cost. --Raymond B. Seed, University of California, Berkeley Read the rest in New Study of Levees Faults Design and Construction. --Mike Gunderloy Read the rest in Ten of the Biggest Mistakes Developers Make With Databases The exciting things that are happening are not all being sourced from Sun. They have to accept things that don’t originate with them, and that’s not what we’ve seen. They’ve tied themselves to NetBeans and haven’t tied into Eclipse. I’m not sure that helps the community very much. --Joe Lindsay, president of QS Labs Read the rest in CRN | JavaOne, Sun Microsystems | Sun Partners Call For More Open Java Control There are a number of people using anti-spam services that cause me a huge amount of grief when sending out announcements. I will not be responsible for clicking a link, sending another email, standing on my head or whatever other action you want me to do. --Jon Eaves on the dev-crypto mailing list, Monday, 08 May 2006 10:26:00 At this point, it's not a question of whether. It's a question of how. --Rich Green, Sun software chief Read the rest in Dr. Dobb's | Sun To Open Java I/O has been a key book for me for years, providing the concrete information I needed to sort out Java's many options for handling Readers, Writers, and other techniques of getting information, especially Unicode, in and out of my programs. Thanks to its examples and detailed explanations, I was able to write a number of projects which gave me vastly more flexibility than an XML parser could provide, which in turn helped me with my editing for O'Reilly. --Simon St. Laurent Read the rest in oreilly.com -. --David Heinemeier Hansson Read the rest in Routing around the WS They were also jobs I didn't want.. --Adam Knight Read the rest in After Apple. --Bruce Tognazzini Read the rest in The Scott Adams Meltdown: Anatomy of a Disast This is a town where everyone says they are for science-based decision making — until the science leads to a politically inconvenient conclusion. And then they want to go to Plan B. --Sherwood Boehlert, R-NY Read the rest in A Science Advocate and 'an Endangered Species,' He Bids Farewell The rhetoric of Bush followers is routinely comprised of these sorts of sentiments dressed up in political language –. --Glenn Greenwald Read the rest in Unclaimed Territory Free and open source software (FOSS) is founded on the four software freedoms: (a) freedom to run; (b) freedom to study; (c) freedom to modify; and (d) freedom to redistribute a program. However, it seems that wider adoption of FOSS can be achieved if greater development effort is focused on the first freedom – the freedom to run. More importantly, this freedom should be understood in the sense of “freedom from complexity”. It is often forgotten that, from the standpoint of an ordinary user, freedom to run a program means the program itself must be user-friendly and it must be easy to download, install and use. This freedom means nothing if the exercise of such right excludes people who do not possess high technical knowledge or advanced skills sets. Without the guarantee of “ease of use”, the freedom to run FOSS for most users is a hollow promise. --bong dizon Read the rest in lawnormscode » Blog Archive » Freedom to Run Means Freedom from Complexity: An Argument for Running FOSS on Windows As I suffered through the nth application crash of the day, I couldn't help thinking of my favorite underappreciated Java feature: fault containment. Between try{}catch James Gosling: on the Java Road. --Mark Stephens Read the rest in PBS | I, Cringely . May 4, 2006 given the supine and cowardly American reporting of the Middle East conflict, you might wonder why the Pentagon wishes to create its absurd "Office of Strategic Influence (OSI)" to peddle truth and lies to the press. US journalists are so gutless -- so quick to adopt the government line -- that it is surely unnecessary to plunder the $10bn supplement to the Pentagon budget to sell this kind of trash. --Robert Fisk Read the rest in Independent Argument. --Michael Amor Righi Read the rest in www. Michael Righi .com. --Dan Eggen and Shankar Vedantam Read the rest in Polygraph Results Often in Question --Peter Yared Read the rest in Will Sun Open. --Cedric Beust Read the rest in Otaku, Cedric's weblog: Why Ruby on Rails won't become mainstream. --William C. Taylor Read the rest in Your Call Should Be Important to Us, but It's Not most of the time, the API I have offered in Saxon has grown out of the implementation. The current Java XQuery interface is an example of that. This almost invariably leads to bad API design. Good APIs are designed from a user perspective, by someone thinking about the design of the user-written application; they are not produced by taking the implementation and deciding which of its classes and methods to expose. --Michael Kay Read the rest in Saxon diaries :: APIs for XML processing Security by obscurity is just hiding the symptom, not tackling the cause. --Angsuman Chakraborty on the wp-hackers mailing list, Tuesday, 25 Apr 2006 10:21:35 Sun's problem is huge and it is simple: Linux. The free operating system, yoked to low-cost processors from Intel and Advanced Micro Devices, has decimated the Unix market by offering customers a cheap alternative to pricey Unix boxes like the ones Sun makes. Sun's top-end machines cost more than $1 million apiece and run a proprietary Unix-based operating system, Solaris, on Sun's proprietary SPARC microprocessors. But who needs those boxes when you can instead just lash together loads of cheap x86-based servers running free Linux? --Daniel Lyons Read the rest in Wired News: Don't Blame Scott. --Jakob Nielsen Read the rest in Enterprise Usability (Jakob Nielsen's Alertbox). --Jacob Weisberg Read the rest in Drug Addled I got an email recently from a recruiter for a high tech company saying that they were very interested in me as a "female thought leader". I didn't reply, because I wasn't interested in the job, but I fantasized replying, "Thank you for your interest. Although my credentials as a thought leader are impeccable, I must warn you that I am not that qualified as a female. I can't walk in heels, I have no clothing sense, and I am not particularly decorative. What aspects of being female are important to this job?" --Radia Perlman Read the rest in Anita Borg Institute for Women and Technology. --Arnold Kling Read the rest in TCS: Tech Central Station). --Johann Hari Read the rest in After three years, after 150,000 dead, why I was wrong about Iraq. --David Friedman Read the rest in Ideas: Howard Dean to the White Courtesy Phone. --Jamie Lincoln Kitman Read the rest in Life in the Green Lane? --Katrina vanden Heuvel Read the rest in The Blog | Katrina vanden Heuvel: The Crucial Difference Between Joe Klein and Reality | The Huffington Post It's not that users are dumb, it's that while many Linux users are busy working on Linux, most users are busy working as housewives or lawyers. It's not that they're dumb, it's that they don't have time to learn Linux the way we have, --Kevin Carmony Read the rest in Carmony dispels Linspire Linux myths This is a kind of classic call in academic freedom.. --David T. Ellwood, Kennedy School Read the rest in Essay Stirs Debate About Influence of a Jewish Lobby People aren't thinking about small, fast, thin systems. Suddenly it's like a very fat person (who) uses most of the energy to move the fat. And Linux is no exception. Linux has gotten fat, too. --Nicholas Negroponte Read the rest in Negroponte: Slimmer Linux needed for $100 laptop | CNET News.com Too often, executive compensation in the U.S. is ridiculously out of line with performance.. --Warren E. Buffett Read the rest in Outside Advice on Boss's Pay May Not Be So Independent. --Cedric Beust Read the rest in Otaku, Cedric's weblog: Why Ruby on Rails won't become mainstream. --James Gosling Read the rest in James Gosling Q & A: Builder AU: Program: At Work I'm sure there must be a big rule written somewhere, that I can't seem to locate, that states that all enterprise software must have a less-than-optimal user experience, especially the interface. --John Loiacono Read the rest in JohnnyL's Blog. --Mark Stephens Read the rest in PBS | I, Cringely . April 6, 2006 I think the problem here is that "intellectual property" isn't property. It isn't a computer, it isn't "real estate", and it isn't cash. As long as there has been a conception of "intellectual property", it's been in its own class, with limited rights relative to other forms of property. Unfortunately, over the last century or so, a key group of those who have had the limited rights have decided that they'd like those rights to be less limited, and the rest of us have watched those limitations decay without doing nearly enough about it. Those rights are limited because unless other forms of property, there's much more value in sharing intellectual property than there is in hoarding it. Licensing pretends to be a happy medium, but even that approach cuts off many of the rights we all used to have with regard to intellectual property. Property rights aren't the problem here. Trying to promote "intellectual property" as just another form of property is the problem. --Simon St.Laurent on the cbp mailing list, Tuesday, 04 Apr 2006 11:50:07 Once, conservatives used to deplore the left's cult of victimhood and ridicule the obsession with real or imagined slights toward women, minorities, and other historically oppressed groups. Now, the right is embracing a victimhood cult obsessed with slights toward a group that makes up 85 percent of the American population. --Cathy Young Read the rest in Reason: What War On Christians? : Disagreement isn't oppression Countless chief executives pledge to improve their company's products and services by listening to the "voice of the customer." Memo to the corner office: Answer the phone! How can companies listen to their customers if those customers have such a hard time reaching a human being when they call? --William C. Taylor Read the rest in Your Call Should Be Important to Us, but It's Not Socialism collapsed because it did not allow the market to tell the economic truth. Capitalism may collapse because it does not allow the market to tell the ecological truth. --Oystein Dahle, Exxon Read the rest in Wired News: I refuse to install Flash on any of my computers. I don't accept any EULA with an audit clause. I see no reason to allow Macromedia to enter my home and examine my computers, so they can audit my compliance with their EULA. Many might argue that they would never actually do that. My response is that if they wouldn't, they shouldn't put the audit clause in the EULA. They put it there for a reason. Call me paranoid, but I have no desire to learn first hand what that reason is. --Ray Lischner on the cbp mailing list, Sunday, 15 Dec 2005 17:11 Read the rest in Defending Spy Program, General Reveals Shaky Grip on 4th Amendment Auto-Responders should no longer be used. You'll actually be spamming innocent email addresses that spammers have forged... as well as spamming your friends when worms get sent around forging their names. Auto-Responders are what's known as backscatter... and contribute to email noise. SpamCop considers backscatter the same as spam. So, if you send an auto-response to someone who never emailed you (which will happen) they are well within their rights to report it to SpamCop. SpamCop will treat it as any other spam and with enough reports, blacklist your mail server. --John T. Haller on the wwwac mailing list, Wednesday, 29 Mar 2006 13:45:57 Rush Limbaugh, Sean Hannity, Bill O’Reilly and the rest of these clowns get paid to host a talk show (or shows), a major component of which is, broadly defined, debate… So why do they act like big pussies whenever they are challenged? To a person, each of these right wing blowhards runs to cut the mic whenever they feel the slightest bit challenged… Telling, no? --Mike Stark Read the rest in Calling All Wingnuts. How then.. Bush of course has been lucky in his adversaries as well—not bin Laden, but the Democrats (not to mention many a media pundit). To this day they seem afraid to make the case that the great war presidency has been a disastrous war presidency, in large part because of the fraudulent Iraq invasion.. --Michael Hirsh Read the rest in Hirsh: Bush’s Poor Leadership in Terror War - Newsweek Politics It's always easier to loosen the rules when it's found to be necessary than to retrospectively tighten them. --Ed Davies on the 'xom-interest' mailing list, Wednesday, 22 Mar 2006 10:10:10 Open source software is not a free lunch, it is stone soup. --Rick Jelliffe on the xml-dev mailing list, Friday, 24 Mar 2006 20:48:31 The Centre for Asia Pacific Aviation (CAPA) is one of those consultancies (this time Australian) that hands out free samples of its thinking from time to time, but unfortunately still chooses to do so in the form of a PDF (rather than through a feed or some other more user-friendly form). As we noted on a previous occasion, since the object of the exercise is presumably to advertise to everyone how bright CAPA is, imprisoning the info within a PDF is probably not a great idea. --idlewild, Read the rest in New World Carrier: Silly Name, Interesting Thought/Where Are Europe's High Touch LCCs?. --Johann Hari Read the rest in After three years, after 150,000 dead, why I was wrong about Iraq Read the rest in Variety.com. --Adam Livingstone, BBC Read the rest in BBC NEWS | Programmes | Newsnight | A bit of BitTorrent bother IDG is claiming they are not issuing media badges like they use to due to limited space and increased interest in Apple. The limited space argument makes some sense, but considering the pressroom is usually somewhat empty after the first day of MacWorld it is a shame they couldn't figure out a way to grant some media access to the pressroom, and some full access media badges according to how big their audience is. Instead they opted to say there is more interest in Apple, which is really a silly argument, for it seems there is enough room for Dave Winer (someone who isn't even in the media). Most of the corporate big name media outlets such as CNN and others simply show up on the day of the keynote, shoot a minute of footage, maybe have one reporter show a line of people playing with what ever Apple releases and that's it. They do not go from booth to booth visiting vendors and writing articles and reviews on new products. They do not publish large galleries of Mac users using new products. They are simply there because their boss told them to be; odds are they most likely don't even own a Mac. The people who will truly be lose by not having Mac media sites with media access are the companies paying thousands of dollars for booths at MacWorld trying to get noticed by both the Mac media and the public. --Trent Lapinski Read the rest in The End Of Mac Media MacWorld Access :: AppleXnet :: Alternative Mac Tech News, Analysis, Reviews, and Opinion Take smoking in public; I favor banning that because I don’t like to be around it. According to Penn and Teller – notable skeptics – there isn’t any good science proving second hand smoke hurts people. So I’ll stop using that argument. But there isn’t any science that says littering hurts you either, and I’m against that because I don’t want to look at it. Second hand smoke is like litter in my nose. --Scott_Adams, Read the rest in Am I a Libertarian? There is no "sweet spot for O/X binding". Anyone who has hung around with me long enough knows that one of my favorite adages is: "databinding is evil". Whether O/R or O/X, the IT community has long suffered through the painful experience of using tools that purport to yield developer nirvana. While these tools often work effectively for the trivial examples shipped with the tool, they typically fail miserably when applied to most real-world use cases either because of impedance mismatch, excruciatingly poor performance, or both. --Chris Ferris Read the rest in developerWorks : Blogs : Chris Ferris. --James Gosling Read the rest in Developer spotlight: James Gosling: Builder AU: Web Development "Demand" for W3C Schema support came from on high as edict, to which W3C-related vendors responded; the grassroots demand for RELAX NG is merit-based and users are in a position to make demands of vendors for support. --G. Ken Holman on the xml-dev mailing list, Wednesday, 08 Feb 2006 13:24:16 one of the great things about open source is ... if you think the project is going in a direction you do not like, you are free to take the code and, dare I say it, start a "fork" that you control. Pissing on the leg of the leadership is not likely to get you anything but ignored. --Douglas Daulton on the WP Hackers mailing list, Saturday, 04 Mar 2006 21:54:17?) --Andreas Pfeiffer Read the rest in ACM Ubiquity In the consumer world, there is more of a tendency to find out just how a consumer will use a product, then focus engineering efforts to build and improve on that process. In the enterprise development world, we tend to build a service or application that serves a need, or more often, meets a spec. (I say we and I readily include Sun in this, though it's a widespread issue in the enterprise software industry.) Only after we build the foundation and frame the house do we ask the "interface" folks to slap on a GUI and maybe (maybe) look at how to improve the usability. I can't tell you how many times I see prototype product demos from my team who warn me, "Don't look at the interface or usability, we'll fix that later. But isn't this incredible functionality?" Ooops. Too late; we've missed it. --John Loiacono Read the rest in JohnnyL's Blog The main advantages of declarative languages are that you need to write less code for achieving a given function point, you operate on a large set of data at once, and that an execution engine can apply rewrites (if they are based on an algebra) and other optimizations to execute it more efficiently. Procedural languages are much harder to optimize due to their often lower expressivness at the operator level, their one-item at a time processing model, and their tendency to allow and sometimes encourage programming by side-effect. --Michael Rys on the xml-dev mailing list, Tuesday, 28 Dec 2004 The macabre, slightly bitter edge to this year's parade -- hazmat suits decorated with sequined penises, little people drowning and writing HELP on their roofs while Mayor Nagin lies in bed masturbating -- made me as proud of New Orleans as anything that's happened since our return. Nothing destroys us so thoroughly that we can't make fun of it, and Mardi Gras is a greater force of nature than any hurricane. --Poppy Z. Brite, Read the rest in Krewe du Vieux. Alan Cullison’s 2004 article based on Zawahiri’s private thoughts is again instructive here. "Al Qaeda understood that its attacks would not lead to a quick collapse of the great powers,” he wrote. “Rather, its aim was to tempt the powers to strike back in a way that would create sympathy for the terrorists. ... One wonders if the United States is indeed playing the role written for it on the computer." What I wonder is, how many more years will we have to wait for Rumsfeld to figure that one out? --Michael Hirsh Read the rest in Hirsh: Bush’s Poor Leadership in Terror War - Newsweek Politics So as I understand it, the SWT team has not found a simple way to fix this in SWT alone, and the Apple team has not found a simple way to fix this in Apples code alone. In my perception, there is the extreme solution left: talk to each other (teams and code. Especially teams). --Gerd Castan Read the rest in Bug 67384. --Martin Fowler Read the rest in GetterEradicator Elliotte Rusty Harold usually has something useful to say but every once in a while he crams his foot into his mouth. Today is one of those days. --HashiDiKo Read the rest in Design Decisions: Too Much Cafe Eventually, all enterprise application development will be done on Eclipse, regardless of the programming language. The exception is, of course, Microsoft which will continue to dominate on the Windows platform where they have the home court advantage. What is interesting about Eclipse is that because its open source and built on a flexible plug-in model, the development world will continue to innovate even if its the only IDE platform available (other than Microsoft Visual Studio). Because Eclipse is not a closed system (a proprietary tool) there is little worry about a single vendor having a stifling effect on innovation. Here is my prediction: In five years Eclipse will be used in 70% of enterprise development regardless of the programming language (excluding Microsoft .NET languages). In 10 years, there will be a small cottage industry of commercial eclipse plug-ins but for the most part everyone who is not developing to the Microsoft platform, will be using open source Eclipse. In fact, I anticipate that Eclipse will invade non-enterprise tooling markets such as IDEs for embedded devices by that time. Like it or not, for the next 20 years the future of the IDE market appears to be Eclipse --Richard Monson-Haefel, Read the rest in Eclipse is decimating the IDE market A failure rate of a few percentage points can still be a pretty big number, and often the folks experiencing the failure aren't equipped to diagnose the problem and/or find the right entity to yell at. They are just as likely to shrug their shoulders, say it doesn't work, and move on to something that does. --Kyle Marvin on the atom-protocol mailing list, Monday, 13 Feb 2006 09:28:16 Recently. --Scott Adams Read the rest in The Dilbert Blog: Caffeine. --Mark Stephens Read the rest in PBS | I, Cringely . February 9, 2006 Dick Cheney is a pussy. 'Tw. But the shooting of Harry Whittington does more than tie Dick Cheney to historic pussy Aaron Burr. It throws into high relief the utter wimpiness of Cheney. Dick Cheney was hunting in a private where quail were almost certain to be present--somewhat better than his previous Pennsylvania killing spree, perhaps, but something no real man would do. Real men, of course, would go hunting where quail may or may not be--go hunting knowing full well that the word implies that they may not find anything. Dick Cheney had no such concerns--he was too much of a pussy to risk failure. Harry Whittington may not have been where Cheney thought he was--like any accident, even the victim may have some fault. But a real man doesn't farm out excuses. He stands up and takes the blame, especially when it comes to the honor of friends. A real man--or even one of us feminized men--jumps in to defend their friend's honor, and to take the blame upon themselves. A pussy has surrogates leak that it was probably someone else's fault. And of course, that right there is the biggest proof of the non-manliness of Dick Cheney of all. A man stands up and takes responsibility, because a man is responsible. Only a pussy's pussy would not only hide from the press, not only try to blame his friend, but shove the woman who owns the ranch out in front of the press in order to avoid the abuse. Only an epic pussy would refuse to answer anyone's question, would only visit his friend in the hospital briefly, and would make his first public statement a discussion of questions about his hunting license. --Jeff Fecke Read the rest in Blog of the Moderate Left- I love the logic of creationism, which goes something as follows: We believe in a magical Sky Fairy that no one has ever seen, spoken to, heard from or even seen evidence that he exists. This gives us the authority to denounce scientific theories that are backed up by evidence, because the evidence will always be somewhat incomplete. Because it’s better to believe something with no evidence whatsoever than to believe something that’s actually backed up by facts. --Amanda Marcotte Read the rest in Freedom from choice is what you want at Pandagon when bugs show up in our GUI code I usually try to write a test case to replicate them. When I have to debug its much faster to debug from a test case than clicking around in the GUI. --Mark Levison on the junit mailing list, Sunday, 9 Feb 2006 20:39:41.. --Glenn Greenwald Read the rest in Unclaimed Territory We are now at 2.5 billion Java devices on the planet--700 million cell phones, 700 million PCs. We had 17 million and 20 million downloads in the last couple months of the J2SE environment. That is a stunning number. The new Blu-Ray spec is going to put a Java virtual machine in every new next-generation DVD player, and all your DVDs are going to have Java bytecode on that gets executed --Scott McNealy Read the rest in McNealy on message I got my PhD, which was nice because although I seldom use a title, if someone obnoxiously insists on knowing whether I'm "Miss" or "Mrs." I can say "Dr." --Radia Perlman Read the rest in Anita Borg Institute for Women and Technology If the limiting factor were typing then yes, writing twice as many lines of code would take longer. If the limiting factor is really other activities: communicating with the rest of the team, understanding the problem, designing, finding and fixing errors, then it is not inconceivable that practicing TDD with JUnit can give you an overall speedup. The trick is learning how to integrate JUnit as part of all of these other activites--activities which all software developers perform. That has been my personal experience and the experience of our teams writing commercial software (usually with fixed-time, fixed-price contracts) for the last 5 years. Consistent JUnit testing by the whole team--using TDD--decreases the time it takes to produce production-ready software. --Jeff Nielsen on the junit mailing list, Friday, 10 Feb 2006 10:25:23. --Alex Tabarrok Read the rest in Marginal Revolution: The Law of Below Averages Read the rest in Stephen Colbert | The A.V. Club Unit Tests are real safety. Static typing is the illusion of safety, I choose the former. --=Daryl Richter on the junit mailing list, Friday, 3 Feb 2006 08:31:14). When I'm writing a function and declare a parameter to be an Image, I am free to trust that it is an Image. I'm free to trust that no one's array access has smashed my data structure. Examples abound. --James Gosling, Read the rest in Safety is Freedom WORA, while a good ideal, hurts Java as an ideology. The first round of WORA war got us a Microsoft technology (.NET) that competes with Java. The second round of WORA war got us an IBM technology (SWT) that competes with Swing. I'm not sure Sun wants to fight another WORA war. For what? To lose the hand held market place? --Wei Gao Read the rest in Weiqi Gao's Observations As I suffered through the nth application crash of the day, I couldn't help thinking of my favorite underappreciated Java feature: fault containment. Between try{}catch Fault Containment: an unsung hero. -- Jeremy LaCroix Read the rest in Linux - How To Take Over The Market Swing is a huge beast, but it is well worth learning. I think the architecture is much cleaner, and this is starting to show. The latest Netbeans 4.0 and 4.1 on Tiger are as fast as native applications, and if you want to get the feeling for what can be done at the top try the Intellij's Early access Preview. --Henry Story on the java-dev mailing list, Monday, 6 Jun 2005 11:38:13 A home that survived for eighty-seven years is falling to pieces on my watch, because of my indecision and poverty, because of the insurance company's foot-dragging, because of the city's inability to let us know what's going to become of our neighborhood, because of the country's unwillingness to give us the protection they'd told us we already had. Today it came out that in the immediate aftermath of the storm, FEMA turned away hundreds of boats, trucks, and rescue workers (many of whom were police and firefighters) that were volunteering to help, then stopped their own search-and-rescue mission after three days even though they knew people were still dying down here, because they didn't have enough resources. --Poppy Z. Brite, Read the rest in In/Sanity. --Adam Bosworth Read the rest in ACM Queue - Learning from THE WEB In the actual halls of power, Democrats are foolishly listening to Republican talk about how bad it is for their future electoral chances to be “obstructionist”, though thankfully now that Kerry’s signed onto the filibuster idea, there might be a bout of common sense coming over the party now. But overall, the trend is really discouraging–liberals are increasingly afraid to stand up for anything, and the reason the fear that is they are believing conservative hype designed to make us afraid. Meanwhile, due to the double standard where conservatives feel free to go beyond the pale while flipping out if a liberal even has a firmly stated opinion, conservatives have amassed a truly jaw-dropping amount of power, especially considering that their policy ideas are a laundry list of How to Fuck Over Everyday Americans–gut the schools, take people’s Social Security money and bet it on the stock market, send our young people off for a colonial war to get killed, and take away our basic rights. But people still vote for them, and the reason people vote for them is that they perceive conservatives standing for something and liberals as wishy-washy idiots who can’t even put together a basic opinion on anything. That conservatives lie outright about what they stand for–they say “family values” when they mean “bankrupt families so Paris Hilton can have even more weird pets”–doesn’t matter so much because they have so much rhetorical ground since they allow themselves the self-righteous anger, the belittlement of their enemies, everything that liberals are told will somehow hurt our cause. Told to us, needless to say, by people who want to hurt our cause. --Amanda Marcotte, Read the rest in Who the hell are you calling “churlish”?. --Werner Moise Read the rest in Smart Software: Software Paradoxes: The Cost of Trying Too Hard Read the rest in CNN.com - Molly Ivins: Not. backing. Hillary. Every good upgrade should have at least one feature, which, once you’ve used it, you come to rely on it so often that you’d fight anyone who tried to take it away from you. --Kelly Turner Read the rest in Macworld: News: First Look: iPhoto 6 the whole point of the GPL in the first place was to ensure certain freedoms, including preventing rapacious businesses from ripping off the community's work, which is a primary reason why the GPL is the most popular license chosen by developers. They trust it. Of course, businesses rarely think of themselves as rapacious, but sometimes they get so honed in on money, honey, they forget about us users and what we'd like and they forget that GPL'd code belongs to the folks that wrote it. It's not public domain. Think SCO if you have any doubts about why one might wish to be alert or about the GPL's efficacy in an attempted rape-and-pillage event. But if decent businesses want to use the code -- and that is voluntary -- perhaps they need to consider being more "freedom friendly" and realize that the GPL community is quite serious about protecting users' and developers' freedoms, by protecting the code's freedom. While many businesses are buying into the DRM, cuff-the-customer balkanization strategy, the GPL stands for users and against the business mentality of profit at *any* cost to anyone and anything. Even Bill Gates said recently that in his view one of the DRM schemes chosen by the Hollywood titans is overly friendly to business and hostile to customers. The GPL simply makes that official, by preventing anyone from using GPL code in such hostile ways. Within the framework of freedom, you can still make money with GPL code -- businesses already do -- but not at the expense of users. --Pamela Jones Read the rest in GROKLAW Beware the Four Horsemen of the Information Apocalypse: terrorists, drug dealers, kidnappers, and child pornographers. Seems like you can scare the public into allowing the government to do anything with those four. --Bruce Schneier on the CRYPTO-GRAM-LIST mailing list, Sunday, Sun, 15 Jan 2006 01:36:16 defining "best" is rarely helpful, especially when we first need to agree on what's "worst"! --J. B. Rainsberger on the junit mailing list, Sunday, 22 Jan 2006 13:04:13 I have terrifying visions of Stephen Harper grinning like the proverbial cat that swallowed the canary, barely able to control his glee: "I'm the Prime Minister. I AM THE PRIME MINISTER! BWAA-HA-HAHAHA." Whether this happens before or after he begs the White House for permission to "perform a sexual favour" for George Bush in the Rose Garden, my imagination can't encompass. --Vanessa Williams Read the rest in fridgebuzz: "Don't Make The Same Mistake We Did" In a sane world, grown men who chew the foreskins off little babies, infect them with diseases and kill them don't get to arrogantly walk out of meetings with health officials. They don't get to create impasses with powerful mayors. In fact, they don't get to meet with health officials or mayors. They're dragged out of their beds at 4 a.m. by police officers, locked up in prison for life and, if they ever get out, forced to register as sex offenders until they die. --The Raving Atheist, Read the rest in Hasadistic. --Jeremy D. Miller Read the rest in Microsoft’s recommendations for Test Driven Development are wrong! Trying to solve almost any non-trivial problem in AppleScript itself is a losing proposition. AS's strength is as a scripting language, not a programming language. Generally, the right question when attacking a problem from AppleScript is, "What tool do I already have on my system that knows how to the solve this problem for me, and how can I tell it to do that from AppleScript?" --Neil Faiman on the applescript-users mailing list, Monday, 28 Feb 2005 18:59:36. Non-free software, by contrast, keeps users divided and helpless. It is distributed in a social scheme designed to divide and subjugate. The developers of non-free software have power over their users, and they use this power to the detriment of users in various ways. It is common for non-free software to contain malicious features, features that exist not because the users want them, but because the developers want to force them on the users. The aim of the free software movement is to escape from non-free software. --Richard Stallman Read the rest in ZNet |Corporate Globalization | Free Software as a Social Movement. --Ezra Klein Read the rest in Ezra Klein: Against Small Business Dear AN IDIOT ON YOUR OWN TIME IN YOUR OWN DRIVEWAY, BUT STOP MAKING IT SUCH A PAIN FOR THE REST OF US WHO HAVE TO SHARE THE FUCKING PARKING LOT WITH YOU. IF YOU'RE OVERCOMPENSATING FOR SOMETHING ELSE, GREAT. YOU'RE NOT A COMPACT CAR!!! YOU CAN'T FIT INTO A COMPACT CAR'S PARKING SPOT SO PLEASE STOP TRYING!!! IT'S SIMPLE PHYSICS, YOU FOOL! IF I SEE ANOTHER ONE OF YOU LAZY-ASS SUV DRIVERS TRYING TO CRAM YOUR VEHICLE INTO A SPACE THAT'S TOO SMALL FOR IT, I'M GOING TO WRITE DOWN YOUR LICENSE PLATE NUMBER AND POST IT ON THE INTERNET FOR EVERYBODY TO SEE. STOP IT!!! STOP IT!!! STOP IT!!! --Chris Pirillo Read the rest in Dear All SUV Owners... A good way to learn Swing is to develop a GUI using an interface builder. Netbeans is really helpful there (better than intellij in some respects). In the end Swing is not quite as difficult as people make it out to be. It just does take 2 weeks of serious playing around with and a good book to get the hang of it. Just watch out for the threading model! In one month I think one can be quite fluent. But User Interface development is a huge field. So you will never end up learning. Just think about the complexities of fonts, of 2D graphics, of 3D, of cross platform variations... The easiest cross platfom UI tool in the end is html, and even there you can spend a huge amount of time getting really good at it. --Henry Story on the java-dev mailing list, Monday, 6 Jun 2005 11:38:13 According. --Scott_Adams, Read the rest in The Devil It wouldn’t surprise me that once the majority of residents are using EZPass, (aka the hook is set), that all of a sudden the government will decide to utilize this new found data to increase their revenues. Distances between toll booths is known to the inch, so with the simple equation of average speed = distance / time, it will be easy to determine who was speeding, and issue a summons, with absolutely no way to wrangle your way out of it. That is of course once the politicians make sure their EZPass accounts are hidden from this scrutiny.. --Don Demsak, Read the rest in Evils of EZPass and an Alternate Solution. The past five years, during which the number of registered lobbyists more than doubled, have proved that, for some Republicans, conservative virtue was merely the absence of opportunity for vice. --George Will Read the rest in For the House GOP, A Belated Evolution if the business rules say that an employee must not work more than 40 hours and the employee says he has worked 43, what should happen? Do you want the database to record incorrect data, on the basis that the correct data is unpalatable? --Michael Kay on the xml-dev mailing list, Monday, 23 Aug 2004 Creating a good install is about 10% definition and about 90% testing and 100% perspiration. --Andrew C. Oliver Read the rest in Hacking Log 4.0 Neward Read the rest in The Blog Ride the semantics of equal/hashCode/clone are trouble, because they are required to have consistent behaviour across so many things, yet most people get them wrong. And if two uses of them have different expectations, then there are incompatible goals. --Steve Loughran on the xom-interest mailing list, Friday, 6 Jan 2006 08:58:34 design flaws are transitive. There is no known method in software engineering able to predict that a detected design flaw in a particular area has not corrupted the design of the rest of the software including the other assertions potentially causing them to falsely accept incorrect contracts --Christopher Diggins Read the rest in Contract Programming 101. --Robert Higgs Read the rest in Traveling Sheep: Newsroom: The Independent Institute McDonald's does not close down and move across the state line when you raise the minimum wage --Dan Cantor, Working Families Party Read the rest in New Yorkers Who Earn the Minimum Get a Raise I Earlier quotes:
http://www.cafeaulait.org/quotes2006.html
CC-MAIN-2018-34
refinedweb
15,449
66.88
The problem with JPA/Hibernate (or the future of ORM) I know, a lot of people are happy to work with JPA and Hibernate. Consider this a post from somebody who thinks things can be improved. I have a love/hate relationship with Hibernate, for many reasons that I don't want to go into now. Overall I do like Hibernate and think it does a good job but it can be improved in many ways. I also believe it was a mistake to base the JEE 5 specifications on Hibernate. An object-relational mapping tool has to bridge the gap between ... classes, objects and tables, records. For me Hibernate is a step in the right direction but it's far from perfect. I would have preferred to not have a persistence specification at all in JEE because we're not there yet, but we're doing well. Object-relational mapping tools have a hard time and not only from all the flack they get. Have you ever looked at how classes and tables are almost each other's opposites? And have you ever wondered how that impacts classes that are mapped with Hibernate? In database tables - in general - when you follow relationships (foreign keys) you go from general to specific. For example, you follow the foreign key in the ADDRESSES table to the PEOPLE table. But why link an address to a person when other things can have addresses as well? Buildings, companies, customers, hotels, ... . Maybe you don't have any of these other things in your database, you only have PEOPLE. Ok, then consider what your Address class looks like: public class Address { private Person person; // rest ommitted } Maybe you're not worried about this, but why does the Address class have a dependency on the Person class? In a pure object-oriented world that relationship would be determined by a List in the Person class. public class Person { private List<Address> addresses = new java.util.ArrayList<Address>(); public void addAddress(Address address) { addresses.add(address); } } I hear you, the world isn't perfect. But ... there is an Java object-oriented framework that would let you save these kind of objects in a relational database. And you don't have to specify any mapping configuration. It's called BeanKeeper (here's an introduction article). First of all, BeanKeeper as it is today can't replace Hibernate or JPA. Since you don't provide a mapping configuration BeanKeeper decides by itself which tables to create for each class. You don't have any control over the relational part. And you can save any object you like, BeanKeeper does the hard work. Still, for me it's proof that things can be different in object-relational mapping. I believe well-designed object-oriented frameworks start with a set of sound and consistent principles of how classes and tables should or could be mapped. Object-oriented framework don't have to solve every possible problem. And they don't have to support every possible mapping. By taking a stance that some mapping constructs are not supported it would actually be possible to have better frameworks. Or at least, it would be possible to have a better experience. A better alternative to Hibernate or JPA would in my opinion have to copy some BeanKeeper ideas. It should be possible to map a one-to-many relationship to a Person class with a List of Addresses. And there will have to be some form of mapping configuration. Hibernate and JPA are a evolutionary step in the right direction, but they are far from perfect. I hope that some people are working today on better alternatives. If you do please post a comment below. If you have your own opinion on the future of object-relational mapping let us know! - Login or register to post comments - 6319 reads - Printer-friendly version (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
http://java.dzone.com/news/problem-jpahibernate-or-future-orm
crawl-002
refinedweb
669
65.01
12 June 2012 By clicking Submit, you accept the Adobe Terms of Use. JavaScript beginner/intermediate, HTML5 beginner/intermediate and a basic knowledge of jQuery. Due to its use of the getUserMedia and audio APIs, the demo requires Chrome Canary and must be run via a local web server. All In this article, I discuss how to detect a user movement using a webcam stream in JavaScript. The demo shows a video gathered from the user webcam. The user can play notes on a xylophone built in HTML, using their own physical movements, and in real time. The demo is based on two HTML5 “works in progress”: the getUserMedia API displays the user's webcam, and the Audio API plays the xylophone notes. I also show how to use a blend mode to capture the user's movement. Blend modes are a common feature in languages that have a graphics API and almost any graphics software. To quote Wikipedia about blend modes, "Blend modes in digital image editing are used to determine how two Layers are blended into each other." Blend modes are not natively supported in JavaScript but, as it is nothing more than a mathematical operation between pixels, I create a blend mode "difference". I made a demo to show where web technologies are heading. JavaScript and HTML5 will provide tools for new types of interactive web applications. Exciting! As of the writing of this article, the getUserMedia API is still a work in progress. With the fifth major release of HTML by the W3C, there has been a surge of new APIs offering access to native hardware devices. The navigator.getUserMediaAPI() API provides the tools to enable a website to capture audio and video. Many articles on different blogs cover the basics of how to use the API. For that reason, I do not explain it too much in detail. At the end of this article is a list of useful links about getUserMedia if you wish to learn more about it. Here, I show you how I enabled it for this demo. Today, the getUserMedia API is usable only in Opera 12 and Chrome Canary, both of which are not public release yet. For this demo, you must use Chrome Canary because it supports the AudioContext to play the xylophone notes. AudioContext is not supported by Opera. Once Chrome Canary is installed and launched, enable the API. In the address bar, type: about:flags. Under the Enable MediaStream option, click the toggle to enable the API. Lastly, due to security restrictions, you must run the sample files within your local web server as video camera access is denied for local access. Now that everything is ready and enabled, add a video tag to play the webcam stream. The stream received is be attached to the src property of the video tag using JavaScript. <video id="webcam" autoplay</video> In the JavaScript, you go through two steps. The first one is to find out if the user's browser can use the getUserMedia API. function hasGetUserMedia() { return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); } The second step is to try to get the stream from the user's webcam. Note: I’m using jQuery in this article and in the demo, but feel free to use any selector you like, such as a native document.querySelector. var webcamError = function(e) { alert('Webcam error!', e); }; var video = $('#webcam')[0]; if (navigator.getUserMedia) { navigator.getUserMedia({audio: true, video: true}, function(stream) { video.src = stream; }, webcamError); } else if (navigator.webkitGetUserMedia) { navigator.webkitGetUserMedia({audio:true, video:true}, function(stream) { video.src = window.webkitURL.createObjectURL(stream); }, webcamError); } else { //video.src = 'video.webm'; // fallback. } You are now ready to display a webcam stream in a HTML page. The next section provides an overview of the structure and assets used in the demo. If you hope to use getUserMedia in production, I recommend following Addy Osmani’s work. Addy has created a shim for the getUserMedia API with a Flash fallback. The detection of the user’s movement is performed using a blend mode difference. Blending two images using difference is nothing more than substracting pixels values. In the Wikipedia article about blend modes is a description of difference: “Difference subtracts the top layer from the bottom layer or the other way round, to always get a positive value. Blending with black produces no change, as values for all colors are 0.” To perform this operation, you need two images. The code loops over each pixel of the image, substracts each color channel from the first image to each color channel of the second image. For example, from two red images, the color channels at every pixel in both images is: - red: 255 (0xFF) - green: 0 - blue: 0 The following operations substract the colors values from these images: - red: 255 – 255 = 0 - green: 0 – 0 = 0 - blue: 0 – 0 = 0 In other words, applying a blend mode difference on two identical images produces a black image. Let’s discuss how that is useful and where those images coming from. Taking the process step by step, first draw an image from the webcam stream in a canvas, at a certain interval. In the demo, I draw 60 images per second, which is more than you need. The current image displayed in the webcam stream is the first image that you blend into another. The second image is another capture from the webcam but at the previous time interval. Now that you have two images, subtract their pixels values. This means that if the images are identical – in other words, if the user is not moving at all – the operation produces a black picture. The magic happens when the user starts to move. The image taken at the current time interval is be slightly different than the image of the previous time interval. If you substract different values, some colors start to appear. This means that something moved between these two frames! It starts to make sense as the motion detection process is almost finished. The last step is looping over all of the pixels in the blended image to determine if there are some pixels that are not black. To make this demo work, you need several things that are pretty common to all websites. You need, of course, an HTML page that contains some canvas and video tags, and some JavaScript to make the application run. Then, you need an image of the xylophone ideally with a transparent background (png). In addition, you need images for each key on the xylophone, as a separate image with a small brightness change. Using a rollover effect, these images give the user visual feedback, highlighting the triggered note. You need an audio file containing each note’s sound for which mp3 files will do. Playing a xylophone without sound wouldn't be much fun. Finally, I think it is important to show a video fallback of the demo in case the user can't or doesn't want to use their webcam. You need to create a video and encode it to mp4, ogg, and webm to cover all browsers. The next section provides a list of the tools used to encode the videos. You can find all the assets in the demo zip file, js_motion_detection.zip. I encoded the video demo fallback into the common three formats needed to display HTML5 videos. I had some trouble with the webm format as most of the tools I found for encoding would not give me the option to choose a bitrate. The bitrate sets both the video file size and quality, usually written as kbps (kilobits per second). I ended up using Online ConVert Video converter to convert to the WebM format (VP8), which worked well: For the mp4 version, you can use tools from the Adobe Creative Suite, such as the Adobe Media Encoder or After Effects. Or you can also use a free alternative such as Handbrake. For the ogg format, I used some tools that encode to all formats at once. I wasn't happy with the quality of the webm and mp4 formats. Although I couldn't seem to change the quality output, the ogg video was fine. You can use either Easy HTML5 Video or Miro. This is the last step before starting to code some JavaScript. Set some html tags. Here are the required HTML tags. (I won’t list everything I used, such as the video demo fallback code which you can download in the source.) You need a simple video tag to receive the user’s webcam feed. Don’t forget to set the autoplay property. Without it, the stream pauses on the first frame received. <video id="webcam" autoplay</video> The video tag will actually not be displayed. Its css display style is set to none. Instead, draw the stream received in a canvas so I can use it for the motion detection. Create the canvas to draw the webcam stream: <canvas id="canvas-source" width="640" height="480"></canvas> You also need another canvas to show what’s happening in real time during the motion detection: <canvas id="canvas-blended" width="640" height="480"></canvas> Create a div that contains the xylophone images. Place the xylophone on top of the webcam: the user can virtually use their hand to play with it. On top of the xylophone are placed the notes, hidden, that display on a rollover when the note is triggered. <div id="xylo"> <div id="back"><img id="xyloback" src="images/xylo.png"/></div> <div id="front"> <img id="note0" src="images/note1.png"/> <img id="note1" src="images/note2.png"/> <img id="note2" src="images/note3.png"/> <img id="note3" src="images/note4.png"/> <img id="note4" src="images/note5.png"/> <img id="note5" src="images/note6.png"/> <img id="note6" src="images/note7.png"/> <img id="note7" src="images/note8.png"/> </div> </div> The JavaScript steps to make this demo work are as follows: Prepare some variables to store what you for the drawing and motion detection. You need two references to the canvas, a variable to store the context of each canvas, and a variable to store the drawn webcam stream. Also store the x axis position of each xylophone note, the sounds notes to play, and some sound-related variables. var notesPos = [0, 82, 159, 238, 313, 390, 468, 544]; var timeOut, lastImageData; var canvasSource = $("#canvas-source")[0]; var canvasBlended = $("#canvas-blended")[0]; var contextSource = canvasSource.getContext('2d'); var contextBlended = canvasBlended.getContext('2d'); var soundContext, bufferLoader; var notes = []; Also invert the x axis of the webcam stream so the user feels like they are in front of a mirror. This makes their movement to reach the notes a bit easier. Here is how to do that: contextSource.translate(canvasSource.width, 0); contextSource.scale(-1, 1); Create a function called update that will be executed 60 times per second and will call other functions that draw the webcam stream onto a canvas, blend the images, and detect the motion. function update() { drawVideo(); blend(); checkAreas(); timeOut = setTimeout(update, 1000/60); } Drawing the video onto a canvas is quite easy and it takes only one line: function drawVideo() { contextSource.drawImage(video, 0, 0, video.width, video.height); } Create a helper function to ensure that the result of the substraction is always positive. You can use the built-in function Math.abs, but I wrote an equivalent with binary operators. Most of the time, using binary operators results in better peformance. You don’t have to understand it exactly, just use it as it is: function fastAbs(value) { // equivalent to Math.abs(); return (value ^ (value >> 31)) - (value >> 31); } Now write the blend mode difference. The function receives three parameters: The arrays of pixels are flattened and contain the color channels values of red, green, blue and alpha: In the demo, the webcam stream has a width of 640 pixels and a height of 480 pixels. The size of the array is: 640 * 480 * 4 = 1,228,000. The best way to loop over the array of pixels is to increment the value by 4 (red, green, blue, alpha), meaning there are now 307,200 iterations - much better. function difference(target, data1, data2) { var i = 0; while (i < (data1.length / 4)) { var red = data1[i*4]; var green = data1[i*4+1]; var blue = data1[i*4+2]; var alpha = data1[i*4+3]; ++i; } } You can now substract the pixel values of the images. For performance – and it seems to make a big difference – do not perform the substraction if the color channel is already 0 and set the alpha to 255 (0xFF) automatically. Here is the finished blend mode difference function (feel free to optimize!): function difference(target, data1, data2) { // blend mode difference if (data1.length != data2.length) return null; var i = 0; while (i < (data1.length * 0.25)) { target[4*i] = data1[4*i] == 0 ? 0 : fastAbs(data1[4*i] - data2[4*i]); target[4*i+1] = data1[4*i+1] == 0 ? 0 : fastAbs(data1[4*i+1] - data2[4*i+1]); target[4*i+2] = data1[4*i+2] == 0 ? 0 : fastAbs(data1[4*i+2] - data2[4*i+2]); target[4*i+3] = 0xFF; ++i; } } I used a slightly different version in the demo to get a better accuracy. I created a threshold function to be applied on the color values. The method either changes the pixel color value to black under a certain limit or to white above the limit. You can also use it as is: function threshold(value) { return (value > 0x15) ? 0xFF : 0; } I also made an average between the three color channels, which results in an image with pixels either black or white. function differenceAccuracy(target, data1, data2) { if (data1.length != data2.length) return null; var i = 0; while (i < (data1.length * 0.25)) { var average1 = (data1[4*i] + data1[4*i+1] + data1[4*i+2]) / 3; var average2 = (data2[4*i] + data2[4*i+1] + data2[4*i+2]) / 3; var diff = threshold(fastAbs(average1 - average2)); target[4*i] = diff; target[4*i+1] = diff; target[4*i+2] = diff; target[4*i+3] = 0xFF; ++i; } } The result is something like this black and white image. The function to blend the images is now ready, you just need to send the right values to it: the arrays of pixels. The JavaScript drawing API provides a method to retrieve an instance of an ImageData object. This object contains useful properties, such as width and height, and also the data property that is the array of pixels you need. Also, create an empty ImageData instance to receive the result, and store the current webcam image for the next iteration of the time interval. Here is the function that blends and draws the result in a canvas: function blend() { var width = canvasSource.width; var height = canvasSource.height; // get webcam image data var sourceData = contextSource.getImageData(0, 0, width, height); // create an image if the previous image doesn’t exist if (!lastImageData) lastImageData = contextSource.getImageData(0, 0, width, height); // create a ImageData instance to receive the blended result var blendedData = contextSource.createImageData(width, height); // blend the 2 images differenceAccuracy(blendedData.data, sourceData.data, lastImageData.data); // draw the result in a canvas contextBlended.putImageData(blendedData, 0, 0); // store the current webcam image lastImageData = sourceData; } The final step for this demo is the motion detection using the blended images we created in the previous section. When preparing the assets, place eight images of the notes of the xylophone to use them as rollovers. Use these note positions and sizes as rectangle areas to retrieve the pixels from the blended image. Then, loop over them to find some white pixels. In the loop, make an average of the color channels and add the result to a variable. After the loop has performed, create a global average of all the pixels in this area. Avoid noise or small motions by seeting a limit of 10. If you find a value that is more than 10, consider that something has moved since the last frame. This the motion detection! Then, play the corresponding sound and show the note rollover. The function looks like this: function checkAreas() { // loop over the note areas for (var r=0; r<8; ++r) { // get the pixels in a note area from the blended image var blendedData = contextBlended.getImageData( notes[r].area.x, notes[r].area.y, notes[r].area.width, notes[r].area.height); var i = 0; var average = 0; // loop over the pixels while (i < (blendedData.data.length / 4)) { // make an average between the color channel average += (blendedData.data[i*4] + blendedData.data[i*4+1] + blendedData.data[i*4+2]) / 3; ++i; } // calculate an average between of the color values of the note area average = Math.round(average / (blendedData.data.length / 4)); if (average > 10) { // over a small limit, consider that a movement is detected // play a note and show a visual feedback to the user playSound(notes[r]); notes[r].visual.style.display = "block"; $(notes[r].visual).fadeOut(); } } } I hope this brings you some new ideas to create video-based interactions, or to step on a territory that has been owned by Flash developers such as myself for years: video-interactive campaigns based on either pre-rendered videos or webcam streams. You can learn more information about the getUserMedia API by following the development of the Chrome and Opera browsers, and on the draft of the API on the W3C website. Creatively, if you are looking for ideas for motion detection or video-based applications, I recommend that you follow the experiments made by Flash developers and motion designers using After Effects. Now that JavaScript and HTML are gaining momentum and new capabilities, there is a lot to learn, try and experiment with the following resources: This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.
http://www.adobe.com/devnet/html5/articles/javascript-motion-detection.html
CC-MAIN-2014-35
refinedweb
3,017
64.41
Hi, Is anyone of devs supports Fireworks! It seems that project is not supported at all? Maybe I am missing something … Hi, It’s supported. Hi, thanks for reply… So that I am clear, I like framework, I used very successfully at nyse. I want to use it but pytask option is dead. Can someone look at that and confirm or provide working solution. I need to know as I have tight deadlines and if this is not working for me. I will use celery for dispatching things if fireworks is not doing pytask. Later I can fork and fix your framework if need be, but now it would be easier if someone with more insights gives me rundown on how stable framework is. PyTasks are still inside of the current repo and can be used. See Nicholas, That is all fine! I am aware of it… What is not ok is that I posted three questions and submitted a bug report with no responses. Look at the PyTask questions and bugs from me on github and discourse. I worked with Anubhav long back and even fixed timestamps for Fireworks at the time. The problem is that Pytask, even examples from documentation, will fail miserably when a rocket is launched. Launchpad and serialization and registration of the task is not working correctly. So that is the issue I have. I need an example that works, but I believe that launchpad is not capable of running PyTasks, due to these issues. I actually provided a temp fix around checking for data types to avoid complete error but this reflects later in lp object as another error. If you look at those tickets you will see what I am talking about. Yes I could use script tasks to execute python app that I am interested in, but I would rather invoke modules and methods more directly via PyTask then dealing with rewrites of my architecture to use script tasks… Regards, I’m not a dev so I don’t know the issue history on github. I just use fireworks often. In any case, I’d probably just suggest ignoring PyTask and using a quick custom Firetask, which definitely work as I use them all the time. fw_timer = Firework(PyTask(func='time.sleep',args=[5])) Becomes @explicit_serialize class Sleep(FiretaskBase): required_params = ["sleep_time"] def run_task(self, fw_spec): time.sleep(self.get("sleep_time")) fw_timer = Firework(Sleep(sleep_time=5)) Which should work fine. Hopefully that works for you. What is not ok is that I posted three questions and submitted a bug report with no responses. On this point, we are open-source codes that ultimately run on good will; in general, people are not paid to work on these codes, and people using the codes are not paying to use them. I am also not a FireWorks developer but, speaking broadly for Materials Project and its codes, it doesn’t make us happy if an issue or a question sits without answers for a while – we would much prefer prompt, timely answers for inquiries – nevertheless, we have many constraints on our time and this is not always possible, and sometimes significant delays are unavoidable. I hope @Nicholas_Winner’s answer can help in the meantime. Yeah, good point… Will do that When we are on the subject of custom tasks, may i ask this: I need to push callable, meaning python objects containing bunch of objects and attributes to mongo queue. I understand you are not dev, but maybe you guys know if this is possible with custom FT. If not I can serialize those objects on NFS and pick them up from required_params …? Thanks for help Hi, yes we know good will! I am down with that, and I do understand that everyone is busy! I am in the same boat and I also have open source projects that I support… I like idea behind fireworks, and I think it is worth developing and pushing it forward. Thanks for chiming in, and please do not take personally my frustrations … Regards, Hi Sashak, Thanks for sharing the issues you’ve found with FireWorks and to echo Matt - we do try to provide timely responses but this is not always possible. As far as I know there haven’t been any recent changes to PyTask. Any idea why it stopped working suddenly? Does it work with a previous version of FireWorks? Note that we are aware that pymongo 4.0 has broken some things and we attempted to fix them, although I am not sure that is the case here. I’ve put two people in my group, Duo Wang and Zhuoying Zhu, in charge to investigate this. Hi Anubhav, Thanks for the reply… PyTask is definitely failing here: self.fireworks.find_one_and_replace({‘fw_id’: fw.fw_id}, fw.to_db_dict(), upsert=True) so: def to_dict(self): … spec[’_tasks’] = [t.to_dict() for t in self.tasks] t is already a dict and spec[’_tasks’] is trying to convert dict to dict failing miserably … {‘spec’: {’_tasks’: [:{‘func’: ‘time.sleep’, ‘args’: [5], ‘_fw_name’: ‘PyTask’}]}, ‘fw_id’: -1, ‘created_on’: datetime.datetime(2022, 1, 16, 20, 20, 16, 789436), ‘updated_on’: datetime.datetime(2022, 1, 16, 20, 20, 16, 789437), ‘name’: ‘Unnamed FW’} so I changed this code to debug a bit: @recursive_serialize def to_dict(self): put tasks in a special location of the spec spec = self.spec spec[’_tasks’] = list() for t in self.tasks: print(t) if isinstance(t, dict): spec[’_tasks’].append(t) else: td = t.to_dict() spec[’_tasks’].append(td) ##spec['_tasks'] = [t.to_dict() for t in self.tasks] m_dict = {'spec': spec, 'fw_id': self.fw_id, 'created_on': self.created_on, 'updated_on': self.updated_on} # only serialize these fields if non-empty if len(list(self.launches)) > 0: m_dict['launches'] = self.launches if len(list(self.archived_launches)) > 0: m_dict['archived_launches'] = self.archived_launches # keep export of new FWs to files clean if self.state != 'WAITING': m_dict['state'] = self.state m_dict['name'] = self.name return m_dict Now firework is working correctly, meaning rocket can finish… problem at this point is: 2022-01-16 15:28:50,762 INFO Rocket finished Traceback (most recent call last): File “/cube/api/py-3.9.7/lib/python3.9/site-packages/fireworks/core/rocket.py”, line 248, in run l_logger.log(logging.INFO, "Task started: s. t.fw_name) AttributeError: ‘dict’ object has no attribute ‘fw_name’ It looks to me now that i am looking into my own post that it might be that documentation needs an update or that Pytask needs some updates on the spec side. Not sure, but I can contribute and help if anyone points to me the whole architecture and where is what. Sorry to hear about pymongo, and that might be an issue with me too. I have 5.x mongo, 3.10 python and latest fireworks. On the side, my question for you is this: I need to push large objects as args to tasks… It looks to me that fireworks in custum task and pyTask does not allow required args to be python objects. I do want to use callable objects to push them to worknodes and let the worknodes do the work. These objects are essentially template structures of info that worknode drivers will use to do the work. in mongo on my side no matter how I construct the firetask i endup with string object in mongo representing python class object instance. All what I need from you guys is yes or no that this can be done, and if not can we do something in custom metacalss for FireBase to actually allow this to be added as a param. maybe is pymongo that is normalizing all of this to strings, but i am pretty sure that mongo can be feed pickle binary … I know how I will go around this. I will serialize py objs with Dill on NFS, put the mapping to object as string into workflow task req field and let driver sort the things when it pick up a task and workflow. it would be nice and I can contribute to change this in your code if someone gives me good rundown on flow of fireworks so that I am not lost in see of code. Thanks again for replying and i am happy that your project lived for so long … It means that all of you who contributed did a good job … Hi Sashak, For the PyTask I will leave to Duo / Zhuoying. In terms of passing objects as arguments you need to make sure the objects can be serialized/deserialized properly. To do that the objects must subclass FWSerializable. The main requirement is that the object has a to_dict() and from_dict() method. This will make sure that the object can be converted into MongoDB and (via to_dict()) and re-instantiated as an object (via from_dict()). Hello @sashak ! Hope @Anubhav_Jain has answered your question in serializable object using FWSerializable (fireworks.utilities package — FireWorks 1.9.8 documentation). Thanks for bringing up this problem in PyTask. We will try to look into the branch and resolve the fw_name() attributeError happened in fireworks/PyTask. You are also welcome to contribute to fireworks by opening PR to fix the to_dict() issue. I will create a separate method for checking types in the class. Then integrate with to_dict method. This way any other method that needs to convert anything to dict coudl utilize this method. If anything else aside from list of tupels need to be converted in the future we can decorate that method to deal with any type that needs to convert. Which branch you need me to do this in … I guess I fork the project do my stuff and create merge for you guys to approve it … Right? Thanks for the note on serialization. Problem that I have is that I am using a state machine to create this object. If I understand correctly: class A(FWSerializable): pass then do the custom task which will also use decorator to register () something like above my problem is that original class A is currently using another metaclass class A(StateMachine … so if I now add class A(StateMachine,FWSerializable): … i am getting metaclasses conflicts … So I am a bit confused… basically my state machine contains everything that I need pass to worker as param so if I do: mpacTask = Firework(MPACWFTask(serviceDriver= self)) mongo will accept this but on def run_task(self, fw_spec): print(self[‘serviceDriver’]) serviceDriver is string representing an object maybe i should within StateMachine create a new FWSerializable object and add attributes to that object thus insulating class inheritance and metaclasses clashes alltogether. Any thoughts? never mind, I just read note from Duo Wang and I will look at the utilities package Hello @sashak. What we usually do here in materials project is to folk the package to your own, and then create new branch and make the change of your own codes. Once you finish, you can pull a request (PR) to the main branch of fireworks. Once all the modified codes are reviewed and all the tests are passed, the persons in charge of maintenance will help you to merge the PR into the main/master branch. Hope this information is helpful. Please let us know for any problems or concerns. Cool thanks Hi, it seems that fireworks can iterate (class.repr) when I create wrapped object for customTask and try to feed to launchpd.add_wf Example: () class MyTaskObject(FWSerializable): @serialize_fw def to_dict(self): return dict(self) @classmethod def from_dict(cls, m_dict): return cls(m_dict) def __repr__(self): return dict(self) self.mpacTask = MyTaskObject() self.mpacTask.someAttrib = ‘sasha’ mpacTask =MPACWFTask(serviceDriver= self.mpacTask) firework = Firework(mpacTask ) launchpad = LaunchPad() launchpad.reset(’’, require_password=False) try: launchpad.add_wf(firework) except Exception as lpErr: logger.error(lpErr) raise PropFailure(lpErr) Unable to get repr for <class ‘FireTaskCustom.MPACWFTask’> so what am I doing wrong … i am not sure, but it seems to me that i am duplicating serialization via my own task implementation and custom task implementation. So possibly that is causing repr and MytaskObject no being iterable. Please provide me with simple example of what you mean by custom task req_param being object that is serialize to dict and back to object on the remote end.
https://matsci.org/t/fireworks/40219
CC-MAIN-2022-21
refinedweb
2,037
63.59
Selenium automates browsers. It automates the interaction we do in a browser window such as navigating to a website, clicking on links, filling out forms, submitting forms, navigating through pages, and so on. It works on every major browser available out there. In order to use Selenium WebDriver, we need a programing language to write automation scripts. The language that we select should also have a Selenium client library available. In this book, we will use Python along with the Selenium WebDriver client library to create automated scripts. Python is a widely used general-purpose, high-level programming language. It's easy and its syntax allows us to express concepts in fewer lines of code. It emphasizes code readability and provides constructs that enable us to write programs on both the small and large scale. It also provides a number of in-built and user-written libraries to achieve complex tasks quite easily. The Selenium WebDriver client library for Python provides access to all the Selenium WebDriver features and Selenium standalone server for remote and distributed testing of browser-based applications. Selenium Python language bindings are developed and maintained by David Burns, Adam Goucher, Maik Röder, Jason Huggins, Luke Semerau, Miki Tebeka, and Eric Allenin. The Selenium WebDriver client library is supported on Python Version 2.6, 2.7, 3.2, and 3.3. This chapter will introduce you to the Selenium WebDriver client library for Python by demonstrating its installation, basic features, and overall structure. In this chapter, we will cover the following topics: Installing Python and Selenium package Selecting and setting up a Python editor Implementing a sample script using the Selenium WebDriver Python client library Implementing cross-browser support with Internet Explorer and Google Chrome As a first step of using Selenium with Python, we'll need to install it on our computer with the minimum requirements possible. Let's set up the basic environment with the steps explained in the following sections. You will find Python installed by default on most Linux distributions, Mac OS X, and other Unix machines. On Windows, you will need to install it separately. Installers for different platforms can be found at. The Selenium WebDriver Python client library is available in the Selenium package. To install the Selenium package in a simple way, use the pip installer tool available at. With pip, you can simply install or upgrade the Selenium package using the following command: pip install -U selenium This is a fairly simple process. This command will set up the Selenium WebDriver client library on your machine with all modules and classes that we will need to create automated scripts using Python. The pip tool will download the latest version of the Selenium package and install it on your machine. The optional âU flag will upgrade the existing version of the installed package to the latest version. You can also download the latest version of the Selenium package source from. Just click on the Download button on the upper-right-hand side of the page, unarchive the downloaded file, and install it with following command: python setup.py install The Selenium WebDriver Python client library documentation is available at as shown in the following screenshot: It offers detailed information on all core classes and functions of Selenium WebDriver. Also note the following links for Selenium documentation: The official documentation at offers documentation for all the Selenium components with examples in supported languages Selenium Wiki at lists some useful topics that we will explore later in this book Now that we have Python and Selenium WebDriver set up, we will need an editor or an Integrated Development Environment (IDE) to write automation scripts. A good editor or IDE increases the productivity and helps in doing a lot of other things that make the coding experience simple and easy. While we can write Python code in simple editors such as Emacs, Vim, or Notepad, using an IDE will make life a lot easier. There are many IDEs to choose from. Generally, an IDE provides the following features to accelerate your development and coding time: A graphical code editor with code completion and IntelliSense A code explorer for functions and classes Syntax highlighting Project management Code templates Tools for unit testing and debugging Source control support If you're new to Python, or you're a tester working for the first time in Python, your development team will help you to set up the right IDE. However, if you're starting with Python for the first time and don't know which IDE to select, here are a few choices that you might want to consider. PyCharm is developed by JetBrains, a leading vendor of professional development tools and IDEs such as IntelliJ IDEA, RubyMine, PhpStorm, and TeamCity. PyCharm is a polished, powerful, and versatile IDE that works pretty well. It brings best of the JetBrains experience in building powerful IDEs with lots of other features for a highly productive experience. PyCharm is supported on Windows, Linux, and Mac. To know more about PyCharm and its features visit. PyCharm comes in two versionsâa community edition and a professional edition. The community edition is free, whereas you have to pay for the professional edition. Here is the PyCharm community edition running a sample Selenium script in the following screenshot: The community edition is great for building and running Selenium scripts with its fantastic debugging support. We will use PyCharm in the rest of this book. Later in this chapter, we will set up PyCharm and create our first Selenium script. The PyDev Eclipse plugin is another widely used editor among Python developers. Eclipse is a famous open source IDE primarily built for Java; however, it also offers support to various other programming languages and tools through its powerful plugin architecture. Eclipse is a cross-platform IDE supported on Windows, Linux, and Mac. You can get the latest edition of Eclipse at. You need to install the PyDev plugin separately after setting up Eclipse. Use the tutorial from Lars Vogel to install PyDev at to install PyDev. Installation instructions are also available at. Here's the Eclipse PyDev plugin running a sample Selenium script as shown in the following screenshot: For the Windows users, PyScripter can also be a great choice. It is open source, lightweight, and provides all the features that modern IDEs offer such as IntelliSense and code completion, testing, and debugging support. You can find more about PyScripter along with its download information at. Here's PyScripter running a sample Selenium script as shown in the following screenshot: Now that we have seen IDE choices, let's set up PyCharm. All examples in this book are created with PyCharm. However, you can set up any other IDE of your choice and use examples as they are. We will set up PyCharm with following steps to get started with Selenium Python: Download and install the PyCharm Community Edition from JetBrains site. Launch the PyCharm Community Edition. Click on the Create New Project option on the PyCharm Community Edition dialog box as shown in the following screenshot: - On the Create New Project dialog box, as shown in next screenshot, specify the name of your project in the Project name field. In this example, setestsis used as the project name. We need to configure the interpreter for the first time. Click on the button to set up the interpreter, as shown in the following screenshot: On the Python Interpreter dialog box, click on the plus icon. PyCharm will suggest the installed interpreter similar to the following screenshot. Select the interpreter from Select Interpreter Path. PyCharm will configure the selected interpreter as shown in the following screenshot. It will show a list of packages that are installed along with Python. Click on the Apply button and then on the OK button: On the Create New Project dialog box, click on the OK button to create the project: WeâMagento. You can find the application at. Note Downloading the example code You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. The example code is also hosted at. In this sample script, we will navigate to the demo version of the application, search for products, and list the names of products from the search result page with the following steps: Let's use the project that we created earlier while setting up PyCharm. Create a simple Python script that will use the Selenium WebDriver client library. In Project Explorer, right-click on setestsand navigate to New | Python File from the pop-up menu: On the New Python file dialog box, enter searchproductsin the Name field and click on the OK button: PyCharm will add a new tab searchproducts.py in the code editor area. Copy the following code in the searchproduct.py tab: from selenium import webdriver # create a new Firefox session driver = webdriver.Firefox()() To run the script, press the Ctrl + Shift + F10 combination in the PyCharm code window or select Run 'searchproducts' from the Run menu. This will start the execution and you will see a new Firefox window navigating to the demo site and the Selenium commands getting executed in the Firefox window. If all goes well, at the end, the script will close the Firefox window. The script will print the list of products in the PyCharm console as shown in the following screenshot: We'll spend some time looking into the script that we created just now. We will go through each statement and understand Selenium WebDriver in brief. There is a lot to go through in the rest of the book. The selenium.webdriver module implements the browser driver classes that are supported by Selenium, including Firefox, Chrome, Internet Explorer, Safari, and various other browsers, and RemoteWebDriver to test on browsers that are hosted on remote machines. We need to import webdriver from the Selenium package to use the Selenium WebDriver methods: from selenium import webdriver Next, we need an instance of a browser that we want to use. This will provide a programmatic interface to interact with the browser using the Selenium commands. In this example, we are using Firefox. We can create an instance of Firefox as shown in following code: driver = webdriver.Firefox() During the run, this will launch a new Firefox window. We also set a few options on the driver: driver.implicitly_wait(30) driver.maximize_window() We configured a timeout for Selenium to execute steps using an implicit wait of 30 seconds for the driver and maximized the Firefox window through the Selenium API. We will learn more about implicit wait in Chapter 5, Synchronizing Tests. Next, we will navigate to the demo version of the application using its URL by calling the driver.get() method. After the get() method is called, WebDriver waits until the page is fully loaded in the Firefox window and returns the control to the script. After loading the page, Selenium will interact with various elements on the page, like a human user. For example, on the Home page of the application, we need to enter a search term in a textbox and click on the Search button. These elements are implemented as HTML input elements and Selenium needs to find these elements to simulate the user action. Selenium WebDriver provides a number of methods to find these elements and interact with them to perform operations such as sending values, clicking buttons, selecting items in dropdowns, and so on. We will see more about this in Chapter 3, Finding Elements. In this example, we are finding the Search textbox using the find_element_by_name method. This will return the first element matching the name attribute specified in the find method. The HTML elements are defined with tag and attributes. We can use this information to find an element, by following the given steps: In this example, the Search textbox has the name attribute defined as qand we can use this attribute as shown in the following code example: search_field = driver.find_element_by_name("q") Once the Search textbox is found, we will interact with this element by clearing the previous value (if entered) using the clear()method and enter the specified new value using the send_keys()method. Next, we will submit the search request by calling the submit()method: search_field.clear() search_field.send_keys("phones") search_field.submit() After submission of the search request, Firefox will load the result page returned by the application. The result page has a list of products that match the search term, which is phones. We can read the list of results and specifically the names of all the products that are rendered in the anchor <a>element using the find_elements_by_xpath()method. This will return more than one matching element as a list: products = driver.find_elements_by_xpath("//h2[@class='product-name']/a") Next, we will print the number of products (that is the number of anchor <a>elements) that are found on the page and the names of the products using the .textproperty of all the anchor <a>elements: print "Found " + str(len(products)) + " products:" for product in products: print product.text At end of the script, we will close the Firefox browser using the driver.quit()method: driver.quit() This example script gives us a concise example of using Selenium WebDriver and Python together to create a simple automation script. We are not testing anything in this script yet. Later in the book, we will extend this simple script into a set of tests and use various other libraries and features of Python. So far we have built and run our script with Firefox. Selenium has extensive support for cross-browser testing where you can automate on all the major browsers including Internet Explorer, Google Chrome, Safari, Opera, and headless browsers such as PhantomJS. In this section, we will set up and run the script that we created in the previous section with Internet Explorer and Google Chrome to see the cross-browser capabilities of Selenium WebDriver. There is a little more to run scripts on Internet Explorer. To run tests on Internet Explorer, we need to download and set up the InternetExplorerDriver server. The InternetExplorerDriver server is a standalone server executable that implements WebDriver's wire protocol to work as glue between the test script and Internet Explorer. It supports major IE versions on Windows XP, Vista, Windows 7, and Windows 8 operating systems. Let's set up the InternetExplorerDriver server with the following steps: Download the InternetExplorerDriverserver from. You can download 32- or 64-bit versions based on the system configuration that you are using. After downloading the InternetExplorerDriverserver, unzip and copy the file to the same directory where scripts are stored. On IE 7 or higher, the Protected Mode settings for each zone must have the same value. Protected Mode can either be on or off, as long as it is for all the zones. To set the Protected Mode settings: Choose Internet Options from the Tools menu. On the Internet Options dialog box, click on the Security tab. Select each zone listed in Select a zone to view or change security settings and make sure Enable Protected Mode (requires restarting Internet Explorer) is either checked or unchecked for all the zones. All the zones should have the same settings as shown in the following screenshot: Finally, modify the script to use Internet Explorer. Instead of creating an instance of the Firefox class, we will use the IEclass in the following way: import os from selenium import webdriver # get the path of IEDriverServer dir = os.path.dirname(__file__) ie_driver_path = dir + "\IEDriverServer.exe" # create a new Internet Explorer session driver = webdriver.Ie(ie InternetExplorerDriverserver while creating the instance of an IEbrowser class. Run the script and Selenium will first launch the InternetExplorerDriverserver, which launches the browser, and execute the steps. The InternetExplorerDriverserver acts as an intermediary between the Selenium script and the browser. Execution of the actual steps is very similar to what we observed with Firefox. Note Read more about the important configuration options for Internet Explorer at and the DesiredCapabilities article at. Setting up and running Selenium scripts on Google Chrome is similar to Internet Explorer. We need to download the ChromeDriver server similar to InternetExplorerDriver. The ChromeDriver server is a standalone server developed and maintained by the Chromium team. It implements WebDriver's wire protocol for automating Google Chrome. It is supported on Windows, Linux, and Mac operating systems. Set up the ChromeDriver server using the following steps: Download the ChromeDriverserver from. After downloading the ChromeDriverserver, unzip and copy the file to the same directory where the scripts are stored. Finally, modify the sample script to use Chrome. Instead of creating an instance of the Firefox class, we will use the Chromeclass in the following way: import os from selenium import webdriver # get the path of chromedriver dir = os.path.dirname(__file__) chrome_driver_path = dir + "\chromedriver.exe" #remove the .exe extension on linux or mac platform # create a new Chrome session driver = webdriver.Chrome(chrome ChromeDriverserver while creating an instance of the Chrome browser class. Run the script. Selenium will first launch the Chromedriverserver, which launches the Chrome browser, and execute the steps. Execution of the actual steps is very similar to what we observed with Firefox. Note Read more about ChromeDriver at and. In this chapter, we introduced you to Selenium and its components. We installed the selenium package using the pip tool. Then we looked at various Editors and IDEs to ease our coding experience with Selenium and Python and set up PyCharm. Then we built a simple script on a sample application covering some of the high-level concepts of Selenium WebDriver Python client library using Firefox. We ran the script and analyzed the outcome. Finally, we explored the cross-browser testing support of Selenium WebDriver by configuring and running the script with Internet Explorer and Google Chrome. In next chapter, we will learn how to use the unittest library to create automated tests using Selenium WebDriver. We will also learn how to create a suite of tests and run tests in groups.
https://www.packtpub.com/product/learning-selenium-testing-tools-with-python/9781783983506
CC-MAIN-2020-40
refinedweb
3,037
53.41
I’ll kick things off by posting my version of the programming exercise solutions for the popular book, C++ Primer Plus 5th edition. All source code for the exercises in this series will be my own. Feel free to reference it or use it for your own purposes. The programming exercises start at chapter 2, so off we go with exercise 1 of chapter 2: 1. Write a C++ program that displays your name and address. #include <iostream> using namespace std; int main() { cout << "Rundata\n"; cout << "Bourbon Street\n"; cout << "New Orleans, LA 70116\n"; return 0; } Easy enough huh? Advertisements
https://rundata.wordpress.com/2012/10/12/c-primer-chapter-2-exercise-1/
CC-MAIN-2017-26
refinedweb
102
71.85
משיב מוביל Hyper-V 2016 VMs stuck 'Creating checkpoint 9%' while starting backups שאלה We have a two clustered W2016 Hyper-V hosts, every couple of days one of the hosts gets stuck when the backup kicks off. In Hyper-V manager the VMs all say 'Creating checkpoint 9%' It's always the same percentage 9%. You can't cancel the operation and the VMMS service refuses to stop, the only way to get out of the mess is to shutdown the VMs, and hard reset the effected node. The backup works for a few days then it all starts again. The only events I can see on the effected node is: Event ID: 19060 source: Hyper-V-VMMS 'VMName' failed to perform the 'Creating Checkpoint' operation. The virtual machine is currently performing the following operation: 'Creating Checkpoint'. Can anybody help please? Cluster validation is clean. Hosts and guests are patched up. תשובות כל התגובות Hi Sir, Are you using windows server backup to backup these VMs ? How long is the backup interval ? Every time the backup will stuck at "9%" ? Best Regards, Elton Please remember to mark the replies as answers if they help. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com. Thanks for responding, The backup is Veeam 9.5 Backup interval is configured to run each night at 23:00, it normally takes 20 minutes to finish. When the backup job starts it must call to the Hyper-V host to take a checkpoint, it this that stalls at 9% each time, not the backup it's self. VMMS becomes unresponsive on the host and I can't even LiveMigration VMs, hard resetting the host seems to be the only way to get out of the situation. @AustinT have you tries restarting VMMS ? restart-service VMMS What does the job information tell you about this job ? gwmi -namespace root\virtualization\v2 -class msvm_concretejob gwmi -namespace root\virtualization\v2 -class msvm_migrationjob gwmi -namespace root\virtualization\v2 -class msvm_storagejob Hi, The VMMS service is unresponsive and won't restart. Here is the output from the msvm_concretejob....the other two returned nothing.PS C:\> gwmi -namespace root\virtualization\v2 -class msvm_concretejob __GENUS : 2 __CLASS : Msvm_ConcreteJob __SUPERCLASS : CIM_ConcreteJob __DYNASTY : CIM_ManagedElement __RELPATH : Msvm_ConcreteJob.InstanceID="8C874D34-8F00-412F-8F92-056A62C954CB" __PROPERTY_COUNT : 41 __DERIVATION : {CIM_ConcreteJob, CIM_Job, CIM_LogicalElement, CIM_ManagedSystemElement...} __SERVER : HV2 __NAMESPACE : root\virtualization\v2 __PATH : \\HV2\root\virtualization\v2:Msvm_ConcreteJob.InstanceID="8C874D34-8F00-412F-8F92-056A62C954CB" Cancellable : True Caption : Creating Checkpoint CommunicationStatus : DeleteOnCompletion : False Description : Creating Virtual Machine Checkpoint DetailedStatus : ElapsedTime : 00000001183119.965512:000 ElementName : Creating Checkpoint ErrorCode : 0 ErrorDescription : ErrorSummaryDescription : HealthState : 5 InstallDate : 16010101000000.000000-000 InstanceID : 8C874D34-8F00-412F-8F92-056A62C954CB231150.000000-000 StartTime : 20170327231150.000000-000 Status : OK StatusDescriptions : {Job is running} TimeBeforeRemoval : 00000000000500.000000:000 TimeOfLastStateChange : 20170327231150.000000-000 TimeSubmitted : 20170327231150.000000-000 UntilTime : PSComputerName : HV2 __GENUS : 2 __CLASS : Msvm_ConcreteJob __SUPERCLASS : CIM_ConcreteJob __DYNASTY : CIM_ManagedElement __RELPATH : Msvm_ConcreteJob.InstanceID="C4CA521A-3309-48D8-B659-F7EF6B95615B" __PROPERTY_COUNT : 41 __DERIVATION : {CIM_ConcreteJob, CIM_Job, CIM_LogicalElement, CIM_ManagedSystemElement...} __SERVER : HV2 __NAMESPACE : root\virtualization\v2 __PATH : \\HV2\root\virtualization\v2:Msvm_ConcreteJob.InstanceID="C4CA521A-3309-48D8-B659-F7EF6B95615B" Cancellable : True Caption : Creating Checkpoint CommunicationStatus : DeleteOnCompletion : False Description : Creating Virtual Machine Checkpoint DetailedStatus : ElapsedTime : 00000001184028.776685:000 ElementName : Creating Checkpoint ErrorCode : 0 ErrorDescription : ErrorSummaryDescription : HealthState : 5 InstallDate : 16010101000000.000000-000 InstanceID : C4CA521A-3309-48D8-B659-F7EF6B95615B230241.000000-000 StartTime : 20170327230241.000000-000 Status : OK StatusDescriptions : {Job is running} TimeBeforeRemoval : 00000000000500.000000:000 TimeOfLastStateChange : 20170327230241.000000-000 TimeSubmitted : 20170327230241.000000-000 UntilTime : The issue came back even with CSV cache disabled. See this thread for people having similar issues. All poster have Dell based Intel 10GbE cards with Windows 2016 installed. Hi, The solution for me was to update the network adapter firmware and use the latest Intel drivers from the Dell support website. IMHO it was the inbox drivers from Microsoft causing the issues, the Intel drivers seem to have fixed the issue. All the best Hey guys, the solution for me was to rename a broken Hyper-V Server so it was not loaded any more. The Hyper-V server was in one folder including disks and machine. So I stopped and killed the hyper-v services and simply renamed the folder. All services started up and all other virtual machines worked fine after this action. Best greets, Daniel Hebel I've got that same issue... stuck at 9% creating checkpoint on one node of a 2-node hyper-v cluster. I"m also using veeam 9.5u4. I"ve got the latest NIC drivers installed and latest updates on windows 2019. Daniel, what do you mean "I renamed the folder". I can't restart the node right now or do anything drastic to try and recover during production hours. I tried restarting one VM and now its stuck unable to fully turn off. I assume from above, I can't simply taskkill vmms or the vmwp processes. I notice two events in the vmms admin event viewer which seem to be at the start of the issue... error 32587 and 32510 . Both say "the description of event ID #### from source cannot be found..." It referenced a VM that was in the off state. I was using hyper-v replication too for a few key VMs and have turned that off per - נערך על-ידי trump26901 יום רביעי 13 מרץ 2019 14:35 production with the check box option to create standard if the guest does not support creation of production checkpoints. there are about 30 VMs in the backup job all of which are in the same cluster. most use the veeam app-aware processing function, but a few are copy only. The VMs that are stuck are all on the same host and are a mixture of app-aware and copy only in veeam. I had three VMs that were set to replicate to an off-cluster host and one of those was on the problem host as well. I go the same outputs for as AustinT back in his old post with the wmi calls and only gwmi -namespace root\virtualization\v2 -class msvm_concretejob gives a response and my response looks almost identical. I didn't try killing vmms since he said that didn't help and at least for the moment I don't want to upset the cluster until I can allow for a more controlled potential outage. Is there a way to force those Msvm_ConcreteJob jobs to stop? 100% it was drivers for me. Is this a Dell server with Intel NICS? Use this PowerShell to see the driver version and more importantly the driver provider. It should say Intel and not Microsoft.Get-NetAdapter | where {$_.InterfaceDescription -notlike "Hyper-V*"} | where {$_.InterfaceDescription -notlike "Microsoft*"}| FT Name, DriverInformation, DriverProvider -AutoSize I'll keep that in mind. maybe the production one increases the chances of the problem coming up, but for now all I can say is that something on the host broke. I should be able to get in a full cluster shutdown tonight, so that should hopefully give me some more breathing room to trouble-shoot. I am having the exact same issue, Dell Servers XC 630 (essentially R730's), Intel cards X520, and using Veeam, drivers are Intel 4.1.4.0. Checkpoints are set to use Production with standard as failback. Did you manage to find anything in your troubleshooting trump26901 ? At the moment I do not appear to be able to stop the checkpoint creation, VM's on here will not shutdown or migrate off, so looking to have to do the forced host reboot. I could do without this happening again, if anyone found any further resolution ? - nothing yet. I did a "controlled" shutdown of the cluster and all running VMs (any that would not shut off, I got them to stop at the shutting off phase and then I shut down the cluster and did taskkill to allow the nodes to reboot. I haven't run into the problem again yet and so I don't want to do anything too drastic and try and fix something that only happens under a very rare set of conditions which we might never see again. If it happens to me again I'll start looking into it more seriously. We had the same issue today with Windows Server 2016 Datacenter running Hyper-V, and VM running Windows Server 2016 Standard, Exchange 2016 15.1.1415.2. Cancelled checkpoint creation from Hyper-V - no result. Graceful stop of Veeam backup job - no result Force stop Veeam backup job - after one minute the checkpoint creation stopped. VM was on, but terminal would not connect. Force shutdown VM and boot again - VM works as normal. Veeam log after stopped job: 02-04-2019 06:02:51 :: Failed to create VM recovery checkpoint (mode: Veeam application-aware processing) Details: Job failed ('Checkpoint operation for '<server name>' failed. (Virtual machine ID <VM GUID>) Checkpoint operation for '<server name>' was cancelled. (Virtual machine ID <VM GUID>) '<server name>' could not initiate a checkpoint operation: This operation returned because the timeout period expired. (0x800705B4). (Virtual machine ID <VM GUID>) and 02-04-2019 06:23:19 :: Retrying snapshot creation attempt (Failed to create production checkpoint.) I found this article too: Was that host in a cluster or just standalone? It happened again to us the other night. I've changed all VMs to standard checkpoint now as opposed to production per mlavie's suggestion. Nice to know that I don't have to totally reboot the host next time as long as I can turn off the veeam server. I didn't see anything particularly obvious for why its getting stuck in my logs so hopefully others in here are watching this thread and together we can work out a commonality. My environment: 2-node S2D Cluster on Windows Server DC 2019 - latest updates Intel X722-4 NICs for hosts/VMs, Mellanox 4lx crossover cables for RDMA/cluster Veeam 9.5u4 (I just looked and there is now a u4a available that I will update to now). Good Afternoon, Please confirm that the Security Policy "User Rights Assignment > Log on as a batch job" is not defined by Group Policy on any Hyper-V Hosts. You can confirm if it is by performing the following steps; - Start - Run - "Secpol.msc", click OK - Local Policies > User Rights Assignment > Log on as a batch job - Confirm that "Add User or Group..." is not greyed-out. If this has been defined, remove the group policy from the host - update group policy, then reboot the host. Confirm if the issue still exists. Thanks. - User Rights Assignment I checked both my cluster hosts and both are NOT greyed-out. Both contain "Administrators", "Backup Operators", and "Performance Log Users" . I"m not sure if the timing is repeatable or just random, but it appears to have happened roughly 3-weeks apart... I installed and setup the system, roughly three weeks later the issue happened, and then roughly three weeks after that it happened again. If it repeats again at the same pace, that will happen in roughly two weeks. I have a host in the same boat, not clustered, Using Quest Rapid Recovery, 2019 STD, VSS gets wacked and then VM's are stuck in 9% checkpoint. Host is an Intel board S2600WFT with X722 10GBATE-T build in adapters. PS does report they are using Microsoft Drivers per one of the comments in this thread. I will see about updating the drivers to Intel drivers after hours. We also have a customer who is affected by this. Their setup: - 3 Node Hyper-V Cluster running Server 2019 Datacenter, all with the latest updates/firmware/drivers - Replication server at remote site - HPE MSA2052 with the latest firmware - Altaro VM Backup 8.2.1.3 So far this has affected VMs on different hosts, so it is not specific to one host. There appears to be no pattern to this. The backups run as scheduled each night, and one VM will get stuck on 'Creating Checkpoint (9%)'. Following this, the VMs on that node can no longer be managed. You cannot: - Create checkpoints - Live migrate to another host - Quick migrate to another host - Manage replication (if replication is enabled for that VM) The following does continue to work: - You can log in to each VM on the affected host, either via RDP or Hyper-V Console - Replication-enabled VMs continue to replicate as normal, except for the affected VM. The affected VM stops replicating. Essentially, VMs on the affected host respond as though there is no issue with this host. Please allow me to re-iterate that this has affected VMs which are configured for replication, and VMs which are not configured for replication. A different VM has been affected, on a different host, each time this has happened. Previously, the following recovered the host: - Restart VMMS (this took a very long time, and crashed out another VM) - Reboot the affected node Following _Dickins suggestion, we removed our GPO from the hosts which define users in 'Log on as a service'. This restored the default account(s) which require this access, but unfortunately made no difference. This is a brand new Infrastructure Refresh, which was only installed in 2019. Everything is fully up to date in terms of drivers/firmware. Each VM has the following Integration Service enabled: - Operating system shutdown - Data Exchange - Heartbeat - Backup (volume shadow copy) And the following disabled: - Time synchronization - Guest services Our customer is using 'Production checkpoints', but I'm considering changing these to 'Standard checkpoints' as a test, as others have said this has resolved the issue. - Well the standard checkpoint didn't fix it for me. I"ve seen a bunch of "Cluster Shared Volume 'CSV#' has entered a paused state because of '(c0e7000b)'. All I/O will temporarily be queued until a path to the volume is reestablished. event5120 and event 5142. The odd thing is that the error is on the node that owned the CSV resource disk and also happened to be the node that has the effected VMs. Not sure if its a pattern yet, but I the last two and possibly three times this happened, it has been the same host with the same problems. Just to note, having the same issue with Acronis Advanced Backup on Windows Server 2019. Stuck at creating chjeckpoint 9% Cannot stop hyper V - stuck at stopping. The only solution is to reboot the server (which promtly hangs at stopping Hyper V), and then after a few seconds of that, remote process kill vmms.exe. The server will then reboot. My NICs are 40G Intel XL710-QDA2 - the drivers are Microsoft, but their date is later than the one on the intel web site, and both are version 6.80. Log on as Batch Job Local security policy as above is OK This only occurs on 2019 - the 2012R2 servers have no problems Hello, I'm facing the similar issue, while trying to create the checkpoint of multiple VMs. The VMs are become unresponsive..... Single VM check point is working fine without any issue Issue started since 10th April. Earlier it was fine. Applied the following patched in the server KB4091664 KB4480961 KB4489882 KB4487026 KB4489882 - Targets to the following components. Unfortunately, customer is denying to take a simultaneous backup of Hyper-V VMs using Windows Server Backup tool Is anybody have a suggestion on this? Please help Jaril Nambiar - נערך על-ידי Jaril Nambiar שבת 20 אפריל 2019 17:27 Also having the same issue with a newly installed 2 node Failover Cluster running Server 2019 /w Hyper-V role. CSV over iSCSi. Latest Intel drivers/firmware, Windows updates, etc are applied. I left the default checkpoint settings of production then standard if not supported. I'm certain our issues are related to the backups which had run successfully for the past 2 weeks but hung on week 3 which others have mentioned above. We use Veritas Backup Exec 20.3 Rev 1188 which is also backing up a 2012 R2 Hyper-V cluster without problems. After noticing our backup job was hung and a VM status showing Creating Checkpoint (9%), I stopped the backup exec agent on the Hyper-V host which took forever to stop. Now the Volume Shadow Copy (VSS) service is in a stopping state. Can't manage/migrate/shutdown VMs but they are thankfully still running. I will have to do a forceful shutdown tonight. Since this issue is happening with both Server 2016 and 2019 Hyper-V, and with various backup software. I'd say this is a Microsoft problem? The problem continues - seems I can get 1 backup done OK before the problem occurs, and then stuck eternally at Creating Checkpoint 9%. This is with the latest Acronis backup software. If I turn off Volume Shadow Copy Service and Volume Shadow Copy Service for virtual machines then the problem does not occur, but the backups would be unreliable (so not an option). I haven't seen this error come back for me since April 15th and that breaks the rough patter I was seeing of every 2-weeks I had experienced prior to that. Some additional notes: I originally created nested mirror accelerated parity drives AND enabled deduplication. I then added a number of additional physical disks to each node and optimized the storage pool each time. I have since moved everything to just simple two-way mirror drives WITHOUT deduplication. Eventually I'll try adding the nested mirror setup back as I"m guessing it was either the dedup chunks or the mirror accelerated parity overhead that might have been contributing to the problem. I also have the same issue on a brand new Hyper-V host running Windows Server 2019 Standard with 5 VM's. 2 x Windows Server 2019, 2 x Windows Server 2008 R2 and 1 x Windows 7 Pro. Backup software is Veritas Backup Exec v20.3 but i noticed the issue already occurs when creating a manual checkpoint myself from the Hyper-V console of one of the 2008 R2 servers and also stuck on 9%. No way to recover without rebooting the Hyper-V host. As I'm a Microsoft partner and having 10 Action Pack incidents I will contact Microsoft Support for this issue. The specific server is a Dell PowerEdge R740 server with quad port Intel i350 Gigabit NIC's... I am having the same issue. Server 2019 STD with Hyper-V. Veeam 9.5 4a running on separate box. Dell Poweredge R730XD with Intel 10GbE and 1GbE cards is the host. Only fix is to hard reboot the server. The problem started for me with a Veeam backup failing on a guest that suddenly acts like it lost its network connection. Veeam backup fails. I try to shutdown the guest and it hangs at "shutting down." The next scheduled Veeam backup then gets stuck at 9% on a fully functioning VM. The VM that is being backed up runs just fine. Trying to shutdown guests from the host, they get stuck at "stopping". The fix is to hard reboot the box. I try to shutdown the guests via RDP to hopefully get them to shutdown somewhat gracefully. Then I try to shutdown the host and wait a good while, about an hour, then I have to reset the server. From all these postings, it really feels like it is an Intel card/driver issue. Could this be resolved by changing out the Intel cards for Broadcom? On the Poweredge's the 10Gbe/1GbE part code is Y36FR, I believe. I am checking with my reseller now to find the availability of that part to ship me one out. I will post with my findings. I do not believe the reboot itself is slow as is the hung up vm that won't shut down. If you kill those tasks first, the reboot would have been normal. That being said, I was (fingers crossed its in the past) having the issue and my production NICs are Intel x722 series cards. I switched to standard checkpoints, but I definitely had one additional recurrence since that happened. I then moved the VMs to a new CSV (I"m using an S2D cluster) and haven't had a problem since. Not sure which was the fix, but so far its been running for over a month without issue now and it used to happen roughly every 2 weeks for me prior to that. I managed to get 21 hours from a reboot before another problem with backups. After the reboot last night, Veeam was able to get several backups out of the host with no issues. I have migrated other guests off the host and all I have left is Exchange 2013. Veeam gets stuck at 9% and won't go any further. Killed the VMMS task and it woudn't register as stopped. Logged into RDP and shutdown Exchange. Wait. I was able to get a successful reboot out of it, which is a good thing. Then I have to retry my Veeam backups for Exchange. I also have checkpoints disabled. Looking at this, seeing that Intel networking is a fairly common thread, I made a change. I stopped/disabled the Intel management service to see if it has any impact. I have the Broadcom 10GbE/1GbE daughtercard coming tomorrow. I will drop it in and we will see how it does.. out of curiosity, did your s2d volumes include either a nested resiliency volume and/or did you add drives to the system after creating any volumes? I haven't had the problem in two months now and it was happening on a pretty regular 2-week schedule for me in the past and the last thing I did was to move all my data from the original CSVs I created to new ones that were not nested resiliency. Oh yea... I also had dedup turned on for some of those volumes and that is now off. No, it is (or should be) a fairly simple setup in that regard. Just a couple of regular CSV's, no dedup. It's been 13 days since last issues, but I really dont trust it. We are going to add extra 10GB NIC's to the hosts soon to seperate data streams (production data vs migration and S2D sync data). This is something a MS tech told us might help. I have the same problem Here the environnement : 2 Server Windows Server 2019 Datacenter (1809) with Hyper-V Role Veeam Backup & Replication 9.5.4.2753 Veeam replica job HyperV01 to HyperV02 Servers are directly connected with Broadcom NetXtreme E-Series Advanced Dual-port 10GBASE-T for the replication. I first met the problem which led me to this technet post : "Creating snapshot at 9%" Backup or replication job failed Cannot launch new backup job or cancel snapshot creation Event ID 19060 Hyper-V VMMS I did a hard reboot of the server one night. And i disabled replication job every 15 minutes and changed production snapshot to standard snapshot. I didn't have any problem with backup during one week until today. Tonight, i will hard reboot the server, update veeam, update 10Gb NIC card... If someone found the solution ? Thanks for help Ok i spoke too fast, same problem this night during backup. - We have now encountered the problem on a third system. On the other two systems, however, everything has been fine for several weeks now. All the systems involved have one thing in common: They were converted from VMWare to HyperV. What does that look like for you? Is it possible to reduce the problem to that? We also have this problem from the start (4 months) of our new HP DL380-G10 HyperV 2019 cluster, MSA2052, 10Gb Intels and Altaro software. It happens every 5-10 day’s. We have all 2012R2 VM’s, and one 2008R2. I removed the 2008R2 from backup. Maybe it helps. All other VM’s were migrated from an older 2012R2 HyperV host (not converted from VMWARE) Tried the option to set production to standard. No luck. The API Altaro uses forces a production snapshot. The VSS integration is checked (default) Ok i think veeam try also to do production checkpoint instead standard checkpoint while i changed in the hyper-v settings of the virtual machine. Event id 18016 Hyper-V-VMMS Can not create production control points for VM01. (Virtual Machine ID: E9E041FE-8C34-494B-83AF-4FE43D58D063) And in Veeam log, i have id 150 VEEAM MP VM VM01 task has finished with 'Failed' state. Task details: Failed to create VM recovery checkpoint (mode: Hyper-V child partition snapshot) Details: Failed to call wmi method 'CreateSnapshot'. Wmi error: '32775' Failed to create VM recovery snapshot, VM ID '260fa868-64f9-418f-a90a-d833bc7ec409'. Retrying snapshot creation attempt (Failed to create production checkpoint.) I have more logs since i disable VSS integration yesterday (necessary for production checkpoint)if i'm not mistaken. I've started a call with Microsoft regarding this issue. At the moment the Microsoft Rep has asked we uninstalled Sophos AV from the Host machine; which we've done. We've got one VM set to Standard Checkpoints, one to Production Checkpoints. Backup software is Altaro. Now awaiting for the issue to replicate and get Microsoft back on the case. Will update when I know more.. Hello Problem happened again four days ago. I had to hard reboot Hyper-V again. In your case, is it a fresh install ? When problem is appears ? Did you upgrade veeam to lastest version or install directly last version ? I open a case with microsoft. I'm waiting return. - Our problem seems to have been fixed by either two things: fully patching the Hyper-V host and also making sure that the VM itself is updated. And other than that we have updated our Intel X710 10gb fiber cards to the latest Intel driver in stead of the Microsoft one. This has solved our backups hanging at 9% but now we have new problems that might be unrelated to this topic. When we connect virtual machines to the Hyper-V virtual switch with the 10gb networkcard, the host disconnects from the network every 30 seconds with a 10400 event in the logs. When we switch the VM's to a Hyper-V virtual switch with the regular RJ45 port everything is OK. Also stable network connectivity on the 10gb card. Really weird, one problem after the other Count me in on this... brand new Server 2019 Core Hyper-V Cluster (Microsoft OS up to date), HPE 460 G10 Blades using HPE QLogic NX2 10Gb drivers, and latest rev of Veeam (9.5up4b). Happens sporadically about once every week to week and a half on any one of my 6 nodes. Just got off the phone with HPE support and confirmed all hardware, firmware, and drivers were up to date and came back green on health check. Was going to open a ticket with Veeam until I ran across this thread. Might go ahead and do it anyway just to make sure, but I am not sure what else to do to be honest. Update... After a little more research, I did run across this forum posting about Windows Defender. Looks like this fixed it for some users. I have it implemented now and will see what happens. I THINK WE FOUND THE SMOKING GUN! . Could it be all related to 10Gb NIC’s + teaming caused by the Virtual Machine Queue (VMQ) ??? Our intel 10Gb 562SFP+ are in teaming and it seems that you have to configure each of the NIC’s in the team to not overlap on the same CPU cores. Enter the following command to check your VMQ setting. (“FIBER*”=NIC NAME) The outcome: BaseVmqProcessor was 0 on both. So they overlapped! Get-NetAdapterVmq | Sort Name | ? Name -Like "FIBER*" | FT -A With the following commands we have configured the VMQ for each adapter. The settings are related to the amount of cpu/cores you have in your server. We have 2 x 8 - No Hyperthreading. Set-NetAdapterRss "Fiber01" -BaseProcessorNumber 0 -MaxProcessors 4 Set-NetAdapterRss "Fiber02" -BaseProcessorNumber 4 -MaxProcessors 4 Set-NetAdapterVmq "Fiber01" -BaseProcessorNumber 8 -MaxProcessors 4 Set-NetAdapterVmq "Fiber02" -BaseProcessorNumber 12 -MaxProcessors 4 Charbel Nemnom vmq-rss (google) has a great article and more info about VMQ After this setting we have rebooted all VM’s and back-up is running smooth for couple of day’s now. We have converted a few VM's (server 2012 and server 2016) from VMWare to Hyper-V. Looks like, only systems that we migrated from VMWare to HyperV (with the 5nine converter) are affected. Or can someone disprove that? Does anyone have the problem with newly installed Windows servers? - Opened a Microsoft Support Call. It is a known issue. but no solution or hotfix available at this time. Microsoft told us to be sure to have no Microsoft drivers with network Cards and switch to Standard Checkpoints until a hotfix is available. i will test this next days. - Do you mind sharing your support case ID? I'd like to open a "me too" case so I can get on the notification list for the fix. And since we're in the process of commissioning the new infrastructure that exhibits this problem, I might be in a better position in terms of being able to get outages scheduled for installation of any hotfix and/or to down-n-up my Hyper-V hosts as sometimes seems to be necessary to resolve the situation after a VM gets into this 'stuck' state. I have the same problem. Brand new DELL Blade servers with W2019 and all the lastest drivers. I'v tried also with the MS basic drivers. I'm are using Netvault backup. I have no migrated VMs, just clean fully patched 2019 virtuals. I created a PS script that takes checkpoints every 10minutes. After a while some virtuals were stuck on 9%. So my conclusion is that there is something fundamentally wrong with Hyper-V 2019. Using production or standard checkpoints the results were same. I also manged to get the Hyper-V stuck when trying to storage migrate (unsuccesfully) VMs from another host. The VMs that were running in the destination (W2019) are in the same state as they were when stuck in the 9% checkpoint. Can't do any operation with them. Hyper-V services restart doesn't help. Only reboot to the host helps. Update from my case with Microsoft; Microsoft have asked for the removal of Altaro backup and Sophos Anti-Virus. They've then asked for the clean-boot of all VM's which are on the Host and the Host it's self; which I've done. I've now got a script creating checkpoints of VM's and removing them - waiting for it to happen again while the host and VM's are in clean-boot. Afraid so, I started the case with a link to this thread to begin with. I followed what they were after, which was the following; - Windows Update the Hypervisor. - Remove Sophos from the Hypervisors & VM's. - Clean boot all VM's and the Hypervisor. After following this, I managed to get the error to reoccur by simply check-pointing the VM's every 10 minutes, then merging the Checkpoints. Got Microsoft back on the phone and he stated the following; The Check-point is stuck at 9% because the internal VSS of the Guest VM is stuck in a "Timed Out" state. Please can you run Windows Update on the VM's along with the Hypervisor. I know that I'm going to Windows Update the VM's and the issue is to reoccur, I'll jump through their hoops the final time to prove once more; this is a problem with Windows Server 2019. FYI; this is a completely standalone host. We have 4 HP ProLiant DL380 Gen10 servers, no Clustering, no 10Gb/s NICs running the VM's on Local - full SSD storage. I have the following script which runs every 10 Minutes to cause the issue; even with the Hypervisor in a clean boot state. $Vms = Get-VM foreach ($Vm in $Vms) { $Snaps = Get-VMSnapshot -VM $Vm if ($Snaps.Length -eq 0) { Checkpoint-VM -VM $Vm } } foreach ($Vm in $Vms) { Remove-VMSnapshot -VM $Vm } $Today = Get-Date Add-Content C:\X\Snapshot-All-Vms.txt "Completed: $Today" @_Dickens - Just to chime in here that we are seeing exactly the same issue on one of our W2019 servers. Some observations below: We managed one, maybe two good backups after the host is rebooted (normally forcibly as the VMMS service hangs on reboot) before we hit the 9% Checkpoint issue again. HP DL380 Gen10. 10Gb NIC (but does the same when using the 1Gb NIC), Sophos in the VM (Not host), Veeam B&R 9.5 Update 4. Hyper-V replica running to an identical host. Several of the VSS writers in the VM go "Timed Out" after the failed Checkpoint. Both VM and host are up to date via Windows Update. Latest HP SSP in the host. Even the though the Checkpoint says 9%, there's only ever a 4Mb AVHDX created that seemingly has no relationship with the parent VHDX as it's never merged and can be safely deleted after shutting the VM down. The VMMS service crashes when creating the Checkpoint. When shutting down the VMs within themselves, the VM always sticks at Shutting Down within Hyper-V manager even though they have fully shutdown. I invariably end up trying to stop the VMMS and Data Sharing Services on the host in a desperate attempt to allow a clean(ish) shutdown in the host. I've performed CHKDSK /f on VM and host. Moved the Checkpoint location to another volume. Specified Standard Checkpoints if Production Checkpoints fail. Disabled RSS and offloading on all NICs. All in all, this has been a nightmare. I initially suspected Veeam was the issue, but having read several accounts of users with Altaro, SolarWinds and various other backup vendors, I've come around to the notion that there's something inherently wrong with the W2019 hyper visor. Tonight I will change the backup to run within the VM rather than at the container level as I can't afford to spend any more time on this issue. Hopefully, MS are monitoring this thread and putting some energy into re-creating and eventually offering a resolution. - We had the problem with three customers in the meantime: Customer 1: Windows Server 2019 HyperV Standalone Veeam 9.5.4.2753 Kaspersky Security 10.1.1 for Windows Servers Proliant DL380 Gen10 - HPE Ethernet 1Gb 4-port 331i (Driver: Hewlett-Packard 214.0.0.0) - HPE Ethernet 10Gb 2-port 530T (Driver: Cavium 7.13.150.0) Customer 2: Windows Server 2019 HyperV Failover Cluster with NetApp E-Series Veeam 9.5.4.2753 No virus protection ProLiant DL360 Gen10 - HPE Ethernet 1Gb 4-port 331i (Driver: Hewlett-Packard 214.0.0.0) - HPE Ethernet 10Gb 2-port 530T (Driver: Cavium 7.13.145.0) Customer 3: Windows Server 2016 HyperV Failover Cluster with NetApp E-Series Veeam 9.5.4.2753 No virus protection ProLiant DL360 Gen9 - HPE Ethernet 1Gb 4-port 331i (Driver: Hewlett-Packard 214.0.0.0) - HPE Ethernet 10Gb 2-port 561T (Driver: Intel 4.1.76.0) All hosts and VMs have the latest Windows updates. - נערך על-ידי Dennis_K5121 יום שלישי 06 אוגוסט 2019 06:45 Worked for me - in Acronis. Was getting same issue with Server 2019 with 40G NICs. Disabling VMQ both on server and VMs made the problem go away. Not sure how much of hit this causes to the network throughput - tried testing, but difficult to get an accurate assessment - I have been just dealing with it for the past couple of weeks, but I too disabled VMQ on servers and VMs just yesterday and was finally able to at least get a good backup of everything again. Hoping this "resolves" the issue until Microsoft can address whatever this ultimately turns out to be. So we had a case open with Microsoft for 3 months now. We have 3 clusters with now 2 having the issue. Initially it was only 1. The 2nd one started having the issue about 2-3 weeks ago. First 2 clusters didn't have the issue, these were configured back in March and April with Server 2019. The third cluster that had the issue since the beginning were installed on May-June wiht Server 2019. I have a feeling one of the newer updates is causing the issue. The 1st cluster not having the problem has not been patched since. To this day nothing was resolved and they have no idea what it might be. Now they are closing the case on us because the issue went from one Host in our Cluster to another host, and our scope was the first Hyper-V host having the issue. Unbelievable. The issue is still there though just happening on another host in the Cluster. The clusters experiencing the issues have the latest generation Dell Servers in them, PE 640s, while the one not having the issue only has older generation PE 520, PE 630, etc. The way we realize the issue is that we have a PRTG Sensor checking our host for responsiveness. At some random point in the day or night, PRTG will report that the sensor is not responding to general Hyper-V Host checks (WMI). After this, no checkpoints, backups, migrations, setting changes can happen because everything is stuck. Can't restart VMMS service or kill it. Here is what we have tested with no solution yet: Remove all 3rd party applications - BitDefender (AV), Backup Software (Backup Exec 20.4), SupportAssist, WinDirStat, etc. - Didn't fix it. Make sure all VMSwitches and Network adapters were identical in the whole cluster, with identical driver versions (Tried Intel, and Microsoft drivers on all hosts) - Didn't fix it. Check each worker process for the VM - When a VM got stuck during a checkpoint or migration. - Didn't fix it. get-vm | ft name, vmid compare vmid to vmworkerprocess.exe seen in details -> Task Manager kill process Hyper-V showed VM running as Running-Critical Restart VMMS service (didn't work) net stop vmms (didn't work) Restart Server -> VMs went unmonitored After restart everything works fine as expected Evict Server experiencing issues in Cluster -> This just causes the issue to go to another host, but the issue is still there. - Didn't fix it. Create two VMS (one from template, one new one) on the evicted host -> No issues here, never gets stuck, but other hosts still experience the issue. Install latest drivers, updates, BIOS, firmware for all hardware in all the hosts of the cluster. - didn't fix it. We migrated our hosts to a new Datacenter, running up to date switches (old Datacenter - HP Switches, new Datacenter - Dell Switches), and the issue still continues. New Cat6 wiring was put in place for all the hosts - Issue still continues. Disable "Allow management operating system to share this network adapter" on all VMSwitches - issue still continues Disable VMQ and IPSec offloading on all Hyper-V VMs and adapters - issue still continues We're currently patched all the way to August 2019 Patches - issue still continues. We asked Microsoft to assign us a higher Tier technician to do a deep dive in to kernel dumps and process dumps, but they would not do it until we exhausted all the basic troubleshooting steps. Now they are not willing to work further because the issue moved from 1 host to another after we have moved from one datacenter to another. So it seems like based on how the Cluster comes up and who's the owner of the disks and network, it might determine which hosts has the issue. Also, our validation testing passes for all the hosts, besides minor warnings due to CPU differences. Any ideas would be appreciated. I had this on a newly built Windows 2019 Dell R430 with Intel 10G X520 Adapters. It was causing an issue with HyperV replication and Production Checkpoints. I had two previous R430s in the cluster and I noticed that the two existing servers were running the Microsoft NIC driver and that the new one was running the Intel NIC driver. So Iremoved the HyperV virtual NIC, broke the team and reverted the new servers NIC drivers to the MS version 3.12.11.1 driver for the X520. Re-established the team, recreated the HyperV virtual switch and the problem has not reoccurred since. Queeg505, thanks for the response. I wish it was that simple for us. I have done the same about a couple of months ago to see if going from the newly installed Intel drivers to the old Microsoft drivers would help. It did not really help for us. For the different NIC types that we have, these are the current driver versions we are running. Intel Gigabit 4P i350-t Adapter - 12.15.22.6 (Previously 12.15.184.0 Intel Driver) Intel Ethernet 10G 2P x540-t Adapter - 3.12.11.1 (Previously 4.1.4.0 Intel Driver) Broadcom NetXtreme Gigabit Ethernet - 214.0.0.0 (Previously 17.2.1.0) Intel Ethernet Converged Network Adapter X710-t - 1.8.103.2 I have verified that all servers are running identical driver versions across these adapters. Just to add our experience until Microsoft actually acknowledge this problem and look at a fix! We have two Server 2019 Hyper-V clusters. Cluster 1 – Brand new 6 node S2D cluster (all flash). Intel 10 GB NICs,100GB Mellanox NICs for storage, S2D storage and ReFS storage. Veeam backups failed nearly every day with checkpoints hanging at 9%. VMMS service will not stop even with process explorer. Only a hard reset would fix the node. We updated the Intel network drivers and disabled receive side coalescing (the driver introduced a new problem with rsc enabled). Checkpoints changed to standard and disabled backup (vss) integration service on each vm. All nodes were rebooted and backups have now succeeded for two weeks. However we are now too worried to live migrate or take checkpoints in case anything breaks again! Cluster 2 – 6 Node Old 2012 R2 cluster with FC SAN storage (which has run for 5 years prior to 2019 upgrade) reinstalled as Server 2019 (fresh install). Emulex 10GB NICs,CSV NTFS Volumes on a Hitachi SAN. Veeam is replicating some VMs to this cluster. Currently hangs at 9% checkpoint nearly every day requiring node hard reboot. Have tried drivers and disabling RSC – no change. Have just disabled RSS and VMQ and awaiting results. I have noticed that when the VMMS service is locked up you cannot use PowerShell to make any changes to the network adapters (hangs). Device Manager also hangs when making any changes to the network adapters. Based on the above it leads me to believe it is related to the network adapters as they become unmanageable at the same time. Just wish we knew the cause or MS would take some interest in fixing it! - נערך על-ידי CEvans2008 יום שני 09 ספטמבר 2019 22:39 Same here. A single Hiper-V server with Windows Server 2019 standard, with only two VM running on it. Backup with ARCServe UDP, without any antivirus nor any other software. Intel10Gb NICs X722 with Microsoft drivers 1.8.103.2. After a few backups, system stuck both VM at 9%...VM machines does not respond, I'm unable to clear reboot the host server, and unique solution is to made a hard reset. I will update drivers and put result here. We had this exact same issue on non-clustered Dell servers with Intel X520 10G NICs, but also had success with the following: - Updated NIC drivers, using Intel's latest X520 drivers (4.1.143.0) - Set Jumbo Packets enabled on the NIC at 9014 bytes (this set previously when we had the Microsoft NIC drivers, so this was not a new change) - Disabled VMQ on all VMs that had it enabled After that, our weekly VM export backups have worked for 2 weeks without issue. Hi. I just want to share my experience that updating Intel NIC driver manually did the trick. Although the newest driver that existed for this NIC was only 3 months newer I really doubt it would work but it did for now (really crossing my fingers that problem went away) SuperMicro motherboard, NIC information: NIC driver model: Intel 82579LM BEFORE THE UPDATE Driver date: 05.04.2016 Driver Version: 12.15.22.6 AFTER Driver date: 25.07.2016 Driver Version: 12.15.31.4 with best regards B BCR - Found a solution on another thread. The issue is related to VMQ, but in order for the changes to work, you most likely have to disable it to all the VMs in the VM Advanced Network Settings in your Cluster, restart the VMs, and also restart the hosts. This is probably why the initial time we disabled VMQ, the fix didn't work. After the host froze and we restarted it didn't happen again. Another solution another person posted was the following: From Microsoft Support we received a powershell command for hyper-v 2019 and the issue is gone ;) Set-VMNetworkAdapter -ManagementOS -VrssQueueSchedulingMode StaticVrss It is a bug from Windows Server 2019 and Hyper-V Hello. Disabling VMQ's seems to have worked for me now. Please can you elaborate on this unsigned file? Is this a driver which you've been asked to install which has been unsigned somehow? Please could you share your Microsoft Case Reference number so I could give this to my Microsoft Support Advisor? Thanks. Oliver. Thank you very much. On our Windows Server 2019 we have set the parameters and are looking forward to see if the problem is solved. From Microsoft Support we received a powershell command for hyper-v 2019 and the issue is gone ;) Set-VMNetworkAdapter -ManagementOS -VrssQueueSchedulingMode StaticVrss It is a bug from Windows Server 2019 and Hyper-V Is there a similar command for Windows Server 2016? The parameter "VrssQueueSchedulingMode" is not available for Windows Server 2016. Hello, the following solution on a Lenovo SR650 Host with Windows Server 2019 OS (only Hyper-V Role) and 4x10GBit Intel X722 LOM has worked: Changes the driver of the Intel X722 4 x 10Gbit LOM card from Microsoft drivers to the new’s Intel drivers (1.10.130.0, 9.5.2019). After this change the network performance of the VMs were absolutely BAD! Then we switched of the driver value of “Recv.-Seqment-Coalescing” (IPv4 and IPv6) from active to inactive. Network-Speed was normal on Host (X722 LOM NIC 10Gbit Port 1) and VMs (X722 LOM NIC 10Gbit Port 2). After testing creating more the 50 checkpoints each day (using the Microsoft script) for two weeks, we assume now, that the problem is been solved. One more interesting note: The checkpoint stuck at 9% was just a symtom for the problem at hand. Even without checkpoints creation there can always be a problem after a few days that the host no longer had control over the VMs. Neither Hyper-V MMC nor Hyper-V Powershell could be used to apply commands such as restart, save, etc. to the VMs. VMs continued to run, Hyper-V replication also worked. However, a VM could not restart if it was initiated from within the VM. The VM simply did not start anymore and in the Hyper-V Manager the status remains at "Shutdown". In this case, the host always had to be switched off using the power switch! Probably this information should help other users to solve such a “miracle” problem. Thank you to all other in this thread, that helped us solving this problem! St. Reppien Hello Someone have good news ? I had the problem again and I tried the followings command in the last 15 days on the hyper-v but i had problem with snapshot 2 days ago. I had no problem for 2 months before.. Set-VMNetworkAdapter -ManagementOS -VrssQueueSchedulingMode StaticVrss Maybe, people think they do not have any problem anymore because it's been 15 days since it's working properly but you have to plan for the long term. I have this problem since July 2019 and no solution was viable. As i said before, sometimes i had no problem during months. I downgrad veeam version from 9.5u4 to 9.5u3 but problem appears again.. Thank you Alexandre Hi Alexandre, Yes, we haven't had the issue since we disabled the advanced features. And this was back around beginning of September. Keep in mind that you may have disabled VMQ and IPSec but any new VMs that may have been created could still have it enabled. Check your VMs and make sure all of them have it disabled. I'm seeing something similar to this too. I have a customer with two hyper-V Failover Clusters and last week alone one of the cluster nodes have stopped responding twice. The behavior is consistent with what you guys are seeing: VMMS looses all control over VMs, can't start, stop os livemigrate VMS and eventually the cluster service goes down. The only way to get things going is to force a reboot of the compromised node. In my case, I have some VMs replicating between the nodes with application consistent checkpoints enabled, so I suspect checkpoints do act like some kind of trigger. I'm also seeing some erros on the logs about moving RSS queues from VMQ during my backup window, so I suspect that VMQ has a role to play in all this, specifically d.VMMQ. That's why I'm guessing that setting VrssQueueSchedulingMode StaticVrss on my managementOS Virtual interfaces should help mitigate the issue. d.VMMQ does some kind of advanced offloading using the NICs driver, and my interfaces being Broadcom we all know what to expect. I'm also setting VrssQueueSchedulingMode StaticVrss at the VMs by running: Get-VM | Get-VMNetworkAdapter | Where-Object VrssQueueSchedulingMode -like Dynamic | Set-VMNetworkAdapter -VrssQueueSchedulingMode StaticVrss Let's see how it goes. Regards, Giovani
https://social.technet.microsoft.com/Forums/windows/he-IL/0d99f310-77cf-43b8-b20b-1f5b1388a787/hyperv-2016-vms-stuck-creating-checkpoint-9-while-starting-backups
CC-MAIN-2020-05
refinedweb
8,426
64.3
Invalid use of non-static data member "ui" Sorry if my terms are incorrect i come from a java background. Im trying to create a util class to just make my project more organised but I'm having problems accessing my UI from an external class, at first in the header file the UI was private so i changed it to public but now its complaining with the error "Invalid use of non-static data member "ui"" Does anyone know how to fix this? Should I be making UI public or should I use another method? Here is my code, only the relevant parts of the classes //QUIZ.CPP //Creates "Quiz" widget Quiz::Quiz(QWidget *parent) : QWidget(parent), ui( new Ui::Quiz) { ui->setupUi(this); ui->console->append("Type \"start\" to go"); } //Destroys widget on exit Quiz::~Quiz() { delete ui; } //QUIZ.H namespace Ui { class Quiz; } class Quiz : public QWidget { Q_OBJECT public: explicit Quiz(QWidget *parent = 0); ~Quiz(); private slots: void on_button_clicked(); void on_input_returnPressed(); public: Ui::Quiz *ui; }; #endif // QUIZ_H //UTIL.CPP void appendConsole(QString string) { Quiz::ui->console->append(string); } void appendInput(QString string) { Quiz::ui->input->setText(string); } QString getInput() { return Quiz::ui->input->text(); } Hi Welcome to C++ then :) It complains because the syntax used Quiz::ui->input->setText(string); should be ui->input->setText(string); The syntax Quiz:: is for calling a static method in a class. but ui is not static. Its just a private class. So compilers whines. :) But here comes the bummer. UI is private so you cannot say ui->input->setText(string); from external class So the options are: 1: use public function to setData without exposing to exernal class what kind of widget that does the real job. void appendConsole(QString string) { QuizInstance->SetConsoleText(string); } 2: Use signals and slot here you would define a new signal and slot say SetConsoleText(QString Text); and connect signal to slot and u can then emit SetConsoleText("logtext"); Since you seem to be using normal non class members functions in UTILS.cpp then public function seems to be the way to go. Also since this is C++, you can make UI public and directly access it but that is considered bad practice as you then expose the widgets to rest of program. - mrjj Lifetime Qt Champion @Hamish Hi The ClassName::Member syntax is used to call static functions in c++. THats is, to call a function without a class instance. UI is not static so even if not private it would not work. Even if UI was public, you would still need a instance to call it Quiz myInstance; myInstance.ui->consolexxx Hope it make sense :) Hmm so the only real way to fix my problem is to add the methods involving the ui back into the Quiz.cpp class. So there is no way to hook the ui object in any way? Hi what you mean hook ? As long as you have not created an instance of the class the UI elements are not live. so UTILS.cpp must have an instance anyway. EVEN is UI was public. void appendConsole(QString string) { QuizPtr->ui->console->append(string); } EDIT: Oh. u did change ui to public.. Then u just need an instance to allow this.. hmm now i get this problem: QWidget: Must construct a QApplication before a QWidget The program has unexpectedly finished. although the Application is instantiated in the main class before everything else... - mrjj Lifetime Qt Champion @Hamish Well, if you make global Widgets variables, this can happen. As globals are created first. Before main is run. @Hamish Yes, often you can Say you have this global widget Quiz MyQuiz; If you do Quiz *MyQuiz; and then in main MyQuiz=new Quiz; It would not complain as global is just a pointer now. But normally we dont use globals at all. All lives in classes. Like mainwindow. ps. remember to call delete MyQuiz; at program end. - kshegunov Qt Champions 2017 I often say "C++ is not Java", but mostly is in different context - memory management. Funnily, here it's even more applicable. In Java you are supposed to put every (public) class in it's own file (if I remember correctly), C++ doesn't care, it also doesn't care how you name your files . You can put the declaration in a header and then put the definitions in any cpp you want (as long as you don't duplicate the class/method names). It also doesn't care how many classes (exported or otherwise) you declare in a header file. Well, if you make global Widgets variables, this can happen. As globals are created first. Before main is run. Can i fix this? You shouldn't create anything that's QObjectderived before the QCoreApplicationconstructor has run. The first QObjectyou create should be the application object. My advice, forget global variables, especially since you appear to not have much experience with C++. In Java they are mostly okay, but with C++ they are a real pain and lead to all sorts of complications. Do as @mrjj suggested and put your objects as members of classes. PS. void appendInput(QString string) { Quiz::ui->input->setText(string); } These functions are global functions, and not class members, you should convert them to methods instead and in these methods you can operate your uiobject. Kind regards.
https://forum.qt.io/topic/66771/invalid-use-of-non-static-data-member-ui
CC-MAIN-2019-30
refinedweb
891
63.9