text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
le MurrayPython Development Techdegree Student 4,494 Points
Hi could you please help me get the right output for this task, I'm getting a syntax error on my first line
What am i doing wrong for this code? Please can you urgently help me with this task. Thank you.
def pop([1,2,3], 1): pop.remove(1) return pop pop.remove(2) return pop pop.remove(100) return pop
3 Answers
Mel RumseyTreehouse Staff
Hi Danielle Murray! There are a few things in your code that aren't quite right. So first we want to make a function that takes 2 parameters.
[1, 2, 3], 1 are just examples. We can simply do
def pop(lst, ind): because it will be taking in any list and any index. Any code that we want the function to perform needs to be inside of the function.
def pop(lst, ind): <code goes here>
We want the function first
try to pop a value from a list at the index. lst.pop(ind).
If the index is out of range this is going to raise an
IndexError. So we want an
except here that excludes index errors and would
return the string
Invalid Index.
Else we can return the list.
Hope this helps!
Mel RumseyTreehouse Staff
def pop(1st, ind): # missing try 1st.pop(ind) except IndexError: return Invalid Index Else: return pop
^ I went ahead and wrapped your code in some code brackets so we could see it formatted. You are much closer here, but there are still a few things to adjust.
- You currently have a parameter that starts with a number. This is throwing a syntax error. you might want to change the 1 to an l (lowercase L) as the shortened version of list since list is a Python keyword that cannot be used.
- You are missing your
trywhich should be right after the function definition
- The except should return a string
- Else should not be capitalized
- You are currently returning
poprather than the list. We want the list parameter to be what is returned in the end.
Danielle MurrayPython Development Techdegree Student 4,494 Points
Hi Mel Rumsey my first line is still giving an error
def pop(1st, ind): try: 1st.pop(ind) except IndexError: return "Invalid Index" else: return 1st.pop(ind)
Mel RumseyTreehouse Staff
Danielle Murray It looks like you still have the number 1 at the beginning of a variable which is going to throw an error. Try changing 1st to say lst or
my_list or anything else that does not have a number at the beginning of the variable. This will cause a syntax error.
Danielle MurrayPython Development Techdegree Student 4,494 Points
Danielle MurrayPython Development Techdegree Student 4,494 Points
Hi Mel Rumsey this is my revised code
def pop(1st, ind): 1st.pop(ind) except IndexError: return Invalid Index Else: return pop
But i am still getting a syntax error on the first line. Please could you help me. | https://teamtreehouse.com/community/hi-could-you-please-help-me-get-the-right-output-for-this-task-im-getting-a-syntax-error-on-my-first-line | CC-MAIN-2021-43 | en | refinedweb |
React Native Familiarization
For those familiar with coding in React and looking to immediately start writing a native iOS or Android app, Facebook would love for you to try React Native. React Native allows you to code in JavaScript, JSX, and CSS, for the most part, but end up with a native application that is fast on phones and tablets.
A Quick Overview
If you are hesitant to start React Native, I assure you it's not so bad…it's almost exactly like working on a React Single Page Application. Converting a web app into a native app? With React Native code from actions and reducers can be shared between iOS/Android (native) and browser, but components do not translate. For example, in native apps we get access to a
<Text>component, but in browsers the equivalent might be a
<span>or
<p>tag—two separate templates must be used. Let's check out an example app and then breakdown some aspects of React Native…
Getting Started
To generate a basic app and see it right away, get NPM and Xcode. Then run the following commands:
npm i -g react-native-cli react-native init AwesomeProject cd AwesomeProject react-native run-ios
A console should pop-up along with the iOS simulator and your Awesome Project! What just happened? We used the
react-native initcommand to generate a boilerplate. If we look into the contents of our newly created files, you can find
index.android.jsand
index.ios.jsfiles—as you might have guessed, this is where it all starts (depending on the platform).
A basic React Native app looks like this:
import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Component { render() { return ( <Text>Hello world!</Text> ); } } AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
Similar to
renderwithin ReactDOM,
AppRegistry.registerComponentis usually used only once and starts the entire app.
Using the reference point of building a web app, lets check out details of using React Native…
Compiling
Compiling is great with React Native. After modifying a file, a watcher recompiles your code. With the iOS Simulator up,
Command⌘ + Rwill refresh and changes can be seen. The compiling tool comes with the React Native
initpackage that was generated earlier.
Standard Components
To give you an idea of what React components come with React Native, here's a list:
ActivityIndicator
Button
DatePickerIOS
DrawerLayoutAndroid
Image
KeyboardAvoidingView
ListView
MapView
Modal
Navigator
NavigatorIOS
Picker
PickerIOS
ProgressBarAndroid
ProgressViewIOS
RefreshControl
ScrollView
SegmentedControlIOS
Slider
SnapshotViewIOS
StatusBar
Switch
TabBarIOS
TabBarIOS.Item
Text
TextInput
ToolbarAndroid
TouchableHighlight
TouchableNativeFeedback
TouchableOpacity
TouchableWithoutFeedback
View
ViewPagerAndroid
WebView
It's not a lot, but there are a lot of additional libraries out there to build that list. Another thing to keep in mind is that these are just basic building blocks that can be used to construct custom components. For coders coming from a browser perspective,
h1and
ptags are used to represent types of content for Search Engine Optimization (SEO) and accessibility purposes—accessibility in React Native is documented, but SEO is neither here nor there for an app. So how does one style a component?
Styling and Structure
Styling is through the
styleattribute in React Native, just like it is in React for the browser (
background-colorin CSS is
backgroundColorin JavaScript). Out of the box there is not an option to use external CSS, but you can group styles in objects and pass them on as a
propor directly, like so:
import React, { Component } from 'react'; import { View, Text, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ text: { color: theme.placeholderTextColor, fontSize: theme.fontSizeH5, } }); export default class SoStylish extends Component { render() { return ( <View> <Text style={styles.text}> Welcome to React Native! </Text> </View> ); } }
Why use
StyleSheet.createat all instead of regular JavaScript objects? It is more performant, according to the docs.
Structure, such as grids and layout, is implemented through flexbox in much the same way as CSS flexbox. Facebook notes "Flexbox works the same way…with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number." Overall styling is great, because flexbox is great! At least I think so.
External Data
React native comes with a
fetchutility that returns a
Promise. There are other libraries out there as well, but this gives you the basics:
function getMoviesFromApiAsync() { return fetch('') .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); }
There is also support for WebSockets and direct access to the XMLHttpRequest API.
Navigation
Navigation is quite a large subject to cover, but here are some notes:
- There is a concept of a "scene": "A scene is nothing other than a React component that is typically rendered full screen"…so a single
Textcomponent would generally not be a scene
- There is a built in
Navigatorcomponent which has
initialRouteand
renderSceneprops
- The
Navigatorcan pass functions telling how child components can change scenes
There's more to research here and probably some good custom components others have built that could be reused for different types of menus. One example is React Native Side Menu.
Considerations
Thinking about adding React Native to an existing project? Here are some considerations:
- New templates for all pages would be required
- Any theming may need to be altered, but mostly reusable
- Reducers should not need altering
- Gulp tasks would need updating
- Actions would need altering for allowing native compatibility, in particular any ajax calls. This could be done with a library that supports browsers and native code.
- It helps to be comfortable with all stages of the deployment process, particularly building a finalized version
- New testing strategies might be needed for the React Native code and the created app
Pros
- Adds ability to create iOS and Android apps
- Reuse redux-based code and some theming
- Easy to code if you are familiar with React/JSX or JavaScript in general
- Easy styling through CSS properties
- Supported by Facebook, which is not going anywhere
- Decent amount of community support (including components to easily add in)
- Fast builds
- Lots of NPM libraries to utilize
Cons
- Working in advanced features requires diving into Swift—it's hard to know how quickly this barrier is hit
- Animations in React aren't easy…React Native animations are probably rough too
- Most components will require writing their own React Native version: basic building blocks (images, text, etc) are defined differently in React Native compared to browsers
- Tied-in to React ecosystem
MERNM Generator Integration
Using React Native is a very approachable way to buildings native iOS/Android apps. Using the MERNM generator is a great way to quickly build a prototype or as foundation for a production ready web app. If a team using MERNM decides they want to also provide a native app to users, bringing in React Native is a great option to have. There is code reuse for what some might consider the hardest parts of an app (the actions and handlers). And, building out styles and components is in a familiar technology (CSS and JSX). This goes the other way around too: building from React Native allows easily portability to creating a great web experience in the React ecosystem. It's nice to know there are options!
Wrap-Up
Folding React Native into an existing project is very possible, but it is a bit of an unknown world. There are optimizations that might not be known and an entire React Native community to become familiar with. There's also other solutions out there, like Ionic, to consider. I see great appeal in using anything related to React, including React Native: it's fast, easy to follow, you get to use Redux, and there is a lot of community support. I hold some hesitation though, because it's not just JavaScript anymore.
Posted January 28th, 2017. | https://sinclair.tech/thoughts/react-native-familiarization | CC-MAIN-2021-43 | en | refinedweb |
Routing is one of the important aspects of any Web Application be it a single page app or a multi-page application. Angular uses Angular Router (@angular/router package) which enables the navigation from one view to other as and when users perform any tasks. Angular Router provides a routing library which helps in maintaining multiple router outlets, access to route parameters and route guards which helps to protect the route from unauthorized access.
The main aim of routing in Angular or more specifically Single Page Applications is that it enables the developers to show multiple views and allow the navigation between these views based on users interaction.
The Basics of Angular 7
At first we will be adding the Routing Module (AppRoutingModule) which will contain our application routes and a router outlet where Angular framework will insert the matched component depending on the browser URL.
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { NotFoundComponent } from './notfound/notfound.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: '**', component: NotFoundComponent } ]; @NgModule({imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
The app-routing.module.ts will contain the above code where we have used @NgModule decorator which is used to create an Angular module. The decorator also takes some meta information like imports and exports. In the imports attribute we call the RouterModule.forRoot(routes) method with the routes as a parameter to register our routes for the main application and thus making our routes known to Angular Framework and in the exports we are just exporting the RouterModule.
In the above code we have created two routes, one with the empty path and onw with the wildcard path. The empty path means that when we navigate to the base url (localhost:4200) the HomeComponent will be routed to. The wildcard path will match any unrecognized path and show the NotFoundComponent.
Note : You also have to add this module to the main app module under imports as :
imports: [ // All other imports, AppRoutingModule ]
Next is to add <router-outlet></router-outlet> to app.component.html file where the Angular Router will render the component based on the routes. Router-Outlet is a directive where the Router inserts the component that gets matched in the Routes based on the browser's URL.
Now we have the routes in place as well as we have rendered them on the component, thus we now need some mechanism to navigate to that routes. This is where the routerLink directives will come into picture which when added on the anchor tags will take the user to that rout when clicked.
<a routerLink="/route">My Route</a>
When to use [routerLink] or routerLink in Angular
You can also write routes without '/' i.e. relative path and it will be of same behavior on the home component but on the child component you might get error like "Error: Cannot match any routes" this is because it appends the path you have specified in teh routerLink to the path already exists.
For Example: If you are in and in that component you have a reload page which has an anchor tag as <a routerLink="route">Reload Page</a>, it will try to navigate to because route is being appended to the existing url which is not in the case of using <a routerLink="/route">My Route</a> because it appends '/route' after the base URL.
The router supports different type of syntax as below :
./ or no leading slash is relative to the current path i.e. it appends the route to the current URL path.
../ to go one level up and then append to the path
We also have a RouterLinkActive directive which lets you add a CSS class based on which link's route is active.
<a routerLink="/route" routerLinkActive"active">My Route</a>
Whenever the url is /route it will add an "active" class to my anchor tag if teh url will change the class will be removed. We can also add routerLinkActiveOptions which will only add the class when the url matches the link exactly as shown below
<a routerLink="/route"
routerLinkActive"active"
[routerLinkActiveOptions]="{exact: true}"
>My Route</a>
Till now we have learned how we can have an anchor tag and add routerLink which will make the anchor tag as a navigate path, but what if we want to do it programatically. To navigate through programatically we need to use Angular Router and navigate to some route as shown below
export class MyComponent { constructor(private router: Router) {} onNavigate() { this.router.navigate(['/route']) } }
We can also pass parameters to the route and fetch those parameters in our TypeScript code. For passing we have to use colon syntax, which creates a slot in the path for a Route Parameter as shown below
{ path: 'home/:id', component: HomeComponent}
To fetch the parameters we will use ActivatedRoute which contains information about a route associated with a component loaded as shown below.
export class MyComponent implements OnInit { constructor(private router: Router, private route: ActivatedRoute) {} ngOnInit() { let id = this.route.snapshot.paramMap.get('id'); } onNavigate() { this.router.navigate(['/route']) } }
We can also use QueryParameters in our route as shown below
<a routerLink="/route" [queryParams]="{isEdit: true}">My Route</a>
OR
this.router.navigate(['/route'], { queryParams: { isEdit: true } });
So we have successfully covered the basics of Routing in Angular, in our next post we will be discussing about Guards. | https://www.codingdefined.com/2019/03/understanding-routing-in-angular.html | CC-MAIN-2021-43 | en | refinedweb |
SIG, but the latter cannot. The default signal sent without parameters for the KILL command is SIGTERM. let the program exit well. Because it can be blocked, when some processes cannot be ended, use kill to send the latter signal. That is: kill-9 process number.
Docker stop and dockkill
docker stop
When we use the docker stop command to stop the container, docker will allow the application in the container 10 seconds by default to stop running.
When the docker stop command is executed, the process with PID 1 in the container (
main process) Send the system signal SIGTERM, and then wait for the application program in the container to terminate execution. If the waiting time reaches the set timeout, or the default 10 seconds, the system signal SIGKILL will continue to be sent to kill the process forcibly. The application program in the container can choose to ignore and not process the SIGTERM signal, but once the timeout period is reached, the program kill be forcibly killed by the system, because the SIGKILL signal is directly sent to the system kernel, and the application program has no chance to process it.
docker kill
By default, the docker kill command does not give the application in the container any chance to gracefully shutdown. It will directly issue a SIGKILL system signal to forcibly terminate the operation of the program in the container.
The difference with the docker stop command is that docker kill does not have any timeout setting. It will directly send SIGKILL signals and other signals specified by the user through the signal parameter.
Docker stop command is more similar to kill command in Linux system, both of which send system signal SIGTERM. The docker kill command is more like kill -9 or kill -SIGKILL command in Linux system, which is used to send SIGKILL signal and forcibly terminate the process.
On Processes with pid 1
Processes with process ID of 1, usually UNIX init processes, play an important role in the operating system: whenever a process exits, if it still has child processes, the child processes become orphan processes and the init processes take over. Unix is designed in such a way that the parent process must explicitly “wait” for the child process to terminate in order to collect its exit status.
After the child process is finished, the kernel will still maintain a basic structure for it, saving its pid, exit reason and status information, which can be obtained by the parent process through waitpid system call. If the parent process does not call waitpid, the status information will remain and become a so-called zombie process. If the child process ends after the parent process, in general, the init process will be responsible for these orphan processes.
According to the general principle that a container only runs one process, for a web service, the pid when it runs in the container is 1. suppose it calls bash’s cgi script, and this script calls grep. after a period of time, the cgi script times out for some reason, and the web service starts to try to kill it, but grep is not affected, so it becomes an orphan process. At this time, the web service with pid=1 should be able to take over, but the vast majority of web services do not have the capability of init, so grep becomes a zombie process.
Pod shutdown mechanism of kubernetes
Pod represents processes running on nodes in a cluster, so that these processes are no longer needed. It is important to exit gracefully (and roughly end with a KILL signal, leaving applications no chance to clean up). The user should be able to request deletion and know it when the room process is terminated, and also ensure the deletion is finally completed. When a user requests to delete pod, the system records the desired graceful exit period. Pod is not allowed to be forcibly killed before this, and the TERM signal will be sent to the main process of the container. Once the deadline for graceful exit has passed, the KILL signal will be sent to these processes and pod will be deleted from the API server. If Kubelet or container manager restarts while waiting for the process to end, the end process will be retried with a complete graceful exit period.
An example process:
1. The user sends a command to delete Pod. The default graceful exit time is 30 seconds.
2. Pod update time in 2.API server, after which Pod is considered dead
3. Within the client command, Pod is displayed as “Terminating”
4. (at the same time as step 3) when Kubelet saw that Pod was marked as exiting, because the time in step 2 had been set, it started the process of pod shutdown.
4.1 If the Pod defines a hook before stopping, it will be called inside the pod. If the hook is still running when the graceful exit time expires, the second step will be called with a very small graceful break.
4.2 The process is signaled as TERM
5. (Concurrent with Step 3) Pod is removed from the service list and is not considered part of the running pod. The slowly shut-down pod can continue to serve the outside world when the load balancer removes them in turn.
6. When graceful exit time expires, any process running in pod will be sent SIGKILL signal and killed.
7.Kubelet will complete the deletion of pod and set the graceful exit time to 0 (indicating immediate deletion). Pod is removed from API and is no longer visible to clients.
By default, the graceful exit time for all delete operations is within 30 seconds. The kubectl delete command supports the option of –grace-period= = to run the user to modify the default value. 0 means that deletion is executed immediately, and a new pod such as deleting pod from API immediately will be created at the same time. On the node, pod, which is set to end immediately, will still give a very short graceful exit period before being forced to kill.
Nginx and SIGTERM
There are two ways to signal the running Nginx process to fully manage the operation: use the -s option of Nginx process or directly use the system command kill to signal the master process. When the -s option is used, nginx will automatically find the running master process ID(master process is responsible for receiving and processing signals, and completes different management operations for all working processes according to different signals).
SIGINT, like SIGTERM, is used to force the Nginx process to exit. When the master process receives the forced exit signal, it will send the forced exit signal to all working processes. if the working process fails to exit in time, master will use the timer to repeatedly send the forced signal, and SIGALRM signal will be sent when the timer is triggered. SIGIO signal is explicitly ignored by Nginx; SIGCHLD signal tells the master process that the working process has exited and needs to complete resource recovery or restart the working process.
Nginx process exits in two ways
When master process receives SIGQUIT signal
Forward this signal to the worker process. The worker process then closes the listening port so as not to receive new connection requests, closes idle connections, and calls ngx_worker_process_exit to exit after waiting for the active connections to reach full normal junction speed. The master process calls ngx_master_process_exit function to exit after all working processes exit.
When master process receives SIGTERM or SIGINT signal
Forward the signal to the worker process. The work process directly calls ngx_worker_process_exit function to exit. The master process calls the ngx_master_process_exit function to exit after all worker processes exit. In addition, if the worker process fails to exit normally, the master process will wait for 1 second and then send a SIGKILL signal to force the worker process to terminate.
Nginx’s graceful exit
-s signal Send signal to the master process. The argument signal can be one of: stop, quit, reopen, reload. The following table shows the corresponding system signals. stop SIGTERM quit SIGQUIT reopen SIGUSR1 reload SIGHUP
among them
Stop-quick shutdown
Quit-graceful exit, exit after executing current request
Reload-Reload the configuration file
Reopen—Reopen the log file
Use kubernetes Lifecycle Hooks to gracefully exit nginx
kind: Deployment metadata: name: nginx-demo namespace: scm labels: app: nginx-demo spec: replicas: 1 template: metadata: labels: app: nginx-demo spec: containers: - name: nginx-demo image: library/nginx-demo imagePullPolicy: IfNotPresent lifecycle: preStop: exec: # nginx -s quit gracefully terminate while SIGTERM triggers a quick exit command: ["/usr/local/openresty/nginx/sbin/nginx","-s","quit"] env: - name: PROFILE value: "test" ports: - name: http containerPort: 8080
Off topic
How to gracefully close java applications
command: ["/bin/bash", "-c", "PID=`pidof java` && kill -SIGTERM $PID && while ps -p $PID > /dev/null; do sleep 1; done;"]
doc
Uinx Signal SIGINT SIGTERM SIGKILL Distinction
Elegant Termination of docker Container
-
Issues with running as PID 1 in a Docker container.
Docker and the PID 1 zombie reaping problem
Docker and PID 1 Zombie Process Problems
Zombie Process in Docker System
kubernetes-chinese-docs-pods
Nginx Source Code Note-Operations Command
Does nginx have a soft quit?
Container Lifecycle Hooks
Graceful shutdown of pods with Kubernetes
Gracefully stopping a Java process in a pod in Kubernetes?
How can I ensure graceful scaling in kubernetes?
Do Kubernetes pods still receive requests after receiving SIGTERM?
Deleting pods and other resources with graceful shutdown | https://ddcode.net/2019/06/23/gracefully-close-nginx-in-kubernetes/ | CC-MAIN-2021-43 | en | refinedweb |
surface alternatives and similar packages
Based on the "Framework Components" category.
Alternatively, view surface alternatives based on common mentions on social networks and blogs.
plug10.0 7.5 surface VS plugA specification and conveniences for composable modules between web applications
commanded9.8 7.5 surface VS commandedUse Commanded to build Elixir CQRS/ES applications
ex_admin9.7 0.0 surface VS ex_adminExAdmin is an auto administration package for Elixir and the Phoenix Framework
torch9.3 7.3 surface VS torchA rapid admin generator for Elixir & Phoenix
addict9.2 0.0 surface VS addictUser management lib for Phoenix Framework
phoenix_html9.1 7.5 surface VS phoenix_htmlPhoenix.HTML functions for working with HTML strings and templates
scrivener9.0 3.9 surface VS scrivenerPagination for the Elixir ecosystem
phoenix_ecto8.9 4.8 surface VS phoenix_ectoPhoenix and Ecto integration with support for concurrent acceptance testing
react_phoenix8.8 0.1 surface VS react_phoenixMake rendering React.js components in Phoenix easy
cors_plug8.7 3.2 surface VS cors_plugAn Elixir Plug to add CORS.
absinthe_plug8.7 5.8 surface VS absinthe_plugPlug support for Absinthe, the GraphQL toolkit for Elixir
corsica8.7 4.1 surface VS corsicaElixir library for dealing with CORS requests. 🏖
Raxx8.6 0.4 surface VS RaxxInterface for HTTP webservers, frameworks and clients
scrivener_html8.5 0.0 surface VS scrivener_htmlHTML view helpers for Scrivener
phoenix_live_reload8.4 4.3 surface VS phoenix_live_reloadProvides live-reload functionality for Phoenix
phoenix_slime8.4 1.9 surface VS phoenix_slimePhoenix Template Engine for Slime
params8.2 0.0 surface VS paramsEasy parameters validation/casting with Ecto.Schema, akin to Rails' strong parameters.
phoenix_pubsub_redis7.9 1.4 surface VS phoenix_pubsub_redisThe Redis PubSub adapter for the Phoenix framework
dayron7.9 0.0 surface VS dayronA repository `similar` to Ecto.Repo that maps to an underlying http client, sending requests to an external rest api instead of a database
rummage_ecto7.9 0.0 surface VS rummage_ectoSearch, Sort and Pagination for ecto queries
kerosene7.9 0.0 surface VS kerosenePagination for Ecto and Pheonix.
passport7.8 0.0 surface VS passportProvides authentication for phoenix application
rummage_phoenix7.7 0.0 surface VS rummage_phoenixFull Phoenix Support for Rummage. It can be used for searching, sorting and paginating collections in phoenix.
phoenix_token_auth7.7 0.0 surface VS phoenix_token_authToken authentication solution for Phoenix. Useful for APIs for e.g. single page apps.
phoenix_haml7.7 0.0 surface VS phoenix_hamlPhoenix Template Engine for Haml
recaptcha7.2 3.4 surface VS recaptchaA simple reCaptcha 2 library for Elixir applications.
plug_graphql7.0 0.0 surface VS plug_graphqlPlug (Phoenix) integration for GraphQL Elixir
sentinel7.0 0.0 surface VS sentinelDEPRECATED - Phoenix Authentication library that wraps Guardian for extra functionality
plugsnag6.9 2.5 surface VS plugsnagA Bugsnag notifier for Elixir's plug
plug_rails_cookie_session_storeRails compatible Plug session store
access pass6.3 0.0 surface VS access passprovides a full user authentication experience for an API. Includes login,logout,register,forgot password, forgot username, confirmation email and all that other good stuff. Includes plug for checking for authenticated users and macro for generating the required routes.
multiverse6.3 0.0 surface VS multiverseElixir package that allows to add compatibility layers via API gateways.
ashes6.1 0.0 surface VS ashesA code generation tool for the Phoenix web framework
plug_auth6.0 0.0 surface VS plug_authA collection of authentication-related plugs
webassembly6.0 0.0 surface VS webassemblyWeb DSL for Elixir
filterable5.9 1.6 surface VS filterableFiltering from incoming params in Elixir/Ecto/Phoenix with easy to use DSL.
scrivener_headers5.8 3.8 surface VS scrivener_headersScrivener pagination with headers and web linking
better_params5.8 0.0 surface VS better_paramsCleaner request parameters in Elixir web applications 🙌
phoenix_pubsub_rabbitmqRabbitMQ adapter for Phoenix's PubSub layer
plug_checkup5.6 1.2 surface VS plug_checkupPlugCheckup provides a Plug for adding simple health checks to your app
Whatwasit5.5 0.0 surface VS WhatwasitTrack changes to your Ecto models
plug_statsd5.4 0.0 surface VS plug_statsdSend connection response time and count to statsd
plug_rest5.0 0.0 surface VS plug_restREST behaviour and Plug router for hypermedia web applications in Elixir
trailing_format_plug4.9 0.0 surface VS trailing_format_plugAn elixir plug to support legacy APIs that use a rails-like trailing format:
raygun4.8 0.0 surface VS raygunA raygun client for Elixir
phoenix_html_simplified_helpersSome helpers for phoenix html( truncate, time_ago_in_words, number_with_delimiter, url_for, current_page? )
phx_component_helpers4.7 7.5 surface VS phx_component_helpersExtensible live_components, without boilerplate
Votex4.6 0.0 surface VS VotexImplements vote / like / follow functionality for Ecto models in Elixir. Inspired from Acts as Votable gem in Ruby on Rails
plug_jwt4.6 0.0 surface VS plug_jwtPlug for JWT authentication
phoenix_pubsub_postgresPostgresql PubSub adapter for Phoenix apps
Scout APM: A developer's best friend. Try free for 14-days
Do you think we are missing an alternative of surface or a related project?
README
Surface
Surface is a server-side rendering component library that allows developers to build rich interactive user-interfaces, writing minimal custom Javascript.
Built on top of Phoenix LiveView and its new LiveComponent, Surface leverages the amazing Phoenix Framework to provide a fast and productive solution to build modern web applications.
Full documentation and live examples can be found at surface-ui.org.
Example
# Defining the component defmodule Hello do use Surface.Component @doc "Someone to say hello to" prop name, :string, required: true def render(assigns) do ~F""" Hello, {@name}! """ end end # Using the component defmodule Example do use Surface.Component def render(assigns) do ~F""" <Hello name="John Doe"/> """ end end
Features
An HTML-centric templating language, designed specifically to improve development experience.
Components as modules - they can be stateless, stateful, renderless or compile-time.
Declarative properties - explicitly declare the inputs (properties and events) of each component.
Slots - placeholders declared by a component that you can fill up with custom content.
Contexts - allows a parent component to share data with its children without passing them as properties..
Compile-time checking of the template structure, components' properties, slots, events and more.
Integration with editor/tools for warnings/errors, syntax highlighting, jump-to-definition, auto-completion (soon!) and more.
Installation
Phoenix v1.5 comes with built-in support for LiveView apps. You can create a new application with:
mix phx.new my_app --live
Then add
surface to the list of dependencies in
mix.exs:
def deps do [ {:surface, "~> 0.5.0"} ] end
If you're using
mix format, make sure you add
:surface to the
import_deps
configuration in your
.formatter.exs file:
[ import_deps: [:ecto, :phoenix, :surface], ... ]
For further information regarding installation, including how to quickly get started using a boilerplate, please visit the Getting Started guide.
Migrating from
v0.4.x to
v0.5.x
Surface
v0.5.0 introduces a new syntax which requires migrating components written in previous versions.
In order to make the migration process as smooth as possible, Surface
v0.5.x ships with a converter that
can automatically translate the old syntax into the new one.
Please see the [Migration Guide](MIGRATING.md) for details.
Tooling
- Surface Formatter - A code formatter for Surface.
- Surface package for VS Code - Syntax highlighting support for Surface/Elixir.
License
Surface source code is licensed under the [MIT License](LICENSE.md).
*Note that all licence references and agreements mentioned in the surface README section above are relevant to that project's source code only. | https://elixir.libhunt.com/surface-alternatives | CC-MAIN-2021-43 | en | refinedweb |
For getting a diversified portfolio, avoiding low volatility, not paying too much in trading costs, not incurring excessive data fees, and being able to trade without running into problems with the minimum size required to trade a particular contract.
However, the times they are a' changing. I've been toying with an idea for a new trading system method that will allow me to trade a very large number of markets; to be more precise it will be an optimisation process with a universe of markets that it could trade, in which I'll only take selective positions that make the best use of my limited capital.
A side effect of this is that I will be able to calculate optimal positions for markets I have no intention of trading at all (because they are too expensive, too large, or not sufficiently liquid) and then use that information to make a better decision about what positions I should hold in another market.
A pre-requisite for that is to actually add more markets to my price database. So that's what this post is all about: deciding which markets to add (using the python interactive brokers [IB] API 'layer' I use, ib_insync), the order to add them in, and explaning the process I follow to include more markets in my open source system, pysystemtrade.
(And yes - one of those markets is Bitcoin!)
Of course you don't have to be a pysystemtrade, ib_insync, or python user; or even an Interactive Brokers customer; as much of what I will say will be relevant to all futures traders (and perhaps even to people who trade other things as well).
It also goes without saying, I think, that this would be useful for someone who is building a list of markets from scratch rather than adding to an existing list.
The initial universe
Sadly my broker, interactive brokers (IB), doesn't seem to have a giant .csv file or spreadsheet list of products - at least not externally. So I went on the IB website and basically copied down the list of all the futures products I could find. I excluded single stock futures, since that would have resulted in an even bigger list and I don't want to go those for now. I also excluded markets that I already trade. The key fields I was after were the IB code and Exchange identifier. For example, Ethanol, has an IB code of 'AC' and the exchange is 'ECBOT'.
Here is the initial list.
EDIT: On my initial pass I missed out quite a few of the Singapore SGX instruments (thanks to @HobbyTrading on ET). These are now included at the end of the file.
Resolving duplicates
Now the symbol and exchange aren't sufficient to uniquely identify every instrument, since in some markets there are multiple contracts with different multipliers and currencies. So I ran the following code (which doesn't require pysystemtrade, only ib_insync):
import pandas as pd
from ib_insync import Future, IB
missing_data = object()
def identify_duplicates(symbol, exchange):
print("%s %s" % (symbol, exchange))
future = Future(symbol=symbol, exchange = exchange)
contracts = ib.reqContractDetails(future)
if len(contracts)==0:
print("Missing data for %s/%s" % (symbol, exchange))
return missing_data
list_of_ccy= [contract.contract.currency for contract in contracts]
list_of_multipliers = [contract.contract.multiplier for contract in contracts]
unique_list_of_ccy = list(set(list_of_ccy))
unique_list_of_multipliers= list(set(list_of_multipliers))
if len(unique_list_of_multipliers)>1:
print("%s/%s more than one multiplier %s" %
(symbol, exchange, str(unique_list_of_multipliers)))
multiplier = str(unique_list_of_multipliers)
else:
multiplier = unique_list_of_multipliers[0]
if len(unique_list_of_ccy)>1:
print("%s/%s more than one currency %s" %
(symbol, exchange, str(unique_list_of_multipliers)))
currency = str(unique_list_of_ccy)
else:
currency = unique_list_of_ccy[0]
return [symbol, exchange, currency, multiplier]
ib=IB()
ib.connect('127.0.0.1', 4001, clientId=5)
all_market_data = pd.read_csv('/home/rob/private/projects/new_markets/Initial_market_list.csv')
new_market_data = []
for row_data in all_market_data.iterrows():
new_data = identify_duplicates(symbol=row_data[1].Symbol, exchange=row_data[1].Exchange)
if new_data is missing_data:
continue
new_market_data.append(new_data)
new_market_data_pd = pd.DataFrame(new_market_data)
new_market_data_pd.columns=['Symbol','Exchange','Currency','Multiplier']
new_market_data_pd.to_csv('/home/rob/with_additional_fields.csv')
Perusing the list there don't appear to be any duplicates for currency, only half a dozen or so for multipliers. We don't want to make a decision at this stage about which multiplier to trade, so I manually split those rows out in the spreadsheet (I could do this with python of course, but there aren't enough instances to make it worth writing the code). For example, if I look at 'BRR/CMECRYPTO' I can see the multiplier is both 5 and 0.1; the latter is the new micro contract for Bitcoin, the former figure is for the original massive contract.
BRR CMECRYPTO USD ['5', '0.1']
BRR CMECRYPTO USD 0.1
BRR CMECRYPTO USD 5
Market selection
- Do they diversify our current set of markets?
- Are they cheap or expensive to trade?
- How much money do I need to trade them?
- What kind of volume is there?
- Can I get market data for them?
Measuring trading volume
- The volumes traded in each contract (we get this from IB)
- The exchange rate (we can get this from IB)
- The multiplier (which we already have)
- The daily standard deviation in price units (we can calculate this, given ~20 business days of closing prices from IB)
How much money do I need to trade a market
Measuring trading costs
- The commission (which I'm just going to paste into my spreadsheet as an extra column)
- The multiplier (which we already have)
- The spread (we need to get this from IB)
- The daily standard deviation in price units (we already need this for volumes)
Running the code to extract market volume and cost data
- NYBOT commodities
- NYSELIFFE
- Canadian CDE markets
- Australia SNFE
- Hong Kong HKFE
- Europe MATIF, MONEP, IDEM, MEFFRV, OMS
- UK ICE: IPE, ICEEU, LMEOTC, ICEEUSOFT
Deciding on a market priority order
- Don't add: Markets without data subscriptions (89 markets) *
- Add later: Markets which fail eithier the maximum cost test (0.01SR), maximum risk per contract ($125,000) or minimum volume ($1.25 million per day in risk units, and 100 contracts per day) (96 markets)
- Add first: Markets that passed all the filters (98 markets)
- A small number of commodities
- Government bonds
- Volatility (just two)
- Stock indices
- IMM FX
- Metals
- Energy markets (just two)
- STIR (just one)
- Bitcoin and Ether
- Real estate
- Interest rate swaps [will be highly correlated with bonds, but useful for fixed income RV trading one of my possible future systems]
- Stock sector indices [will be correlated to stock indices]
- Corporate bonds (iBoxx) [though will be correlated with bonds, and have insufficient volume]
- Priority 'zero' (in practice will come a bit later as will require some careful surgery of my configuration files when rolling - I won't actually be downloading more prices): Mini and micro contracts that replace existing instruments (7 instruments)
- Bitcoin and Real estate (2 instruments)
- Swaps (2)
- Stock sectors (22)
- New commodity, energy and metals (13)
- New currencies and Spanish BONOS, New stock indices (14)
- Currency crosses, and missing points off the German,Italian and US bond curve. KOSDAQ150 (8)
- 'Last day' crude and gas (2)
- Two I already trade which got included in the list by accident
- Another 5 year IRS: I don't need two five year swaps, thanks.
- Larger versions of contracts where I've opted to trade the micro or mini
- Dollar NIKKEI 225 (I will trade the Yen version for reasons discussed in 'Smart Portfolios')
A case study: Bitcoin
Backfilling prices with barchart
import os
from syscore.fileutils import files_with_extension_in_pathname
from syscore.dateutils import month_from_contract_letter
def strip_file_names(pathname):
file_names = files_with_extension_in_pathname(pathname)
for filename in file_names:
identifier = filename.split("_")[0]
yearcode = int(identifier[len(identifier)-2:])
monthcode = identifier[len(identifier)-3]
if yearcode>50:
year = 1900+yearcode
else:
year = 2000+yearcode
month = month_from_contract_letter(monthcode)
marketcode = identifier[:len(identifier)-3]
instrument = market_map[marketcode]
datecode = str(year)+'{0:02d}'.format(month)
new_file_name = "%s_%s00.csv" % (instrument, datecode)
new_full_name = "%s%s" % (pathname, new_file_name)
old_full_name = "%s%s.csv" % (pathname, filename)
print("Rename %s to\n %s" % (old_full_name, new_full_name))
os.rename(old_full_name, new_full_name)
return None
market_map = dict(
BT="BITCOIN")
strip_file_names("mypathname")
import pandas as pd
from syscore.dateutils import adjust_timestamp_to_include_notional_close_and_time_offset
from sysdata.csv.csv_futures_contract_prices import csvFuturesContractPriceData, ConfigCsvFuturesPrices
from sysobjects.futures_per_contract_prices import futuresContractPrices
from sysobjects.dict_of_futures_per_contract_prices import dictFuturesContractPrices
def process_barchart_data(instrument):
config = ConfigCsvFuturesPrices(input_date_index_name="Date Time", datapath="/home/rob/data/barchart_csv",
input_skiprows=1, input_skipfooter=1,
input_column_mapping=dict(OPEN='Open',
HIGH='High',
LOW='Low',
FINAL='Close',
VOLUME='Volume'
))
csv_futures_contract_prices = csvFuturesContractPriceData(datapath=datapath,
config = config)
all_barchart_data_original_ts=csv_futures_contract_prices.get_all_prices_for_instrument(instrument)
all_barchart_data=dict([(contractid, index_to_closing(data, csv_time_offset, original_close, actual_close))
for contractid, data in all_barchart_data_original_ts.items()])
all_barchart_data=dictFuturesContractPrices([(key, futuresContractPrices(x)) for key, x in all_barchart_data.items()])
return all_barchart_data
def index_to_closing(data_object, time_offset, original_close, actual_close):
"""
Allows us to mix daily and intraday prices and seperate if required
If index is daily, mark to actual_close
If index is original_close, mark to actual_close
If index is intraday, add time_offset
:param data_object: pd.DataFrame or Series
:return: data_object
"""
new_index = []
for index_entry in data_object.index:
# Check for genuine daily data
new_index_entry = adjust_timestamp_to_include_notional_close_and_time_offset(index_entry, actual_close, original_close, time_offset)
new_index.append(new_index_entry)
new_data_object=pd.DataFrame(data_object.values, index=new_index, columns=data_object.columns)
new_data_object = new_data_object.loc[~new_data_object.index.duplicated(keep='first')]
return new_data_object
# slightly weird this stuff, but basically to ensure we get onto UTC time
original_close = pd.DateOffset(hours = 23, minutes=0, seconds=1)
csv_time_offset = pd.DateOffset(hours=6)
actual_close = pd.DateOffset(hours = 0, minutes = 0, seconds = 0)
barchart_data = process_barchart_data("BITCOIN")
barchart_prices_final = barchart_prices.final_prices()
barchart_prices_final_as_pd = pd.concat(barchart_prices_final, axis=1)
barchart_prices_final_as_pd.plot()
perc=barchart_prices_final_as_pd.diff()/barchart_prices_final_as_pd.shift(1)
perc.plot()
from sysdata.arctic.arctic_futures_per_contract_prices import arcticFuturesContractPriceData
from sysobjects.futures_per_contract_prices import futuresContractPrices
from sysobjects.contracts import futuresContract
def write_barchart_data(instrument, barchart_prices, delete_first=False):
artic_futures_price_data = arcticFuturesContractPriceData()
# want a clean sheet
if delete_first:
artic_futures_price_data.delete_all_prices_for_instrument_code(instrument, areyousure=True)
list_of_contracts = barchart_prices.keys()
for contractid in list_of_contracts:
futures_contract = futuresContract(instrument, contractid)
artic_futures_price_data.write_prices_for_contract_object(futures_contract, barchart_prices[contractid])
write_barchart_data("BITCOIN", barchart_prices)
Multiple and adjusted prices
barchart_prices['20210400'].VOLUME.resample("1B").sum().plot()
barchart_prices['20210500'].VOLUME.resample("1B").sum().plot()
from sysinit.futures.rollcalendars_from_arcticprices_to_csv import *
build_and_write_roll_calendar("BITCOIN")
from sysinit.futures.multipleprices_from_arcticprices_and_csv_calendars_to_arctic import *
process_multiple_prices_single_instrument("BITCOIN", ADD_TO_CSV=True)
from sysdata.arctic.arctic_multiple_prices import arcticFuturesMultiplePricesData
a = arcticFuturesMultiplePricesData()
price = a.get_multiple_prices("BITCOIN")
from sysinit.futures.adjustedprices_from_mongo_multiple_to_mongo import *
process_adjusted_prices_single_instrument("BITCOIN", ADD_TO_CSV = True)
from sysdata.arctic.arctic_adjusted_prices import *
a = arcticFuturesAdjustedPricesData()
a.get_adjusted_prices("BITCOIN").plot()
Bitcoin in simulation
from systems.provided.futures_chapter15.basesystem import *
system = futures_system()
system.config.instrument_weights=dict(BITCOIN=1.0)
system.data.get_raw_price("BITCOIN")
system.data.get_instrument_raw_carry_data("BITCOIN")
system.data.get_raw_cost_data("BITCOIN")
system.rules.get_raw_forecast("BITCOIN", "ewmac64_256").plot()
system.rules.get_raw_forecast("BITCOIN", "carry").plot()
system.combForecast.get_combined_forecast("BITCOIN").plot()
system.positionSize.get_subsystem_position("BITCOIN").plot()
system.config.notional_trading_capital
250000
system.config.percentage_vol_target
20.0
system.config.base_currency'USD'
system.accounts.pandl_for_instrument("BITCOIN").curve().plot()
Calibrating an instrument
Production trading configuration
Live sampling
Live system 'backtest' and optimal trades
============================================================= Optimal versus actual positions ============================================================= current optimal breaks .....
medium_speed_TF_carry PALLAD 0.0 -0.017/0.017 False medium_speed_TF_carry BITCOIN 0.0 0.517/1.111 True
Let's buy some bitcoin then
Summary
- It's quite nice to just use raw IB_insync for simple work
- You can see the power of 'risk adjusting everything' when creating some filters to use when deciding which market to trade.
- There are a lot of futures markets out there which are reasonably liquid, not expensive, and not too big! Even without paying a fortune for market data.
- The mini/micro futures are a lot cheaper and more liquid than when I first looked at them, so I really ought to be trading them.
- It's worth rechecking that your instruments still pass filters, probably more than once every seven years
- Actually adding markets is something you should do carefully.
- By all means backtest a new market to make sure the sizing and 'plumbing' is correct, but don't make in sample decisions, especially based on just a few years of data.
To get expired contract data from IB:
- Open a Price History window
- Add the expired contract to a watchlist
- The Price History window will be blank, but, on the Price History window, Options, Export, enter your dates, and voila!
I'm just starting out, and this is how I downloaded much of my historic data. I haven't tried smaller contracts, but it certainly works with the more common contracts.
What's a 'price history' window? Is this something on TWS. Because I don't use that.
I've edited the post to show how you can get a couple of years worth of data using the API.
Yes, sorry, should have given more detail. TWS.
Hello Rob, I've also scanned virtually every futures market IB offers for shortlisting.
My biggest challenge is deciding reasonable liquidity cutoffs. Of the 400+ markets available through IB, maybe only 25% have daily volume (as according to IB historical data with 32 day trailing average) over 1,000.
Example would be CME Lumber, has a beautiful trend, but only ~200 contracts volume per day. Perhaps I don't fully understand the mechanics of futures markets, but that seems so thin. The risk is difficulty getting out of positions and major moves being driven by industry insider knowledge.
How are you defining "liquid enough" instruments? 800 contracts per day? 8000 per day? I know it depends on how many contracts you trade.
I can't find any information about "safe" liquidity in terms of futures.
Apologies, I missed your section on volume as I skimmed!
Actually it's a fair point, because if something trades the $1.5m a day, but that's only a single massive contract, is it really liquid? If we want to be 1% of the market, then we'd need to see a minimum volume of 100 contracts. So I'd probably add a minimum of 100 contracts a day as a filter.
Trading volume alone is not the full picture. "tradability" also depends on how big the Limit Order Book is at your trading time. Liquidity might always be there just not being taken out.
That's true, but much harder to get a quantitative answer without actually trading the market.
Outstanding post, Rob! I'm really curious to see how much diversification the new instruments will bring you, especially the cryptos you're so "reluctant" to trade : )
Is there really much of a reason to trade the interest rate swap futures when you already trade the Treasury futures? Their correlations must be very close to 100%.
By my calculations (and there are different ways to do it), F1U is 97.6% correlated to FV and N1U is 97.3% correlated to TN. Unless there's something I'm missing, it doesn't seem worthwhile to add those interest rate swaps.
Not in my current system, but in two possible future systems. Firstly, having both F1U and FV (say) means I get a 'cleaner' signal of where US 5 year interest rates are going overall. Having both means I can then pick the best of those two contracts to take a position in, which will usually be the cheapest.
Secondly, it means I can run fixed income RV systems swap vs futures, which incidentally is the first piece of payed quantitative analysis I ever did.
Sounds good to me. I do the same thing. For example, I trade both Eurodollars and SOFR. But since these swaps trade nearly the same as the Treasuries, I'll wait until I have something more significant to add and then I'll add them along with those other instruments. | https://qoppac.blogspot.com/2021/05/adding-new-instruments-or-how-i-learned.html | CC-MAIN-2021-43 | en | refinedweb |
Namespace: MailBee.ImapMailNamespace: MailBee.ImapMail
public bool UploadMessage( MailMessage msg, string folderName, string flags, string dateTimeString, bool batchMode, UidPlusResult result )
Public Function UploadMessage ( msg As MailMessage, folderName As String, flags As String, dateTimeString As String, batchMode As Boolean, result As UidPlusResult ) As Boolean
This method implements APPEND command of the IMAP4 protocol.
To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).
To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property.
To get standard message flags as string in IMAP4 format (e.g. "\Seen \Flagged"), the developer can use SystemFlagsToString(SystemMessageFlags) method.
In addition to the flags specified by the application, the server also sets "\Recent" flag. Thus, the uploaded message will always have at least "\Recent" flag set.
To get datetime string in IMAP4 format (e.g. "01-May-2004 05:26:59 -0600"), the developer can use GetImapDateTimeString method.
batchMode value is ignored if the server does not support LITERAL+ extension. However, even if LITERAL+ is supported, the developer may still decide not to use batch mode if there is a risk that the server will reject the message due to its size. If this happens, the client will waste bandwidth transferring the entire message. If the client wouldn't have used the LITERAL+, this could have been avoided, because the server would have rejected the initial small request containing the length of the data to be uploaded, and thus second large request containing the actual message data would have never been sent. In general, however, if the application is not going to upload very large messages frequently, it's more effective to keep batch mode on. Other overloads of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method always upload messages in batch mode if LITERAL+ is supported.
When result is specified and the server supports and correctly implements UIDPLUS extension, UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method will set the supplied UidPlusResult object properties as below:
If UIDPLUS capability is not supported by the server, IsSupported will be set to false. When working with the server which lacks UIDPLUS support, the application can obtain UID of the uploaded message from UidNext value of FolderStatus object returned by GetFolderStatus(String) method. However, the application must call GetFolderStatus(String) method BEFORE making upload (see the sample).
The developer can also try to avoid calling GetFolderStatus(String) method if the UIDNEXT value is already available in UidNext property (the destination folder must be selected in this case, and some other restrictions apply, see remarks in UidNext topic for more information).
Some servers claim they support UIDPLUS but in fact there is no UIDPLUS data in the response (of the data has incorrect format). IsSupported will still be true but IsValid will be false in this case.
using System; using MailBee; using MailBee.ImapMail; using MailBee.Mime; class Sample { static void Main(string[] args) { Imap imp = new Imap(); // Connect to the server and log in the account. imp.Connect("mail.server.com"); imp.Login("jdoe", "secret"); // Load the message from C:\Temp\message.eml file. MailMessage msg = new MailMessage(); msg.LoadMessage(@"C:\Temp\message.eml"); // Prepare the object that will receive upload results. UidPlusResult res = new UidPlusResult(); long uid = 0; if (imp.GetExtension("UIDPLUS") == null) { FolderStatus status = imp.GetFolderStatus("Inbox"); uid = status.UidNext; } // Upload the message and fill res with upload results. imp.UploadMessage(msg, "Inbox", MessageFlagSet.SystemFlagsToString( SystemMessageFlags.Seen | SystemMessageFlags.Flagged), "12-Apr-2006 19:30:00 +0100", true, res); if (res.IsSupported) { Console.WriteLine("UID of the uploaded message is " + res.DestUidString + ", UIDPLUS supported."); } else { Console.WriteLine("UID of the uploaded message is " + uid.ToString() + ", UIDPLUS not supported."); } // Disconnect from the server. imp.Disconnect(); } }
Imports System Imports MailBee Imports MailBee.ImapMail Imports MailBee.Mime Module Sample Sub Main() Dim imp As New Imap ' Connect to the server, login and select inbox. imp.Connect("mail.domain.com") imp.Login("jdoe", "secret") ' Load the message from C:\Temp\message.eml file. Dim msg As New MailMessage msg.LoadMessage("C:\Temp\message.eml") ' Prepare the object that will receive upload results. Dim res As New UidPlusResult Dim uid As Long = 0 If Not imp.GetExtension("UIDPLUS") Is Nothing Then Dim status As FolderStatus = imp.GetFolderStatus("Inbox") uid = status.UidNext End If ' Upload the message and fill res with upload results. imp.UploadMessage(msg, "Inbox", _ MessageFlagSet.SystemFlagsToString( _ SystemMessageFlags.Seen Or SystemMessageFlags.Flagged), _ "12-Apr-2006 19:30:00 +0100", True, res) If res.IsSupported Then Console.WriteLine("UID of the uploaded message is " & _ res.DestUidString & ", UIDPLUS supported.") Else Console.WriteLine("UID of the uploaded message is " & _ uid.ToString() & ", UIDPLUS not supported.") End If ' Disconnect from the server. imp.Disconnect() End Sub End Module | https://afterlogic.com/mailbee-net/docs/MailBee.ImapMail.Imap.UploadMessage_overload_5.html | CC-MAIN-2018-51 | en | refinedweb |
The binding element describes how a web service is going to be bound to a protocol. We have already defined what are the abstract messages that our web service could be exchanging, but we still have to specify how these messages will be exchanged between the client and the web service provider.
With the binding element you specify a concrete message format and a transmission protocol detailed for an interface. Each operation and fault in an interface must have these details.
The following is an example of the binding element in a WSDL 2.0 file.
<binding name = "myServiceInterfaceSOAPBinding" interface = "tns:myServiceInterface" type = "" wsoap: <operation ref = "tns:checkServiceStatusOp" wsoap: <fault ref = "tns:dataFault" wsoap: </binding>
Binding
A binding element has the following attributes:
<binding name = "myServiceInterfaceSOAPBinding"
The name attribute defines the name of the binding. With this name you can reference it when defining a service endpoint. Every binding name must be unique within the WSDL 2.0 target namespace.
interface = "tns:myServiceInterface"
The interface attribute defines the name of the interface (previously defined in the WSDL 2.0) we are referring in this binding.
type = ""
The type attribute defines which message format is going to be used. In our example is SOAP.
wsoap:
The wsoap:protocol attribute defines the underlying transport protocol. This defines that the messages are going to be transported using HTTP.
Operation
The operation element within the binding element defines which previously defined operation we are binding.
<operation ref = "tns:checkServiceStatusOp"
The ref attribute of the operation element references a specific operation (already defined in the interface section).
wsoap:
The wsoap:mep attribute defines the message exchange pattern for SOAP
Fault
The fault element within the binding element defines which previously defined fault we are binding.
<fault ref = "tns:dataFault"
The ref attribute of the fault element references a specific fault (already defined in the interface section).
wsoap:
The wsoap:code attribute of the fault element defines the fault code that will trigger sending this fault message. | http://wideskills.com/wsdl-tutorial/wsdl-20-binding-element | CC-MAIN-2022-27 | en | refinedweb |
Learn smart - Learn online. Upto 80% off on courses for a limited time. View Courses
New User?
Start here.
Error goes here
Please upload all relevant files for quick & complete assistance.
C-Rated?
The completed table is shown below (Morningstar, 2016a, 2016b, 2016c)
There is an inverse relationship between credit rating and yield to maturity. This is primarily because corporate bonds having lesser credit rating are more vulnerable to default and hence there is a higher risk for the investors. As a result, investors tend to expect a higher yield on these bonds that acts as compensation to the additional risk assumed by the investor (Damodaran, 2008).
The coupon rate along with the YTM defines whether the bond would be traded at a premium, par or discount. Hence, when the coupon rate and YTM are equal, then the bonds tend to trade at par since the coupon rate offered is equal to the yield expected by the investors. However, when the coupon rate is greater than the YTM, then the bond would trade at a premium (i.e. greater than the par value) since the coupon offered by the bond is greater than the expected yield on the bond due to which there is a greater demand of such bonds in the market. Additionally, when the coupon rate is lower than the YTM, then the bond would trade at a discount (i.e. lesser than par value) as the coupon offered by the bond is less than that expected by the investors (Kane & Marcus, 2013).
A decrease in the maturity date tends to decrease the YTM and thus increases the bond prices. Whereas, an increase in the maturity date tends to increase the YTM and thus decreases the bond prices (Parrino & Kidwell, 2011).
The completed table is shown below (Yahoo Finance, 2016).
Company
5-year Risk-Free Rate of Return
Beta (β)
5-Year Return on Top 500 Stocks
Required Rate of Return (CAPM)
Microsoft
1.45%
1.02
8.77%
8.92%
Apple
1.06
9.21%
IBM
0.63
6.06%
The risk–free rate is taken as the yield on US treasury 5 – year bond that comes out as 1.45% pa. The beta of the various stocks has been estimated from Yahoo Finance website. As per the CAPM model (Brealey, Myers & Allen, 2008).
Required rate of return = Risk free rate + Beta*(Market return – Risk free rate)
Required rate of return (Microsoft) = 1.45 + 1.02*(8.77-1.45) = 8.92% pa
Required rate of return (Apple) = 1.45 + 1.06*(8.77-1.45) = 9.21% pa
Required rate of return (IBM) = 1.45 + 0.63*(8.77-1.45) = 6.06% pa
Current Dividend ($)
Projected Growth Rate (next year)
Estimated Stock Price (Gordon Model)
Current Stock Price
Over/Under Priced
1.24
4%
26.2
50.80
Over
2.08
4.5%
46.2
96.30
5.2
3.5%
210.2
129.56
Under
Estimated stock price (Microsoft) = 1.24*1.04/(0.0892-0.04) = $26.2
Estimated stock price (Apple) = 2.08*1.045/(0.0921-0.045) = $ 46.2
Estimated stock price (IBM) = 5.2*1.035/(0.0606-0.035) = $ 210.2
Estimated Earning (next year)
P/E Ratio
Estimated Stock Price (P/E)
3.12
33.51
104.5
10.49
10.35
108.6
15.01
8.97
133.14
All the relevant data for the above table has been obtained from Yahoo Finance (2016).
As per the Gordon dividend growth model,
Estimated stock price = Dividend next year/(Required return – dividend growth rate)
Thus, the estimated stock price is inversely proportional to the required return on stock while it is directly proportional to the dividend growth rate. This is primarily because a higher dividend growth rate would increase the numerator and also would decrease the denominator and thus, lead to a higher estimated stock price. Additionally, a higher dividend paying stock would have a higher value assuming that denominator remains constant similar to the higher price of a higher coupon paying bond assuming YTM as constant. As per the Gordon dividend model, the current stock is the present value of all the dividends that would be paid over the life of the stock assuming perpetual holding period (Kane & Marcus, 2013).
It is an easy and convenient method to estimate the value of the stock of a particular company irrespective of the industry it belongs to (Parrino & Kidwell, 2011).
It cannot be used to estimate the stock price of those companies that do not pay dividends (Marcus & Kane, 2013).
It does not give emphasis to factors other than dividends for the determination of stock price particularly the presence of intangible assets that are critical in modern knowledge based economy (Parrino & Kidwell, 2011).
The dividend growth does not remain constant and typically varies even for mature stocks.
The dividend growth rate always has to be lower than the required rate on equity that is not always true and thus, prices of such stocks cannot be determined (Damodaran, 2008).
The P/E approach primarily relies on estimation of EPS in the next year and multiplying that with the current P/E ratio so as to determine the estimated price of the stock in the next year assuming that P/E ratio remains constant (Parrino & Kidwell, 2011).
Hence, estimated value of stock = Current P/E ratio * Estimated EPS in the next year
The P/E model seems to be more accurate in determining the value of stock. This is primarily because the prices in the Gordon dividend growth model are highly sensitive to the dividend growth rate that cannot be predicted with high degree of accuracy in the future. As a result, the values obtained through P/E multiple are closer to the current market price (Brealey, Myers & Allen, 2008).
If the growth rate of the company would increase, then the value of the stock would increase as the next year dividend would increase while the denominator in Gordon growth model would decrease. An increase in the required rate of return would lower the stock value. Further, an increase in the dividends would increase the stock price in line with the Gordon growth model where the stock price is directly proportional to the dividends being paid. If the EPS of the stock would increase, then the stock price would increase due to higher profitability in line with the P/E approach (Damodaran, 2008).
Brealey, R., Myers, S. & Allen, F. (2008), Principles of Corporate Finance, New York: McGraw Hill Publications
Damodaran, A. (2008), Corporate Finance, London: Wiley Publications
Kane, B.Z. & Marcus, A.J. (2013). Essentials of Investment, Singapore: McGraw-Hill International
Morningstar (2016a), Verizon Communications Inc, MorningStar Website, Retrieved on January 12, 2016
Morningstar (2016b), KLA-Tencor Corp, MorningStar Website, Retrieved on January 12, 2016 ttp://quicktake.morningstar.com/StockNet/bonds.aspx?Symbol=KLAC&country=USA
Morningstar (2016c), Oracle Corp, MorningStar Website, Retrieved on January 12, 2016
Parrino, R. & Kidwell, D. (2011), Fundamentals of Corporate Finance, London: Wiley Publications
Yahoo Finance (2016), Historical prices, Yahoo Finance, Retrieved on January). Principles Of Corporate Finance: Essentials Of Investment. Retrieved from.
"Principles Of Corporate Finance: Essentials Of Investment." My Assignment Help, 2016,.
My Assignment Help (2016) Principles Of Corporate Finance: Essentials Of Investment [Online]. Available from:[Accessed 25 June 2022].
My Assignment Help. 'Principles Of Corporate Finance: Essentials Of Investment' (My Assignment Help, 2016) <> accessed 25 June 2022.
My Assignment Help. Principles Of Corporate Finance:.
MyAssignmentHelp.com is not sponsored or endorsed by this college or university. | https://myassignmenthelp.com/free-samples/principles-of-corporate-finance-essentials-of-investment | CC-MAIN-2022-27 | en | refinedweb |
A paint effect which draws a glow within a picture. More...
#include <qgsgloweffect.h>
A paint effect which draws a glow within a picture.
Definition at line 262 of file qgsgloweffect.h.
Definition at line 248 of file qgsgloweffect.cpp.
Definition at line 254 of file qgsgloweffect.cpp.
Duplicates an effect by creating a deep copy of the effect.
Implements QgsPaintEffect.
Definition at line 266 of file qgsgloweffect.cpp.
Creates a new QgsInnerGlowEffect effect from a properties string map.
Definition at line 259 of file qgsgloweffect.cpp.
Specifies whether the glow is drawn outside the picture or within the picture.
Implements QgsGlowEffect.
Definition at line 281 of file qgsgloweffect.h.
Returns the effect type.
Implements QgsPaintEffect.
Definition at line 276 of file qgsgloweffect.h. | https://api.qgis.org/api/2.12/classQgsInnerGlowEffect.html | CC-MAIN-2022-27 | en | refinedweb |
This WorkSession completes the basic one, by adding : More...
#include <XSControl_WorkSession.hxx>
This WorkSession completes the basic one, by adding :
Clears the whole current Context (nullifies it)
In addition to basic ClearData, clears Transfer and Management for interactive use, for mode = 0,1,2 and over 4 Plus : mode = 5 to clear Transfers (both ways) only mode = 6 to clear enforced results mode = 7 to clear transfers, results.
Reimplemented from IFSelect_WorkSession.
Returns the current Context List, Null if not defined The Context is given to the TransientProcess for TransferRead..
Returns the TransientProcess(internal data for TransferReader)
produces and returns a new Model well conditioned It is produced by the Norm Controller It can be Null (if this function is not implemented)
Returns the norm controller itself.
Prints the transfer status of a transferred item, as being the Mapped n0 <num>, from MapWriter if <wri> is True, or from MapReader if <wri> is False Returns True when done, False else (i.e. num out of range).
Returns the name of the last Selected Norm. If none is defined, returns an empty string By default, returns the complete name of the norm If <rsc> is True, returns the short name used for resource.
Selects a Norm defined by its name. A Norm is described and handled by a Controller Returns True if done, False if <normname> is unknown.
The current Profile for this Norm is taken.
Sets the current Context List, as a whole Sets it to the TransferReader.
Selects a Norm defined by its Controller itself.
Changes the Map Reader, i.e. considers that the new one defines the relevant read results (forgets the former ones) Returns True when done, False in case of bad definition, i.e. if Model from TP differs from that of Session.
Changes the Map Reader, i.e. considers that the new one defines the relevant read results (forgets the former ones) Returns True when done, False if <FP> is Null.
Sets a Transfer Reader, which manages transfers on reading.
Returns the Transfer Reader, Null if not set.
Commands the transfer of, either one entity, or a list I.E. calls the TransferReader after having analysed <ents> It is cumulated from the last BeginTransfer <ents> is processed by GiveList, hence :
Commands the transfer of all the root entities of the model i.e. calls TransferRoot from the TransferReader with the Graph No cumulation with former calls to TransferReadOne.
Returns the check-list of last transfer (write) It is recorded in the FinderProcess, but it must be bound with resulting entities (in the resulting file model) rather than with original objects (in fact, their mappers)
Returns the Transfer Reader, Null if not set.
Transfers a Shape from CasCade to a model of current norm, according to the last call to SetModeWriteShape Returns status :Done if OK, Fail if error during transfer, Error if transfer badly initialised. | https://dev.opencascade.org/doc/occt-7.6.0/refman/html/class_x_s_control___work_session.html | CC-MAIN-2022-27 | en | refinedweb |
You can use Application Real-Time Monitoring Service (ARMS) Prometheus to manage Kubernetes clusters that are deployed across regions in a unified manner. This topic describes how to enable ARMS Prometheus for a registered Kubernetes cluster by deploying an application in the cluster.
Prerequisites
Procedure
- Log on to the ACK console.
- In the left-side navigation pane of the ACK console, choose .
- On the Marketplace page, click the App Catalog tab. On the App Catalog tab, find and click ack-arms-prometheus.A large number of applications are displayed on the App Catalog tab. You can enter ack-arms-prometheus or a keyword in the search box to search for the application.
- On the ack-arms-prometheus page, click Deploy.
- In the Deploy wizard, select a cluster and namespace, and then click Next.
- On the Parameters wizard page, configure the parameters and click OK.Notice
- If an Express Connect circuit is deployed between the cluster and the virtual private cloud (VPC) in which the cluster resides, the Express Connect circuit is automatically used.
- If the external cluster is registered over the Internet, you must delete vpc in the address of the image registry on the Parameters wizard page. For example, after vpc is deleted, the address of the image registry is registry.cn-hangzhou.aliyuncs.com/arms-docker-repo/arms-prom-operator:v0.1. | https://www.alibabacloud.com/help/en/container-service-for-kubernetes/latest/enable-arms-prometheus-for-a-registered-kubernetes-cluster | CC-MAIN-2022-27 | en | refinedweb |
Analytics ready!
In the option object of the plugin there's a callback function available that fires when analytics.js or analytics_debug.js is loaded
always remember that the debug version is more heavy than the production one and might take more to load
import VueAnalytics from 'vue-analytics' Vue.use(VueAnalytics, { beforeFirstHit () { // this is right after the tracker and before every other hit to Google Analytics }, ready () { // here Google Analytics is ready to track! } })
It is also possible to use the
onAnalyticsReady method, which returns a promise.
import VueAnalytics, { onAnalyticsReady } from 'vue-analytics' Vue.use(VueAnalytics, { ... }) const App = new Vue({ ... }) onAnalyticsReady().then(() => { App.$mount('#app') }) | https://matteogabriele.gitbooks.io/vue-analytics/content/docs/when-google-analytics-is-loaded.html | CC-MAIN-2022-27 | en | refinedweb |
Bulma CSS Framework
Install Bulma into React.js
Bulma is a modern CSS framework.
I have always been a big fan of Bootstrap. Recently I try to some other frameworks. But I Recently find the Bulma framework.
Bulma is a modern CSS framework. Bulma is open source like bootstrap. Bulma also provides you ready to use frontend components that component help make the website fast and easy. You also easily combine with other components.
I don't use Bulma soo much on my project daily basis. I’m just exploring the Bulma framework and try to understand how to use it.
Note:
In This Article, I'm told how to add the Bulma framework in react app. if you create an intarweb with Bulma. I personally recommend you use the react-bulma-components library to create your own web app.
react-bulma-components is a great way to add bulma to your app. react-bulma-components also provide in-build react components for your app.
Installation
Most common two ways to add Bulma in your project. In Project, I always recommended you to add Bulma help of Npm or yarn.
- Contact delivery network CDN
- Npm or Yarn
- Requirements
Contact delivery network CDN
Bulma also provide a Contact delivery network
<link rel="stylesheet" href="">or@import ""
Npm or Yarn
My Recommended way to add Bulma into reacting app.
npm install bulma
or
yarn add bulma
Requirements
Bulma works correctly in your reactJS. Firstly, add two lines of code in our react app.
Follow two steps
- HTML5 doctype
- Add meta tag
- How to use
HTML5 doctype
Firstly define html5 doctype in your HTML. Document Type Declaration gives instructions to the web browser about the version of the markup language.
<!DOCTYPE html>
Add meta tag
Firstly setup doctype after adding a response meta tag in your app. response meta helps responsive your app to different web browsers.
<meta name="viewport" content="width=device-width, initial-scale=1">
Note
If you create react, use
npx create-react-app my-appthe npx command. By default, npx adds HTML 5 doctype and also adds a responsive meta tag in-app.
How to use it
two ways you add Bulma into react.js
Let's start code
- CDN ways
- NPM ways
CDN ways
You copy the CDN file and paste it into the react.js public/index HTML file in CDN ways. After saving it.
<" /><link rel="stylesheet" href=""><title>React App</title></head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body>
</html>
NPM ways
Firstly go to react index.js app and import Bulma CSS files into node_modules.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';import 'bulma/css/bulma.min.css';ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,document.getElementById('root'));
After start write coding in react app.js.
import './App.css';function App() {return (<section className="section"> <div className="container">
<h1 className="title"> Hello World </h1>
<p className="subtitle"> My React app with <strong>Bulma</strong> </p>
</div></section>
);
}export default App;
Reference
Getting started with Bulma
Getting started with Bulma You only need 1 CSS file to use Bulma Bulma is a CSS library. Bulma means it provides CSS…
bulma.io
jgthms/bulma
Modern CSS framework based on Flexbox. Contribute to jgthms/bulma development by creating an account on GitHub.
github.com
Conclusion
In my opinion, Bulma is a great CSS framework. You build a responsive website very easily and in fast ways. You defiantly use it and build its own site.
Bulma also provides scss support for developers. You easily customize the sass variable according to your own thought.
Bulma provides all browser support. Like Chrome, Edge, Firefox, Opera, and Safari.
Bulma also partially support Internet Explorer (10+). | https://medium.com/frontendweb/install-bulma-into-react-js-b835b2fe2204?source=post_internal_links---------7---------------------------- | CC-MAIN-2022-27 | en | refinedweb |
This is a synthetic dataset that can be used by users that are interested in benchmarking methods of explainable artificial intelligence (XAI) for geoscientific applications. The dataset is specifically inspired from a climate forecasting setting (seasonal timescales) where the task is to predict regional climate variability given global climate information lagged in time. The dataset consists of a synthetic input X (series of 2D arrays of random fields drawn from a multivariate normal distribution) and a synthetic output Y (scalar series) generated by using a nonlinear function F: R^d -> R.
The synthetic input aims to represent temporally independent realizations of anomalous global fields of sea surface temperature, the synthetic output series represents some type of regional climate variability that is of interest (temperature, precipitation totals, etc.) and the function F is a simplification of the climate system.
Since the nonlinear function F that is used to generate the output given the input is known, we also derive and provide the attribution of each output value to the corresponding input features. Using this synthetic dataset users can train any AI model to predict Y given X and then implement XAI methods to interpret it. Based on the “ground truth” of attribution of F the user can assess the faithfulness of any XAI method.
NOTE: the spatial configuration of the observations in the NetCDF database file conform to the planetocentric coordinate system (89.5N - 89.5S, 0.5E - 359.5E), where longitude is measured in the positive heading east from the prime meridian.
Neural Network Attribution Methods for Problems in Geoscience: A Novel Synthetic Benchmark Dataset, Antonios Mamalakis
Mamalakis, A., Ebert-Uphoff, I. & Barnes, E. (2022) "CSU Synthetic Attribution Benchmark Dataset", Version 1.0, Radiant MLHub [Date Accessed]
from radiant_mlhub import Dataset ds = Dataset.fetch('csu_synthetic_attribution') for c in ds.collections: print(c.id)
Python Client quick-start guide | https://mlhub.earth/data/csu_synthetic_attribution | CC-MAIN-2022-27 | en | refinedweb |
++
>>
c++ add input in
“c++ add input in” Code Answer
c++ add input in
cpp by
KeWols
on May 23 2022
Donate
Comment
0
cin >> variable; // sample 1 int x; cout << "x: "; cin >> x; cout << x << endl; //sample 2 int num; for (int i = 0; i < 10; i++){ cout << "Give a number: "; cin >> num; }
Add a Grepper Answer
C++ answers related to “c++ add input in”
C++ user input
input a string in c++
user input c++
how to get input in cpp
c++ linker input and output
user inptu in cpp
how to input in cpp
add for input output file in c/c++
input full line as input in cpp
input in c++
How to add numbers in c++
c++ addition
c++ program to take input from user
C++ User Input
C++ queries related to “c++ add input in”
cin c++
c++ cin
input c++
cin in cpp
getting input in c++
how to cin in c++
input function c++
inputs in cpp
input from user in c++
how to take input in c++
meaning of cin in c++
cin in c++
input in c++
c++ input
c++ input program
how to read input in cpp
cpp cin <<
cin c++ int
user input c++
cpp cin
c++ input with text
cpp cin
cin cpp
how to add input in c++
cpp input
cin meaning in c++
c++ input alma
how to create input in c++
take input in c++
command line cin c++
get input c++
More “Kinda” Related C++ Answers
View All C++ Answers »
ue4 c++ print to screen
cin.tie c++
c++ hello word
cpp boilerplate
arduino uno hello world
how to hide the console c++
fast io
how to make i/o fast in c++
fast i/o c++
c++ directory listing
print all file names in directory cpp
hello world c++
c++ clear console
c++ time nanoseconds
how to use python sleep function on c++
c++ show time elapsed
c++ measure time
c++ measure time of function
c++ code to print hello world
c++ hide console
all library in c++
what library to mention for swap function in c++
cpp all in one header
c++ all in one header file
master library in c++
c++ - include all libraries
how to include everything in c++
#include<bits/stdc++.h>
fast i/o in c++
fast input output cpp
suppress individual warnings in visual c++
disable a warning in visual c++
conditional cout in c++
how to print list in c++
c++code
print stack c++
unreal engine delay c++
arduino for command
c++ get files in directory
number of cores c++
c++ lambda thread example
exp() c++
c++ get filename from path
'std::ifstream file' has initializer but incomplete type
'std::ifstream file' has incomplete type and cannot be defined
how to complie with c++ 17
c++ get file content
taking input from user in array in c++
clear screen in c++
how to print in c++
make cin cout faster
c++ hide cursor
modify file CPP
ue4 spawn actor c++
compile multiple files C++ linux
check if directory exists cpp
get current date in c++
C++ sleep for seconds
c++ usleep()
c++ system delay
C++ pause program
UNIX c++ delay
sleep in cpp
simple C++ game code
clear buffer memory in c / c++
c++ flush stdin
check compiler version c++
c++ read console input
c++ execution time
how to use winmain function
c++ get cursor position console
c++ fast
c++ message box error
log base c++
clear file before writing c++
move mouse c++
how to shut down windows in c++
compile cpp with specific version
how to print hello world in c++
hello world c++ visual studio
c++ delete directory
print hello world c++
c++ hello world program
crt secure no warnings in c++
how to take user input in a client server program in c++
C++ try catch
for loop reverse C++
fastio in c++
how to use sleep function in c++ windows
c++ edit another processes memory address
print to console c++
cpp how to input a variable without hitting enter
check file exist cpp
leveling system c++
should i learn c or c++
master header file c++
print array c++
c++ pause
set platformio to C++17
exit() in c++
hide terminal window c++
print set c++
c++ copy file to another directory
cpp read csv
ue4 ftext c++
file descriptor linux c++
ue4 get socket location c++
how to fix class friendship errors in c++
c++ visual studio 19 how to make colord button from code
how to lock window resize c++ sfml'
get current directory cpp
how to output to console c++
read variable to file cpp
Get Blackboard in UE C++
how to type hello world in c++
C++ add value to exception message
c++ get input without loop
set platformio to C++14
dev c++ tahe last word error
print linkedstack cpp
ue4 bind function to button clicked c++
time measurement c++
create n threads cpp
C++ std::async wait is taking forever
gcc run c++
c++ cmd program run in background
c++ short if
write variable to file cpp
c++ unary minus overload
c++ wait for user input
c++ throw exception
C++ Multi-line comments
c++ for else
did greeks write c++ codes?
c++ run loop for 5 seconds
ue4 cpp OnHit
cpp executing without console
set cmd size c++
c++ read image opencv in folder
How to block window resize sfml c++
c++ file exists
use c++17 g++
ue4 c++ enumaeration
ue4 find component c++
how to clear screen in C++ console
print queue c++
C compile SDL program using mingw
c++ overwrite file
cout.flush() in c++
how to print text on C++
c++ file is empty
ue log c++ unreal
regex for phone number c++
c++ check open processes
for in c++
how to open and print in a file in c++
remove () not working c++
C++ shortcuts in desktopp app
set clear c++
c++ chrono
note++
save all output in log file c cpp
how to open and read text files in c++
c++ check if file exits
merge images opencv c++
C++ mutex lock/unlock
c++ std::fmin
print 5 table in c++
user input c++
c++ memory leak
c++ print current time
c++ std::copy to cout
print hello world on c++
c++ in linux
c++ windows error message
c++ print to standard error
c++ print hello world
c++ multiline string
how to read a line from the console in c++
time function c++
c++ looping
C++ Infinite for loop
how to run a c++ file from terminal linux
run c++ file putty
clang cpp compile command
retu7rn this c++
c++ loop programs
clear console c++
system cls c
how to run a c++ program in the background
how to ensure the user inouts a int and not anything else c++
how to make sure the user inputs a int and not anything else c++
C++ user input
in c++ ++ how to write if without if
c++ lock
c++ create threads
hello world C++, C plus plus hello world
how to read wav file in C++
how to hide the c++ console
C++ switch - case - break
cpp switch
c++ switch case break
c++ case
cpp case
c++ switch
switch statement in C++
cases in cpp
C++ switch cases
how to get last element of set in c++
how to get input in cpp
c++ read integers from file
c++ program to take input from user
how to clear console c++
parallelize for loop c++
c++ nested switch statements
c++ ros publisher
infinite loop c++
how to make a hello world program in c++
simple c++ program
helloworld in c++
easy c++ code
c++
input in c++
delete file cpp
delete file c
findung the mode in c++
c++ hide show console
c++ simple projects
how to install boost c++ on windows
c++ get time
doubly linked list c++ code
chrono library c++
chrono start time in c++
get line C++
run c++ program in mac terminal
pbds in c++
how to play sound in c++
c++ console color
c++ terminal color
c++ foreach
compile notepad++ c++
macro c++
how to add colored text in c++
file open cpp
do while loop c++ loops continuously
how to check size of file in c++
size of stack in c++
c++ cout format
how to make a typing effect c++
c++ typing animation
c++ how to make a typewriter effect
mkdir c++
c++ sleep
C++ cin cout
terminal compile c++
Macros in c++
how to send email in c++ program
continue c++
OpenGL C++ Version
read and write file in c++
for loop C++
c++ open file
play audio c++
time delay in c++
file c++
c++ get full line of input
hello world in cpp
check if set contains element c++
run cmd command c++
sleep system function linux c++
c++ switch statement
cpp detect os
cpp define function
cpp ifdef
c++ elif
c++ preprocessor operations
c++ pre-processor instructions
c++ #include
C++ #define
cpp macro
cpp define
c++ colored output
cpp when use size_t
print in c++
how to use cout function in c++
create file c++
c++ open all files in directory
c++ compare time
c++ how to read from a file
flags for g++ compiler
How to pause a c++ program.
C++ keyboard input
throw exception c++
c++ clamp
sleep c++
detect end of user input cpp
c++ if example
C++ Conditions and If Statements
how to compile opencv c++ in ubuntu
c++ if else
c++ remove text file
how do you wait in C++
how to print in new lines in C++
concurrency in c++
c++ threads
c++ concurrency
c++ multithreading
multithreading
multithreading in c++
c++ measure time in microseconds
std::iomanip c++
hello world in c++
hello world in c/++
cout hex c++
c++ thread incide class
draw rectangle opencv c++
c++ fstream create if not exists
cpp mutex
c++ filesystem read directory
how to delete a node c++
opencv c++ hello world
how to play sounds in c++
cpp ifstream
See Compilation Time in c++ Program
c++ starter
getline of file C++
c++ output
compile in c++
c++ compile
cpp while
how to write hello world in c++
c++ how to check whether a file exists?
continue statement in c++ program
getline in c++
c++ uint32_t
For Loop in C++
notepad++
error handling in C++
c++ simple car game
c++ 14 for sublime windoes build system
which version c++ single file in sublime is
get data from terminal c++
How to create files in C++
How to read files in C++
How to write into files in C++
debugging c/c++ with visual studio code
c++ saying hello world
C++ press enter to continue function
c++ hello world linux
show stack c++
time of a loop in c++
Visual studio code include path not working c++
sleep in c++
how to make a comment in c++
cout in C++
add for input output file in c/c++
run c++ program mac
SETW C++
c++ header boilerplate
format c++ discord
print stack without pop c++
life the universe and everything solution c++
could not find the task c c++ active file
getline cpp
check if file is empty c++
system cpp
c++ cout colored output xcode
c++ for loop multiple variables
c++ basic snippet
C++ continue with for loop
c++ progress bar
for loop in cpp
Cout C++
a c++ program to set a countdown timer
overload of << c++
c++ write to csv file append
How do I read computer current time in c++
cin exceptions c++
c++ lettura file
c++ compile to exe command line
c++ compile to exe
c++ in cmd
cpp execute command
cpp get exception type
break statement in c++ program
for statement in c++
C++ sudoku solver
How to get cursor position c++
C++ break with for loop
opencv c++ feature detection
visual studio cpp compiler
system("pause") note working c++
iostream c++
Can I write code in Cpp?
Cpp code?
Code cpp
learn C++
how learn C++
New cpp project
begin cpp
PRINT IN C ++
input full line as input in cpp
read full line in c++
C++ Exceptions
print hello world in c++
fast input and output c++
memory leak in cpp
how to add c++14 in sublime text
how to input in cpp
how to say hello world in c++
c++ pause linux
c++ read matttrix from text file
c++ cout
c++ queue
ifstream
how to make loop in c++
c++ check if debug or release visual studio
what is thread in c++
how to delete a file in cpp
stack class implementation to file unix-style in c++
linux c++ sigint handler
walk filesystem in c++
doubly linked list code in c++
sfml keyboard events cpp
for c++
fstream read write mode
clear previous terminal output c++
disallowcopy c++
prevent copy c++
cpp custom exception
check if c++ is installed
unknown amount of threads cpp
adddynamic ue4 c++
unknown number of threads cpp
oncomponentendoverlap ue4 c++
hello world cc++
c++ code executio canntot proceed because glew32.dll was not founud
cin c++
add input in c++
c++ add input in
c++ input
input c++
C++ switch..case Statement
Disabling console exit button c++
c++ pass ofstream as argument
C++ New Lines
c++ delay
if else in C++
c++ thread wait fro 1 sec
change colour of output to terminal c++
C++ cout iostream
c++ write to file
hello c++
what is the default include path in ubuntu c++
cout stack in c++
c++ getline doesn't wait for input
how to add space in c++
access last element of set c++
closing a ifstream file c++
cpp gui
declare a tab c++
C++ detaching threads
c++ loop pyramid
c++ triangle
for statement c++
how to run cpp using gcc vscode
c++ while
C++ While Loop
switch c++
error uploading arduino code
clear the input buffer in cpp
Character cin(userInput) in c++
c++ write to file in directory
c++ client service ros
hide window c++
c++ for loop syntax
delete c++
c++ output current timestamp
executing an opencv c++ code
while loop c++
do while c++
ex: cpp
C++ Recursion
Vs Code cpp not run
if not c++
short hand if else in c++
conditions in c++
if statement in c++
c++ create thread
Calloc C++
opencv compile c++
for_each c++
if else c++
c++ formatting
c++ preprocessor commands
how to run a cpp file in visual studio
error in c++
c++ custom printf
files c++
cpp foreach
login system with c++
c define
c include
c ifdef
c elif
c preprocessor operations
c #include
c #define
c detect OS
c define function
c pre-processor instructions
c++ freecodecamp course 10 hours youtube
Browse Folder Dialog, Search Folder and All Sub Folders using C/C++
c++ bind port
is there garbage collection in c++
c++ single comment
for llop in c++
factorial loop C++
c++ over load oprator to print variable of clas
what does catch(...) mean in c++
compile c++ program
C++ Files
hello world program in c++
C++ Single Line Comments
c++ read_ascii
passing reference to thread c++
c++ program
cout
last element of a set in c++
labs c++
c++ konsolenausgabe
comment in C++
function for reversing an array c++ stl
C++ thread header
pcl c++ read .pcd
qt/c++ exception handler
c++ for loop
stack overflow c++
c++ localtime unsafe
Basic Makefile C++
easy way to encrypt a c++ file line by line
Ninja c++
how to make a running text in c++
how to block the screen c++
how to run c++ on cmd
Z-function
create and write to a file c++19
c++ profiling tools
c++ open webpage
C++ file .
Pretty Print c++ chegg
c++ fstream read line write ,creat file program
c++ print out workds
cpprestsdk header
export gcc g++
scan input c++
define for loop c++
how to list directory in c++
c++ poitner
c++ schleife abbrechen
apertura file in c++
c++ break Statement
cpp pass function with input to thread
printf cpp
c++ starting syntaz
practice problems for nested loops in c++
C++ Thread
c++ ignore_line
c++ catch Unhandled exception
ifstream file (“code2.txt”); dev C++
turbo c++ easy programs
C++ Comments
pthread c++ example with output
warning in range-based for loop in C++. How to resolve it in vscode?
vsearch c program stdlib
compile and run cpp file on mac c++
c++ get microseconds since epoch
how to use run total in C++
c++ compile to msi
c++ SFINAE doesn't work in recursive function
C++ fibo
.txt file into .cpp
ue4 endoverlap c++
C++ CHEAT SHEAT
c++ cout without include iostream
C++ loop maker
c++ throe
getline takes last line break c++
shrek c++
how atan work c++
get future from promise c++
C if
Print value of data in c++
getline trong c++
In every C++ program:
ue4 foreach loop c++
C++ if...else...else if statement
find out if it is the last iteration of the for loop c++
c++ put a function in a other thread
C++ Join thread
hello command not printing in c++
Exit Button c++ code
time_t c++ stack overflow
c++ hide credentials
C++ Else
c++ rewrite file
C++ Return Statement
makefile for single cpp file
file is good in c++
conditional variable c++
crtdbg c++
c++ move semantics for `this`
compilling c++ and c by console
c++ error missing terminating character
c++ loop
c++ camera capture
check .h files syntax c++
how to fix in c++ "cannot open imgui.h"
if statement C++
properties of loop in c++ and how it works
c++ segmentation fault
cpp serial print override always in same place
C++ if...else...else if
compile c++ MPI Program
parking charge system project c++
how to add values in empty array using python
C++ check if thread is joinable
how to run cpp in visual studio
c++ code
c++ while loop decrement
libraries required for gaming in c++
C/C++ loop for
how to print an array in cpp in single line
C++ Else If
3 conditions for a while loop c++
c++ move second line
get start with c++
cpp starting code
C++ Things to Remember
how to measure cpp code performace
getline() and cin.ignore() in C++
C++ OpenCV Face Recognition
assert warning c++
how to print in cpp
why we use iostream in C++ programming
c++ region
rethrow exception c++
How to clear keyboard buffer c++
remove element from c++
web dev c++
cout alternative c++
show mouse c++
C++ ss
visual studio code terminal keeps closing c++
c++ asio read full socket data into buffer
C++ Nested if...else
sleep function i nc++
cout ascii art c++
can you use rand to read in from an external file inc++
c++ suare
Runtime error(Exit status:153(File size limit exceeded)) c++
cout hello world
if in c++
how to install open cv2 in c++ on ubuntu
windows install cppcheck
overwrite windows mbr c++
CPP print executable name
Distinct Numbers CSES
how to create windows warning message c++
why wont a function stop C++
c++ read entire file into a variable
how to do if command in c++
how to print items in c++
gcc compile multi thread
onactorbeginoverlap c++
c++ CRL multiline string
how to input a file path in c++
Restart the computer in c++ after the default time (30) seconds. (Windows)
c++ write number to registry
converting a for loop to a while loop C++
run c++ files on chrome book
c for loop decrement
C++ Display a text 5 times
c++20 inizialize a thread
C++ thread id
namespace file linking c++
C++ Short Hand If Else
even number program in c++ using for loop stack overflow
CPP Find options passed from command line
c++ execute thread and forget
c++ login
txt to pdf CPP
c++ awitch statements
prompt user for bool statement C++
The iostream is the head er file which contains all the functions of program like cout, cin and etc.
how to writte comment in c++
opencv read gif c++
how to seek to the start of afile in c++
deadlock detection in c++coding ninjas
c++ multiple if conditions
C++ Ranged Based for Loop
add comment in c/c++
c++ sleep function
librerias matematicas en c++ para numeros aleatorios
code runner c++ syntax error
iomanip header file in c++
how to use printf with microseconds c++
how to save system function output into a variable in c++
press any key to exit c++
c++ how to print out
qt c++ thread example
how to delay text in c++ console app
haxelib install cpp
c++ start thread later
read a file line by line c++ struct site:stackoverflow.com
cpp read from file
command loop ctrl D c++
log base 10 c+_+
how-to-read-until-eof-from-cin-in-c++
c++ rgb code
Code début C++
C++ do...while Loop
c++ exam
crud with template c++
taking integer input from file in c++
run program until ctrl-d c++
c++ click event
c++ threadpool
how to use printf with <cinttypes> c++
nested loop c++ program example
new lien c++
C++ Break and Continue
How to remove the % in zsh that show after running c++ file
c++ cout update percentage
C++ Detect when user presses arrow key
C++ wchar_t
C++ Battery Low
c++ server service ros
file streams in c++
displaying m images m windows opencv c++
lap trinh file explorer c++
txt auslesen c++
switch cout print with a prameter c++
cpp full form
c++ anti debugging
number of words in c++ files
how to use qdebug c++
cpprestsdk send file
qpushbutton clicked connect c++
c++ SDL2 window
ros pointcloud2 read_points c++
button creation in C++ GUI
how to refresh multiple command lines in C++ stream
how to change the icon of an exe in c++
open url from dev cpp
c program runner
c++ comment
C++ Infinite while loop
c++ iterator shorthand
variadic template in c++
how to read and write to a file in qt c++
user inptu in cpp
print hello world c++
C++ Memory Address
cpp console progressbar
comment installer boost c++ sur windows
how to use string in if else statement c++
std::ifstream cant read file to large
cpp vscode multipe compilation
C++ Integer Input/Output
how to open file without override c++
Temporary file using MSFT API in cpp
displaying m images one window opencv c++
onoverlapbegin ue4 c++
how to type a vertical stack program c++
number of characters in c++ files
print an array c++
circle game
C++ system("pause")
How to execute a command and get return code stdout and stderr of command in C++
thread group c++
C++ selectin file location using Win32 API
input time from console C++
c++ file handiling
C++ for vs while loops
ask a question and answer it in code c++
statement that causes a function to end in c++
what is a .h file in c++
log like printf c++
Code Example of Switch Statement in C++/Java
c++ start process and get output
deal with bad input cpp
C++ (.NET CLI)
easy way to learn file handling in c++ array
read large files part by part in C++
ranged based for loop c++
C++ Taking Multiple Inputs
c++ get active thread count
cout console
how to check code execution time in visual studio c++
how to create a custom event in ue4 c++
cpp get keystroke in console only
how to use for c++
play sound opencv video c++
fast scan in c++
number of lines in c++ files
in built function to find MSB in cpp
how to get steam id c++
hii
Configuring an c++ OpenCV project with Cmake
ex:c++ gcc start adress
Hiring Test codechef solution in c++
c++ linker input and output
auto in cpp
pause the console c++
ex:c programming
if c++
iterator c++
c++ cin
fast io c++
auto i cpp
c++ if else if
c++ auto loop
dev c++ graphics download
iteration in c++
who made c++
how to write hello world c++
Default code in C++ for VSCode
c++ for loops
c++ for
loop in c++
how to make sound in c++
console clear c+
c++ filesystem remove file
run with cpp version
c++ press any key
hello world
get list of files in directory c++
c++ handling
hello world program in c ++ using standard namespace
C++ hello world
CPP hello world
cpp set time
Hello world cpp
read from standard input cpp
flags of open operation c++
c++ check if function exists
what does for do in c++
c++ forloop
C++ mutex header
how to make a c++ iostream program restart when finished
do while loop c++
run time calculator c++
c++ excel cell blank cells++
DateFormat in Flutter
flutter datetime format
flutter convert datetime in day of month
remove value from vector c++
delete specific vector element c++
file objects in c++
how to do file handling in c++
file handling in c++
creating and writing into txt file cpp
c++ files
how to output to a file in c++
create and write to a file c++19
how to load from files C++
c++ writing to file
File handling
how to list environments with conda
list conda environments
conda list envs
range of long long in c++
removing a character from a string in c++
input a string in c++
c++ reverse vector
remove element by index from vector c++
string to char array c++
convert string to char c++
c++ vector print
cpp print vector
convert whole string to lowercase c++
if vector contains value c++
c++ map iterator
sqrt cpp
access last element in vector in c++
stl for sorting IN C++
how to sort a vector in reverse c++
dynamically generating 2d array in cpp
how to make a n*n 2d dynamic array in c++
array 2d dynamic allocation c++
c++ optimization dynamic 2d array
c++ random
c++ vector pop first element
cpp pop front
c++ int to string
c++ vector iterator
gcd of two numbers c++
greatest common divisor c++
random in c++
how to sort a string in c++
accumulate c++
bold text latex
c++ remove whitespace from string
how to remove spaces from a string
c++ remove whitespace from string and keep the same size
max element in vector c++
underline in latex
format string cpp
convert binary to decimal c++ stl
flutter margins
how to sort in descending order c++
find length of array c++
c++ min
how to make a 2d vector in c++
c++ check if string contains substring
convert int to string c++
c++ how to generate a random number in a range
queue in c++
abs c++
how to check string contains char in c++
how to convert int to string c++
c++ random number between 1 and 10
how to iterate in string in c++
2d vector c++ declaration
cpp split string by space
c++ vector element search
Using find in Vector c++
c++ replace character in string
pi in c++
torch cuda is available
how to convert a string to a double c++
fast io c++
venge io
fast io++
convert a int to string c++
cpp rand
c++ check if string is empty
insert at position in vector c++
remove first element from vector c++
setw in c++
remove or erase first and last character of string c++
fork was not declared in this scope
fork c
undefined reference to `pthread_create' c++
convert int to binary string c++
convert string to number c++
for loop vector
how to print a decimal number upto 6 places of decimal in c++
c++ estimate deciimal to a point
std cout 2 digits float
C++ srand()
c++ rand
cpp random in range
Random in range C++
C++ random number generator
c++ rand()
C++ randomization
c++ get last character of string
size of 2d array in c++
length of 2d array c++
c++ remove last element from vector
inserting at start in vector c++
initialize 2d vector of ints c++
sort in descending order c++ stl
December global holidays
or in cpp
how to initialized a 2d vector
gcd function c++
count occurrences of character in string c++
how to check if a value is inside an array in c++
getch c++ library
clrscr in cpp
c++ file to string
c++ vector combine two vectors string get spaces c++
how to check datatype of a variable in c++
reverse c++ string
swap values in array c++
set precision in c++
c++ is string a number
Arduino LED code
convert string to stream c++
how to run a msi file raspbrain
honeygain linux
wine linux
iterating string in cpp
loop through char in string c++
taking user input for a vector in c++
initializing 2d vector
Count set bits in an integer.
setprecision in c++
cpp sample code
for loop with array c++
initialize all elements of vector to 0 c++
copy array c++
print data type of a variable in c++
how to iterate through a map in c++
recursive binary search
remove at index vector c++
cout was not declared in this scope
c++ code for selection sort
c++ code for insertion sort
double max value c++
reverse sort cpp
std string to const char * c++
print vector
cpp random number in range
how to write something in power of a number in c++
screen record ios simulator
best clips recording software for cs go
get type of variable in c++
fibonacci series in c++ Recursive
shuffle vector c++
vector unique in c++
jupyter lab use conda environment
initialize vector to all zeros c++
gcd recursion c++
string to vector c++
c++ initialize array with all zeros
void value not ignored as it ought to be
bits/stdc++.h visual studio
how to print a string to console in c++
c++ random between two values
how to get a random number between two numbers in c++
initialzing a 2d vector in cpp
number to binary string c++
char vector to string c++
Modulo Exponentiaon,Iteratve Modulo Exponentiation
binary exponentiation modulo m
binary exponentiation
make random nuber between two number in c++
sieve of eratosthenes c++
sum vector c++
arduino get size of array
c++ convert binary string to decimal
temporary mobile number
infinity c++
how to use comparator funtion in priority queue in c++
srand() c++
how to print items in arduino
check variable type c++
delete 2d dynamic array c++
how to delete a 2d dynamic array in c++
Length of int or decimal
length of number c++
how to get 4 decimal places in c++
find all occurrences of a substring in a string c++
c++ absolute value
c++ check if string contains uppercase
how to return 2d array from function c++
shuffle elements c++
how to make crypto
qt messagebox
qt qmessagebox
unordered_map of pair and int
include all libraries in c++
how to hide ui elements unity
capitalize first letter c++
extends c++
string count occurrences c++
iomanip
convert long int to binary string c++
c++ check first character of string
how to disable buttons in unity
appending int to string in cpp
border radius layout android xml
lopping over an array c++
how to traverse a linked list in c++
c++ round number up
no indentation latex
C++ Type Casting
cpp get data type
how to find typein c++
resize two dimensional vector c++
c++ compare strings ignore case
convert vector to set c++
angle to vector2 godot
rotation to vector2 godot
angle to vector2
Array sum in c++ stl
print 2d vector c++
c++ print every element in array
cpp binary tree
get elements of tuple c++
c++ unordered_map check if key exists
c++ generate random char
c++ display numbers as binary
generate random double c++
max value of double c++
stack implementation using linked list in cpp
max three values c++
quick sort c++
git branch in my bash prompt
prints all the keys and values in a map c++
string hex to int c++
c++ round number to whole
return the index where maximum element in a vector
c++ main function
c++ string to integer without stoi
insertion sort c++
get min and max element index from vector c++
delete a node from binery search tree c++
latex piecewise function
how to change string to lowercase and uperCase in c++
c++ print colorful
input 2d vector c++
Fibonacci in c++
qt debug
qdebug
how to convert character to lowercase c++
how to print numbers with only 2 digits after decimal point in c++
c++ milliseconds
repeat character n times c++
how to get a word from file c++
c++ chrono get milliseconds
std::string to qstring
Area of a Circle in C++ Programming
0009:err:mscoree:CLRRuntimeInfo_GetRuntimeHost Wine Mono is not installed
slice std::array cpp
vhdl integer to std_logic_vector
‘setprecision’ was not declared in this scope
prime number in c++
gcd and lcm in c++
how to print with the bool value in cpp
minimum value in array using c++
c++ messagebox
Messagebox windows
MessageBox
c++ allocate and free dynamic 2d array
how to get ipv4 address in php
program to convert int to int array c++
c++ reference
resizing dynamic array c++
c++ colour text
C++ red text output
c++ text formatting
C++ system text format
colourful text in c++
output coloured text in cpp
c++ bold text
c++ find minimum value in vector
how to specify how many decimal to print out with std::cout
how to easily trim a str in c++
c++ set console title
window title in c
c++ custom comparator for elements in set
c++ custom compare in set
float max value c++
check if an element is in a map c++
vector of int to string c++
c++ pi
tuple c++
read file into vector
sort a vector of strings according to their length c++
howt o initialize 3d vector in c++
lpcwstr to string c++
how to get command arguments c++
c++ find index of an element
check if double is integer c++
c++ find largest number in array
How to make copy constructor in c++
how to convert qt string to string
npm install error
cpp goiver all the map values
sfml draw line
find largest number in vector c++
c++ print byte as bit
fatal error: opencv2/opencv.hpp: No such file or directory
c++ cli convert string to string^
Optimized Bubble Sort
random number in a range c++
pyramid shape in c++
linked list with classes c++
select one random element of a vector in c++
how can I replace a pattern from string in c++
use regex replace in c++
Vector2 c++
c++ virtual function in constructor
hwo to calculate the number of digits using log in c++
int_min in cpp
watermelon codeforces solution
you wanna import math on c++
get first element of tuple c++
C++ Default Parameters
c++ erase last element of set
separation between paragraphs latex
flake8 max line length
compare float values c++
c++ int to qstring
int to qstring
c++ evaluate expression
singleton c++
include spaces while reading strings in cpp
c++ product of vector
c++ check if string contains non alphanumeric
vector with pinter cout c++
error: ‘memset’ was not declared in this scope in cpp
sfml mouse click
2d vector c++ size
qt int to string
c++ stream string into fiel
minimum and maximum value of a vector in C++
elixir update map
print std map
cpp take lambda as parameter
loop over multidimensional array c++
c++ fill array with 0
calculate time difference cpp
c++ string to wstring
c++ 2d vector assign value
C++ Math
binary search return index c++
round all columns in R dataframe to 3 digits
web scraping with cpp
copy 2 dimensional array c++
split vector in half cpp
add partition mysql
c++ convert int to cstring
isprime c++
how to downgrade numpy
regex match all between parentheses
c++ pointer null vs nullptr
add on screen debug message ue4
delete a head node in link list
frequency of a substring in a string c++
ue4 log float
random c++
initialize 2d array c++ memset
C++ Split String By Space into Vector
C++ Swap 2 Variables Without Using 3rd Variable
Arduino Sring to const char
internet explorer
how to check sqrt of number is integer c++
precision of fixed in c++
go read file to string
cpp mst
c++ mst kruskal
c++ competitive programming mst
c++ kruskal algorithm
kruskal in c++
interpreter latex matlab
minimum spanning trees c++
c++ std::sort
sfml draw tex
how to get a letter from the user c++ string
how to get a letter from the users string in c++
How to find the individual letters of a string c++
c++ random number generator uniform distribution
tarray ue4 c++
Runtime Error: Runtime ErrorBad memory access (SIGBUS)
qlabel set text color
qt popup window
qt label set text color
c++ string erase all occurrences
qlabel font color
iff arduino
how to cehck if list has element c++
crypto npm random bytes
c++ initialize array 1 to n
recursive power in c++
string to wstring
integer type validation c++
swap using Function template in c++
typedef vector c++
c++ enum rand
winmain example
I2c scanner arduino
if not defined c++
vector of structs c++
c++ std::find with lambda
how to speed up cin and cout
c++ set intersection
sum of stack c++
to_string c++
c++ round number down
convert int to enum c++
landscape overleaf
Programs for printing pyramid patterns in C++
c++ swapping two numbers
('Failed to import pydot. You must `pip install pydot` and install graphviz (), ', 'for `pydotprint` to work.')
check if point is left or right of vector
how to get double y dividing 2 integers in c++
vbs check if file exists
excel vba delete worksheet if exists
g++ optimization flags
c++ main environment variables
c++ addition
c++ print vector without loop
mpi_bcast
what is the short cut way to find the max and min element in an array in c++
how to iterater map of sets in c++
change to lowercase in notepad++
delete map elements while iterating cpp
whole size of the internet
count bit 1 c++
c++ print number not in scientific notation
eosio multi index secondary index
C++ Area of a Rectangle
print linked list recursively c++
how to find index of a vector in c++
all of the stars lyrics
print space in array cpp
unambiguous
arduino sprintf float
C++ Area of Triangle
qt double en qstring
prime number generator c++
Matrix multiply using function c++
pointers in c++
how to print fixed places after decimal point in c++
qstring to char*
input pdf latex
coordinate in 1d array c++
Sort array using inbuilt sort function in decreasing order
coordinate in 1d array
spicoli
check if intent has extras
1d array
taking a vector in c++ containing element
rank() in c++
C++ structure (Struct)
cout char32_t c++
how to check is some number is divisible by 3 in c++
c++ find_if
iterate vector from end to begin
python
c++ how to loop through a vector but not the last element
why do we use pointers in c++
platform io change baud rate
c++ primality test
quotation in c++ string
Find first and last digit of int
cpp vs c#
how to loop a 2 dimensional vector in c++ starting from second element
operator overload
C++ String Copy Example
C++ Constructors
cpp cout more than 1 value
max pooling in c++
bootstrap
C++ Converting Centimeters to Meters
height of the tree
c++ program to convert fahrenheit to kelvin
sort a 2d vector c++ stl
c to c++ code converter
whatsup
flutter margins
what are various sections of process
euclid algorithm
access first value in a set c++
unreal get eobjecttypequery cpp´
how to initialize 2d array with values c++
sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument]
get rest of a stringstream c++
How to get the last element of an array in C++ using std::array
c++ function as paramter
c++ take n number from the user and store them in array and get the max, min number of them and also find the average/summation of these numbers
std::hash
memset array bool
find text in string c++ true false
c++ std::sort
accepting multiple values from a function in cpp
how can we create 4 digit random number in c++
sort vector in reverse order c++
shuffle elements c++
unity decompile il2cpp
prisma client
file transfer socat
convert fahrenheit to celsius
replace character in a string c++ stack overflow
C++ Point to Every Array Elements
random number of 0 or 1 c++
c++ code 2d block
python remove repeated characters from string
type casting in cpp
copy constructor for vector c++
sum function in c++
c++ string find last number
max circular subarray sum gfg practice
Lucky Four codechef solution in c++
c++ round number down
bfs sudocode
huffman encoding in c++
c++ vector extend vector
remove a element from an array c++
class operator overloading c++
bitwise count total set bits
binary search return index c++
all in one c++
number triangle c++
'to_string' was not declared in this scope
stack in c++
convert decimal to binary in c++
cpp print vector
programs using vectors in c++
invalid next size (normal) c++
decemal representation
even and odd numbers 1 to 100
left margin c++
get an array with c++
beecrowd problem 1001 solution
is the c++ 20 char te same as the old one
rand() cpp 10 and 100 inclusive
C++ Assignment Operators
c++ program to generate all the prime numbers between 1 and n
erosion and dilation c++
a function to create double quotes for alphabet in c++
C++ Structures (struct)
add on screen debug message ue4
qt get hexa value from qstring
c++ loop through array
how to use dec in C++
initalising array c++
what is the time complexitry of std::sort
c++ random number generator uniform distribution
qt qmessagebox
sieve of eresthossis cp c++
tic tac toe in cpp
c++ default array value not null
C++ red text output
OPA in expanse
c++ standard library source
C++ random
best clips recording software for cs go
convert wchar_t to to multibyte
how to scan vector in c++
cpp tutorial
built in function in c++ for binary to decimal
c++ struktura kolejki
sideways triangle c++ xy plane
rotateArray
toupper c++
choose endianness in cpp
how print fload wiht 3 decimal in c++
age in days in c++
Find N Unique Integers Sum Up to Zero
how to round a double to 2 decimal places in c++
rotate an array of n elements to the right by k steps
permutation in c++ with backtracking
arrow operator c++
FACTORIAL IN C++
initialise a vector c++
know what the input data is whether integer or not
return by reference in cpp
flutter date format
never gonna give you up
level order traversal of binary tree c++
high school hacking competition
maximum subarray leetcode c++
c++ graphics online compiler
how to get a word from file c++
nth fibonacci number
c++ add to array
how to make c++ read strlen
print vector
variables in c++
cpp sample code
stoi
what is ++i and i++
how to make an enum in c++
Valid Parentheses leetcode in c++
length of number c++
c++ convert int to cstring
char type casting in c++
c++ friend class
convert c++ to python online
floor and ceil in cpp
how to remove special characters from a string
pointers and arrays in c++
c++ remove last character from string
int to string Using to_string method
binary to int c++ bitset
how to get mouse position on window sfm;
&& in cpp
std string to const char * c++
c++ online compiler
data types ranges c++
get range sum
how to convert string to int in c++
C++ area & circumference of a circle
Program To Calculate Number Power Using Recursion In C++. The power number should always be positive integer.
watermelon codeforces solution
how to code string to int converter c++
the amount of input is unknown
read a whole line from the input
c++ find largest number in array
what is 10 + (-4)
ubuntu dotnet create blazorserver linux
pointer
pointeur cpp
c++ matrix as argument
intersection between vector c++
Implementation of Extended Euclidian theorem
ascii allowed in c++
1822. Sign of the Product of an Array leetcode
split string on character vector C++
cplusplusbtutotrail
how to modify set C++
random key generator c++ all unique characters
convert string toupper and tolower in cpp
call function from separate bash script
malloc in c++
c++ erase last element of set
recuva recovery software for pc with crack
how to create a structure c++
C++ program to print all possible substrings of a given string
c++ nerds
remove duplicates from sorted list solution in c++
how to declare a 2d boolean vector in c++
operator using
Hash Sort in C++
gcd and lcm in c++
ue4 execute delegate from blueprint
reverse string upper to lower
how to output to a file in c++
Temparory Email Id
quick_sort
what type is this c++
big o notation practice c++
how to print double value up to 9 decimal places in c++
initialize string with length c++
how to convert malloc function to cpp
find max value in array c++
grep xargs sed
stl for sorting IN C++
i++ and++i
malloc 2d array cpp
C++ Area of Triangle
c++ evaluate expression
83. remove duplicates from sorted list solution in c++
is power of 2
convert std vector to array
remove element from array c++
dijkstra algorithm in c++ geeksforgeeks
. | https://www.codegrepper.com/code-examples/cpp/c%2B%2B+add+input+in | CC-MAIN-2022-27 | en | refinedweb |
Indexing of ndarrays can be done using the standard python x[obj] syntax, where x is the array and obj the selection.
There are three kinds of indexing available −
What kind of indexing will be there depends on obj. In this section, we are going to mainly concentrate on basic slicing & advanced indexing.
We can divide advanced indexing into two parts −
Python basic concept of slicing is extended in basic slicing to n dimensions. As with python slice object which is constructed by giving a start, stop & step parameters to slice function. To get specific output, the slice object is passed to the array to extract a part of an array.
import numpy as np arr = np.arange(25) s = slice(2, 21, 4) print (arr[s])
[ 2 6 10 14 18]
In the above example, we first created a ndarray object (arr) using arange() function. Then a slice object is created by assigning start, stop and step value to it (s). When we passed the slice object to the ndarray, we get part (slice) of the array starting with index 2 up to 21 with a step of 4.
Another way to write the above program,
# Another way to write above program import numpy as np arr = np.arange(25) s = arr[2:21:4] print (s)
[ 2 6 10 14 18]
#Slice single item from an array import numpy as np arr = np.arange(10) s = arr[9] print(s)
9
#slice item starting from index import numpy as np arr = np.arange(10) s = arr[3:] print(s)
[3 4 5 6 7 8 9]
#slice item between indexes import numpy as np arr = np.arange(10) s = arr[3: 7] print(s)
[3 4 5 6]
Above two methods will be applied to multi-dimensional ndarray too, like below −
#slice item between indexes import numpy as np arr = np.array([[[1],[2],[3]], [[4],[5],[6]], [[7], [8], [9]]]) s = arr[1:] print(s)
[[[4] [5] [6]] [[7] [8] [9]]]
Integer array indexing:
Let’s create a simple array with integers
arr=np.array([[1,2],[3,4],[5,6]]) print(arr)
[[1 2] [3 4] [5 6]]
Let’s try to select a specific element from the array, like elements with row index [0, 1, 2] and column index [1, 0, 1] from the multidimensional ndarray.
import numpy as np arr=np.array([[1,2],[3,4],[5,6]]) s = arr[[0, 1, 2],[1, 0, 1]] print(s)
[2 3 6]
Selecting with 0 indexes will give you first row −
>>> arr=np.array([[1,2],[3,4],[5,6]]) >>> print(arr[0]) [1 2]
Similarly, we can select a single item from the array, for example- select the 1 as row index and 1 as the column index element which gives an array value of 4.
>>> print(arr[[1], [1]]) [4]
We can arithmetic operation like addition and returns the value of a particular index after performing the addition.
>>> print(arr[[1], [1]]+ 1) [5]
As we can see the index value is incremented by 1 but the actual array remains the same.
>>> arr array([[1, 2], [3, 4], [5, 6]])
But we can change the values of the array and returns the new copy of an array.
>>> arr[[1], [1]] +=1 >>> arr array([[1, 2], [3, 5], [5, 6]])
We used boolean indexing when the result is going to be the outcome of boolean operations.
>>> arr=np.array([[0,1,2], [3,4,5], [6,7,8], [9,10,11]]) >>> arr array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]])
Returns the values which are 1.
>>> arr[arr == 1] array([1])
Returns the values which are even numbers
>>> arr[arr %2 == 0] array([ 0, 2, 4, 6, 8, 10]) | https://www.tutorialspoint.com/basic-slicing-and-advanced-indexing-in-numpy-python | CC-MAIN-2020-50 | en | refinedweb |
[DISCLAIMER:Please Note: Any Image/data in this presentation/video is from SAP internal systems, sample data, or demo systems. Any resemblance to real data is purely coincidental]
Dear All,
In this blog, I would like to explain the steps to create extension field in supplier invoice excel template in SAP Business ByDesign System.
Agenda:
- Pre-Requisite
- Steps to add extension field in supplier invoice excel
Pre-Requisite:
Add the extension field via Adaption Mode and add the field in Inbound Services as per below screenshot:
Steps to add extension field in Excel:
In the below case, we have taken the header extension field ‘Test_SIV_PDI’ as example.
- Go to Supplier Invoicing work center -> select view: Invoices and Credit memos.
- Download the excel template from ‘Import from Microsoft excel’ option as per below screenshot.
3. Once the file is downloaded, open the file location and rename .xlsx to .zip. This will automatically convert the excel file to zip and open it with your preferred zip tool.
XML file location: NewSupplierInvoices_US_EN.zip\xl
4. Extract the XML file to specified folder and edit the same using Notepad ++ .
a) We need to add the field as part of the structure as mentioned below:
<xs:element minOccurs=”0″ maxOccurs=”1″ name=”Test_SIV_PDI” type=”xs:string”/>
b)There is one more change necessary in the xmlMaps.xml , in the transformations section.
<xsl:template match=”Test_SIV_PDI”> <xsl:element namespace=”” name=”Test_SIV_PDI”> <xsl:value-of select=”.”/>
</xsl:element>
</xsl:template>
5. Replace the XML in that zip and rename it from .zip to xlsx
6. Open the excel file and go to Developer->Source. You would be able to see extension field in XML maps ‘SAP_BYD_MAIN’.
Note: If you are unable to see, select it from the drop-down list.
As of now, the extensibility function is not provided in standard invoice upload excel file , hence , please contact your bydesign partner to implement the above steps as per your business requirement.
You can also check following blogs related to excel scenarios: | https://blogs.sap.com/2020/03/05/how-to-add-extension-field-in-supplier-invoice-upload-excel-template/ | CC-MAIN-2020-50 | en | refinedweb |
!- Search Loader --> <!- /Search Loader -->
At my workplace, we are upgrading the Intel TBB library to Version 2020. After integrating the library we have started seeing deprecation warnings on all the platforms. On windows (MS Visual Studio 2017), these warnings are treated as error and on macOS (XCode 10.14) , Linux (GCC 6.3) these are warnings are displayed as harmless pragma message. For ex. on Windows the warning will be as below
1: foo.cpp 2: c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\exception(375): warning C4996: 'tbb::captured_exception::~captured_exception': was declared deprecated 3: C:\path\tbb\include\tbb\tbb_exception.h(206): note: see declaration of 'tbb::captured_exception::~captured_exception' 4: C:\path\tbb\include\tbb\tbb_exception.h(345): note: see reference to function template instantiation 'std::exception_ptr std::make_exception_ptr<tbb::captured_exception>(_Ex) noexcept' being compiled 5: with 6: [ 7: _Ex=tbb::captured_exception 8: ]
On linux and macOS
../path/tbb/include/tbb/task_scheduler_init.h:21:154: note: #pragma message: TBB Warning: tbb/task_scheduler_init.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual. #pragma message("TBB Warning: tbb/task_scheduler_init.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.")
While Linux and macOS are OK for the time being, (as we will migrate to newer or standard library features as suggested in the warnings and Intel TBB Webpages here and here) whats concerning us is the warnings on the Windows platform as mentioned above. There are more than 1200 instances of this particular warning and all of them are emanating Intel TBB header file tbb_exception.h.
The warning is highlighting
1) MSVC's header file exception since tbb_exception.h's deprecated classes are using exception header's classes
2) Any header file that includes tbb_exception.h e.g. concurrent_map.h
We are aware that we can suppress these warnings via TBB_SUPPRESS_DEPRECATED_MESSAGES macro.
Having said all this, is the TBB development team aware of this issue of warnings and this particular warning emanating from tbb_exception.h ?
If yes, do they plan to get rid of these warnings in the future version of TBB library ?
Hello,
We are transitioning to oneTBB: with what we call revamped TBB API. Please see the document that you can access from the link mentioned here:
or directly
In oneTBB these features that you see now as deprecated -- will be removed. So longer turn we hope that you can consider switching to new API. Please let us know if you see any problems with this proposal. Meanwhile, we will continue to support old API with TBB 2020 product (and earlier versions).
Are you concerned that there are too many messages about deprecation are printed? Were you aware of the information above?
Hello,
Both cases look strange, could you provide more details regarding build environment (compiler version, OS version, build options)?
Hi folks,
Thanks for your response.
1) I have updated the post with "Small standalone reproducible example". It contains info regarding build environment (compiler version, OS version, build options).
The thing that we have observed is that it if we include any TBB header after standard exception header i.e.
#include <exception> #include "tbb/concurrent_queue.h"
it blurts out this warning from the header file tbb_exception.h. If the order is reversed, warning disappears.
Let us know if there are any workaround(s) or separate flag to get rid of this warning. Or is there just one flag for now i.e. TBB_SUPPRESS_DEPRECATED_MESSAGES ?
2) Yes we are aware of TBBRevamp.pdf document and we are going to recommend our developers to change their code to honor that :)
Hi Recker,
These extra warnings were caused by environmental issues in some VS versions.
Thank you for reporting!
This problem will be solved in future releases.
Thanks for your response. One more thing, for the same platform and compiler combination(s) a small code like below will blurt out the #pragma message
#include "tbb/atomic.h" int main() { return 0; }
Linux :
tbb/include/tbb/atomic.h:21:141: note: #pragma message: TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual. #pragma message("TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.")
Windows
TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.
This is ok since the whole header is getting deprecated. | https://community.intel.com/t5/Intel-oneAPI-Threading-Building/Intel-TBB-Version-2020-Warnings/td-p/1182898 | CC-MAIN-2020-50 | en | refinedweb |
Repeat a scipy csr sparse matrix along axis 0
sort sparse matrix python
scipy sparse multiply matrix
compressed sparse row format to numpy array
scipy csr to csc
scipy matrices
numpy sparse tensor
matlab sparse in python
I wanted to repeat the rows of a scipy csr sparse matrix, but when I tried to call numpy's repeat method, it simply treats the sparse matrix like an object, and would only repeat it as an object in an ndarray. I looked through the documentation, but I couldn't find any utility to repeats the rows of a scipy csr sparse matrix.
I wrote the following code that operates on the internal data, which seems to work
def csr_repeat(csr, repeats): if isinstance(repeats, int): repeats = np.repeat(repeats, csr.shape[0]) repeats = np.asarray(repeats) rnnz = np.diff(csr.indptr) ndata = rnnz.dot(repeats) if ndata == 0: return sparse.csr_matrix((np.sum(repeats), csr.shape[1]), dtype=csr.dtype) indmap = np.ones(ndata, dtype=np.int) indmap[0] = 0 rnnz_ = np.repeat(rnnz, repeats) indptr_ = rnnz_.cumsum() mask = indptr_ < ndata indmap -= np.int_(np.bincount(indptr_[mask], weights=rnnz_[mask], minlength=ndata)) jumps = (rnnz * repeats).cumsum() mask = jumps < ndata indmap += np.int_(np.bincount(jumps[mask], weights=rnnz[mask], minlength=ndata)) indmap = indmap.cumsum() return sparse.csr_matrix((csr.data[indmap], csr.indices[indmap], np.r_[0, indptr_]), shape=(np.sum(repeats), csr.shape[1]))
and be reasonably efficient, but I'd rather not monkey patch the class. Is there a better way to do this?
Edit
As I revisit this question, I wonder why I posted it in the first place. Almost everything I could think to do with the repeated matrix would be easier to do with the original matrix, and then apply the repetition afterwards. My assumption is that post repetition will always be the better way to approach this problem than any of the potential answers.
from scipy.sparse import csr_matrix repeated_row_matrix = csr_matrix(np.ones([repeat_number,1])) * sparse_row
scipy.sparse.csr_matrix, with another sparse matrix S (equivalent to S.tocsr()) is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] csr_matrix((data, indices, indptr), dtype=int).toarray() array([[2, 1, 0, 0], [0, 1, 1, 1]]) Return indices of maximum elements along an axis. Returns a copy of row i of the matrix, as a (1 x n) CSR matrix (row vector). log1p Element-wise log1p. max ([axis, out]) Return the maximum of the matrix or maximum along an axis. maximum (other) Element-wise maximum between this and another matrix. mean ([axis, dtype, out]) Compute the arithmetic mean along the specified axis. min ([axis, out])
It's not surprising that
np.repeat does not work. It delegates the action to the hardcoded
a.repeat method, and failing that, first turns
a into an array (object if needed).
In the linear algebra world where sparse code was developed, most of the assembly work was done on the
row,
col,
data arrays BEFORE creating the sparse matrix. The focus was on efficient math operations, and not so much on adding/deleting/indexing rows and elements.
I haven't worked through your code, but I'm not surprised that a
csr format matrix requires that much work.
I worked out a similar function for the
lil format (working from
lil.copy):
def lil_repeat(S, repeat): # row repeat for lil sparse matrix # test for lil type and/or convert shape=list(S.shape) if isinstance(repeat, int): shape[0]=shape[0]*repeat else: shape[0]=sum(repeat) shape = tuple(shape) new = sparse.lil_matrix(shape, dtype=S.dtype) new.data = S.data.repeat(repeat) # flat repeat new.rows = S.rows.repeat(repeat) return new
But it is also possible to repeat using indices. Both
lil and
csr support indexing that is close to that of regular numpy arrays (at least in new enough versions). Thus:
S = sparse.lil_matrix([[0,1,2],[0,0,0],[1,0,0]]) print S.A.repeat([1,2,3], axis=0) print S.A[(0,1,1,2,2,2),:] print lil_repeat(S,[1,2,3]).A print S[(0,1,1,2,2,2),:].A
give the same result
and best of all?
print S[np.arange(3).repeat([1,2,3]),:].A
scipy.sparse.bsr_matrix, BSR is appropriate for sparse matrices with dense sub matrices like the last example below. more efficient than CSR and CSC for many sparse arithmetic operations. 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, argmax ([axis, out]), Return indices of minimum elements along an axis. Format of a matrix representation as a string. Maximum number of elements to display when printed. Number of stored values, including explicit zeros. Returns a copy of row i of the matrix, as a (1 x n) CSR matrix (row vector). Element-wise log1p. Return the maximum of the matrix or maximum along an axis.
After someone posted a really clever response for how best to do this I revisited my original question, to see if there was an even better way. I I came up with one more way that has some pros and cons. Instead of repeating all of the data (as is done with the accepted answer), we can instead instruct scipy to reuse the data of the repeated rows, creating something akin to a view of the original sparse array (as you might do with
broadcast_to). This can be done by simply tiling the
indptr field.
repeated = sparse.csr_matrix((orig.data, orig.indices, np.tile(orig.indptr, repeat_num)))
This technique repeats the vector
repeat_num times, while only modifying the the
indptr. The downside is that due to the way the csr matrices encode data, instead of creating a matrix that's
repeat_num x n in dimension, it creates one that's
(2 * repeat_num - 1) x n where every odd row is 0. This shouldn't be too big of a deal as any operation will be quick given that each row is 0, and they should be pretty easy to slice out afterwards (with something like
[::2]), but it's not ideal.
I think the marked answer is probably still the "best" way to do this.
scipy.sparse.csr_matrix, Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, Disadvantages of the CSR format csr_matrix( (3,4), dtype=int8 ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=int8) max([axis]), Maximum of the elements of this matrix. Last updated on May 11, 2014. scipy.sparse.bsr_matrix format is very similar to the Compressed Sparse Row (CSR) format. Return the maximum of the matrix or maximum along an axis.
scipy.sparse.dia_matrix, with another sparse matrix S (equivalent to S.todia()) data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0) >>> offsets = np.array([0, -1, 2]) >>> dia_matrix((data, offsets), Compute the arithmetic mean along the specified axis. Sum the matrix elements over a given axis. Parameters axis {-2, -1, 0, 1, None} optional. Axis along which the sum is computed. The default is to compute the sum of all the matrix elements, returning a scalar (i.e. axis = None). dtype dtype, optional. The type of the returned matrix and of the accumulator in which the elements are summed.
scipy.sparse.coo_matrix, COO is a fast format for constructing sparse matrices Constructing a matrix with duplicate indices >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) >>> col = np.array([0, 2, 1, 3, 1, 0, Return indices of maximum elements along an axis. scipy.sparse.csr_matrix.mean¶. Compute the arithmetic mean along the specified axis. Returns the average of the matrix elements. The average is taken over all elements in the matrix by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.
scipy.sparse.bsr_matrix, BSR is appropriate for sparse matrices with dense sub matrices like In such cases, BSR is considerably more efficient than CSR and CSC for many sparse arithmetic operations. 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, Return indices of maximum elements along an axis. cupyx.scipy.sparse.spmatrix axis (int or None) – Axis along which the sum is comuted. Convert this matrix to Compressed Sparse Row format.
- Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
- this answer only works when the sparse matrix to be repeated is actually a sparse vector. just using basic linear algebra...
- @user3357359 if you're repeating a sparse vector, it's seems much quicker to just do something like
sparse_row[np.zeros(repeat_number),:]
S[np.arange(3).repeat([1,2,3]),:]is genius, and in some quick testing was also much faster than my method. | http://thetopsites.net/article/50759652.shtml | CC-MAIN-2020-50 | en | refinedweb |
In this blogpost I’m going into details for a specific part of the End-To-End implementation – how to install apps from within an app. In a previous post I described the allover scenario to set up a full CI/CD chain for an IoT application running on Windows 10 IoT Core, orchestrated by Visual Studio Team Services. If you are already familiar with UWP apps you might wonder how installation of a new application is realized on Windows IoT Core. (If you are not working with Windows 10 IoT Core as your IoT platform you may have to come up with a similar solution for your device/platform. )
On Windows 10 devices in general capabilities of Universal Windows Apps are limited per default for security reasons. Part of the unavailable functionality is installation of software directly from a downloaded file, this means it is not possible to simply download an app and then trigger the installation of that downloaded app from within a running application without user interaction. To recap: This is exactly what we want in our IoT Scenario. I want to update the application without any user interaction based on a downloaded file.
However Windows 10 IoT Core gives you (the developer) control over the device and you can access additional capabilities if you explicitly allow them for your application. So what I basically have to do is two things.
- I have to add additional capabilities within the app manifest
- In this specific case I have have to add a special registry key on all devices to allow installation of apps from within an app
While #1 is not a problem at all and clearly just a developer task #2 might make you frown because you could think it is something that has to be done manually. If we stick with the refrigerator sample this would mean I have to add registry keys in millions of refrigerators. First it’s important to know that this has to be done only once per devices. Second of course this isn’t something you would do manually instead you could e.g. put this into a custom Windows 10 IoT Image you might be providing for your device anyway.
It’s important to note that besides the application which will be the IoT application you are really working on (e.g. the refrigerator control) I’m using a second application which handles installation and updates of the refrigerator control. While the Refrigerator App is really “just” a normal app, the second Installer App” has extended capabilities. This app is also required to communicate with IoT Hub.
Modifing the *.appxmanifest
To add the additional capabilities add the following namespaces in your app manifest of your Installer app.
xmlns:iot="" xmlns:rescap=
and add iot and rescap to the list of ignorable namespaces. You have to do this in XML there’s no UI for that. Use the context menu to switch between code view and design view.
After adding the namespaces add the following capabilities in the capabilities section of your manifest:
<iot:Capability
<rescap:Capability
Modifing the device registry
Now you have to modify the registry on your IoT Device. You need the installation folder of your application. Therefore you can either simply deploy your app to the device and remote into the system (e.g. via Powershell) to find out the path or you guess it based on the default values.
You add the key by running a command like this on Powershell remoted into your device :
REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\EmbeddedMode\ProcessLauncher" /v AllowedExecutableFilesList /t REG_MULTI_SZ /d "c:\windows\system32\applyupdate.exe\0c:\windows\system32\deployappx.exe\0c:\installer\appinstall.cmd\0c:\Data\Users\DefaultAccount\AppData\Local\Packages\PACKAGEFAMILYNAME\LocalState\installer\AppInstall\appinstall.cmd\0"
This key contains executables which are allowed to run. You have to add the correct path to your executable which executes the installation. In my case I’m downloading the appinstall.cmd and the app from FTP into the LocalState folder of my installer app. Therefore I have to adjust the path using the Package Family Name of the installer App (as found in appxmanifest, see below) and had to adjust the path to the *.cmd depending on the directory structure I’m using in my downloaded files.
When you have completed this you made sure your installer app is now able and allowed to install apps on your target device.
Installing an app from within an app
To trigger the installation what you do is just call the process launcher and pass in the path to your executable which installs the app. In my case as stated above, this is the appinstall.cmd file.
// var cmd = something like …\LocalState\installer\AppInstall\appinstall.cmd” depending on your structure
var result = await ProcessLauncher.RunToCompletionAsync(cmd, args);
You may wonder where I got that appinstall.cmd file from. This is something that my private build agent creates which has the Windows 10 ADK installed.
This post showed you how to set up an installer app which can install and update another app. This is one of the key “tricks” to get the scenario working if you’re using Windows 10 IoT Core. If you’re not using Windows 10 IoT Core you might have to deal with challenges differently to get an app installed without user interaction. I will point out other interesting aspects of the full DevOps scenario in a subsequent post. | https://blogs.msdn.microsoft.com/dmx/2017/01/30/devops-for-iot-part-2-installing-an-app-from-within-an-app/ | CC-MAIN-2017-34 | en | refinedweb |
Here is a problem im working on for my intro to java class:
1.Design a class named Location for locating a maximal value and its location in a twodimensional
array. The class contains:
2.Private data fields row and column that store the indices it a two dimensional
array as int type.
3.A no-arg constructor that creates a location with default values.
4.A constructor with the arguments for row and column.
5.The method named locateLargest(double [][] x) that returns the location of the
largest element in a two-dimensional array. The return value is an instance of
Location. This method should also print the largest value of the array.
2/3
The method is: public Location locateLargest(double [][] x) {}
6.A toString() method that prints a Location object in the form [row][column].
My code:
Code :
package classAssignment; import java.util.Scanner; public class Location { private int row; private int column; private int[][] array = new int[row][column]; public static void main(String[] args) { Scanner numberInput = new Scanner(System.in); System.out.println("Enter the number of rows and columns of the array: "); int row = numberInput.nextInt(); int column = numberInput.nextInt(); Location l1 = new Location(row, column); }//end main Location(){}//end constructor Location(int row, int column){ this.row = row; this.column = column; }//end arg constructor public Location locateLargest(double[][] x){ double max = 0; for (int i = 0; i < x.length; i++){ for (int j = 0; j < x.length; i ++){ if (x[i][j] > max) max = x[i][j]; } } return x; }//end locateLargest() public int getRow(){ return this.row; }//end getRow() public int getColumn(){ return this.column; }//end getColumn() }//end class
My problem is in the locateLargest method. I can't return the max because it is of type location and I have no idea how to convert it into a double. I've even tried declaring the array in multiple other places like in another class or in the locateLargest method itself but those ideas didn't work either. Any help would be appreciated. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/33812-type-mismatch-problem-printingthethread.html | CC-MAIN-2017-34 | en | refinedweb |
In the current version of Gecko, the XML serializer is used to serialize XHTML content. However, it doesn't serialize like the HTML serializer does for HTML documents (pretty-printing, specific serialization for some tags etc.) so it isn't really usefull for Composer. I'm going to fix this bug. I think I will create a new nsXHTMLContentSerializer class. It will support features of nsHTMLContentSerializer, and of course will take care of all XML stuff like namespaces etc.
After working few hours on the serializers, I decided to make improvements in the XML serializer at the same time, to do pretty printing, wrapping etc. In fact, I need it for my wysiwyg XML editor (ETNA).
Created attachment 330248 [details] [diff] [review] Work in progress #1 First patch. It is not finished. Worked only on the XML serializer so I didn't updated mochitests for the HTML serializer. Indentation doesn't work very well and then some xpcshell tests fail for the XML serializer. You need to apply the patch for bug 424359 before applying this patch.
Created attachment 334297 [details] [diff] [review] Work in progress #2 The XML serializer is almost finished. Indentation is better than in the old HTML serializer (text content is well indented). Some tests should be still added to check attributes and namespaces serialization. I worked on the HTML serializer but it's not finished.
Created attachment 335045 [details] [diff] [review] Work in progress #3 HTML and XML serializers are fines now. All tests pass :-) I'm working now on a new nsXHMLContentSerializer class, which will inherit from nsXMLContentSerializer and nsHTMLContentSerializer will inherit from nsXHTMLContentSerializer.
Created attachment 338851 [details] [diff] [review] the patch, version 1.0 I think my patch is ready for a first review. Remember that you need to apply the patch for bug 424359 before applying this patch. So, what's this patch doing ? - it adds a new content serializer for XHTML : there is a new class nsXHTMLContentSerializer which inherits from nsXMLContentSerializer. This serializer is called only for pages which have a application/xhtml+xml content type. This serializer respects the XML serialization specification, but also specificities of HTML serialization (pre elements, script elements etc..). - most of features of nsHTMLContentSerializer are moved into the XML serializer, or into the XHTML serializer. - nsHTMLContentSerializer now inherits from nsXHTMLContentSerializer. - the XML serializer supports now this flags : OutputFormatted, OutputWrap (+ OutputLFLineBreak and OutputCRLineBreak added by the patch of bug 424359) - indentation and wrapping are better (there were some problems in the HTML serializer). - unit tests are added (and I will add more tests later) - documentation of flags on nsIDocumentEncoder is updated
Created attachment 342079 [details] comments See comments in the attachment This is so huge patch that few iterations are needed. Sorry that reviewing has taken so much time.
> This is so huge patch that few iterations are needed. > Sorry that reviewing has taken so much time. Don't worry, no problem, I understand :-) Here are responses to some of your questions in your comments. > But why does OutputRaw wrap? How is XHTML handled. There isn't any wrap when you set the OutputRaw flag. But if you don't set any flags (no OutputFormatted, no OutputRaw, no OutputWrap), it acts like OutputRaw but it wraps long lines. And I don't know why, so I just kept the current behavior. Perhaps it is related to the editor, or mail... > do we really want HTML entities in XHTML? Yes, the specification of XHTML says : "The XHTML entity sets are the same as for HTML 4". >Actually, why are these no-op? What if CDATA or PI is added to an HTML document using scripts? > How does this work currently? Sorry, I thought that SGML didn't support CDATA or PI, and this is not the case, according to the specification, even if the HTML specification says that the user agent should ignore them. The current HTML serializer supports CDATA and PI. I will remove this empty methods. >And when is mozdirty used? We really shouldn't have anything like that. > It might be better to use some property in a content object. (Set/GetProperty) We already talked about it on irc :-). I created a new bug 459212 >+nsXHTMLContentSerializer::AppendEndOfElementStart(nsIDOMElement *aOriginalElement, >+... >But this method is in XHTML serializer, not HTML. Yes, of course, because the end of an HTML element is always ">", so we don't need this method in the HTML serializer. The behavior of this methods is for old HTML browser which doesn't support XHTML. >Make sure this all works with nested bodies and when there are several sibling bodies. (Maybe you're testing that, haven't yet read the tests) Yes there are tests, which are provided by the patch of bug 424359. >+ // for backward compatibility with old HTML user agents, >+ // empty elements should have an ending tag, so we mustn't call >+ // nsXMLContentSerializer::CheckElementEnd >But this is XHTML serializer. Why do we need to care about HTML UAs? Why not ? It is needed by the editor, to generate pages that can be viewed in old HTML UAs. If a web developer creates a page with Mozilla Composer, BlueGriffon or else, I think he would like to see his page in his old browser (well, there are some chance that the rendering is not the expected one, but if we can minimize unexpected behaviors, at least by doing a good serialization for this old browsers...). >+void >+nsXHTMLContentSerializer::IncrIndentation(nsIAtom* aName) > ... >Why most /***/? Should you check namespace? In fact, I hesitate: we can increment indentation on only few elements, but is it really necessary ? I don't know. I will attach a new patch with all corrections you ask in your other comments. It is almost ready, I just have to add new tests.
Created attachment 342862 [details] [diff] [review] version 1.1 It fixes bad things pointed by Olli: bad spelling in a comment, style nits, indentation, assignement of the forceFormat attribute, namespace checking in various methods, new test with a <pre> from an other namespace. Thank you Olli for your review
Comment on attachment 342862 [details] [diff] [review] version 1.1 I will update the patch tomorrow, since some changes have been made on the patch of bug 424359.
Created attachment 343031 [details] [diff] [review] patch 1.2 : updated after changes on the patch of bug 424359
Comment on attachment 343031 [details] [diff] [review] patch 1.2 : updated after changes on the patch of bug 424359 Please use -P when generating patches. Whenever casting is needed, use C++ style (static_cast<> etc.), not C's '()'. >- if (mIsCopying && mIsFirstChildOfOL && (aTagName == nsGkAtoms::li) && >- (attrName == nsGkAtoms::value)){ >+ if (mIsCopying && mIsFirstChildOfOL && (aTagName == nsGkAtoms::li) >+ && (attrName == nsGkAtoms::value)) { No need for this. It just makes the patch even bigger. >@@ -588,19 +186,6 @@ > } > > attrName->ToString(nameStr); >- >- /*If we already crossed the MaxColumn limit or >- * if this attr name-value pair(including a space,=,opening and closing quotes) is greater than MaxColumn limit >- * then start the attribute from a new line. >- */ >- >- if (mDoFormat >- && (mColPos >= mMaxColumn >- || ((PRInt32)(mColPos + nameStr.Length() + >- valueStr.Length() + 4) > mMaxColumn))) { >- aStr.Append(mLineBreak); >- mColPos = 0; >- } Without -P it is hard to say which method this code belongs to. >+NS_IMETHODIMP >+nsXHTMLContentSerializer::Init(PRUint32 aFlags, PRUint32 aWrapColumn, >+ const char* aCharSet, PRBool aIsCopying, >+ PRBool aIsWholeDocument) >+{ >+ // to keep compatibility with existing calling code >+ // XXXLJ perhaps we should remove these two tests ? >+ if (aFlags & nsIDocumentEncoder::OutputFormatted ) { >+ aFlags = aFlags | nsIDocumentEncoder::OutputWrap; >+ >+ } else if (!(aFlags & nsIDocumentEncoder::OutputRaw)) { >+ aFlags = aFlags | nsIDocumentEncoder::OutputWrap; >+ } Could you explain why this all? What compatibility? >+nsXHTMLContentSerializer::HasLongLines(const nsString& text, PRInt32& aLastNewlineOffset) >+{ >+ PRUint32 start=0; >+ PRUint32 theLen=text.Length(); Add space before and after '=' >+ PRBool rv = PR_FALSE; >+ aLastNewlineOffset = kNotFound; >+ for (start = 0; start < theLen; ) { >+ PRInt32 eol = text.FindChar('\n', start); >+ if (eol < 0) { >+ eol = text.Length(); >+ } >+ else { >+ aLastNewlineOffset = eol; >+ } >+ if (PRInt32(eol - start) > kLongLineLen) >+ rv = PR_TRUE; >+ start = eol+1; Nit, Add space before and after '+' >+ if (aNamespaceID != kNameSpaceID_XHTML && !mIsHTMLSerializer) { >+ return PR_FALSE; >+ } I guess this should be if ((mIsHTMLSerializer && aNamespaceID != kNameSpaceID_None) || (!mIsHTMLSerializer && aNamespaceID != kNameSpaceID_XHTML)) Similar thing also elsewhere. >+nsXHTMLContentSerializer::Inc::tbody) || >+ (aName == nsGkAtoms::form) || >+ (aName == nsGkAtoms::frameset) || >+ (aName == nsGkAtoms::blockquote) || >+ (aName == nsGkAtoms::li) || >+ (aName == nsGkAtoms::dt) || >+ (aName == nsGkAtoms::dd)) {*/ >+ nsXMLContentSerializer::IncrIndentation(aName); >+ //} >+} >+ >+void >+nsXHTMLContentSerializer::Dec::li) || >+ (aName == nsGkAtoms::tbody) || >+ (aName == nsGkAtoms::form) || >+ (aName == nsGkAtoms::blockquote) || >+ (aName == nsGkAtoms::dt) || >+ (aName == nsGkAtoms::dd) || >+ (aName == nsGkAtoms::frameset)) {*/ >+ nsXMLContentSerializer::DecrIndentation(aName); >+ //} >+} Why you have commented out most of the code? Either the code should be there and do something reasonable, or it shouldn't be there at all. >+ // To keep track of startvalue of OL and first list item for nested lists >+ struct olState { >+ olState(PRInt32 aStart, PRBool aIsFirst):startVal(aStart),isFirstListItem(aIsFirst) >+ { >+ } >+ PRInt32 startVal; >+ PRBool isFirstListItem; >+ }; >+ >+ nsAutoVoidArray mOLStateStack;// Stack to store one olState struct per <OL>. I know you're just moving this code, but could you make this something like nsTArray<olState> mOLStateStack; That way there isn't need to manually |new| and |delete| You may want to add a copy constructor to struct olState. >@@ -468,13 +565,13 @@ >- >+ No need for whitespace changes. Those just make the patch even bigger. Same thing also elsewhere. >+void >+nsXMLContentSerializer::IncrIndentation(nsIAtom* aName) >+{ >+ // we want to keep the source readable >+ if(mDoWrap && mIndent.Length() >= mMaxColumn - 15) { >+ mIndentOverflow ++; >+ } What is this magical 15? >+ else { >+ mIndent.AppendLiteral(" "); Why 3 spaces? Maybe better to #define it somewhere. >+void >+nsXMLContentSerializer::AppendToStringConvertLF(const nsAString& aStr, >+ nsAString& aOutputStr) >+{ >+ if (mDoRaw) { >+ nsAutoString str (aStr); >+ PRInt32 lastNewlineOffset = str.RFindChar('\n'); >+ AppendToString(aStr, aOutputStr); >+ >+ if (lastNewlineOffset != kNotFound) { >+ PRInt32 lastNewlineOffset2 = str.RFindChar('\r'); >+ if (lastNewlineOffset2 != kNotFound) { >+ lastNewlineOffset = lastNewlineOffset2; >+ } >+ >+ mColPos = aStr.Length() - lastNewlineOffset; Could you add some comment here what these offsets are meant for. ... >+ // if there was a line break before this substring >+ // AppendNewLineToString was call, so we should reverse >+ // this flag >+ mMayIgnoreLineBreakSequence = PR_FALSE; 'was call' -> 'was called'? >+nsXMLContentSerializer::AppendWrapped_NonWhitespaceSequence( ... >+ if (aPos == aEnd || foundWhitespaceInLoop) { >+ // there is enough room for the complete block we found >+ if (mDoFormat && !mColPos) { >+ AppendIndentation(aOutputStr); >+ } >+ >+ if (mAddSpace) { >+ aOutputStr.Append(PRUnichar(' ')); >+ mAddSpace = PR_FALSE; >+ } So we want both AppendIndentation and Append(PRUnichar(' ')) ? >+ if (foundWrapPosition) { >+ if (!mColPos && mDoFormat) { >+ AppendIndentation(aOutputStr); >+ } >+ if (mAddSpace) { >+ aOutputStr.Append(PRUnichar(' ')); >+ mAddSpace = PR_FALSE; >+ } Same here. Is there a test for the case when !mColPos && mDoFormat && mAddSpace? (if that is even possible case.) >+ // try some simple fallback logic >+ // go forward up to the next whitespace position, >+ // in the worst case this will be all the rest of the data >+ mColPos += length; You added this. Could you explain why it is needed. >+ // if the current line already has text on it, such as a tag, >+ // leading whitespace is significant >+ PRBool mayIgnoreStartOfLineWhitespaceSequence = (!mColPos >+ || (mIsIndentationAddedOnCurrentLine >+ && sequenceStartAfterAWhitespace >+ && mColPos == mIndent.Length())); Perhaps newline after '=' and start the expression from the next line. >+void >+nsXMLContentSerializer::AppendWrapped_WhitespaceSequence( >+ nsASingleFragmentString::const_char_iterator &aPos, >+ const nsASingleFragmentString::const_char_iterator aEnd, >+ const nsASingleFragmentString::const_char_iterator aSequenceStart, >+ nsAString &aOutputStr) >+{ Note to myself: so this isn't replacing nsHTMLContentSerializer::AppendWrapped_WhitespaceSequence, but there is nsXMLContentSerializer::AppendFormatedWrapped_WhitespaceSequence for that, sort of. Documented in nsXMLContentSerializer.h ... >+ // Handle the complete sequence of whitespace. >+ // Continue to iterate until we find the first non-whitespace char. >+ // Updates "aPos" to point to the first unhandled char. >+ mAddSpace = PR_FALSE; >+ mIsIndentationAddedOnCurrentLine = PR_FALSE; >+ >+ PRBool leaveLoop = PR_FALSE; >+ nsASingleFragmentString::const_char_iterator lastPos = aPos; >+ >+ do { >+ switch (*aPos) { >+ case ' ': >+ case '\t': >+ // if there are two many spaces on a line, we wrap 'two many' -> 'too many' >\ No newline at end of file Fix these warnings
New patch coming?
Yes, it's coming :-) I already updated my local patch with your comments, but I added also some unit tests to test serialization of OL element with the htmlcopyencoder, and also on the serialization of a selection, of a single node etc. It appears that some of these tests fail. My patch brokes some few things :-). I currently try to fix these bugs. There are also few problems when we use the XHTML serializer on a HTML document (and I didn't already test the HTML serializer on an XHTML document). I will try to fix that too. I think I have also to modify the htmlcopyencoder to use the XHTML serializer when the document is in XHTML. I think a new version of the patch will be ready at the end of the week.
Created attachment 348652 [details] [diff] [review] patch v2 Here is a new version of the patch. It includes all wanted improvements: - used static_cast instead of () - canceled changes on whitespaces and indentation - added spaces where needed - changed test on namespaces as indicated - removed nsXHTMLContentSerializer::IncrIndentation and nsXHTMLContentSerializer::DecrIndentation - changed the type of mOLStateStack to nsTArray<olState> - put the "magical 15" and the default indentation into #define - removed unuseful code in nsXMLContentSerializer::AppendToStringConvertLF - fixed tests in nsXMLContentSerializer::AppendWrapped_NonWhitespaceSequence and added details in comments And I added also: - some unit tests on the serialization of selections, range, node etc.. - some unit tests on the serialization of OL lists - unit tests on htmlcopyencoder - a test for bug 270145 to verify I do not break something - support of "autoplay" and "controls" attributes on video and audio elements And I changed flags in nsContentAreaDragDrop to keep the original serialization of dragged content.
Created attachment 348653 [details] [diff] [review] diff between v1.2 and v2 Just a diff between patch v1.2 and patch v2...
The patch breaks /tests/embedding/test/test_bug293834.html and I think also /tests/toolkit/components/url-classifier/tests/mochitest/test_classifier.html
Created attachment 357873 [details] [diff] [review] patch v2.1 This is an update of the patch for the current trunk (patch on a Makefile.in was broken). No modification in the part of the patch on the serializer itself. This new patch includes a modification on test_bug293834.html to pass the test. No modification with test_classifier.html since it passes on my machine.
Do you know why the patch breaks test_bug293834.html? And is the new behavior more correct than the old one?
In fact, in this test, there is a serialisation, and the serialized content is then "unserialized" in a new iframe. Then the test check if a simple string "form state" is in textarea or input contents. However, the new serializer has a better wrapping, and then there is now a linebreak in some input contents : "form\nstate". This is why the test failed. So I changed the regular expression in the test : from /form state/ to /form\s+state/.
Created attachment 357942 [details] comments
Created attachment 358388 [details] [diff] [review] patch v2.2 >@@ -1415,17 +1415,18 @@ nsTransferableFactory::SerializeNodeOrSe >Is there some testcase for this? Or is it even possible to test this >automatically? At least you have tested this manually, right? It seems to be complex to do such testcase automatically (perhaps there are some functions in mochitests to facilitate to write test case for it ? Or am I wrong ?). So yes, I've done manual tests. However, I saw that this method use the "html copy encoder", so I added some test on it in test_htmlcopyencoder.html and test_htmlcopyencoder.xhtml. >+ mPreLevel--; >Use prefix operator (it is faster, though compiler probably knows how to optimize it) Done, and also in all other lines where ++ and -- is used. > mPreLevel decrement happens now somewhere else, right? Yes, in nsXHTMLContentSerializer::MaybeLeaveFromPreContent() >+PRBool >+nsXHTMLContentSerializer::IsJavaScript(nsIAtom* aAttrNameAtom, const nsAString& aValueString) >This should handle also XUL and SVG inside XHTML, right? Perhaps the method >could have an nsIContent* aContent parameter, and based on its type >it could check whether the attribute is an event attribute name. Yes you're right. So I moved the IsJavascript method to the nsXMLContentSerializer, then XHTML/SVG/XUL attributes into any XML content can be checked too. Its new signature is PRBool IsJavaScript(nsIContent * aContent, nsIAtom* aAttrNameAtom, PRInt32 aAttrNamespaceID, const nsAString& aValueString); And I restored the original IsJavascript method into the nsHTMLContentSerializer. >+void >+nsXHTMLContentSerializer::AppendEndOfElementStart(nsIDOMElement *aOriginalElement, >+ nsIAtom * aName, >+ PRInt32 aNamespaceID, >+ nsAString& aStr) >+{ >+ // this method is not called by nsHTMLContentSerializer >+ // so we don't have to check HTML element, just XHTML >Could you add an assertion that this isn't an nsHTMLContentSerializer I added NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !"); Also in other places where you told me... >+nsXHTMLContentSerializer::IsShorthandAttr(const nsIAtom* aAttrName, >+ const nsIAtom* aElementName) >Is there a testcase which checks that shorthand attributes works in HTML and XHTML, >and don't if the element is in some other namespace? No. I added some in file_xhtmlserializer_1. In XHTML, this method is called only when we are on a XHTML element. So it is not called on any other elements. However, it was called for attributes which have a specific namespace, then I fixed it. >+ PRPackedBool mInPseudoCDATA; >Perhaps better to call this something else than ***CDATA. >Maybe mInNoEntityEncoding ? Ok, I renamed it to mDisableEntityEncoding. >Btw, how does this handle the case when 'script' or 'style' etc. have >child elements? I know, that isn't probably valid, but still possible >if the DOM is modified by a script. Perhaps using a counter would be >better than just a simple flag. Yes, you're right, I changed this. >+ // To keep track of startvalue of OL and first list item for nested lists >+ struct olState { >I'd prefer having an explicit copy-constructor, and maybe even operator= >(depends on what nsTArray requires) I added an explicit copy-constructor. >+// the string used to indent. >+#define INDENT_STRING " " >Why 3 spaces? This is an arbitrary value.. >+ >+ mDoRaw = (mFlags & nsIDocumentEncoder::OutputRaw) ? PR_TRUE >+ : PR_FALSE; >mDoRaw = !!(mFlags & nsIDocumentEncoder::OutputRaw); ok >+ >+ mDoFormat = (mFlags & nsIDocumentEncoder::OutputFormatted >+ && !mDoRaw) ? PR_TRUE >+ : PR_FALSE; >Why not just > mDoFormat = (mFlags & nsIDocumentEncoder::OutputFormatted && !mDoRaw); ok >+ >+ mDoWrap = (mFlags & nsIDocumentEncoder::OutputWrap >+ && !mDoRaw) ? PR_TRUE >+ : PR_FALSE; >Similar thing here ok >Use NS_NAMED_LITERAL_STRING for <![CDATA[ ok. Done for "<!--" too. > if (!data.IsEmpty()) { >- AppendToString(NS_LITERAL_STRING(" "), aStr); >+ AppendToString(PRUnichar(' '), aStr); >Nit, is there any reason for this change? Because I think it uses less memory since with a PRUnichar, we don't instantiate any object... >- if ( *buf == PRUnichar('\'') ) >- { >+ if (*buf == PRUnichar('\'')) { >Why this change? The coding style is anyway a bit strange around here. Ok, I canceled this change. I fixed also all other little things indicated in your comments: about syntax, about whitespaces, about C++/Idl comments etc. I fixed also testcases which didn't pass on windows.
Created attachment 358437 [details] comments
Comment on attachment 358388 [details] [diff] [review] patch v2.2 I could mark this r+ now, but this needs good sr too. The patch is just so huge (although lots of it is moving code).
Created attachment 359039 [details] [diff] [review] patch v2.3 Fixed Olli's latest comments. For the isJavascript method, I need to know how to make the difference between a HTML content and a XML node without a namespace. Should I do a QueryInterface each time I run this method ?
Maybe aContent->IsNodeOfType(nsINode::eHTML)
Created attachment 359058 [details] [diff] [review] patch v2.4 Thanks Olli, I removed the isJavascript method from nsHTMLContentSerializer. Oh, and the bug for MathML is bug 475518.
Comment on attachment 359058 [details] [diff] [review] patch v2.4 >@@ -685,649 +265,143 @@ nsHTMLContentSerializer::AppendElementSt > //If OL has "start" attribute, first LI element has to start with that value > //Therefore subtracting 1 as all the LI elements are incrementing it before using it; > //In failure of ToInteger(), default StartAttrValue to 0. > if (NS_SUCCEEDED(rv)) > startAttrVal--; > else > startAttrVal = 0; > } >- olState* state = new olState(startAttrVal, PR_TRUE); >- if (state) >- mOLStateStack.AppendElement(state); >+ olState state (startAttrVal, PR_TRUE); >+ mOLStateStack.AppendElement(state); No space before the '('. Also, I think you could write this as mOLStateStack.AppendElement(olState(startAttrVal, PR_TRUE)); >+nsXHTMLContentSerializer::SerializeAttributes(nsIContent* aContent, ... >+ NS_NAMED_LITERAL_STRING(_mozStr, "_moz"); ... >+ // Filter out any attribute starting with [-|_]moz >+ const char* sharedName; >+ attrName->GetUTF8String(&sharedName); >+ if ((('_' == *sharedName) || ('-' == *sharedName)) && >+ !nsCRT::strncmp(sharedName+1, kMozStr, PRUint32(sizeof(kMozStr)-1))) { >+ continue; >+ } is the '+1' there really correct? Seems like this will filter attributes starting with "__moz" or "-_moz" Other than that I couldn't find anything. But this patch is a bit enormous and so hard to review. sr=me either way
Created attachment 372288 [details] [diff] [review] patch v2.5 Unfortunately, the applying of the patch 2.4 fails on the current trunk because of some recents changes on nsHTMLContentSerializer.* and nsXMLContentSerializer.*. This changes are on the nsVoidArray properties ( and ). On nsHTMLContentSerializer, my patch 2.4 contains already this changes (asked by Olli, see comments below), but it doesn't includes changes on nsXMLContentSerializer. I updated my patch. >Also, I think you could write this as >mOLStateStack.AppendElement(olState(startAttrVal, PR_TRUE)); Yes, it is already made in the trunk >is the '+1' there really correct? Seems like this will filter attributes starting with "__moz" or "-_moz" no, because kMozStr equals to "moz", not "_moz". I added some tests about this in this new patches. Thanks for your superreview Jonas :-)
Created attachment 372289 [details] [diff] [review] the diff between the latest two patches here are the differences between patch v2.4 and v2.5. I forgot to say that I also updated some few unit tests that I forgot to modify for patch 2.4 (difference of number of spaces for indentation). For patch 2.5, I launched mochitests and xpcshell tests on linux and mac, and all is green, except on some tests in toolkit/content/tests/widgets/test_textbox_number.xul and browser/base/content/test/test_contextmenu.html. However I don't think it is related to the serializer.
Should I ask a new review/superreview or can we land the patch in the trunk ?
The patch is so huge that perhaps worth to use tryserver before landing to trunk.
Ok Olli. I haven't rights to use tryserver. Could somebody test my patch on a tryserver please ?
Olli has landed the patch into tryservers. The results are : For build only, it's ok - linux: - mac: - windows: For build+test - mac: ok: - leaks on linux : However, these leaks appear on many components which are not related to the serializer I mean (ex: mozstorage). - a test failed on windows Apparently, it is because of a difference on end-of-line characters.. I will fix this test :-/
Created attachment 373667 [details] [diff] [review] patch v2.6 I just fixed the test which fails. It was just a missing flag OutputLFLineBreak when calling the encoder.
Olli, could you test this patch on try servers please ?
Uploaded to tryserver. Look for 'laurentj_serializers_26'
Thank you Olli. All box are greens except one. Here are the reports for all green boxes: The fail : The browser crashed during talos tests. I don't know why. Log file is not very detailed about the fail. Is it significant or can we commit the patch into mozilla-central ?
Yesterday Olli has re-pushed the patch on try servers, and all were greens.
I'll push this once my build is ready.
Thank you Olli for all, and thanks Jonas for your superreview :-)
This seems to have added a warning which looked like a serious bug to me at first glance (virtual methods not being overridden correctly): mozilla/src/content/base/src/nsXHTMLContentSerializer.h:114: warning: ‘virtual void nsXHTMLContentSerializer::SerializeAttributes(nsIContent*, nsIDOMElement*, nsAString_internal&, const nsAString_internal&, nsIAtom*, nsAString_internal&, PRUint32, PRBool)’ was hidden by ‘virtual void nsHTMLContentSerializer::SerializeAttributes(nsIContent*, nsIDOMElement*, nsAString_internal&, const nsAString_internal&, nsIAtom*, nsAString_internal&)’ After spending an hour or so reading through this code, I _think_ that it's correct. But is there a reason the HTML one has a different signature? Or isn't called SerializeHTMLAttributes or something?
Actually, I think there is no reason to define this nsHTMLContentSerializer::SerializeAttributes method with the same name of the nsXHTMLContentSerializer one. Yes, we could call it SerializeHTMLAttributes. Do you want I create a bug and provide a patch ?
That would be wonderful!
This patch broke the wrapping behavior when serializing HTML. See bug 549295.
What's the use case for having the W3CEntities (MathML) configuration? | https://bugzilla.mozilla.org/show_bug.cgi?id=422403 | CC-MAIN-2017-34 | en | refinedweb |
Migrate from GTK+ to Qt
Contents
- 1 Introduction
- 2 GObject vs QObject
- 3 GtkWidget vs QWidget
- 4 Tree/Model/View architecture of Qt
- 5 Special notes for using Qt with glib/GObject and gio
- 6 Using CMake to Build Your Code
- 7 Translation (i18n)
- 8 ABI Issues For C++ Libraries
- 9 Appendix: List of equivalent GTK+ and Qt functionality
- 9.1 Development Tools
- 9.2 Windows
- 9.3 Display Widgets
- 9.4 Buttons and Toggles
- 9.5 Numeric/Text Data Entry
- 9.6 Multiline Text Editor
- 9.7 Tree, List and Icon Grid Widgets (Tree Model/View architecture)
- 9.8 Menus, Combo Box, Toolbar
- 9.9 Selectors (Color/File/Font)
- 9.10 Layout Containers
- 9.11 Scrolling
- 9.12 Printing
- 9.13 Miscellaneous
- 9.14 Abstract Base Classes
- 9.15 Cross-process Embedding
- 9.16 Recently Used Documents
- 9.17 Choosing from installed applications
- 9.18 Interface builder
- 9.19 Application support
- 9.20 Deprecated
Introduction
Qt is a nice platform for GUI application development. More and more people are using Qt. One of the famous Linux distros, Ubuntu, is also moving from Gnome/GTK+ to Qt. Normally, people start learning Qt from reading the Qt tutorial/books and the "hello world" example. For those who already know GTK+, learning Qt is much easier since most of the GTK+ concepts still applies. Only some "translation" is needed. This document focuses on translating your existing GTK+ knowledge and experience to Qt. So you can start to develop with Qt "immediately".
- If you don't know what's GTK+ or Qt, this doc is not for you. Go to find a Qt tutorial and read it.
- If you're using GTK+ and want to use Qt instead, this is definitely for you
- If you plan to use QML, this is not for you. We focus on desktop development with Qt Widgets.
A very efficient shortcut for a GTK+ developers to migrate to Qt is:
- Read a Qt tutorial (hello world) [1]
- Read this guide
- Start coding immediately (Create your project with KDevelop or QtCreator can make your life much easier. Personally I highly recommend KDevelop)
- If you encounter any problem, use Qt assitant to look it up in Qt API doc, or ask questions in the KDE/Qt community.
At the end of this document we provide a table listing the Qt equivalence of some common Gtk+ classes.
GObject vs QObject
In Gtk+, nearly everything is a GObject. In Qt, almost all major classes are derived from QObject. They provides very similar functionality but also differs in many ways.
GtkWidget vs QWidget
Tree/Model/View architecture of Qt
In Qt, it also has model/view architecture, just like GTK+ has GtkTreeModel and GtkTreeView. Their designs, however, differ in some ways.
In GTK+, To create a list-like view, you need to do this:
- Create a GtkListStore as the model providing data source
- Create a GtkTreeView for display the model
- Add several GtkTreeViewColumn objects to the GtkTreeView to add columns
- Set column attributes to map columns in the model (list store) to the visible columns in the view.
- Pack several GtkCellRendererPixbuf and GtkCellRendererText renderers into GtkTreeViewColumn to paint the content of that column
- Set the model to the view
In Qt, you have two choices for your model
- QStandardItemModel: a ready-to-use generic model class which has more feature than GtkListStore and GtkTreeStore. This should work in most of the cases.
- QAbstractItemModel: a base class for deriving your own model class if QStandardItemModel is not enough. more complicated, roughly equals to implementing your own GtkTreeModel interface with GObject.
There are several places where Qt is quite different:
- Columns in the view are created by adding GtkTreeViewColumn objects while in Qt the column information (title, size, ...) is "provided by the model", not the view. However, if you need to change the column header, it's managed by QHeaderView which can be retrieved by calling QTreeView::header().
- Qt does not use cell renderer layout. Every cell can have an optional icon and text, and even other data associated with it. Qt calls different data stored in a cell "roles". Icons are decoration roles, and text for display in the cell is called display role.
- In Gtk+, to refer to a row, you have to use GtkTreePath and GtkTreeIter. In Qt what you only need is QModelIndex, which provides functionality of GtkTreePath + GtkTreeIter.
- In Gtk+ every "row" have a GtkTreePath and GtkTreeIter. Different cells in a row are referenced by using different column indicis or IDs. In Qt, every single cell can have their own QModelIndex.
- If you need to draw custom content in a cell, in Gtk+ you can create a custom GtkCellRenderer. With Qt, derive your own QStyledItemDelegate, which is essentially a Qt cell renderer.
- Gtk+ provides various kinds of cell renderers, Qt does not. You have to derive your custom item delegates for this. This is not difficult and a Google search usually gives you many examples for how to do it.
- Gtk+ cell renderers provides rich text rendering (markup text), but Qt does not provide it. You can emulate the same feature with a custom delegate. Here are some good examples from Razor-Qt project and Stack overflow
Here are some good Qt model/view examples:
At the end of the article, we have a table summarizing equivalent Gtk+ and Qt classes for model/view architecture. Jump to the table
Special notes for using Qt with glib/GObject and gio
Forget the political issues. Qt and Gtk/Gnome are not enemy and there are many really nice non-GUI libraries from the Gnome/Gtk world. Qt now has glib mainloop integration. So using glib-based libraries is possible in Qt programs. (The Qt library must be compiled with glib support turned on, thogh)
There are some issue developers need to pay attention to.
Initialize GObject type system
You need to call g_type_init() before using any GObject-based stuff. Normally gtk_init() calls g_type_init() for us if you're using Gtk. With Qt, however, you need to initialize the GObject type system manually.
Disable the Qt keywords
To make programming easier, Qt added some "Qt-specific" reserved words to C++, such as the notorious "signals", "slots", "emit", and "foreach". They received much criticism on not using standard C++ syntax here. Non-standard, however, is not the real issue. The problem is, these words are used in other C++ libraries for class, methods, or variable names. The most famous one is boost::signal. These Qt keywords create significant name clashes. Glib/gio also uses these Qt keywords for variable names in their header files. So it creates a big headache. Fortunately, in Qt 4 this improved. Instead of new keywords, you can replace all of the "keywords" with macros. Use Qt macros Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), Q_EMIT, and Q_FOREACH to replace the old "keywords" and everything will compile. You also need to define "QT_NO_KEYWORDS" with compiler flags -DQT_NO_KEYWORDS to make it work.
String encoding issues
- While glib uses UTF-8 to encode all strings, Qt uses UTF-16 internally. A C-style string, if not specified, is treated as a latin1 string. To convert from UTF-8 to UTF-16, calling QString::fromUtf8() explicitly is needed. If you don't do this, UTF-8 strings will be treated as latin1 by default and the bug can be hard to find.
- To avoid the error, define QT_NO_CAST_FROM_ASCII flag to disable automatic conversion from C string to UTF-16.
Make C Header Files C++ compatible
- Avoid using C++ reserved words as variable or function names in your C code, especially in the header files. The most common example: Replace "class" with "klass" in your C code because class is a reserved word in C++. Don't use "new" as your function or variable name since its a C++ operator.
- If you use glib, add G_BEGIN_DECLS and G_END_DECLS in your C language *.h files like this:
#include <glib.h> G_BEGIN_DECLS // Your function declaration here // ... G_END_DECLS
Please refer to glib API doc for the explanation of these two macros. They're translated to something like this:
#ifdef __cplusplus extern "C" { #endif // Your function declaration here //... #ifdef __cplusplus } #endif
This prevent C++ compilers from doing name mangling.
- If you're not using glib, do the above ifdef and extern "C" manually
Known bugs or limitations of the Qt glib support
- Qt QTBUG-32859: Calling QObject::deleteLater() inside a glib signal, timeout, or idle handlers has no effect. To workardound this bug, use QTimer::singleShot(0, object, SLOT(deleteLater()));
Using CMake to Build Your Code
While using Autotools to build Qt code is possible, I won't recommend doing that. The officially suggested way to build Qt code is to use qmake bundled with Qt and *.pro project file. This approach, however, is not suitable for more complicated real world applications. Many huge projects developed with Qt, like KDE, uses CMake instead.
CMake Basics
TODO
Using pkg-config in CMake
TODO
Qt support in CMake
TODO
Some useful macros:
- qt4_add_resources to add embedded resources to your app,
- qt4_wrap_ui to add a widget form,
- qt4_create_translation for translation,
- qt4_add_dbus_adaptor & qt4_add_dbus_interface to generate D-Bus-related code.
Add compiler flags
- The -DQT_NO_KEYWORDS flag: turn off Qt specific keywords
- The -fpermissive flag: If you're using some C libraries in your Qt code, you may encounter some type-casting related errors. Because C++ is more strict on type safety, some code allowed in C is not allowed in C++. You should fix the code if possible. Otherwise, add -fpermissive flag to omit the errors to make it compile.
Add linker flags
TODO
Build binary programs
TODO
Build libraries
TODO
Build tarballs
TODO
Translation (i18n)
GNU gettext vs QTranslator
TODO
Generate *.ts file from the source code
TODO
Integrate with CMake
Load the translation in Qt code
TODO
Use GNU gettext in Qt
TODO
ABI Issues For C++ Libraries
What's ABI?
ABI = application binary interface. It's extremely important for you if you're developing a library. Wikipedia has introduction for it. [3]
How to prevent breaking ABI compatibility
Due to the design and language features of C++, ABI (application binary interface) can break much more easily than in C if developers do not pay special attention to it.
KDE teams provide a very comprehensive guide about how to prevent C++ ABI breakage. Please read the nice article here [4].
What if I really need to break the ABI
Then make sure you bump the libtool version number. See this doc explaining how to set the version info correctly:
Appendix: List of equivalent GTK+ and Qt functionality
Development Tools
The following list of Gtk classes is taken from gtk+ API doc here:
Windows
Display Widgets
Buttons and Toggles
Numeric/Text Data Entry
Multiline Text Editor
Tree, List and Icon Grid Widgets (Tree Model/View architecture)
Menus, Combo Box, Toolbar
Selectors (Color/File/Font)
Layout Containers
In Gtk+, widget layout are largely done with boxes. In Qt, however, there are no box containers. Instead, they used QLayout objects to manage the layout of widgets. QLayout and its derivatives are not containers nor widgets. They're just "managers" of the layout of child widgets. The child widgets belongs to their parent container widgets, not belongs to the layout managers. This is totally different from Gtk+. | https://wiki.lxde.org/en/Migrate_from_GTK%2B_to_Qt | CC-MAIN-2017-34 | en | refinedweb |
COpenBuffer is a class for simplified access to open prices of bars in the history.
COpenBuffer class provides a simplified access to open prices of bars in the history.
class COpenBuffer: public CDoubleBuffer
#include <Indicators\TimeSeries.mqh>
CObject
CArray
CArrayDouble
CDoubleBuffer
COpenBuffer
Data Update
virtual Refresh
Updates the buffer
virtual RefreshCurrent
Updates the current value
Methods inherited from class CObject
Prev, Prev, Next, Next, Compare
Methods inherited from class CArray
Step, Step, Total, Available, Max, IsSorted, SortMode, Clear, Sort
Methods inherited from class CArrayDouble
Delta, Type, Save, Load, Reserve, Resize, Shutdown, Add, AddArray, AddArray, Insert, InsertArray, InsertArray, AssignArray, AssignArray, At, operator, Minimum, Maximum, Update, Shift, Delete, DeleteRange, CompareArray, CompareArray, InsertSort, Search, SearchGreat, SearchLess, SearchGreatOrEqual, SearchLessOrEqual, SearchFirst, SearchLast, SearchLinear
Methods inherited from class CDoubleBuffer
Size, At, SetSymbolPeriod | https://www.mql5.com/en/docs/standardlibrary/technicalindicators/cindicators/copenbuffer | CC-MAIN-2018-51 | en | refinedweb |
import com.sleepycat.db.*;
public int get_type();
The Db.get_type method returns the type of the underlying access method (and file format). The returned value is one of Db.DB_BTREE, Db.DB_HASH, Db.DB_RECNO, or Db.DB_QUEUE. This value may be used to determine the type of the database after a return from Db.open with the type argument set to Db.DB_UNKNOWN.
The Db.get_type interface may be called only after the Db.open interface has been called.
The Db.get_type method may fail and throw an exception encapsulating a non-zero error for the following conditions:
Called before Db.open was called.
The Db.get_type method may fail and throw an exception for errors specified for other Berkeley DB and C library or system methods. If a catastrophic error has occurred, the Db.get_type method may fail and throw a DbRunRecoveryException, in which case all subsequent Berkeley DB calls will fail in the same way. | http://doc.gnu-darwin.org/api_java/db_get_type.html | CC-MAIN-2018-51 | en | refinedweb |
ISO/IEC JTC1 SC22 WG21 N2889 = 09-0079 - 2009-06-21
Lawrence Crowl, crowl@google.com, Lawrence@Crowl.org
Problem Description
Solution Domain
Thread Resources
Solution Value
Related Work
Proposed Solution
Acknowledgements
The
async Function
Thread Joining
Execution Policies
Eager and Lazy Evaluation
Direct Execution
New Future Type
Proposed Wording
30.6.1 Overview [futures.overview]
30.6.? Function template
async [futures.async]
30.6.? Class template
joining_future [futures.joining_future]
One of the simplest methods for exploiting parallelism is to call one subroutine in parallel with another. However, with the current threading facilities, doing so is a difficult task.
There have been repeated requests for a simpler mechanism, all of which were rejected by the committee as not being within the spirit of the Kona compromise. However, there are now national body comments requesting such a facility.
UK-182 30.3.3.2.2
Future, promise and packaged_task provide a framework for creating future values, but a simple function to tie all three components together is missing. Note that we only need a simple facility for C++0x. Advanced thread pools are to be left for TR2.
async( F&& f, Args && ... );Semantics are similar to creating a thread object with a packaged_task invoking
fwith
forward<Args>(args...)but details are left unspecified to allow different scheduling and thread spawning implementations. It is unspecified whether a task submitted to
asyncis run on its own thread or a thread previously used for another async task. If a call to async succeeds, it shall be safe to wait for it from any thread. The state of
thread_localvariables shall be preserved during async calls. No two incomplete async tasks shall see the same value of
this_thread::get_id(). [Note: this effectively forces new tasks to be run on a new thread, or a fixed-size pool with no queue. If the library is unable to spawn a new thread or there are no free worker threads then the async call should fail.]
Concurrency and parallism represent broad domain of problems and solutions. Mechanisms are generally appropriate to a limited portion of that domain. So, mechanisms should explicitly state the domain in which they are intended to be useful.
The anticipated domain for the following
async solution
is extracting a limited amount of concurrency
from existing sequential programs.
That is, some function calls
will be made asynchrounous where appropriate
to extract high-level concurrency from program structure,
and not from its data structures.
The facility is not intended to compete with OpenMP or automatic parallelizers
that extract loop-level parallelism.
To be concrete,
the
async facility would be appropriate
to the recursive calls to quicksort,
but not to the iteration in a partition.
In this domain, the programming model is:
In this model, nested asynchronous calls are not only supported, but desired, as they provide the implementation the opportunity to reuse threads for many potentially, but not actually, asynchronous calls.
The central technical problem in providing an asynchronous execution facility is to provide it in a manner that does not require the use of thread pools, while at the same time avoiding problems synchronizing with the destructors for any thread-local variables used by any threads created to perform the asynchronous work. See N2880: C++ object lifetime interactions with the threads API, Hans-J. Boehm, Lawrence Crowl, ISO/IEC JTC1 WG21 N2880, 2009-05-01.
While not explicit, the essential lesson of N2880 is as follows.
Threads have variables in the form of thread-local variables, parameters, and automatic variables. To ensure that the resources held by those variables are released, one must join with the thread so that those variables are destroyed. To ensure that destructors of those variables are well-defined, one must join with the thread before its referenced environment is destroyed.
Some consequences of this observation are:
In addition to the technical details, the committee must consider the value in any solution that meets the procedural bounds of the Kona compromise and the technical bounds embodied in N2880. In particular, external facilities like Cilk, the Threading Building Blocks, and the Parallel Patterns Library are known to be better able to handle fined-grained parallelism. So, is the solution space of sufficient value, relative to these external facilities, for standardization in C++0x?
The value in a solution is relative not only to external facilities,
but also relative to facilities in the current standard.
Our concurrency primitive,
std::thread,
does not return values,
and getting a value out through
std::packaged_task
and
std::unique_future
may take more training than many programmers are willing to accept.
So, is the solution space of sufficient value,
relative to these internal facilities,
for standardization in C++0x?
In this paper, we presume that the value in the solution comes from its improvement over existing internal facilities. The wording of the UK national body comment implies the same conclusion. On that basis, we propose the following solution.
Oliver Kowalke is implementing boost.task
(formerly known as boost.threadpool).
In this library,
launch_in_thread() reuses existing threads.
The function returns a returns handle object for both thread and return value.
This library also allows task interruption.
It is available at the Boost Vault
(
— section 'Concurrent Programming')
or from the Boost sandbox
(svn —).
Herb Sutter has proposed an alternate solution in draft text, generally taking a different choice for those issues in which consensus has not formed. This paper should appear as N2901.
The proposed solution consists of
a set of
async functions to launch asychronous work
and a future to manage the function result.
This solution derives from an extensive discussion on the C++ threads standardisation <cpp-threads@decadentplace.org.uk> mailing list. That discusson has not yet reached consensus. We highlight points of disagreement below. Note that the presentation in this paper is substantially expanded from earlier drafts, clarifying several issues, so the disagreements may be weaker than they were in discussion.
Thanks to the following contributors to the discussion on this topic: Hans Boehm, Beman Dawes, Peter Dimov, Pablo Halpern, Howard Hinnant, Oliver Kowalke, Doug Lea, Arch Robison, Bjarne Stroustrup, Alexander Terekhov, and Anthony Williams. In particular, we are extremely grateful to Herb Sutter for forcing a thorough analysis into the issues.
asyncFunction
The
async functions
use the standard techniques for deferring function execution.
The function and its arguments are listed separately
as parameters to the
async functions,
which are later combined at the point of invocation
to call the designated work.
For example, consider computing the sum of a very large array. The first task is to not compute asynchronously when the overhead would be significant. The second task is to split the work into two pieces, one executed by the host thread and one executed asynchronously.
int parallel_sum(int* data, int size) { int sum = 0; if ( size < 1000 ) for ( int i = 0; i < size; ++i ) sum += data[i]; else { auto handle = std::async(parallel_sum, data+size/2, size-size/2); sum += parallel_sum(data, size/2); sum += handle.get(); } return sum; }
Because Kona compromise prohibits thread pools and because we must join with any thread created, any asynchronous execution facility must ensure, at the very least, that any thread created is joined before the resulting handle is destroyed. (And, of course, the programmer must destroy the handle, not abandon it to free store.)
A consequence of the joining is that threads cannot be reused. Otherwise, some section of the program would lose control of the resources accreted in the thread being reused.
This issue has not yet reached consensus.
Given that the thread must join,
there are two implementation strategies,
intrusively implement
async
or keep the
std::thread
within the future for later
joining.
In the intrusive
async,
the implementation within the thread
must
set_valueor
set_exceptionfunction of the
promisecorresponding to the future.
That is, the promise effectively joins the thread before the future becomes ready.
When storing the
std::thread within the future,
the implementation of
async
is a straightforward composition of
packaged_task,
unique_future,
and
std::thread.
One consequence of
storing the
std::thread within the future
is that either
unique_future
must be substantially modified
or that we introduce a new future type.
Another consequence of
storing the
std::thread within the future
is that the waiting function changes
from a condition-variable
wait
to a thread join.
The
std::thread class
does provides neither a
timed_join
nor a
try_join,
and so a joining future
cannot implement the full interface of
unique_future.
The
async functions have a policy parameter.
Three policies are defined in this paper.
The intent of this proposal is to closely follow
the parameters and overloads of the
std::thread constructors.
We expect this consistency to provide the least surprise to users.
Because
std::thread has a variadic constructor,
the
std::async function has a variadic overload.
A consequence is that the standard technique
for implementing a default policy
via a defaulted paramter
does not work.
Hence the proposal places the policy at the front of the parameter list
and implements the default policy
with a separate overload that does not have that parameter.
This placement seems unnatural to many members of the committee,
and they desire to place policy parameter at the end.
The only way to provide the policy parameter at the end
and to be consistent with
std::thread constructors
is to remove the variadic constructor from
std::thread.
Doing so would not lose a great deal of syntactic consiceness,
because the lambda facility can encapsulate many parameters.
The
async form above can be written as follows.
auto handle = std::async( [=]{ return parallel_sum( data+size/2, size-size/2); }, fully_threaded );
We have no objection to that approach.
Indeed, it would make the referencing environment of
the executed function quite explicit
in the form of the lambda-capture.
Should the variadic
std::thread constructor be removed,
we will modify the proposal to move the policy parameter
to the end of the list and default it.
Alternatively,
one could have inconsistent parameters
for
std::thread constructors
and
std::async overloads.
This choice has not reached consensus.
When the work is invoked serially, we propose to do so at the point of value request, rather than at the point of initiation. That is, work is invoked lazily rather than eagerly. This approach may seem surprising, but there are reasons to prefer invocation-on-request.
asyncfunctions have already committed to an eager serial execution.
asyncmight introduce deadlock. In contrast, executing the work serially at the call to
getcannot introduce any deadlock that was not already present because the calling thread is necessarily blocked.
asyncearlier. When there are sufficient processor resources, the function executes concurrently and speculatively. When there are not sufficient resources, the function will execute only when truly needed.
Eager semantics seem more natural when programmers think of "waiting to use the return value". On the other hand, lazy semantics seem more natural when programmers think of "moving the call earlier". Consider the following examples.
int original( int a, b ) { int c = work1( a ); int d = work2( b ); } int eager( int a, b ) { auto handle = async( work1, a ); int d = work2( b ); int c = handle.get(); } int lazy( int a, b ) { auto handle = async( work2, b ); int c = work1( a ); int d = handle.get(); }
Note also that in the proposed lazy semantics,
any serial execution will be in the context
of the thread that executes the
get().
While we expect that this thread will nearly always
be the same as the thread that executes
async()
it need not be because a future can be moved.
There are consequences to lazy evaluation.
In particular,
the future returned from
async
must either be a modified version of the existing
unique_future
or the future must be of a new type.
The reason is that lazy evaluation
requires that the future carry an
std::function
to represent the computation needed.
A desirable implementation
in the case of synchronous execution
is direct execution,
in which the call to the
std::function representing the work
returns its result or exception directly to the caller.
In lazy evaluation,
direct execution is straightforward;
the implementation of a synchronous
get()
simply calls the
std::function and returns its result.
Any exeption is simply propogated as in a normal function call.
In eager evaluation,
one must necessarily save the result in a variable
for later copy/move at from the
get() call.
However, propogating the exception at the
async() call
would introduce a second place in which the programmer
must protect against an exception.
That burden is undesirable,
so the
async() call should also save
any exception for later propogation by the
get() call.
All of this means that eager evaluation cannot exploit direct execution.
Direct execution has a consequence however.
Since the value or exception status is unknown until the
get call,
the
has_value and
has_exception queries
cannot provide meaningful results before then.
That is, direct execution
invalidates part of the interface to
unique_future.
Note, however,
that the
has_value and
has_exception queries
are meaningful with lazy evaluation
so long as the first call to them
invokes the
std::function
in an indirect manner.
As hinted several times earlier,
we must make a choice in the future type returned by
async:
unique_future,
unique_future, or
Based on the discussion above,
Furthermore,
a modified
unique_future
would necessarily induce more overhead
on the original intended uses of
unique_future.
The direct overhead might be as low as a few words
and a couple of tests or virtual calls.
Unfortunately, tests and virtual calls
tend to introduce pipeline bubbles
and virtual calls tend to be barriers to optimization.
So, the indirect overhead might be substantially higher.
However, we have no measurements
comparing that overhead
to the normal cost of
unique_future.
Even so,
the original uses of
unique_future,
such as in coordinating thread pools invocations,
are likely to be in more performance-sensitive
code than are uses of
async.
Therefore, avoiding potential performance impact to thread pools
implies a new future type.
Modifying
unique_future
implies revisiting aspects of the working draft
that we thought were stable.
Introducing a new future type
would avoid potentially destabilizing the draft.
On balance,
we believe that a new future type is the best overall
solution to the conflicting desireable features in
the return type of the
async function.
This choice has not reached consensus.
Given that we have a new future,
we remove
timed_wait,
is_ready,
has_value, and
has_exception,
from the interface.
That is, the new future interface,
a
joining_future,
is modeled in part on
thread,
which has a unique owner and is therefore only movable.
The proposed wording is as follows. It consists primarily of two new subsections.
Add to the synopsis the appropriate entries from the following sections.
async[futures.async]
Add the following section.
enum async_policy { fully_threaded, fully_synchronous, impl_discretion }
-
template<class F>
requires Callable<F>;
joining_future<Callable::result_type>
async(async_policy policy, F f);
-
template<typename F, typename ... Args>
requires Callable<F, Args...>;
joining_future<Callable::result_type>
async(async_policy policy, F&& f, Args&&...);
-
template<class F>
requires Callable<F>;
joining_future<Callable::result_type>
async(F f);
-
template<typename F, typename ... Args>
requires Callable<F, Args...>;
joining_future<Callable::result_type>
async(F&& f, Args&&...);
-
Requires:
Fand each type
Tiin
Argsshall be
CopyConstructibleif an lvalue and otherwise
MoveConstructible.
INVOKE(f, w1, w2, ..., wN)(20.7.2) shall be a valid expression for some values w1, w2, ..., wN, where
N == sizeof...(Args).
Effects: Constructs an object of type
joining_future<Callable::result_type>([futures.joining_future]). If
policyis
fully_threaded, creates an object of type
threadand executes
INVOKE(f, t1, t2, ..., tN)in a new thread of execution, where t1, t2, ..., tN are the values in
args.... Any return value is captured by the
joining_future. Any exception not caught by
fis captured by the
joining_future. If
policyis
fully_synchronous, the thread calling
joining_future::get()([future.joining_future]) executes
INVOKE(f, t1, t2, ..., tN)in the caller's own thread of execution, where t1, t2, ..., tN are the values in
args.... The invocation is said to be deferred. If
policyis
impl_discretion, the implementation may choose either policy above at any call to
async. [Note: Implementations should defer invocations when no more concurrency can be effectively exploited. —end note] If there is no
policyparameter, the behavior is as if there was a
impl_discretionparameter was specified.
Synchronization: The invocation of the
asynchappens before (1.10 [intro.multithread]) the invocation of
f. [Note: This statement applies even when the corresponding
joining_futureis moved to another thread. —end note]
Throws:
std::system_errorif
policyis
fully_threadedand the implementation is unable to start a new thread.
Error conditions: —
resource_unavailable_try_again— if
policyis
fully_threadedand either the system lacked the necessary resources to create another thread, or the system-imposed limit on the number of threads in a process would be exceeded.
[Example: Two items of work can be executed in parallel as below.
extern int work1(int value); extern int work2(int value); int work(int value) { auto handle = std::async(std::impl_discretion, work2, value); int tmp = work1(value); return tmp + handle.get(); }
—end example:] [Note: The statement
return work1(value) + handle.get();
might not result in parallelism because
get()may be evaluated before
work1(), thus forcing
work2to be evaluated before
work1(). —end note:]
joining_future[futures.joining_future]
Add the following section after the one above.
namespace std { template<class R> class joining_future { public: joining_future(joining_future &&); joining_future(const joining_future& rhs) = delete; ~joining_future(); joining_future& operator=(const joining_future& rhs) = delete; // retrieving the value see below get(); // functions to check state and wait for ready }; }
The implementation shall provide the template
joining_futureand two specializations,
joining_future<R&>and
joining_future<void>. These differ only in the return type and return value of the member function
get, as set out in its description, below.
-
joining_future(joining_future&& rhs);
-
Effects: move constructs a
joining_futureobject whose associated state is the same as the state of
rhsbefore. The associated state derives from the
asynccall that provided the original future. The state consists of one or more of any
threadcreated by the call, the function object and its arguments, the return value of its invocation, or the exception of its invocation.
Postcondition:
rhscan be safely destroyed.
-
~joining_future();
-
Effects: destroys
*thisand its associated state if no other object refers to that. If the invocation has been deferred, but not yet executed via
get, the invocation is not executed.
Synchronization: If the invocation has been deferred, then the associated
asynccall happens before (1.10 [intro.multithread]) the destructor return. Otherwise, as if associated-thread
.join().
-
R&& joining_future::get();
-
R& joining_future<R&>::get();
-
void joining_future<void>::get();
-
Note: as described above, the template and its two required specializations differ only in the return type and return value of the member function
get.
Effects: If the invocation has been deferred, then executes
INVOKE(f, t1, t2, ..., tN)where t1, t2, ..., tN are the values in
args....
Returns: If the invocation has been deferred, then
-
joining_future::get()returns the rvalue-reference of the result of the invocation.
-
joining_future<R&>::get()returns the reference of the result of the invocation.
-
joining_future<void>::get()returns nothing.
Otherwise,
-
joining_future::get()returns an rvalue-reference to the value stored in the asynchronous result.
-
joining_future<R&>::get()returns the stored reference.
-
joining_future<void>::get()returns nothing.
Throws: If the invocation has been deferred, then any exception from the invocation. Otherwise, the stored exception, if an exception was stored and not retrieved before.
Synchronization: If the invocation has been deferred, and the return from the invocation happens before (1.10 [intro.multithread]) the
getreturns. Otherwise, as if associated-thread
.join().
Remark: the effect of calling
get()a second time on the same
joining_futureobject is unspecified. | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2889.html | CC-MAIN-2018-51 | en | refinedweb |
Information describing an image
#include <img/img.h> typedef struct { union { struct { uint8 *data; unsigned stride; } direct; struct { img_access_f *access_f; Uintptrt data; } indirect; } access; unsigned w, h; img_format_t format; unsigned npalette; img_color_t *palette; unsigned flags; union { uint8 index; uint16 rgb16; img_color_t rgb32; } transparency; unsigned quality; } img_t;
The img_t structure describes a decoded frame. The members include:
Using the direct access model, anyone operating on the image data can access it directly via a pointer. The beginning of the image data is pointed to by direct.data, and it is assumed that the data pointed to is a contiguous buffer of h scanlines of direct.stride bytes each.
Using the indirect access model, anyone operating on the image data does it through a function; the function pointer is given by indirect.access_f, and indirect.data provides a facility to give your access function some context.
An access function is a function you provide to read or write a run of pixels to or from your image. An access function must be coded either as a reader or writer, there is no way to tell from the parameters the direction of data flow.
void access_f(uintptr_t data, unsigned x, unsigned y, unsigned n, uint8_t *pixels)
Image library | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.libimg/topic/img_t.html | CC-MAIN-2018-51 | en | refinedweb |
flow
Write more understandable Haskell.
See all snapshots
flow appears in
Module documentation for 1.0.17
There are no documented modules for this package.
Flow
Write more understandable Haskell.
Flow is a package that provides functions and operators for writing more
understandable Haskell. It is an alternative to some common idioms like
($) for function application and
(.) for function composition.
Requirements
Flow requires a Haskell compiler. It is tested with recent versions of GHC, but older or different compilers should be acceptable. For installation with Cabal, Flow requires at least Cabal 1.8.
Installation
To add Flow as a dependency to your package, add it to your Cabal file.
build-depends: flow ==1.0.*
See the change log for a detailed list of changes.
Usage
Flow is designed to be imported unqualified. It does not export anything that conflicts with the base package.
import Flow
Cheat sheet
For more information about Flow, please read the Haddock documentation.
Changes
Change log
Flow uses Semantic Versioning. The change log is available through the releases on GitHub. | https://www.stackage.org/nightly-2018-12-02/package/flow-1.0.17 | CC-MAIN-2018-51 | en | refinedweb |
By Deepika M S on Jan 23, 2017 6:05:58 AM
Definition:
Properties are central repository to store our information. A property is a named string value that can be accessed from a script.
There are two types of properties in SoapUI, namely, Default Properties and Custom (User-Defined) Properties.
Types of Properties:
Default Properties:
These are the sets of properties which comes by default with every SoapUI. We can change the values of these properties (but not in every case) and consume as and when needed.
Custom Properties:
These are the properties which user defines as per requirements. It can be used as a temporary storage for validating the end result of tests.
Also, in SoapUI definitions of properties are at multiple levels like Projects, Test Suites, Test Cases, Test Steps and Global Properties. Now, we shall look at each one of these in detail.
Levels of Properties:
Project Properties:
Project properties are the properties which are associated with the current project. This property can accessed by all the subsets like test suite, test case, test step, script of the project.
Below are the Groovy scripts to get and set properties from project:
//get property
def projectProperty = testRunner.testcase.testsuite.project.getPropertyValue(“projectProperty”)
//set property
testRunner.testCase.testSuite.project.setPropertyValue(“projectProperty”, value)
Test Suite Properties:
Test suite property specifies the properties associated with the current test suite. This property can be used by its subsets like test case, test step and script of test suite.
Groovy scripts to get and set properties from Test Suite:
//get property
def testSuiteProperty = testRunner.testcase.testsuite.getPropertyValue(“suiteProperty”)
//set property
testRunner.testCase.testSuite.setPropertyValue(“suiteProperty”, value)
Test Case Properties:
Specify the properties associated with the current test case. It can be used by test step and script of the test cases.
Groovy scripts to get and set properties from Test Case:
//get property
def testCaseProperty = testRunner.testcase.getPropertyValue(“caseProperty”)
//set property
testRunner.testCase.setPropertyValue(“caseProperty”, value)
Test Step Properties:
Test step properties specify the properties associated with the current test step. It can be used by its subsets like test step, property transfer and script of the test steps.
Groovy scripts to get and set properties of Test Steps:
//get property
def testStepProperty = testRunner.testcase.testStep.getPropertyValue(“stepProperty”)
def myteststep = testcase.getTestStepAt(IndexNumber)
def teststep = TestCase.getTestStepByName(“Name of the Step”)
//set property
testRunner.testCase.testStep.setPropertyValue(“stepProperty”, value)
Global Properties:
Global properties define the properties associated with installed version of soapui. These properties can be accessed across the project, test suites, test cases and so on.
Groovy scripts to get and set properties from Global:
//get property
def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue(“GlobalProperty”)
//set property
Com.eviware.soapui.SoapUI.globalProperties.setPropertyValue(“GlobalProperty”, value)
Conclusion:
Properties are helpful for transferring the data between the test steps such as test suites , test steps and test cases. Property can be defined through groovy script. Also, we can assign and retrieve data of the properties through the groovy script. | https://blog.trigent.com/properties-groovy-scripting-in-soapui | CC-MAIN-2018-51 | en | refinedweb |
The grid bag layout manager is the most advanced and yet easy to use layout manager. A GridBagLayout arranges the component in a grid of rows and columns. It allows different sized components to span multiple rows or columns. Also, each row in the grid can have different number of columns. Grid bag layout specifies a grid of cells with the container determines the component's size and then positions each component in one or more cell accordingly.
The grid bag layout manager can be created by using the following constructor.
GridBagLayout ()
Information such as, size and location of each component in a grid bag is determined by a set of constraints contained in an object of type GridBagConstraints. The variables in the class GridBagConstrain ts that represent these constraints are given below:
• gridx and gridy: gridx and gridy specify the x and y coordinates to position the component. gridx and grid y represent the number of cells at the left of the component and the number of cells at the top of the component, respectively. By default, the value of both gridx and gridy is relative. It places the component at position next to the component added last in a row or a column.
• gridwidth and gridheight: gridwidth and gridheight specify the number of columns and rows, respectively occupied by the components. The default value for both gridwidth and gridheight is 1. The value REMAINDER can be assigned to gridwidth and gridheight to indicate that the component should be the last one in a row or a column. Ifwe want the component to be the next to last one in a row or a column, the value RELATIVE is used.
• fill: fill specifies how the component should expand within its display area if the area is larger than the component. Any one of the following values can be assigned to fill.
NONE: To specify that the size of the component remains unchanged. It is the default value.
VERTICAL: To specify that the component can expand only vertically.
HORIZONTAL: To specify that the component can expand only horizontally.
BOTH: To specify that the component can expand vertically as well as horizontally.
• ipadx and ipady: ipadx and ipady specify extra width and height of the component, respectively. The default value is 0. Negative values can also be used to tighten the spacing between the components.
• insets: It specifies the amount of space to leave between the borders of the component and the edges of display area. The Insets class specifies the separate values of top, left, bottom, and right. The default value is (0,0,0,0).
• anchor : It specifies where the component should be placed within the display area if it is smaller than its display area. The location of the component is usually given as a compass direction. Any one of the following values can be assigned to anchor.
CENTER(default), NORTH, SOUTH, NORTHEAST, SOUTHWEST, EAST, WEST, SOUTHEAST,NORTHWEST
• weightx and weighty: weightx and weighty specify how the extra horizontal and vertical spaces be adjusted while resizing the container. The component will occupy extra space in the specific direction according to the weight assigned to it.
Consider Example. In this example, grid bag layout is set as the layout for the frame. Five buttons are created and their grid bag constraints are specified. Then the buttons are added to the frame.
Example: A Program to demonstrate the use of GridBaglayout
import javax.swing.*;
class myGridBag extends JApplet
{
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane)
{
if (RIGHT_TO_LEFT)
{
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints gb =new GridBagConstraints();
button= new JButton("Button 1");
if (shouldWeightX)
{
gb.weightx = 0.5;
}
gb.fill = GridBagConstraints.HORIZONTAL;
gb.gridx = 0;
gb.gridy = 0;
pane.add(button, gb);
button= new JButton("Button 2");
gb.fill = GridBagConstraints.HORIZONTAL;
gb.weightx = 1;
gb.gridx = 1;
gb.gridwidth = 2;
gb.gridy = 0;
pane.add(button, gb);
button= new JButton("Button 3");
gb.fill = GridBagConstraints.VERTICAL;
gb.ipady = 30;
gb.weightx = 2;
gb.gridwidth = 4;
gb.gridx = 0;
gb.gridy = 1;
pane.add(button, gb);
button= new JButton("Button 4");
gb.fill = GridBagConstraints.VERTICAL;
gb.ipady = 0; //reset to default
gb.weighty = 1.0;
gb.anchor = GridBagConstraints.PAGE_END;
//bottom of space
gb.insets =new Insets(10,0,0,0); //top padding
gb.gridx = 1;
gb.gridwidth = 2;
gb.gridy = 2; //third row
pane.add(button, gb);
button= new JButton("Button 5");
gb.fill = GridBagConstraints.HORIZONTAL;
gb.weighty = 1.0;
gb.anchor = GridBagConstraints.PAGE_END;
gb.insets =new Insets(10,0,5,0);
gb.gridx = 0;
gb.gridwidth = 2;
gb.gridy = 3; //fourth row
pane.add(button, gb);
}
private static void displayGUI()
{
JFrame frame= new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(500, 300);
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
displayGUI ();
}
}) ;
}
}
The output of the program | http://mail.ecomputernotes.com/java/swing/swing-gridbaglayout | CC-MAIN-2018-51 | en | refinedweb |
The class describes the settings for a game/MOD. More...
#include "GameConfig.hpp"
The class describes the settings for a game/MOD.
Some of the settings are loaded from the CaWE-spefific config file (edited by the user in the main "Configure CaWE" dialog). Other settings are loaded directly from the files and data in the game/MOD directory.
All GUIs that are created in this game config (no matter if in the Map Editor, the Gui Editor, or the Model Editor) share their font and model resources via the returned GuiResourcesT instance.
Returns the model for the given FileName that is relative to ModDir.
Saves this game configuration to CfgFile that has been set to the proper path (directory / group) by the caller. | https://api.cafu.de/c++/classGameConfigT.html | CC-MAIN-2018-51 | en | refinedweb |
VULNERABILITY DETAILS
Happened after a redirect to from (which occured instantly when prompted the first page). The browser declared the page as "secure" although the certificate used was issued to gateway.login.live.com (a Microsoft service).
If needed, i can send the aformentioned certificate.
VERSION
Chrome Version: Version 56.0.2924.76 (64-bit) stable
Operating System: Linux 4.9.6-1-ARCH
REPRODUCTION CASE
Extremely rare (occured twice in 2 days of testing) and conditions are still unknown.
Go to and pray for a redirection to google.com or google.fr.
Thanks for the report. We've received one other report of the same issue but weren't able to get any more information from the reporter.
If you are able to reproduce this, it would be extremely helpful to get a net-internals log as described at. (I know that may be impossible to get since you can't reproduce on demand, though.)
I'm cc'ing jam and clamy because this feels similar to issue 662267, which I highly suspect was introduced by jam's refactor to move SSLStatus to NavigationHandleImpl and which clamy incidentally fixed (I suspect) in.
Maybe there's some path through which a redirected navigation request preserves the SSLStatus from the first hop of the redirect?
I've tried to reproduce the bug unsuccessfully for the past two days.
I am currently trying to get directly in touch with the Microsoft Team to determine what could trigger that redirection.
I'll get back to you as soon as they reply.
We're investigating this but haven't had any luck reproducing yet. OP, do you know how you ended up on from the Microsoft page? Did you click on a link which redirected to Google, or did the page just spontaneously redirect to google, or something else?
It just spontaneously redirected me to google. However i do have some news to this.
1°) You'll find below the answer Microsoft Security Team gave me when i asked for insights about that redirection.
----
Thank you for contacting the Microsoft Security Response Center (MSRC). Unfortunately, we were unable to reproduce your findings. As such, we have determined that this is not a valid vulnerability. As far we are aware, there are no open redirect issues on this domain. Therefore, this could potentially be an issue with your browser or a malicious attacker.
----
I find the "malicious attacker" issue to be unlikely since it happened on two different PCs with two different OSes (ArchLinux and Windows10) and on different networks.
2°) It seems that waiting a day or two without navigating to imagine.microsoft.com drastically increases chances of that redirection happening.
3°) Thanks to that new info and less than 10 secondes before receiving your email, i managed to capture the net-internals logs. I hope you'll find something useful.
CHROME VERSION 56.0.2924.76 on 4.9.8-1-ARCH
Did you edit that log file using some other tool? It has a bunch of 0x0A octets embedded in it that prevented reloading the file.
A fixed version is attached.
The server definitely appears to be sending the redirect @592077
POST /en-US/Account/FinishSignInUsingRPS?RedirectionToURL=https%3a%2f%2f HTTP/1.1
Host: imagine.microsoft.com
HTTP_TRANSACTION_READ_RESPONSE_HEADERS
HTTP/1.1 302 Found
Location:
Not at all, but the text editor i used warned me about the file being too large. Maybe it got corrupted when i saved it. Sorry about that.
Nice to learn. If i can be of any more help, i'll be glad to.
Thanks for the log! This is very interesting.
I'm not sure how/why that request to the open redirector... is happening, but something funky looks to be happening when following it. We process the 302 redirect, but the request is cancelled before following the redirect. Maybe the Adblock Plus extension is cancelling it. And then another request to happens right afterwards, which might be the navigation request that ends up committing. I'm not sure what might be initiating that separate request; maybe an extension or maybe there's a retry somewhere that gets triggered when the initial request is cancelled.
In any case, I bet there is a navigation path that gets the two requests mixed up (the cancelled redirect and the separate).
I'll try reproducing in a fresh profile with Adblock Plus installed.
OP, would you be willing to share a list of extensions that you have installed?
Braindump since I have to head out in a few minutes:
I can almost sort of kind of reproduce the sequence of events in the netlog by modifying ResourceLoader::FollowDeferredRedirectInternal to call CancelRequest() and return when the redirect URL is, and then following these steps:
1. When *not* logged into Microsoft, visit
2. Open chrome://net-internals in another tab
3. In the first tab, open DevTools and run the following JS:
f=document.createElement("form"); f.action=""; f.method="POST"; document.body.appendChild(f); f.submit();
The resulting netlog matches the events in comment 5. Notably, the imagine.microsoft.com request redirects to but the request is cancelled before following the redirect, and a subsequent request happens afterwards, which looks like it has something to do with a Service Worker (the URL_REQUEST netlog entry contains SERVICE_WORKER_START_REQUEST). But, the certificate behavior doesn't repro -- I'm still ending up on with the proper cert -- so there must be some race somewhere that I'm still not hitting.
Nice debugging. Emily also mentioned in person she suspecteted the bug is with RenderFrameHostImpl::TakeNavigationHandleForCommit. I originally thought it was a bug in NavigationController since I caused several bugs there, but I looked at those codepaths and I don't think they're to blame. So maybe the race is that the old NavigationHandle is still alive when TakeNavigationHandleForCommit is called and it incorrectly uses it. Somehow the old SSLStatus is used.
For my active chrome extensions :
1 - Adblock Plus 1.12.4 (id: cfhdojbkjhnklbpkdaibdccddilifddb)
2 - Ember inspector 2.0.4 (id: bmdblncegkenkacieihfhpjfppoconhi)
3 - Momentum 0.92.2 (id: laookkfknpbbblfpciffpaejjkokdgca)
Addendum to my "repro" in comment 9: it seems like you have to log in and then log out of login.live.com first for those instructions to work to reproduce the sequence of events in the OP's net log.
(But, I'm not sure this is all that useful, anyway -- I've tried a gazillion ways and can't repro the actual bug using this sequence of steps.)
OP, if you see this happen again, could you please take a screenshot that includes the tab title? Or do you happen to remember if the tab title and favicon was for Google or for Microsoft?
That would help us narrow down what might be going on. Thanks!
The following revision refers to this bug:
commit c32cd2069ae8062b52e5b7b1faf5936bd71a583a
Author: estark <estark@chromium.org>
Date: Thu Feb 16 08:37:31 2017}
[modify]
@est...@chromium.org, related to comment 16, i can confirm that the favicon and tab title are both correct (favicon is current google logo, and title is 'Google').
The page is totally functional aswell.
The only Microsoft related thing is the certificate as far as i can tell.
Users experienced this crash on the following builds:
Mac Canary 58.0.3015.0 - 5.11 CPM, 3 reports, 3 clients (signature [Dump without crash] content::`anonymous namespace'::MaybeDumpCopiedNonSameOriginEntry)
If this update was incorrect, please add "Fracas-Wrong" label to prevent future updates.
- Go/Fracas
Users experienced this crash on the following builds:
Win Canary 58.0.3015.0 - 8.83 CPM, 32 reports, 32 clients (signature [Dump without crash] content::`anonymous namespace'::MaybeDumpCopiedNonSameOriginEntry)
Mac Canary 58.0.3015.0 - 6.59 CPM, 7 reports, 7 clients (signature [Dump without crash] content::`anonymous namespace'::MaybeDumpCopiedNonSameOriginEntry)
If this update was incorrect, please add "Fracas-Wrong" label to prevent future updates.
- Go/Fracas
This crash has high impact on Chrome's stability.
Signature: [Dump without crash] content::`anonymous namespace'::MaybeDumpCopiedNonSameOriginEntry.
Channel: canary. Platform: win.
Labeling issue 688425 with ReleaseBlock-Dev.
If this update was incorrect, please add "Fracas-Wrong" label to prevent future updates.
- Go/Fracas
Removing ReleaseBlock label, the crash is a DumpWithoutCrashing that we added to gather more data.
The following revision refers to this bug:
commit b1730dabdf125160dc23db993e08f453fc648fc8
Author: estark <estark@chromium.org>
Date: Sun Feb 19 00:06:26 2017}
[modify]
[modify]
[modify]
@erasmus425: can you try using Canary channel to reproduce this? And please enable crash/error reporting. @estark added logging and it would be great if we can confirm where the error is. Thanks.
I might be mistaken, but i'm reading everywhere that the canary version isn't available to the Linux platform. Do you have any solution ?
Since my main computer is on Linux, it might take a while before i can reproduce this bug in a Windows environment.
Issue 694184 has been merged into this issue.
@eramus425: ah you're right, I didn't notice you're on Linux.
Regardless, Emily seems to have tracked this down to the code path.
For Googlers reading this, per Maria here's a convenient link to look at all the crash reports that came with the debugging info Emily added:
This shows all the crash keys in one table. The main takeways are:
-RendererDidNavigateToNewPage is not involved
-all of the reports are from RendererDidNavigateToExistingPage
-there are no in_page hits
The following revision refers to this bug:
commit 7e735c119621aadf893858adb6c37b58325d5e94
Author: jam <jam@chromium.org>
Date: Tue Feb 21 21:18:54 2017
Revert of Use ScopedCrashKey for RendererDidNavigate crash dumps (patchset #4 id:60001 of )
Reason for revert:
We got the data we wanted.
Original issue's description:
>}
> Committed:
TBR=creis@chromium.org,rsesek@chromium.org,ananta@chromium.org,estark@chromium.org
# Not skipping CQ checks because original CL landed more than 1 days ago.
BUG= 688425
Review-Url:
Cr-Commit-Position: refs/heads/master@{#451834}
[modify]
[modify]
[modify]
It seems like estark@ is making good progress on this, please re-assign if you aren't the right owner.
jam@'s got a fix coming soon.
The following revision refers to this bug:
commit c5608a34fd0112511e9165179a91cdd9277518b2
Author: jam <jam@chromium.org>
Date: Wed Feb 22 09:49:13 2017
Revert of Add DumpWithoutCrashing in RendererDidNavigateToExistingPage (patchset #3 id:40001 of )
Reason for revert:
We got the data we wanted.
Original issue's description:
>}
> Committed:
TBR=nasko@chromium.org,estark@chromium.org
# Not skipping CQ checks because original CL landed more than 1 days ago.
BUG= 688425
Review-Url:
Cr-Commit-Position: refs/heads/master@{#451960}
[modify]
The following revision refers to this bug:
commit a78746ec1a1bfa668f5bcb01d2b2665d2c514369
Author: jam <jam@chromium.org>
Date: Wed Feb 22 17:21:57 2017
Fix SSL certificate being wrong in the intended_as_new_entry fase}
[modify]
Tomorrow I can merge 452106 to 57
Please mark security bugs as fixed as soon as the fix lands, and before requesting merges. This update is based on the merge- labels applied to this issue. Please reopen if this update was incorrect.
For more details visit - Your friendly Sheriffbot
+awhalley@ for M57 merge review.
govind@ - this will be good for M57 tomorrow after some more time in canary.
jam@ - thanks for the investigation and fix!
Thank you awhalley@. Please update after Canary baking. If all looks good, I will approve the merge. Thank you.
Thanks, will check in tomorrow.
Emily tracked this down; the fix is trivial after she localized it :)
@awhalley @govind
ok to merge?
Approving merge to M57 branch 2987 after discussing with awhalley@. Please merge ASAP. Thank you.
The following revision refers to this bug:
commit d37f8f3c85e4c2f6c5d040478f5067969f278650
Author: John Abd-El-Malek <jam@chromium.org>
Date: Fri Feb 24 19:20:11 2017
Fix SSL certificate being wrong in the intended_as_new_entry case}
(cherry picked from commit a78746ec1a1bfa668f5bcb01d2b2665d2c514369)
Review-Url: .
Cr-Commit-Position: refs/branch-heads/2987@{#680}
Cr-Branched-From: ad51088c0e8776e8dcd963dbe752c4035ba6dab6-refs/heads/master@{#444943}
[modify]
The following revision refers to this bug:
commit 43f7ab4d121be7ad05f31728ccc130d500232031
Author: nasko <nasko@chromium.org>
Date: Wed Mar 01 21:47:48 2017}
[modify]
The following revision refers to this bug:
commit 494a3b618ecf62e96f14c195a0d2234b20db785c
Author: jam <jam@chromium.org>
Date: Wed Mar 01 22:07:16 2017
Revert of Change CHECK into DCHECK. (patchset #1 id:1 of )
Reason for revert:
(per discussion, I was using this to get a signal. I'll send a cl to fix)
Original issue's description:
>}
> Committed:
TBR=creis@chromium.org,nasko@chromium.org
# Skipping CQ checks because original CL landed less than 1 days ago.
NOPRESUBMIT=true
NOTREECHECKS=true
NOTRY=true
BUG= 688425
Review-Url:
Cr-Commit-Position: refs/heads/master@{#454058}
[modify]
Congratulations! The panel decided to award $3,000 for this! A member of our finance team will be in touch.
*********************************
I did not know that would fit in the Google reward Bounty program, that's awesome !
Would it be possible to give a part to charity ?
To whom shall i address for it ?
erasmus425@ - great to hear! I've followed up in email.
This bug has been closed for more than 14 weeks. Removing security view restrictions.
For more details visit - Your friendly Sheriffbot | https://bugs.chromium.org/p/chromium/issues/detail?id=688425 | CC-MAIN-2018-51 | en | refinedweb |
Apache OpenOffice (AOO) Bugzilla – Issue 115789
No manifest:version attribute in manifest:manifest element
Last modified: 2011-01-24 14:20:56 UTC
Files from OpenOffice.org Writer fail the validation at the OpenOffice
validation site allegedly because the manifest:manifest (root) tag in the
META-INF/manifest.xml file lacks a version attribute.
upload:///Test from Win 7.odt/META-INF/manifest.xml[2,88]:Error:element
"manifest:manifest" is missing "version" attribute
upload:///Test from Win 7.odt/META-INF/manifest.xml[5,85]:Error:element
"manifest:file-entry" is missing "media-type" attribute
upload:///Test from Win 7.odt:Info:validation errors found
upload:///Test from Win 7.odt:Info:Generator: OpenOffice.org/3.3$Win32
OpenOffice.org_project/330m15$Build-9546
There's no requirement that I can find that manifest:manifest takes ANY
attribute other than the namespace declaration.
Created attachment 75141 [details]
Fails validation in META-INF/manifest.xml
reassigned
Set target to 3.4, and re-assigned issue.
I can confirm the issue, in the attached document with the latest version of the
online validator
The version attribute is missing in the root element of the manifest.xml.
Instead the missing mimetype attribute is a problem of the validator.
It can also reproduced by the latest online available OOo version
OOo-dev/3.4$Win32 OpenOffice.org_project/300m94$Build-9547
and
OpenOffice.org/3.3$Win32 OpenOffice.org_project/330m15$Build-9546
By saving any document, for instance an empty text document.
Respectfully, in the normal course of affairs when might this problem be resolved?
(I'm an advocate for the OpenDocument Text format, choosing to distribute ODT
files of biblical text at my site <tanach.us>. In promoting this new feature
and ODT I've claimed that my files validate with your validator. And they did a
few weeks ago. Now they don't, a source of consternation and embarrassment.)
fixed in cws fwk162
Today, 6 dec 2010, fails to
validate the trival OpenWriter file test.odt attached. Same error results.
Are the repairs to "cws fwk162" for the validator or OpenOffice Writer? When
will they take effect for the site users?
Thanks,
Chris Kimball
The changes in cws fwk162 fix the bug in package generation in OOo. As the
target field shows it is going to be integrated in OOo3.4 branch.
If you would like to test the cws after the integration in the development
branch you should wait for integration of the cws. Before the cws is integrated
this bug have to be set to Verified ( that would mean that the cws is already in
QA ). After the bug is verified you can track the status of the cws using the
following link:
The response by sus Mon Nov 29 11:39:22 +0000 2010 indicates the problem is in
the validator:
"The version attribute is missing in the root element of the manifest.xml.
Instead the missing mimetype attribute is a problem of the validator."
In creating my own manifest files, nothing is accepted by your validator. Would
you please provide an example of a valid manifest file? Or at least its root
element.
The latest ODF1.2 draft explicitly requires that manifest:manifest element
contains manifest:version attribute. Before this bug was fixed, it had not been
the case.
I have no information regarding the validator problem with the media-type that
sus has mentioned.
Changing the Summary to avoid further confusions. This bug is only about
manifest:version attribute in manifest:manifest element. I am not sure how the
validator issues are handled, but if issuezilla bugs are used for them as well,
then we need a new issue for validator.
The ODF validator has, apparently, been repaired. My unchanged files now
validate. OOWriter 3.3 files don't.
Thanks,
Chris
mav->mru: Please verify in fwk162.
Verified in CWS fwk162.
Checked in DEV300m98. | https://bz.apache.org/ooo/show_bug.cgi?id=115789 | CC-MAIN-2018-51 | en | refinedweb |
JTextPane: Change Text Properties - Online Code
Description
This is a code which describes some of the advantages of JTextPane Attributes. First select the Text and press the BNold Button and see the result.
Source Code
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TextAttributes extends JFrame { public TextAttributes() { setTitle("Change the properties of Text");... (login or register to view full code)
To view full code, you must Login or Register, its FREE.
Hey, registering yourself just takes less than a minute and opens up a whole new GetGyan experience. | http://www.getgyan.com/show/542/JTextPane%3A_Change_Text_Properties | CC-MAIN-2016-40 | en | refinedweb |
eh, why dont you just try doing -->
#ifndef GRAPH_HPP
#include <graph.hpp>
#define GRAPH_HPP
#endif
<-- the odds of this working are slim to none, but it worked for me 1ce, And I think I did it a little differently, oh well cant heart!
:) :) :) :) :p :p :p | http://cboard.cprogramming.com/cplusplus-programming/16039-question-where-sharpinclude-my-library-2-print.html | CC-MAIN-2016-40 | en | refinedweb |
ASP.NET HTTP Modules:
HTTP Modules:
HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching....
HTTP Modules are activated/called/invoked before and after HTTP Handler execution.
HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.
When any request goes to web server, request passes through different phases and then at last response gets generate for client.
HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.
Before HTTP Modules, web developers/programmers used to implement Internet Server Application Programming Interface (ISAPI) Filters like me (wish interviewer asked me about by terms of ISAPI at that time then I tell him (:D)), anyhow jokes apart.
As name implies ISAPI is a web server based API and used to manage request which comes to web server and generate response. ISAPI based upon web server (IIS) where as NSAPI is Netscape based web server API.
ISAPI is based upon win32 DLL and programmed in unmanaged code C/C++, which is somehow painful (:$) and due to unmanaged code, is less reliable, scalable and quite complex to implement than HTTP Modules by managed code under the framework of .Net. Hope you got it why ISAPI Filters replaced by HTTP Modules (;))
Asp.net requests goes through HTTP Modules events just like (oil flowing through pipeline and that pipeline has some filters to refine that oil)
HTTP Modules Events:
Every HTTP Module must implement following two methods of IHTTPModule interface:
Init: To register/initialize event handler to the events of HTTP Module for HTTP based application.
Dispose: To perform a clean up code means resource releasing, object removing from memory and such other resources releasing which used explicitly.
Following are list of events with their brief description:
BeginRequest: Event fired whenever any asp.net based request sent to web server. If you need to do perform at the beginning of a request for example, modify show banners, log HTTP Header information, Get/Set cultures, Response.Filter to generate response for browser according to your need.
AuthenticateRequest: If you want to check authentication of request that request comes from authenticated user or not means wants to implement custom authentication scheme. For example, look up a requested user credentials against a database to validate.
AuthorizeRequest: This method is used specifically to implement authorization mechanisms means authenticated user/request has what privileges/rights/access in that specific application for example, either user has access on all pages or not of that website or has write to create file or not or visit report pages and like this.
ResolveRequestCache: This event determines if a page from output back to the Output cache. If you are building a custom cache module, you have to write the output back to your cache.
Error: this event always occurs when any exception (unhandled error occurs in application, this event specifically uses to handle or log error messages of that web application. (Heavily used in Error Logging Modules and Handlers (ELMAH) kind of applications). You can learn about ELMAH more from following link in detail:
EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information on the page.
By above events list you must be getting wonder about difference between Global.asax as somehow events of Global.asax are pretty same, so let me tell you difference between Global.asax and HTTP Module (another common question asked in interviews)
But you need to register/initialize these Events explicitly in “Init” method; following is sample code of IHTTPModule implementation for couple of events.
"kwd">using System;
"kwd">using System.Web;
"kwd">using System.Collections;
"kwd">public class HelloWorldModule : IHttpModule
{
"kwd">public String ModuleName
{
"kwd">get { "kwd">return "st">"HelloWorldModule"; }
}
"cmt">// In the Init function, register for HttpApplication
// events by adding your handlers.
"kwd">public void Init(HttpApplication application)
{
application.BeginRequest += ("kwd">new EventHandler("kwd">this.Application_BeginRequest));
application.EndRequest += ("kwd">new EventHandler("kwd">this.Application_EndRequest));
}
"cmt">// Your BeginRequest event handler.
"kwd">private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("st">"<h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");
}
"cmt">// Your EndRequest event handler.
"kwd">private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("st">"<hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>");
}
"kwd">public void Dispose()
{
}
}
Ref: msdn
HTTP Module vs Global.asax
2. According to life cycle of Request, Request passed through HTTP Module first and then through Global.asax
3. Following are list of events which are supported in Global.asax but unfortunately not in HTTP Module.
Here I would like to share one more interview experience of me but now its about my friend’s interview, for which he did preparation from me/took my help or guidance for it Anyhow whilst I was helping him in his preparation for asp.net technical interview, I asked him: “ tell me when session starts?” He replied: “Simple when user logins from login page”, I said ok! Suppose site has no login page and could be accessible by anonymous user, session will never start and Session_OnStart event of Global.asax will never fire then is it? He replied: of course, I couldn’t stop me to smile; I might not laugh if he has no experience or less experience but he has more than 4 years of experience. Anyhow next day when he went for interview, interviewer asked him the same question and he smiled and said, “If you think I will say when user login session_Onstart event will fire then you are wrong. (They also started laughing).
Anyhow normally people say or according to books to tell reader in easy way that session are user based, NO! Sessions are actually browser based. Anyhow shouldn’t go away from topic as much.
Registering HTTP Module
The following is an example of registering/adding an HTTP module:
<httpModules> <add type="ClassName, AssemblyName" name="ModuleName" /> <httpModules>
Following is the list of module is defined at machine.config or web.config by default. ($WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG\ CONFIG Files)
Performance:
You can improve performance of your application by removing default (but not in used) HTTP Modules registered in machine.config file as these are activated/invoked/called on each request for your application unnecessarily by <remove …> for example,
But please make sure before its implementation/applying that you are not using them. If you are using any of these, you may exclude that from existing list.
Conclusion
HTTP Modules are quite simple to understand and quite flexible by means of its number of events. HTTP modules integrate with whole application and every request passed through HTTP Module. So HTTP Module should be implemented very carefully. Take the time to completely understand its advantages, disadvantages, implementation and concepts before implementing a solution.
To get more detailed understanding of HTTP Modules with real time examples implmentation, I would recommend you to visit following links:
For URL Redirection example click here
For Security based example click here
For IP based security example click here
For Error Manager Example click here
For Videos click. | http://www.codeproject.com/Articles/32475/Asp-net-HTTP-Modules?msg=2878463 | CC-MAIN-2016-40 | en | refinedweb |
From time to time we see the need for Varnish to switch behavior based on an external event. Let's have a look at how that can be done.
Some time ago I was asked how a ticket auction site should deal with massive traffic spikes. These sites can get an horrendous amount of traffic in a rather short time frame and the content is in its nature quite dynamic. This is what advice we gave them in order to quickly build something that would scale.
Firstly we recommend to cache everything. You don't have to cache it for a long period, just caching stuff for a second will reduce the load on the backend from hundreds or thousands per second to one single request. That alone can make a huge difference.
They also wanted to be able to change the behavior of the caching layer depending on whether the concert was sold out or not. The ideal place to do this would obviously be in the response headers coming from the backend but for some reason they couldn't or wouldn't do that. What to do?
One of the hidden gems of Varnish Cache is Tollefs Variable VMOD. It is a really simple piece of code that very easily gives you access to variables, or rather associative arrays in VCL.
Lets say the site had a URL structure like this site.com/tickets/$EVENT - where $EVENT would be a unique identifier for the event. Normally we would enforce a one second TTL on everything below /tickets/. In case the event is sold out we can set the TTL to one hour.
This would consist of two parts. First the part that governs the TTL:
in vcl_fetch:
import var; (..) if (req.url ~ ^/tickets/) { set beresp.ttl = 1s;
Now we have enforced the one second TTL. We now would like to override the sold out events.
# Pick the event out of the URL and place it in a var: var.set("event", regsub(req.url, "/tickets/([^/]+).*", "\1")); if (var.global_get(var.get("event") == "soldout") { set beresp.ttl = 1h; } }
That wasn't so hard. Now we only need a way to set the event as sold out. We define /set/$EVENT/$STATUS to set the $EVENT to $STATUS. In real life you probably want to protect this part with ACLs.
in vcl_recv:
if (req.url ~ "/set/[^/]+/[^/]+" { var.set("event", regsub(req.url, "/set/([^/]+).*", "\1")); var.set("status", regsub(req.url, "/set/[^/]+/([^/]+)", "\1")); }
Now, the moment an event sells out they call /set/$EVENT/soldout and change the TTL to one hour.
You should note that the variable VMOD stores the variables in a simple list. This works really well as long as the amount of variables is rather small. If you plan on storing a huge number of variables you'd probably need to rewrite the variable vmod to use a more advanced data structure. I'm pretty sure Tollef will be happy for a patch.
Picture is (c) DBduo Photography used under a CC license. | https://info.varnish-software.com/blog/switching-behavior-dynamically-varnish | CC-MAIN-2016-40 | en | refinedweb |
Hi,
I am trying to create an object which contains data members from the base class and the inherited class.
vehicle.h:
Code:#include <iostream> using namespace std; class Vehicle { public: void EnterNewVehicle() { cout << "Inside Vehicle class" << endl; } private: int m_MPG; }; class Car : public Vehicle { public: private: int m_NoOfDoors; };
main.cpp:
So I'm trying to create an object called 'node' of type Car which will have both the data members MPG and NoOfDoors.So I'm trying to create an object called 'node' of type Car which will have both the data members MPG and NoOfDoors.Code:#include <iostream> #include "vehicle.h" using namespace std; int main() { int choice = 0; cout << "Enter 1 to create a car" << endl; cin >> choice; switch(choice) { case 1: //Create an object of type Car Vehicle node; //I need to create a Car object with data members from both Vehicle and Car node.EnterNewVehicle(); case 2: break; } system ("PAUSE"); return 0; }
I can ask the user for the MPG value, but don't know how to then transition into asking and entering the value for NoOfDoors.
If someone could be so kind as to tell me how this is done I'd be most grateful, but PLEASE try and explain it to me in VERY basic terms because I won't 'get it' otherwise.
Many thanks! | http://cboard.cprogramming.com/cplusplus-programming/114298-polymorphism-newbie-question.html | CC-MAIN-2016-40 | en | refinedweb |
IronRuby is a Ruby implementation that is written on top of the .NET framework. It runs on top of the DLR (Dynamic Language Runtime), the bridge between the .NET framework and the dynamic languages that are written on top of it.
The main goal of IronRuby is to provide seamless integration with .NET objects that is achieved in a very elegant way; to work with a .NET assembly, just load it using Ruby’s require method (similar to adding a reference in C#/VB.NET).
For example, assuming you have the next C# class that features two methods which indicate whether a given time is daytime or nighttime and it is saved in an assembly named CustomTools.dll:
using System; namespace CustomTools { public class DayNightHelper { public bool IsDay(DateTime value) { if (value.Hour > 7 && value.Hour < 19) return true; else return false; } public bool IsNight(DateTime value) { bool isDay = IsDay(value); return !isDay; } } }
Using this class from IronRuby is easy as pie:
require "DayNightHelper.dll" # Call C# class constructor helper = CustomTools::DayNightHelper.new # Call C# method day = helper.is_day(Time.now) if day then puts "The sun is in the sky, go out!" else puts "Good night!" end
Because calling .NET assemblies is so easy from IronRuby code, it enables developers to take advantage of Ruby’s libraries and frameworks together with .NET assemblies, and make the most out of this combination.
One of the areas that pops to my mind instantly, which makes the Ruby/.NET combination shine the most, is using Ruby’s incredible testing frameworks to test .NET code.
In this article, I will introduce three of Ruby’s testing frameworksRSpec, Cucumber, and riotand show you how to use them to test .NET code.
RSpec
RSpec is one of the most popular testing frameworks in Ruby, if not the top one. It follows BDD (Behavior Driven Development) principles, a fact that reflects on its terms. Basically, in RSpec you separate your tests into behaviors which are the test containers. Every behavior contains multiple examples, which are the test methods. The logic behind the terms is to give you the illusion that you do not test codeyou validate behavior.
RSpec provides a DSL (Domain Specific Language) for tests that result in clean and elegant test code. A behavior is contained within a method named describe. This method receives a textual description of the behavior or a class type, if a single class is being tested. Inside the describe call body, you can add multiple examples via a method named it. This method receives a textual description as well, and contains the actual test code. In addition, every example must have some kind of comparison between the expected result and the actual one. This is done with the should method, which is added to all Ruby objects.
For example, a simple RSpec code to validate the behavior of the DayNightHelper class is as follows. Notice the clean code:
require "DayNightHelper.dll" # The following require statements are needed for RSpec to run require "rubygems" require "spec" require "spec/autorun" # Define a behavior with describe describe "Test DayNightHelper class for perfection" do # Define examples with it it "should be day on 15:00" do instance = CustomTools::DayNightHelper.new result = instance.is_day(Time.local(2012,12,21,15,0)) # Compare actual and expected result with should result.should == true end it "should not be night on 15:00" do instance = CustomTools::DayNightHelper.new result = instance.is_night(Time.local(2012,12,21,15,0)) # There are also some cool methods to do common comparisons. # For example, the next line is identical to "result.should == false": result.should be_false end end
Executing behaviors is done from the command line using the IronRuby interpreter: ir.exe. Assuming the RSpec code is located in a file named rspec_test.rb, executing it will be done as follows:
>ir rspec_test.rb .. Finished in 0.168009 seconds 2 examples, 0 failures
It is also possible to show the textual descriptions of the behavior and examples in the report by using --format s:
>ir rspec_test.rb --format s Test DayNightHelper class for perfection - should be day on 15:00 - should not be night on 15:00 Finished in 0.158009 seconds 2 examples, 0 failures
What I brought you here is only a taste of RSpec capabilities. To learn more about it, visit the RSpec official site. | http://www.informit.com/articles/article.aspx?p=1583174&seqNum=3 | CC-MAIN-2016-40 | en | refinedweb |
Created attachment 567424 [details]
Input to trigger the crash.
The attached SVG file causes a nasty looking crash at least in Firefox 8.0. I haven't tested with other versions yet. The original file crashed at 0x4, but the address moved while looking for a simpler triggering file and ended up at 0xff000004. High crash addresses often imply security impact, so reporting this as a security bug to be on the safe side.
Crash report:
7.0.1 crashed at NS_NewAtom, address 0x1800004 -
Local debug build I'm getting a crash at:
> xul.dll!nsGenericElement::GetAttributes(aAttributes=0x0fd29d78) Line 2510 C++
`this` == 0xffffffc8
xul.dll!mozilla::SVGMotionSMILAnimationFunction::RebuildPathAndVerticesFromMpathElem(aMpathElem=0x11dea100) Line 251 C++
xul.dll!mozilla::SVGMotionSMILAnimationFunction::RebuildPathAndVertices(aTargetElement=0x0988de30) Line 309 C++
And the bug is very likely to be in this code:
which also needs a namespace check
Created attachment 567469 [details] [diff] [review]
Check node type, not just name, rev. 1
Setting tracking flags, to be sure this makes it to stable branches. (There's an aurora/beta channel/triage meeting this Thursday -- hopefully we can get approval and land this on branches on that day or the next)
Comment on attachment 567469 [details] [diff] ()).
i.e. just add something like this
genericTarget->GetNameSpaceID() == kNameSpaceID_SVG &&
either before or after the Tag() check.
IsSVG() includes some stuff that's not in the SVG namespace (I'm actually not entirely sure what, offhand), and it's probably better to be more specific. It's also more consistent with the related function "GetFirstMpathChild"
which checks the namespace explicitly.
(In reply to Daniel Holbert [:dholbert] from comment #6)
> Comment on attachment 567469 [details] [diff] [review] [diff] [details] ()).
Agreed. Other code elsewhere has namespace checks so we should be consistent here.
Created attachment 567512 [details] [diff] [review]
Check namespace, not just name, rev. 2
This is the patch without the tests for immediate committal: the test will be embargoed until this is released/made public.
Created attachment 567515 [details] [diff] [review]
Automated test
bsmedberg, is this fix ready for review? If so, please request... Also, tracking for 8 and 9, we have a patch and it's a critical bug with a trivial fix, might as well take it.
Comment on attachment 567512 [details] [diff] [review]
Check namespace, not just name, rev. 2
It's got implicit r+ (I r+'d the obsolete earlier version, and then requested this tweak).
explicitly marking r+ for clarity.
FTR, landed earlier today ;-)
Comment on attachment 567515 [details] [diff] [review]
Automated test
Just for good measure, r+ on the crashtest, too, though as bsmedberg said in comment 8, it should wait until the fix has made it to releases.
I tested it locally (with directory-targeted "make crashtests") and successfully crashed, in an unpatched build.
Excellent! Sorry I missed the earlier review on the obsoleted patch. Please request approval for the relevant branches as soon as this is looking good on m-c.
Landed on m-c:
We'll need a backport for 3.6 as well if this affects that branch.
Comment on attachment 567512 [details] [diff] [review]
Check namespace, not just name, rev. 2
---------------------------------[ Triage Comment ]---------------------------------
Approving for 8beta and 9aurora as this is a sg:crit bug filed by an external reporter and the patch looks safe.
Please land ASAP.
(In reply to Christian Legnitto [:LegNeato] from comment #16)
> We'll need a backport for 3.6 as well if this affects that branch.
Happily, this doesn't affect that branch. The feature being exploited here (SVG SMIL, animateMotion support in particular) was new in Firefox 4.
Verified fixed using the attached testcase in Firefox 8.0.1, 9.0b3, and 10.0a2 | https://bugzilla.mozilla.org/show_bug.cgi?id=694953 | CC-MAIN-2016-40 | en | refinedweb |
QBluetoothTransferManager
Since: 1.2
#include <QtConnectivity/QBluetoothTransferManager>
More information will be added here shortly. For now, you'll find more extensive information about this class in the Qt reference for QBluetoothTransferManager
The QBluetoothTransferManager class allows the application to send data objects to other devices.
Currently implemented using OPP.
QBluetoothTransferManager uses OBEX to send get and put commands to remote devices.
Overview
Public Types Index
Public Functions Index
Signals Index
Public Types
This enum describes the type of operation that a transfer request is for.
GetOperation The get operation is used to retrieve an object from a remote device. Not implemented. PutOperation The put operation is used to send an object to a remote device.
- GetOperation
-
- PutOperation
-
Public Functions
Constructs a new QBluetoothTransferManager with parent.
Destructor.
QBluetoothTransferReply *
Sends the contents of data to the remote device request and returns a new QBluetoothTransferReply, that can be used to track the request's progress.
Signals
void
This signal is emitted when the transfer for reply | https://developer.blackberry.com/native/reference/cascades/qbluetoothtransfermanager.html | CC-MAIN-2016-40 | en | refinedweb |
ofxparse 0.1
Tools for working with the OFX (Open Financial Exchange) file format
ofxparse
of. This library has been tested with BankAccount files. The other two types, CreditAccount and InvestmentAccount have not been tested. If you have a sample of these other types that could be used to help this project, please see the Help! section below.
Example Usage
Here’s a sample program:
from ofxparse import OfxParser ofx = OfxParser.parse(file('file.ofx')) ofx.account # An account with information ofx.account.number # The account number ofx.account.routing_number # The transit id (sometimes called branch number) ofx.account.statement # Account information for a period of time ofx.account.statement.start_date # The start date of the transactions ofx.account.statement.end_date # The end date of the transactions ofx.account.statement.transactions # A list of account activities ofx.account.statement.balance # The money in the account as of the statement date ofx.account.statement.available_balance # The money available from the account as of the statement date
I’m looking for different types of accounts to make this library more robust. I’m looking for sample credit account or investment account files. Please (anonymize first) and mail to jseutter dot ofxparse at gmail dot com.
License
ofxparse is released under an MIT license. See the LICENSE file for the actual license text. The basic idea is that if you can use Python to do what you are doing, you can also use this library.
- Author: Jerry Seutter
- Keywords: ofx,Open Financial Exchange,file formats
- License: MIT License
- Categories
- Package Index Owner: jseutter
- DOAP record: ofxparse-0.1.xml | https://pypi.python.org/pypi/ofxparse/0.1 | CC-MAIN-2016-40 | en | refinedweb |
Read and write data in spreadsheet files, including
.xls and
.xlsx files.
Import spreadsheet data interactively using the Import Tool. Import or export spreadsheet data
programmatically using the functions on this page. To compare primary
import options for spreadsheet files, see Ways to Import Spreadsheets.
Select Spreadsheet Data Using Import Tool
This example shows how to import data from a spreadsheet into the workspace with the Import Tool.
Import a Worksheet or Range
This example shows how to import mixed numeric
and text data from a spreadsheet into a table, using the
readtable function.
Import All Worksheets from a File
This example shows how to import worksheets
in an Excel file that contains only numeric data (no row or column
headers, and no inner cells with text) into a structure array, using
the
importdata function.
Import and Export Dates to Excel Files
Microsoft Excel software can represent dates as text or numeric values.
Export to Excel Spreadsheets
This example shows how to export a numeric
array and a cell array to a Microsoft Excel spreadsheet file,
using the
xlswrite function.
Import or Export a Sequence of Files
To import or export multiple files, create a control loop to process one file at a time.
Define Import Options for Tables
Typically, you can import tables using the
readtable function.
Ways to Import Spreadsheets
You can import data from spreadsheet files into MATLAB® interactively, using the Import Tool, or programmatically, using an import function.
System Requirements for Importing Spreadsheets
If your system has Excel for Windows® installed, including the COM server (part of the typical installation of Excel): | http://uk.mathworks.com/help/matlab/spreadsheets.html?requestedDomain=uk.mathworks.com&nocookie=true | CC-MAIN-2016-40 | en | refinedweb |
#include "petscsys.h" PetscErrorCode PetscLogEventRegister(const char name[],PetscClassId classid,PetscLogEvent *event)Not Collective.
The classid is associated with each event so that classes of events can be disabled simultaneously, such as all matrix events. The user can either use an existing classid, such as MAT_CLASSID, or create their own as shown in the example.
If an existing event with the same name exists, its event handle is returned instead of creating a new event.
Level:intermediate
Location:src/sys/logging/plog.c
Index of all Profiling routines
Table of Contents for all manual pages
Index of all manual pages | http://www.mcs.anl.gov/petsc/petsc-dev/docs/manualpages/Profiling/PetscLogEventRegister.html | CC-MAIN-2016-40 | en | refinedweb |
is a method that must not proceed until a shared variable
joy has been set by another thread. Such a method could, in theory, simply loop until the condition is satisfied, but that loop is wasteful, since it executes continuously while waiting.
public void guardedJoy() { // Simple loop guard. Wastes // processor time. Don't do this! while(!joy) {} System.out.println("Joy has been achieved!"); }
A more efficient guard invokes
Object.wait to suspend the current thread.!"); }
waitinside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
Like many methods that suspend execution,
wait can throw
InterruptedException. In this example, we can just ignore that exception we only care about the value of
joy.
Why is this version of
guardedJoy synchronized? Suppose
d is the object we're using to invoke
wait. When a thread invokes
d.wait, it must own the intrinsic lock for
d otherwise an error is thrown. Invoking
wait inside a synchronized method is a simple way to acquire the intrinsic lock.
When
wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke
Object.notifyAll, informing all threads waiting on that lock that something important has happened:
public synchronized notifyJoy() { joy = true; notifyAll(); }
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of
wait..
public(); } }
The producer thread, defined in
, sends a series of familiar messages. The string "DONE" indicates that all messages have been sent. To simulate the unpredictable nature of real-world applications, the producer thread pauses for random intervals between messages.
Producer
import"); } }
The consumer thread, defined in
, simply retrieves the messages and prints them out, until it retrieves the "DONE" string. This thread also pauses for random intervals.
Consumer
import) {} } } }
Finally, here is the main thread, defined in
, that launches the producer and consumer threads.
ProducerConsumerExample
public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } }
Dropclass was written in order to demonstrate guarded blocks. To avoid re-inventing the wheel, examine the existing data structures in the Java Collections Framework before trying to code your own data-sharing objects. For more information, refer to the Questions and Exercises section. | http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html | CC-MAIN-2016-40 | en | refinedweb |
import "Accessibility_Hyperlink.idl";
List of all members.
Hyperlinks may have multiple "anchors", where an anchor corresponds to a reference to a particular resource with a corresponding resource identified (URI). Hyperlinks may be queried for their URIs, or queried for the objects corresponding to their anchors. The objects thus obtained are instances of Accessible, and may be queried, and manipulated via the Action interface.
Definition at line 47 of file Accessibility_Hyperlink.idl. | https://people.gnome.org/~billh/at-spi-new-idl/html/html/classAccessibility_1_1Hyperlink.html | CC-MAIN-2016-40 | en | refinedweb |
Bug in AsyncEnumerable or AsyncCTP?
- Wednesday, February 09, 2011 7:36 PM
I think I've found a bug in either the AsyncCTP or the IAsyncEnumerable implementation.
I have an observable source of integers, generated with time, converted to an async enumerable. When I use this IAsyncEnumerable in a while loop (i.e. while (await ...)), the resulting continuation only appears to run once and then hangs (or never comes back).
If I remove the time delay (see [1] below), the loop runs to completion. If I add a side effect (see [2] below) after the call to ToAsyncEnumerable, the loop runs to completion.
I have written a minimal test case that exhibits the bug. In the continuation of the while(await ...) loop, we're pushing each integer on the stack and sleeping (blocking) for a bit. At the end of the test, we verify that all integers have been pushed in a "reasonable" amount of time. Here is the code:
using System; using System.Collections.Generic; using System.Concurrency; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AsyncAwaitBugTest { [TestClass] public class AsyncAwaitBugTests { [TestMethod] public void TestPushPopAsync() { var stack = new Stack<int>(); var count = 10; var observable = Observable.GenerateWithTime( 0, i => i < count, i => i + 1, i => i, i => TimeSpan.FromMilliseconds(1), // change this to 0 to avoid the problem [1] Scheduler.ThreadPool); var task = DoSomethingAsync(observable, stack); // we give it a timeout so the test can fail instead of hang task.Wait(TimeSpan.FromSeconds(2)); Assert.AreEqual(10, stack.Count); } private async Task DoSomethingAsync(IObservable<int> observable, Stack<int> stack) { var ae = observable .ToAsyncEnumerable() //.Do(i => Debug.WriteLine("Bug-fixing side effect: " + i)) // [2] .GetEnumerator(); while (await ae.MoveNext()) { var i = ae.Current; Debug.WriteLine("Doing something with " + i); Thread.Sleep(50); stack.Push(i); } } } }
All libraries are up-to-date as of the time of this writing:
Visual Studio 2010 Premium: version 10.0.30319.1
.NET 4.0 runtime version v4.0.30319
AsyncCtpLibrary.dll version 1.0.3951.36518
System.CoreEx.dll, System.Linq.Async.dll, System.Reactive.dll version 1.0.2838.104
Any advice or suggestions would be greatly appreciated. Thanks!
- Edited by Aaron Olson Wednesday, February 09, 2011 7:38 PM formatting issues
-
All Replies
- Monday, February 14, 2011 3:51 PM
The "smallest" side-effect I've found that avoids the bug is Thread.Sleep(0) instead of writing a string somewhere.
Presumably, all that's needed is to surrender the thread.
- Monday, February 14, 2011 6:29 PM
I also ran into this problem, and have traced it to a bug in the implementation of ToAsyncEnumerable<TSource>(). In this method, and in the private ToAsyncEnumerableObserver<TSource> class, TaskCompletionSource.SetResult() is called inside a lock. Despite its innocent-sounding name, SetResult() has a side effect of running any continuations waiting for the task to complete. In general, it's a bad idea to run arbitrary callback code inside of a lock. In your example the continuation results in a call to MoveNext() which re-acquires the lock (since it's on the same thread which already has the lock), violating some of the locking logic used to decide whether to dequeue or defer for the next value. Introducing the .Do() after ToAsyncEnumerable() avoids the bug because the continuation now no longer calls MoveNext(). In fact .Do(i => {}) is sufficient to avoid the bug.
The fix is fairly simple - move the call to SetResult() and SetException() outside of the lock region. Hopefully the team can get this on the list for the next release.
Steve.
- Wednesday, February 23, 2011 1:11 AMThanks for reporting this. It will be fixed soon.
- Marked As Answer by fixedpoint Wednesday, February 23, 2011 1:11 AM
- | http://social.msdn.microsoft.com/Forums/en-US/rx/thread/f1b0ca02-675f-4dd7-9519-9670b6b2594a | CC-MAIN-2013-20 | en | refinedweb |
How to Calculate Return on Investment of Social Marketing simple:
ROI = (Gain from Investment - Cost of Investment) ÷ Cost of Investment
The devil is, as usual, in the details. The cost of an investment means more than cold, hard cash. Depending on the type of effort for which you’re computing ROI, you may need to include the cost of labor (including your own!), subcontractors, fees, and advertising for an accurate picture. When calculating ROI for your entire business, be sure to include overhead, cost of goods, and cost of sales.
You can affect ROI positively by either increasing the return (revenues) or reducing costs. That’s business in a nutshell.
Because the formula is flexible, be sure that you know what other people mean when they talk about ROI.
You can calculate ROI for a particular marketing campaign or product or an entire year’s worth of marketing expenses. Or, compare ROI among various forms of marketing, comparing the net revenue returned from an investment in social media to returns from SEO or paid advertising.
Run ROI calculations monthly, quarterly, or yearly, depending on the parameter you’re trying to measure.
Try the interactive ROI calculator. You can modify this model for social media by treating Monthly Site Visits as social media visits, Success Events as click-throughs to your main site, and Value of Success Events as the value of a sale. See what happens when you improve the business metric (the value of a sale) instead of, or in addition to, improving performance (site traffic or conversion rate).
ROI may be expressed as a rate of return (how long it takes to earn back an investment). An annual ROI of 25 percent means that it takes four years to recover what you put in. Obviously, if an investment takes too long to earn out, your product — or your business — is at risk of failing in the meantime.
If your analysis predicts a negative ROI, or even a very low rate of return over an extended period, stop and think! Unless you have a specific tactical plan (such as using a product as a loss leader to draw traffic), look for an alternative effort with a better likelihood of success.
Technically speaking, ROI is a business metric, involving the achievement of business goals, such as more clicks from social media that become sales, higher average value per sale, more repeat sales from existing customers, or reduced cost of customer acquisition. wall, or retweet your comments
These measurements may be worth monitoring, but they’re only intermediate steps in the ROI process.
Here’s how to calculate your return on investment:
Establish baselines for what you want to measure before and after your effort.
For example, you may want to measure year-over-year growth.
Create activity timelines that display when specific social media marketing activities take place.
For example, mark an event on an activity timeline when you start a blog or Twitter campaign.
Plot business metrics over time, particularly sales revenues, number of transactions, and net new customers.
Measure transactional precursors, such as positive versus negative mentions online, retail store traffic, or performance metrics.
For example, keep a tally of comments on a blog post or of site visits.
Line up the timelines for the various relevant activities and transactional (business) results.
Look for patterns in the data that suggest a relationship between business metrics and transactional precursors.
Prove those relationships.
Improvement in performance metrics doesn’t necessarily produce better business results. The only two metrics that count toward ROI are whether your techniques reduce costs or improve revenue. | http://www.dummies.com/how-to/content/how-to-calculate-return-on-investment-of-social-ma.html | CC-MAIN-2013-20 | en | refinedweb |
Moving on from simply panning, zooming and generally controlling the map view it is also possible to add Pushpin markers and more general shapes.
The Silverlight map control uses a special Pushpin class and additional GeoCoordinate(38, -1.5)};
Pushpin pin = new Pushpin(){Location= new GeoCoordinate(38, -1.5)};
This creates a Pushpin at the specified position. To make the pin display you need to add it to the map object:
MyMap.Children.Add(pin);
The default Pushpin
At this point you might be disappointed with the appearance of the default Pushpin. It may not look impressive but it behaves in a different way to the desktop version and it is much easier to customise. good news is that the content displays within the Pushpin's top display area which also grows to accommodate it.
Pushpin with content GeoCoordinate(38, -1.5)};pin.Width = 50;pin.Height = 200;pin.Content = new Ellipse(){ Fill = new SolidColorBrush(Colors.Red), Height = 100,Width = 100};
map1.Children.Add(pin);
Pushpin pin = new Pushpin(){ Location= new GeoCoordinate(38, -1.5)};pin.Width = 50;pin.Height = 200;pin.Content = new Ellipse(){ Fill = new SolidColorBrush(Colors.Red), Height = 100,Width = 100};
map1.Children.Add(pin);
A custom Pushpin
The default look of the Pushpin is set by a template. Of course you can set the Template property yourself:my="clr-namespace:Microsoft.Phone. Controls.Maps; assembly=Microsoft.Phone.Controls.Maps"
With this resource defined you can set the appearance of a Pushpin dynamically in code using:
Pushpin pin = new Pushpin(){ Location= new GeoCoordinate(38, -1.5)};pin.Width = 50;pin.Height = 100;pin.Template = (ControlTemplate)Application.Current.Resources["PinTemplate"];map1.Children.Add(pin);
Pushpin pin = new Pushpin(){ Location= new GeoCoordinate(38, -1.5)};pin.Width = 50;pin.Height = 100;pin.Template = (ControlTemplate)Application.Current.Resources["PinTemplate"];map1. Of course you can display text in the same way and you can set a custom bitmap using the Source property.
<ASIN:0672333481>
<ASIN:1430229284>
<ASIN:0470922443>
<ASIN:1430233125> | http://www.i-programmer.info/programming/mobile/1357-windows-phone-7-the-bing-maps-control.html?start=2 | CC-MAIN-2013-20 | en | refinedweb |
09 November 2010 15:22 [Source: ICIS news]
RIO DE JANEIRO (ICIS)--Braskem is targeting an increase of $50/tonne (€36/tonne) for all grades of polyethylene (PE) sold in ?xml:namespace>
The price hikes would take effect in the second half of November, said Braskem export manager Marco Cione.
Cione was speaking on the sidelines of the Latin American Petrochemical Association’s (APLA) annual meeting.
The price of Brazilian PE imports in
Cione attributed the proposed increases to changing market conditions.
Similarly, PP prices may rise by $50-100/tonne in the second half of the month for the same reason.
The price of Brazilian PP imports in
($1 = €0.72). | http://www.icis.com/Articles/2010/11/09/9408730/apla-10-braskem-targets-50tonne-pe-hikes-in-colombia.html | CC-MAIN-2013-20 | en | refinedweb |
CDF inv
Evaluates the inverse of the hypergeometric cumulative density function.Controller: CodeCogs
Contents
This function evaluates the inverse of the hypergeometric cumulative density function.
Example 1
#include <iostream> #include <codecogs/statistics/distributions/discrete/hypergeometric/cdf_inv.h> int main() { std::cout << "hypergeometric CDF inverse (0.9, 2, 3, 2) = "; std::cout << Stats::Dists::Discrete::Hypergeometric::CDF_inv(0.9, 2, 3, 2) << std::endl; return 0; }Output:
hypergeometric CDF inverse (0.9, 2, 3, 2) = 1
Authors
- Lucian Bentea (September 2005)
Source Code
Source code is available when you agree to a GP Licence or buy a Commercial Licence.
Not a member, then Register with CodeCogs. Already a Member, then Login. | http://www.codecogs.com/code/statistics/distributions/discrete/hypergeometric/cdf_inv.php | CC-MAIN-2013-20 | en | refinedweb |
If your program needs to support many languages at the same time, you may want to create multiple translation instances and then switch between them explicitly, like so:
import gettext lang1 = gettext.translation(languages=['en']) lang2 = gettext.translation(languages=['fr']) lang3 = gettext.translation(languages=['de']) # start by using language1 lang1.install() # ... time goes by, user selects language 2 lang2.install() # ... more time goes by, user selects language 3 lang3.install()
See About this document... for information on suggesting changes.See About this document... for information on suggesting changes. | http://docs.python.org/release/2.1/lib/node195.html | CC-MAIN-2013-20 | en | refinedweb |
20 January 2010 16:36 [Source: ICIS news]
By Malini Hariharan
The ?xml:namespace>
It was not too long ago that projections were being made of a benzene surplus in the
The new regulation requires an annual benzene average of 0.62% by volume in a refiner’s system wide gasoline pool. Small refiners have time until 1 January 2015 to meet this requirement.
The size of the
But Dewitt & Co in a recently concluded study questions whether the effect would be as great as that foreseen by the EPA and other analysts.
“The experience in
“A refiner can precut naphtha to eliminate the precursors of benzene. There are also other things; hydrogen is cheap in the US because of low gas prices. So refiners can saturate it to make cyclohexane which is a good gasoline component. Or they can optimise to other products,” Nicholson says.
The US is estimated to have imported around 1m tonnes of benzene last year as production fell sharply due to cuts in refinery operating rates on weak gasoline demand and poor economics.
Poor gasoline demand resulted in decreased demand for octane and therefore for reformate, which is the leading source of benzene in
“We estimate that
A previous study done by the consultancy in 2007 had predicted that the impact of the MSAT II regulations would be much less than estimates by most commentators. And the main message from the new study is that the US will continue to be a significant importer of benzene.
But import volumes will depend on operating rates at US styrene plants and demand from
DeWitt estimates that the
“This was because domestic demand declined and also because of competitive ethylene,” points out Nicholson. Natural gas-based ethylene economics in the US improved significantly last year following a softening in the prices of ethane.
“So even if benzene prices are higher, the ethylene advantage will allow the
US styrene producers have struggled in the last few years with poor profitability and weak demand growth for key derivatives. The industry has seen considerable rationalisation of capacity, but more plant closures and alliances are possible as producers fear thin margins and sluggish demand recovery in 2010.
“Further rationalisation of styrene capacity in the
While Dewitt’s study makes an assessment of US benzene balances in the coming years, Nicholson stresses that the analysis is not straightforward.
“If the
He also points out that the 2007 Dewitt study had forecast that the
“That view has changed; there will be continuous imports from outside the region. Asia will export to the US and volumes will depend on price and end-use markets,” says Nicholson.
And within. | http://www.icis.com/Articles/2010/01/20/9327528/insight-us-to-continue-as-key-market-for-asian-benzene.html | CC-MAIN-2013-20 | en | refinedweb |
15 May 2012 10:18 [Source: ICIS news]
SINGAPORE (ICIS)--ONGC Mangalore Petrochemicals Limited (OMPL) has issued a tender for long-term export of paraxylene (PX) and benzene from its new aromatics project, expected to begin commercial production early next year, according to a company document obtained on Tuesday.
The complex, to be located in New Mangalore, is likely to come on line in March-April 2013.
The company is also seeking potential investors to build a downstream purified terephthalic acid (PTA) plant “in and around Mangalore” to received feedstock PX via a pipeline from the company’s new aromatics facility.
The aromatics facility has a design capacity to produce up to 920,000 tonnes of PX and 270,000 tonnes of benzene per annum, according to the the tender document.
The PX will be sold on a ex-plant basis and will be priced against 50% Asian Contract Price (ACP): 50% CFR Taiwan quotes minus freight rates between Mangalore and south Korea plus alpha plus beta; where alpha is a price determined by OMPL through the tender and beta is the biddable parameter for the sell-tender.
Benzene will also be sold on a ex-plant basis and will be priced against FOB ?xml:namespace>
Bids for the long-term PX sell-tender should be submitted by 18 June while bids for the benzene sell-tender should be submitted by 19. | http://www.icis.com/Articles/2012/05/15/9559714/indias-ompl-issues-tender-to-export-pxbenzene-from-new-project.html | CC-MAIN-2013-20 | en | refinedweb |
This command describes an expression that belongs to the current scene. The expression is a block of code of unlimited length with a C-like syntax that can perform conversions, mathematical operations, and logical decision making on any numeric attribute(s) in the scene. One expression can read and alter any number of numeric attributes. Theoretically, every expression in a scene can be combined into one long expression, but it is recommended that they are separated for ease of use and editing, as well as efficiency.Note, expressions that alter or use per-particle attributes of a particle shape should use the ‘dynExpression’ command.
Derived from mel command maya.cmds.expression
Example:
import pymel.core as pm pm.expression( s='a.translateX = b.translateX * sin(c.translateX)' ) pm.expression( o='ball', s='tx = sin(time);' ) | http://www.luma-pictures.com/tools/pymel/docs/1.0/generated/functions/pymel.core.effects/pymel.core.effects.expression.html | CC-MAIN-2013-20 | en | refinedweb |
Package: grep Version: 2.5.1.ds1-4 Severity: normal I also tested this with the binary from Version 2.5.1.ds2-5 (i386) and got the same results. both binaries give the same --version output: $ grep --version grep (GNU grep) 2.5.1 Copyright 1988, 1992-1999, 2000, 2001 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ Per the documentation (--help, info, man pages) -D skip or --devices=skip should cause FIFOs to be skipped. In testing, however, FIFOs are not skipped. The program and the documentation should be consistent (either correct the program to match the documentation, or vice versa). example demonstration of bug: -D, --devices=ACTION how to handle devices, FIFOs and sockets ACTION is 'read' or 'skip' $ mknod p p && ls -lond p prw------- 1 1003 0 Sep 14 13:42 p $ >out grep -D skip RE p & echo REmatch>>p; wait; cat out [2] 22002 [2]- Done grep -D skip RE p >out REmatch $ I did also test character special device - without options the device is not skipped, and with -D skip the character special device is skipped, so the bug is apparently limited to only certain device type(s) (e.g. FIFOs). In the latest upstream source (e.g.: ) it would appear the source at least intends to behave consistent with the documentation: #ifndef DJGPP if (devices == SKIP_DEVICES && (S_ISCHR(stats->stat.st_mode) || S_ISBLK(stats->stat.st_mode) || S_ISSOCK(stats->stat.st_mode) || S_ISFIFO(stats->stat.st_mode))) #else if (devices == SKIP_DEVICES && (S_ISCHR(stats->stat.st_mode) || S_ISBLK(stats->stat.st_mode))) #endif I haven't checked to see precisely where the bug creeps in between the (most current) upstream source's apparent intent, and bug apparently being present in most current Debian (at least in unstable and testing binaries, and stable binary). references: news:address@hidden news:address@hidden -- System Information: Debian Release: 3.1 Architecture: i386 (i686) Kernel: Linux 2.4.29 Locale: LANG=C, LC_CTYPE=C (charmap=ANSI_X3.4-1968) Versions of packages grep depends on: ii libc6 2.3.2.ds1-22sarge4 GNU C Library: Shared libraries an -- no debconf information | http://lists.gnu.org/archive/html/bug-grep/2006-09/msg00001.html | CC-MAIN-2013-20 | en | refinedweb |
The 1997 Mathews Radio-Baton & Improvisation Modes
From the Proceedings of the 1997 International Computer Music Conference Thessaloniki Greece
Richard Boulanger & Max Mathews
rboulanger@berklee.edu & mvm@ccrma.stanford.edu
Berklee College of Music & Stanford University
Introduction
The Radio-Baton is a controller for live computer music performances. It tracks the motions, in three dimensional space, of the ends of two Batons which are held in the hands of a performer. The X, Y and Z trajectories of each Baton are used to control the performance. The Radio-Baton is a MIDI instrument in the sense that it has MIDI input, output, and thru connectors. All electrical communication with the Baton is done over MIDI cables using standard MIDI conventions. The Baton was designed to work with MIDI synthesizers and MIDI-based sequencing and programming software.
How the Radio-Baton Works
The Radio-Baton uses a simple technique to determine the XYZ coordinates of the batons. At the end of each baton is a small radio transmitting antenna. On the receiving antenna surface are 5 receiving antennas as sketched on the figure--four long thin antennas arranged along the four edges of the board and one large antenna covering the entire center area of the board. The closer a baton is to a given receiver, the stronger the signal at that receiver. By comparing the signal strengths at the #1 and #2 antennas, the computer in the electronics box can determine the X position of the baton. Comparing the #3 and #4 strengths gives the Y position. The #5 strength gives the height above the board or Z position. The two batons operate at different frequencies and thus can be independently tracked.
A low frequency of about 50kHz is used for the radio signals. It is appropriate to describe the Radio-Baton as a capacitance sensor. The radio-frequency signal is really used as a method of measuring the capacitance between a transmitting antenna electrode and a receiving antenna electrode. The measurement technique is simple and robust. The relationship between antenna signal strengths and XYZ coordinates is complex but the Radio-Baton computer is good at making the needed conversions. A table lookup procedure is used to speed the calculation.
The Radio-Baton can compute the positions of the batons every 4 milliseconds. The accuracy of measurements is about 1 part in 100. The X and Y information is linearized and mapped onto the standard MIDI range of 0-127. The Z information is not linearized. The Z data decreases from about 100 when a Baton is on the antenna surface to about when the Baton is about 3 feet above the antenna surface.
Triggers
In addition to providing XYZ data, one of the most important functions of the Radio-Baton is to send triggers over MIDI. A trigger can be generated when either Baton touches an invisible plane which can be positioned at various heights above the antenna board. This plane is called the HIT-LEVEL. In order to avoid DOUBLE-TRIGGERING, a second plane is also positioned slightly above the HIT plane. This plane is called the SET-LEVEL. A Baton must be raised above the SET-LEVEL before a second trigger can be generated. This method for generating triggers and avoiding double triggers using a HIT-LEVEL and a SET-LEVEL works well for most musical purposes.
Principal Programs
The processor in the Radio-Baton can execute a number of different programs but the two main modes are the IMPROV mode and the CONDUCTOR mode. The IMPROV mode is used for executing improvisations and algorithmic programs and the CONDUCTOR mode is used to play traditional scores.
The IMPROV Mode
In the IMPROV mode, the Radio-Baton is a simple controller which sends XYZ position information and triggers to a control computer. The control computer interprets this information musically according to whatever program is being run in the control computer.
The CONDUCTOR Mode
When the Conductor Program is running in the Radio-Baton, a control computer loads a score into the processor in the Radio-Baton. The Baton plays this score according to the conductor-gestures made by the performer. In response, the Radio-Baton sends MIDI commands from its MIDI out connector to a synthesizer which plays the notes.
Typical Commands
When the Radio-Baton is powered up or reset, it's processor enters a polling loop looking for commands received at it's MIDI input terminal. Most commands are encoded as MIDI system-exclusive messages which contain only an operation code as a single information character. For most commands the Radio-Baton sends a confirmation message from its MIDI output to the control computer.
TEST
Received Message ?240?1?247
Response??240?1?247
This command is used to test whether the Baton is working and whether the MIDI is correctly patched.
UART
Received Message?240?33?247
Response ??240?33?247
This command puts the Baton into the UART mode in which all MIDI characters received are simply transmitted from the MIDI out jack. The Radio-Baton can only be gotten out of the UART mode by pushing the reset push button or button B15+ on the Baton box. When B15+ is pushed the Baton transmits:
???240?44?247
to confirm that it has left the UART mode.
IMPROV
Received Message ?240?46?247
Response??240?46?247
This command puts the Baton into the IMPROV mode where it functions as a simple controller.
PLAY
Received Message?240?4?247
Response??none
This command puts the Baton into the CONDUCTOR mode where it will play a specified score under the expressive control of baton gestures. This mode has already been described in other publications and will not be further discussed here.
The IMPROV Protocol
When in the IMPROV mode, the Baton functions as a simple controller and sends triggers and other controller information from its MIDI out jack. Usually a computer receives this information. The task of making musical sense from the controller information falls entirely on the computer, its program, and its programmer. The conversation between the Baton processor and the computer is two-way. For example, in order to reduce the load on the midi cable, the Baton only sends the XYZ position data for the Batons when this information is requested by the computer.
Although a number of examples are provided with the system, the user is expected to program their own improvization algorithms. To assist in this task, a support program and template are provided. Starting with the template, the user merely needs to fill in the blank functions. In addition to those functions provided in the template, the user can access various functions for sending MIDI commands to a synthesizer and can read a millisecond clock which is provided automaticaly by the support program.
The IMPROV Programming Template in the C Language
#include <stdio.h>
#include <conio.h>
#include "drivers.h"
#include "define.h"
#include "impr.h"
/*---------------------initialization algorithms------------------------*/
initialization(){}
/*--------------------main loop algorithms -------------------------------*/
mainloopalgorithms(){}
/*--------------------triggered algorithms------------------------------*/
stick1trig(){}
stick2trig(){}
b14plustrig(){}
b15plustrig(){}
b14minusup(){};
b14minusdown(){};
b15minusup(){};
b15minusdown(){};
noteplay(){}
/*---------------------------poll response algorithms-------------------*/
stick1pollresponce(){}
stick2pollresponce(){}
potspollresponce(){}
/*----additional functions and variables provided by the support program---*/
m_send(a)-----------------------send midi character
m_poll()------------------------receive midi character
m_play(chan,keyno,keyvel)-------play note
m_cont(chan,controller,value)---control change
m_pc(chan,program)--------------program change
t_time--------------------------clock in milliseconds
A Simple Improvisation Program:
Play Notes with Baton 1 and Sustain them with the Pedal
#include <stdio.h>
#include <conio.h>
#include "drivers.h"
#include "define.h"
#include "impr.h"
short keyno;
/*---------------------initialization algorithms--------------------------*/
initialization(){
printf("Baton1 Trigger plays note on MIDI channel#1: X Axis = Note\n");
m_pc2(0,25); printf("Initial Patch is #25 on MIDI Channel #1\n");
}
/*--------------------triggered algorithms--------------------------------*/
stick1trig(){
m_play2(0,keyno,0);
keyno=44+x1t/3;
m_play2(0,keyno,127);
printf("keyno= %d\n",keyno);
}
b14minusup(){m_cont2(0,64,0); printf("pedal b14- up\n"); }
b14minusdown(){m_cont2(0,64,127);printf("pedal b14- down\n");}
Boulanger Radio Sonata #1
Mvt 1 Opening Scored in the Mathews Conductor Program
I K0# v30
q0 h11 v127 c7 q0 h12 v110 c7 q1 h11 x2 -c10
q2 h12 x2 c10 q3 h11 y2 c11 q4 h12 y2 c11
2 o84 h11 ky1 t88
3 o36 h11 ky1
4 o36 h12 ky1 t81
16 h16 t2
*0*
0 /....
*1*
0 /........ ........ ........
3 !FFGab
4 !#F!#G#a
*2*
0 /........ ...... .. /........
2 f^e........ ......r.. #Gg
*3*
0 ...... .. /........ ...... ..
2 ......r.. #Aa........ ......r..
*4*
0 /........ ...... .. /........
2 o60Cb........ ......r.. !D#C
*5*
0 ...... ..
2 ......r..
3 ......r..
4 ......r..
*7*
0 /.... .... /........
4 F.... .... #a
Conducting a MIDIFILE with the Mathews Conductor Program
I?????*Initialize the Baton*
v100?????*Set initial Tempo*
Z110?????*Reduce Velocity from MIDI File*
q0 h7 v100 c7 ???*On MIDI Channels 7-10
q0 h8 v120 c7????*Assign Controller 7 Constants with Patchcords*
q0 h9 v127 c7
q0 h10 v110 c7
1 h7 kv100 t66 q2 h7 y2 c11?*Send Programs & Map Controllers to Axis*
2 h8 kv100 t114 q3 h8 y2 c11?
3 h9 kv100 t12 q4 h9 y2 c11
4 h10 kv100 t1 q5 h10 x2 c11
16 h16 t0????*Send Program Change #1 on Channel 16*
*1*
0
M ?????*Jump to the MIDI File*
0
Max V. Mathewsw wrote programs (Music I through Music V and Groove) for playing music on digital computers. He has been called the father of computer music. In 1987 he joined the Stanford University Music Department in the Center for Computer Research in Music and Acoustics (CCRMA) as Professor of Music (Research). Here he developed a new pickup for electron violins and real-time computer systems for music perfomance. His latest system is the Radio Baton and CONDUCTOR & IMPROV Programs.
Richard Boulanger (b.1956) is a composer and performer of interactive computer music. He did his Ph.D. at the University of California in San Diego and worked there with Roger Reynolds and Dick Moore. For more than a decade now, he has collaborated extensively with Max Mathews on the Radio Baton and Barry Vercoe on Csound. Currently, Boulanger is a Professor of Music Synthesis at the Berklee College of Music in Boston.
The Mathews Radio-Baton - 1997
The Mathews Radio-Batonis a controller for musical performances. It consists of two batons, a receiving antenna board, and an electronics box. This device tracks the motion of the two batons as they are moved by a musician in three-dimensional space above the receiving antenna.
The electronics box contains a processor which analyses the gestures made by the musician and uses this information to control the music being played by a synthesizer. The electronics contains a standard set of midi in, out, and thru connectors. All communication between the Radio-Baton and the synthesizer is done via MIDI. The Radio-Baton can interact with any computer that can send and receive MIDI.
The Radio-Baton operates in two principal modes the Conductor Mode and the Improv Mode. In the Conductor Mode, the Radio-Baton simulates an orchestra. The musician loads a score of the piece to be played from a Computer into the Radio-Baton. She then uses one baton to beat time and thus to control the tempo of the performance and the other baton to control the dynamics, balance, and timbres of the voices.
In the Improv Mode, the Radio-Baton serves as a simple controller which sends triggers and the x,y,z positions of the two batons to a computer. The musician must write a program in the computer to interpret this information and to send MIDI commands to play music on a synthesizer. The Improv Mode can run with any computer (for example, a MacIntosh running the Max program). It is a more general mode than the Conductor Mode, but it requires that the musician write the complete program to make a musical interpretation of her gestures.
A Radio-Baton can be obtained from the MARMAX Company for $1200 plus shipping costs and any applicable sales tax. Included in the price are:
The Radio-Baton electronics box, antenna board, power supply, two batons, and interconnecting cables.
A copy of the Conductor Program (Bat.exe) which runs on a PC computer under either the DOS or the Windows 95 operating system and the source code (Bat.c) for the Bat program. The source code is written in the Microsoft C language.
An instruction manual and a floppy disk of sample scores for the Conductor Mode.
In contrast to the Improv Mode, which can be used with any computer that speaks MIDI, the Conductor program runs ONLY on a PC computer and requires a Midiator ms124 MIDI interface. The ms124 connects to an rs232 serial port on the computer and can be obtained from Key Electronics 7515 Chapel Ave., Fort Worth, TX USA 76116
To obtain more information about the Radio-Baton contact MARMAX and ask for a copy of the instruction manual or contact us via email at m.v.mathews@worldnet.att.net
MARMAX223 PRECITA AVE. SAN FRANCISCO CA 94110 415-821-4661 | http://www.csounds.com/max/papers/ICMC1997_HTML/BatonICMC97.html | CC-MAIN-2013-20 | en | refinedweb |
03 August 2009 14:16 [Source: ICIS news]
SINGAPORE (ICIS news)--Linear low density polyethylene (LLDPE) futures on the Dalian Commodity Exchange (DCE) rose 4.9% on Monday, partly due to the Chinese government’s assurance that its expansionary monetary policy would remain in place in the near term, industry sources said on Monday.
“The Chinese government said three times last week through different mediums that it would maintain a relaxed monetary policy. That assurance boosted investor confidence,” said a source at Shanghai Zhongqi, a Chinese futures brokerage.
“It reinforces investors’ belief that cash will continue to be easily accessible, and that commodity prices will rise in the coming months due to inflationary pressure caused by the easy credit,” the source said.
September contracts closed at yuan (CNY) 11,565/tonne ($1,691/tonne) on Monday, up CNY540/tonne from Friday’s settlement price, according to data published on DCE’s website.
“Ample cash in the Chinese economy is definitely one of the price drivers,” said a source at Chinese futures brokerage International Futures.
Some investors also believed that LLDPE futures would rise further in the coming months, as they held the view that the commodity was underpriced in the domestic physical market, the International Futures source said.
“Prices in the domestic physical market fell sharply last year when the global financial crisis triggered panic selling. The price recovery process is still ongoing,” the source said.
Asian LLDPE was priced at around $1,260/tonne CFR (cost and freight) ?xml:namespace>
Positive economic data also helped push LLDPE futures prices higher, said a source at Zhejiang Province Yongan Futures Broker.
“All types of commodity futures have risen in
“The futures market, regardless of the product, will continue to rise as long as the
($1 = CNY6. | http://www.icis.com/Articles/2009/08/03/9236954/dalian+lldpe+futures+rise+4.9+on+assurance+of+easy.html | CC-MAIN-2013-20 | en | refinedweb |
I wish to display an image on a lightbox for larger view when clicked from a Repeater on Dynamic Category Page . The lightbox is trigged when the image is clicked but the image is not displayed. Kind help please with the codes. This is my dynamic category page code and screen:
----------------------------------------------------------------------------------------------------------
import wixWindow from 'wix-window';
export function image4_click(event, $w) {
wixWindow.openLightbox('SpecimenPhoto', $w('#dynamicDataset').getCurrentItem());
}
Lightbox code and screen:
---------------------------------------------------------------------------------------------------------------
import {lightbox} from 'wix-window';
$w.onReady( () => {
let item = lightbox.getContext();
$w("#Dorsal").src = item.Dorsal;
});
* Dorsal in item.Dorsal is the database field name
A newbie here :) Thanks in advance!
Leana
Hi Leana,
This is a great idea!
I tried your code, and it worked for me. Do you get any errors in the developer console?
Also, note that you need to use the field key in the code, it is not necessarily the same as the field display name. For example, notice how the field name is "Dorsal" whereas the field key (which we need to use in the code) is "dorsal":
Hi Tomer!
I got it and it's working fine. Thank you very much for your help, I can sleep soundly now :)
Best,
Leana
No errors on Sending Page, but on Lightbox code:
// For full API documentation, including code examples, visit import {lightbox} from 'wix-window'; $w.onReady( () => { let item = lightbox.getContext(); $w("#LBoepartno").src = item.oe_part_no; $w("#LBcomments").src = item.comments; });
-------------------------------------------------------------
I am trying to implement this and am getting error:
'src' does not exist on '#LBoepartno;
'src' does not exist on '#LBcomments;
WHAT IS WRONG HERE???
Thanks
JD
Are the '#LBcomments' and '#LBoepartno' IDs of image elements? Have you tried console log the "item" variable to make sure that you get the object when using "lightbox.getContext();" ?
Yes, I logged item on both sending page and the lightbox. I see all the elements of the database.
the assignment of the item elements to the #placehoders gives that error.. Also notice that it cant read the photoURL which is the MAIN thing I want ot show on this lightbox.
DEBUG LOG
Loading the code for the site. To debug this code, open masterPage.js in Developer Tools.
Loading the code for the CV-PartXREF-PIC popup. To debug this code, open va6l4.js in Developer Tools.
Loading the code for the CVOA-PartsXREF (All) page. To debug this code, open lcqdw.js in Developer Tools.
undefined
undefined
TypeError: Cannot read property 'photo_image_url' of undefined
Loading the code for the CV-PartXREF-PIC popup. To debug this code, open va6l4.js in Developer Tools.
undefined
{"_id":"2","gm_group":"0.01","description":"GASKET SET - engine (lower end)","oe_part_no":"N.S.","qty_per_car":1,"model_usage":"<font face=arial size=3>71-77 Vega (122 140)<br>75-77 Astre (140)<br>75-77 Monza (140)<br>76-77 Sunbird Starfire (140)","part_no_history":"N/A","aftermkt_vendor_part_no":"[a] CVOA-PT-03","comments":"CVOA set includes:<br>- oil pan set<br>- oil pump set<br>- rear main seal set<br>- water pump gasket<br><br>see also Gasket Set (lower end - aftermarket) / Gr. 0.289 - for complete overhaul<br><br>does this include the seal for crankcase vent pipe (Gr. 1.745)?","aftermkt_interchange":"[a] CVOA Parts Project","newField3":null,"image_url":null,"_updatedDate":"2018-06-11T22:05:47.250Z","_createdDate":"2018-06-11T22:02:14.061Z","link-CVOA-PartsXREF-all":"/CVOA-PartsXREF/"}
I got rid of the error by changing and eliminating the # in front of the placeholder text property name.
$w("#LBoepartno").src = item.oe_part_no;
$w("#LBcomments").src = item.comments;
so NO longer have any errors on page
Here is current Lightbox code to display all item in the lighbox:
// For full API documentation, including code examples, visit
import {lightbox} from 'wix-window';
$w.onReady( () => {
let item = lightbox.getContext();
console.log(item)
$w("CVPartImg").src = item.photo_image_url;
$w("LBdescription").src = item.description;
$w("LBoepartno").src = item.oe_part_no;
$w("LBcomments").src = item.comments;
});
HOWEVER. NO items show up on lightbox. Does the lightbox have to have the dynamic database attached?
I also console.logged each of the item.<elements> and they showed in the log. It appears that the assignment of the values is not working?
OK. Progress is finally being made: I modified the code as follows and now all repeater elements are displayed in the Lightbox with the exception of the IMAGE, which is an IMG_URL?
// For full API documentation, including code examples, visit
import {lightbox} from 'wix-window';
$w.onReady( () => {
let item = lightbox.getContext();
let repimg = item.image_url;
let repdesc = item.description;
let reppart = item.oe_part_no;
let repcomments = item.comments;
$w("#CVPartImg").url = repimg; <---ERROR : 'url' does not exist on #CVPartImg
$w("#LBdescription").text = repdesc;
$w("#LBoepartno").text = reppart;
$w("#LBcomments").text = repcomments;
});
REAL CLOSE..... PLEASE, SOMEBODY HELP ME!!!!!
Current Lightbox Code:
// For full API documentation, including code examples, visit
import {lightbox} from 'wix-window';
$w.onReady( () => {
let item = lightbox.getContext();
// console.log(item)
// console.log("===========================================================REPEATER DATA===================================")
let repimg = item.image_url;
console.log("from Repater",item.image_url)
console.log("derived for LB", repimg)
let repdesc = item.description;
let reppart = item.oe_part_no;
let repapart = item.aftermkt_vendor_part_no;
let repcomments = item.comments;
$w("#CVPartImg").link = repimg;
$w("#LBdescription").text = repdesc;
$w("#LBoepartno").text = reppart;
$w("#LBaftermkt").text = repapart;
$w("#LBcomments").text = repcomments;
console.log(repimg)
console.log('#CVPartImg').link;
});
See Uploaded Error Log from Preview Mode:
Following! Same Errors!
Hi Leana, can you please show us the code that you're using? I was trying your code but I'm stock. I hope you can help us.
Thanks!
Problem Solved.... changed:
$w("#CVPartImg").link = repimg;
TO
$w("#CVPartImg").lsrc = repimg;
Hi eMG! Here is my simple code. I made a simpler lightbox that shows only one image and text to demonstrate.
(1) On the Dynamic category page: Code and screen shot (modified to show links):
import wixWindow from 'wix-window'; import wixData from 'wix-data'; export function image4_click(event, $w) { wixWindow.openLightbox('Dorsal_Photo', $w('#dynamicDataset').getCurrentItem()); }
(2) Lightbox code and screen shot modified to show links to lightbox and database:
import {lightbox} from 'wix-window'; $w.onReady( () => { let item = lightbox.getContext(); $w("#Dorsal").src = item.dorsal; $w("#Sciname").text = item.sciname;
});
Hope this helps. Good luck!
Leana | https://www.wix.com/corvid/forum/community-discussion/display-image-from-repeater-to-lightbox | CC-MAIN-2020-05 | en | refinedweb |
Better integration of org-mode and email
Posted June 08, 2014 at 08:57 PM | categories: org-mode, email | tags: | View Comments
I like to email org-mode headings and content to people. It would be nice to have some records of when a heading was sent, and to whom. We store this information in a heading. It is pretty easy to write a simple function that emails a selected region.
(defun email-region (start end) "Send region as the body of an email." (interactive "r") (let ((content (buffer-substring start end))) (compose-mail) (message-goto-body) (insert content) (message-goto-to)))
that function is not glamorous, and you still have to fill in the email fields, and unless you use gnus and org-contacts, the only record keeping is through the email provider.
What I would like is to send a whole heading in an email. The headline should be the subject, and if there are TO, CC or BCC properties, those should be used. If there is no TO, then I want to grab the TO from the email after you enter it and store it as a property. You should be able to set OTHER-HEADERS as a property (this is just for fun. There is no practical reason for this yet). After you send the email, it should record in the heading when it was sent.
It turned out that is a relatively tall order. While it is easy to setup the email if you have everything in place, it is tricky to get the information on TO and the time sent after the email is sent. Past lispers had a lot of ideas to make this possible, and a day of digging got me to the answer. You can specify some "action" functions that get called at various times, e.g. after sending, and a return action when the compose window is done. Unfortunately, I could not figure out any way to do things except to communicate through some global variables.
So here is the code that lets me send org-headings, with the TO, CC, BCC properties, and that records when I sent the email after it is sent.
(defvar *email-heading-point* nil "global variable to store point in for returning") (defvar *email-to-addresses* nil "global variable to store to address in email") (defun email-heading-return () "after returning from compose do this" (switch-to-buffer (marker-buffer *email-heading-point*)) (goto-char (marker-position *email-heading-point*)) (setq *email-heading-point* nil) (org-set-property "SENT-ON" (current-time-string)) ;; reset this incase you added new ones (org-set-property "TO" *email-to-addresses*) ) (defun email-send-action () "send action for compose-mail" (setq *email-to-addresses* (mail-fetch-field "To"))) (defun email-heading () "Send the current org-mode heading as the body of an email, with headline as the subject. use these properties TO OTHER-HEADERS is an alist specifying additional header fields. Elements look like (HEADER . VALUE) where both HEADER and VALUE are strings. save when it was sent as s SENT property. this is overwritten on subsequent sends. could save them all in a logbook? " (interactive) ; store location. (setq *email-heading-point* (set-marker (make-marker) (point))) (org-mark-subtree) (let ((content (buffer-substring (point) (mark))) (TO (org-entry-get (point) "TO" t)) (CC (org-entry-get (point) "CC" t)) (BCC (org-entry-get (point) "BCC" t)) (SUBJECT (nth 4 (org-heading-components))) (OTHER-HEADERS (eval (org-entry-get (point) "OTHER-HEADERS"))) (continue nil) (switch-function nil) (yank-action nil) (send-actions '((email-send-action . nil))) (return-action '(email-heading-return))) (compose-mail TO SUBJECT OTHER-HEADERS continue switch-function yank-action send-actions return-action) (message-goto-body) (insert content) (when CC (message-goto-cc) (insert CC)) (when BCC (message-goto-bcc) (insert BCC)) (if TO (message-goto-body) (message-goto-to)) ))
This works pretty well for me. Since I normally use this to send tasks to people, it keeps the task organized where I want it, and I can embed an org-id in the email so if the person replies to it telling me the task is done, I can easily navigate to the task to mark it off. Pretty handy.
Copyright (C) 2014 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.6 | http://kitchingroup.cheme.cmu.edu/blog/2014/06/08/Better-integration-of-org-mode-and-email/ | CC-MAIN-2020-05 | en | refinedweb |
I am using a sklearn for the multi-classification task. I need to split data into train_set and test_set. I want to take randomly the same sample number from each class. Actually, I am using this function
X_train, X_test, y_train, y_test = cross_validation.train_test_split(Data, Target, test_size=0.3, random_state=0)
but it gives an unbalanced dataset! Any suggestion.
You can simply use the train test split method available in scikit learn:
For example:
#import classfrom sklearn.model_selection import train_test_split#assign variablesX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)
#import class
from sklearn.model_selection import train_test_split
#assign variables
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)
Hope this answer helps.
If you wish to learn more about scikit learn visit this Scikit Learn Tutorial. | https://intellipaat.com/community/9488/how-to-split-data-on-balanced-training-set-and-test-set-on-sklearn | CC-MAIN-2020-05 | en | refinedweb |
Java, J2EE & SOA Certification Training
- 35k Enrolled Learners
- Weekend
- Live Class
In Java, we come across situations where we need to use objects instead of primitive data types. To accomplish this, Java provides wrapper class Character for primitive data type char. In this article on Char in Java, let us understand the same in detail.
The following topics will be covered in this article:
Let’s begin!
The Character class generally wraps the value of all the primitive type char into an object. Any object of the type character may contain a single field whose type is char. The Character class offers a number of useful classes (i.e., static) methods for working with characters.
To create a character object with the character constructor −
Character ch = new Character('a');
The above statement creates a character object which contains ‘a’ of type char. There is only one constructor in character class which expects an argument of the char data type.
Next in this article on Char in Java, let us see few escape sequences used with the characters in Java.
A character preceded by a backslash () is generally called an escape sequence. There is a table mentioned below that will help you in understanding this concept.
Since you have understood the escape sequences, let us move ahead and understand the methods that character class offers in Java.
The following table discusses a few important methods of the character class.
Next, in this article on Char in Java, let us see the practical implementation of the above-discussed methods.
import java.util.Scanner; public class JavaCharacterExample1 { public static void main(String[] args) { // Ask the user for the first input. System.out.print("First input:"); // Use the Scanner class to get the user input. Scanner scanner = new Scanner(System.in); // Gets the user input. char[] value1 = scanner.nextLine().toCharArray(); int result1 = 0; // Count the characters for a specific character. for (char ch1 : value1) { result1 = Character.charCount(ch1); } // Print the result. System.out.print("Value: "+result1+"n"); System.out.print("Second input:"); char[] value2 = scanner.nextLine().toCharArray(); for (char ch2 : value2) { int result2 = Character.hashCode(ch2); System.out.print("The hash code for the character '"+ch2+"' is given as:"+result2+"n"); } System.out.print("Third input:"); char[] value3 = scanner.nextLine().toCharArray(); for (char ch3 : value3) { boolean result3 = Character.isDigit(ch3); if(result3){ System.out.println("The character '" + ch3 + "' is a digit. "); } else{ System.out.println("The character '" + ch3 + "' is not a digit."); } System.out.print("Fourth input:"); char[] value4 = scanner.nextLine().toCharArray(); for (char ch4 : value4) { boolean result4 = Character.isISOControl(ch4); System.out.println("The fourth character '"+ch4+"' is an ISO Control:"+result4); } } } }
First input:89 Value: 1 Second input:J The hash code for the character 'J' is given as:74 Third input:5 The character '5' is a digit. Fourth input:h The fourth character 'h' is an ISO Control:false
With this, we come to an end to this article on Char in Java. I hope you understood the fundamentals of Java. If you found this article on “Char in Java”, “Char in Java” and we will get back to you as soon as possible. | https://www.edureka.co/blog/character-class-java | CC-MAIN-2020-05 | en | refinedweb |
Hello,
I am attempting to create a new organization user form, after which a new user and portal profile is added. The user form is the instantiation form, and it contains the new user's username. For testing purposes, password is a static string. After the form is submitted, a system task is created that runs a script that generates the new user and the user's portal profile. The user part works fine, but I am unable to create the user's Portal Profile.
Here is the Bonita Engine Log error:
I created a groovy script in order to get users has a specific role in a specific group.
I set the actor with groovy script
import org.bonitasoft.engine.api.IdentityAPI;
import org.bonitasoft.engine.identity.Group;
import org.bonitasoft.engine.identity.GroupCriterion;
import org.bonitasoft.engine.identity.User;
import org.bonitasoft.engine.search.SearchOptionsBuilder
import org.bonitasoft.engine.search.SearchResult.
I created a timer connector inside Bonita bpm process. I set the end date with a groovy script. However, I cannot get the result.
There is no error, however, the timer doesn't evoke the next trigger
I would like to get the exact time like 2019-02-20 13:11:00
My code is as follows.
I am developing on a kind of scheduler process.
Manager created multiple tasks which have a due date. Whenever the due date reaches I would like to send a notification to the user and manager at the same time.
I returned the due dates into a process variable as an object, however, in the timer condition, only allowed java.util.Date type.
is it possible to set the fixed dates as multiple dates in the groovy script?
In the case of my process, how to approach the solution?
I am sorry the question is vague.;
Hello,
I asking about the possibility of making script lines in the decision table for making a transition or it is only a comparison test?
if yes, can I, in the groovy script, make controls on information of organisation actors (country, job,..) and also access to data in MySQL database?
.:
How to remove a certain item from BDM through a script in Groovy?
I can access my BDM Logs but I can not delete them, how can I do this?
I'm getting the data from my PostgreSQL database and saving in my BDM to be able to display this data in a table in my UI Designer, that's fine, but I do not want the same information to be added twice in BDM, for that reason I created this script that checks if the information that is being fetched from my external database is no longer added in BDM | https://community.bonitasoft.com/tags/groovy | CC-MAIN-2020-05 | en | refinedweb |
Hey,
Aside from the discretionary access control (DAC) permissions associated with
files (e.g., “users with UID X can read”), there is an extra permission bit that
can be stored in a file's inode: the
setuid bit.
Once set in an executable, it allows the user who's executing that binary to do so with the UID of the owner of that file.
a
setuidprogram is a program that allows a process to gain privileges it would not normally have, by setting the process’ effective user ID to the same value as the user ID (owner) of the executable file.
As an example, consider the case of “run-as-root” example bellow, which, lets you run an executable (initially, without any privilege escalations):
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char** argv, char** envp) { if (argc < 2) { printf("Usage: %s <executable> <args ...>\n", argv[0]); return 1; } execve(argv[1], argv + 1, envp); perror("execve"); return 1; }
For instance, with it, we can execute the
/usr/bin/id:
./run-as-root /usr/bin/id -u 1001
Clearly not root.
Now, if we change the owner of that file to be UID 0 (root), and set the setuid bit:
# as root, change the ownership of the # file to `root` # sudo chown 0 ./run-as-root # as root, set the `setuid` bit # chmod u+s ./run-as-root # run `run-as-root` again # ./run-as-root /usr/bin/id -u 0
Note how in the last run of
run-as-root we elevated our privileges, going from
1001 to 0 without the use of
sudo - our
run-as-root was able to do that for
us.
It's important to realize that
setuid will make a program inherit the uid of
the owner of the file only in the case of linux binaries - the use of
setuid
on an interpreted piece of code won't work.
For instance, consider a second version of
run-as-root:
run-as-root.sh.
#!/bin/bash exec $@
If we go again through the process of getting the
setuid bit set and the file
owned by UID 0, we can see no effect:
sudo chown 0 ./run-as-root.sh chmod u+s ./run-as-root.sh ./run-as-root.sh /usr/bin/id -u 1001
ps.: not only uid 0 is able to set the
setuid bit - in practice, having
the
CAP_FOWNER capability is what matters (and, for setting the uid of the
file,
CAP_SETUID).
pps.: this behavior does not take effect on calling threads with
no_new_privs
attribute set via
prctl, or if it's being
ptraced, or in case the underlying
filesystem is mounted with
nosuid (
MS_NOSUID). See
execve(2)
under the hood
inheriting the effective uid from a file
When getting prepared to execute a Linux binary (during
__do_execve_file),
the kernel gets to fill the “binary parameter” structure (
struct linux_binprm), a data structure that holds the arguments that are used when
While this process is interesting in itself (e.g., see Using Go as a scripting language in Linux, what matters for us here is the moment when the kernel is filling that struct with a UID.
What we can see above is essentially that if the file that we're looking at
contains the
setuid bit in its mode (via the
mode & S_ISUID check), then it
leverages that file's
uid to set its
euid.
Another thing worth noting there is the set of checks on lines
18 and
21.
The first is all about ensuring that if the file comes from a filesystem with
the
MS_NOSUID bit set, that we'll take
setuid into consideration, and the
second, verifying that the current task does not have the
no_new_privs bit
set (see)
uid inheritance (in the non setuid case)
Under regular circumstances, i.e., a process being created from another through
clone(2) will inherit the security context from its parent.
For instance, let's consider the following example:
#include <stdio.h> #include <unistd.h> int main(int argc, char** argv) { if (!~fork()) { perror("fork"); return 1; } printf("pid=%d uid=%d\n", getpid(), getuid()); return 0; }
Compiling that code and running it, we can see how the child inherits the parent real UID:
# compile the code # gcc -O2 -static -o fork main.c # run it # ./fork pid=30044 uid=1001 pid=30045 uid=1001
At the kernel level, we can see that inheritance at the moment that the kernel is performing the copying of the process.
prepare_creds+1 copy_creds+1 copy_process.part.38+1085 _do_fork+248 __x64_sys_clone+39 do_syscall_64+90 entry_SYSCALL_64_after_hwframe+68
Given that in the struct that represents a runnable thread (
struct task_struct) contains the security context for it too (the process credentials
in
struct cred), it also performs a copy of those, and then mutates them
accordingly.
To truly observe the credentials being copied, we can place
kretprobe on
prepare_creds and see how the new
struct cred looks like after the copy
(during
copy_process):
#include <linux/sched.h> #include <linux/cred.h> BEGIN { printf("%-8s %-8s %-8s %-8s %-8s\n", "REAL", "SAVED", "EFFEC", "VFS", "TYPE"); } kretprobe:prepare_creds / comm == "bash" / { $old_creds = (struct cred *) curtask->cred; $new_creds = (struct cred *) retval; printf("%-8d %-8d %-8d %-8d %-8s\n", $old_creds->uid.val, $old_creds->suid.val, $old_creds->euid.val, $old_creds->fsuid.val, "old"); printf("%-8d %-8d %-8d %-8d %-8s\n", $new_creds->uid.val, $new_creds->suid.val, $new_creds->euid.val, $new_creds->fsuid.val, "new"); printf("\n"); }
Now, running
./fork again, we can verify how
new and
old compare:
REAL SAVED EFFEC VFS TYPE 1001 1001 1001 1001 old 1001 1001 1001 1001 new 1001 1001 1001 1001 old 1001 1001 1001 1001 new
mixing
setuid and real uid inheritance
Now, what happens if you have a process that gets started from a
setuid
program (whose effective UID gets set to 0)?
Exactly the mix of both!
By the time the process gets copied (during the execution of
clone(2)), the
struct cred gets copied too (as seen above), and then at the moment of
executing the binary (through
execve(2)), the credential switch takes place,
modifying the effective UID and saved set.
If that new process calls
clone(2), once again, the same first step would then
occur - the credentials would be copied, and then passed along to the new
process.
my_process clone(2) // process copying goes on, making uids be inherited execve(2) // new effective & saved set clone(2) // process copy once again | https://ops.tips/notes/setuid-or-how-sudo-works/ | CC-MAIN-2020-05 | en | refinedweb |
euc 1.0.2+4
euc #
EUC-JP and Shift_JIS Encoding and Decoding Library for Dart Language
Releases #
- v1.0.0+1 First Implementation
- v1.0.0+2 Add Example and Changelog
- v1.0.1+3 Support Encoder
- v1.0.2+4 Add Shift_JIS Support
import 'package:euc/euc.dart'; import 'package:euc/jis.dart'; main() { // EUC-JP Encoding and Decoding print(EucJP().decode([ 164, 170, 164, 207, 164, 232, 164, 166, 192, 164, 179, 166 ])); print(EucJP().encode("おはよう世界")); // Shift_JIS Encoding and Decoding print(ShiftJIS().decode([ 130, 168, 130, 205, 130, 230, 130, 164, 144, 162, 138, 69 ])); print(ShiftJIS().encode("おはよう世界")); }
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: euc: ^1.0:euc/euc.dart';
We analyzed this package on Jan 14, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.4 | https://pub.dev/packages/euc | CC-MAIN-2020-05 | en | refinedweb |
There's low traffic in the eap forum, so if you have some
time left, check this statement:
return format(rec.getMinX() + "," + format(rec.getMinY() + " - " +
format(rec.getMaxX() + "," + format(rec.getMaxY() +
" w=" + format(rec.getWidth() + " h=" + format(rec.getHeight();
obviously there are some closing brackets missing.
What I did was doing a replace on the original statement, which looked like this:
return (long) rec.getMinX() ...
So I replaced (long) by format(
which of coursed leaded to missing closing brackets.
-> so this leads to the first possible improvement that
comes to my mind: if I could make the replace like this:
replace "(long) $EXPRESSION" with "format($EXPRESSION)"
I guess it's not that trivial - but you get the IDEA ;)
-> second possible improvement:
if you take the first statement above and try shift-ctrl-enter (complete statement)I with it, you'll
see it fail gracefully ;) it just ends a lot of braces
at the very end of the statement.
So, what kind of intellig(j)ence would be required to
place the correct closing braces automatically?
I'm aware that it might not be 100% determinable.
But what about this: first do the current logic, then
find out that the resulting statement causes compiler failure. Then try the other logic = directly add a closing
bracket after each format(rec.getMinX()
-> find out that after it, the compiler is green and
leave it that way.
Would sth. like this be yet possible by current open APIs?
It can't be that difficult... ;)
There's low traffic in the eap forum, so if you have some
Michael Damberger wrote:
This first part is what Structured Search and Replace is for, I think.
It's a new feature. Haven't used it myself, but this is a clear case for it.
--
Rob Harwood
Software Developer
JetBrains Inc.
"Develop with pleasure!"
The first item could also be accomplished with regular expressions and replacement groups. I've used to often to handle just this case: converting one method call to another, preserving the arguments.
Michael Damberger wrote:
Using Pallada you could do this with Strutural Search and Replace. Try
defining the template as "(long) $exp$" and the replacement as
"format($exp$)".
Ciao,
Gordon
--
Gordon Tyler (Software Developer)
Quest Software <>
260 King Street East, Toronto, Ontario M5A 4L5, Canada
Voice: 416-643-4846 | Fax: 416-594-1919 | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206952195-intellijent-code-completion | CC-MAIN-2020-05 | en | refinedweb |
What is an Array in Python 3?
An array is a data structure that can contain or hold a fixed number of elements that are of the same Python data type. An array is composed of an element and an index. Index in an array is the location where an element resides. All elements have their respective indices. Index of an array always starts with 0.
Unlike other programming languages, such as Java, C, C++, and more, arrays are not that popular in Python since there are many iterable data types in Python that are flexible and fast to use such as Python lists. However, arrays in Python 3 are still used in certain cases. In this module, we will learn all about all the important aspects of arrays in Python 3, from what they are to when they are used.
Following is the list of topics covered in this Python module.
- Difference_between_Array_and_List in Python
- Creating an Array in Python 3
- Accessing a Python Array Element
- Basic Operations of Arrays in Python
So, without further delay, let’s get started.
Learn more about Python from this Python for Data Science Course to get ahead in your career!
Difference between Array and List in Python
The basic difference between arrays and lists in Python is that lists are flexible and can hold completely arbitrary data of any data type while arrays can only hold data of the same data type.
Arrays are considered useful in terms of memory efficiency, but they are usually slower than lists. As mentioned above, the Python array module is not that popular to use, but they do get used in certain cases such as:
Creating an Array in Python 3
The array module supports numeric arrays in Python 3. So, to create an array in Python 3, we will have to import the array module. Following is the syntax for creating an array. Now to understand how to declare array in Python, let us take a
look at the python array example given below:
from array import * arraname = array(typecode, [Initializers])
Here, typecode is what we use to define the type of the value that is going to be stored in the array. Some of the common typecodes used in the creation of arrays in Python are described in the following table.
Now, let’s create a Python array using the above-mentioned syntax.
Example:
import array as arr a = arr.array(‘I’, [2,4,6,8]) print(a) Output: array(‘I’, [2, 4, 6, 8])
Interested in learning Python? Enroll in our Python Course in London now!
Accessing a Python Array Element
We can access the elements of an array in Python using the respective indices of those elements, as shown in the following example.
from array import* array_1 = array(‘i’, [1,2,3,4,5]) print (array_1[0]) print (array_1[3]) 1 4
The index of the array elements starts from 0. When we printed the value of array1[0], it displayed the first element.
Basic Operations of Arrays in Python
Following are some of the basic operations supported by array module in Python:
- Traverse of an Array in Python: Iterating between elements in an array is known as traversing. We can easily iterate through the elements of an array using Python for loop as shown in the example below.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) for x in array_1: print (x) Output: 1 2 3 4 5
- Insertion of Elements in an Array in Python:Using this operation, we can add one or more elements to any given index.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1.insert(1,6) for x in array_1: print (x) Output: 1 6 2 3 4 5
- Deletion of Elements in an Array in Python:Using this operation, we can delete any element residing at a specified index. We can remove any element using the built in remove() method.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1.remove(2) For x in array_1: print (x) Output: 1 3 4 5
- Searching Elements in an Array in Python:Using this operation, we can search for an element by its index or its value.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) print (array_1.index(3)) Output: 2
In the above example, we have searched for the element using the built-in index() method. Using index(3) returned the output 2 which means that 3 is at the index number 2 in array_1. If the searched value is not present in the array, then the program will return an error.
- Updating Elements in an Array in Python:Using this operation, we can update an element at a given index.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1[2] = 100 for x in array_1: print(x) Output: 1 2 100 4 5
Kick-start your career in Python with the perfect Python Course in New York now!
In the above example, we have updated the already existing value at index 2 instead of adding a new element.
With this, we have come to the end of this module in Python Tutorial. We learnt about arrays in Python 3, how to define array in Python 3, accessing an Python Array, and different operations of Python array.. | https://intellipaat.com/blog/tutorial/python-tutorial/python-arrays/ | CC-MAIN-2020-05 | en | refinedweb |
We previously wrote a brief introduction to networking, however networking is a larger topic than that, so we've decided to produce a larger series to try and do the subject justice.
Binding services to sockets
We're going to illustrate binding this service from Python since shell is not appropriate, and C is too verbose.
However we're going to use the low-level Python bindings rather than the socketserver class, to show how it works beneath the layers of abstraction.
As with some previous articles, we are going to describe how it works in the form of a script with commentary. You can download the full script here.
#!/usr/bin/python #chuckle.py
Python's bindings are in the socket module, we're doing a qualified import to resemble the API from C.
from socket import socket, AF_INET, SOCK_STREAM
There's lots of setup stages involved in making a connection available, following the general builder pattern, rather than having a single syscall that takes a huge number of options, as it is more extensible.
The
socket() syscall takes the parameters family, socket type and
protocol. This describes exactly what kind of socket to create. This will be
explained in greater detail later, but here we create a socket with an IP
address which acts as a stream.
s = socket(AF_INET, SOCK_STREAM, 0)
One side of the connection needs to bind to a port, so that the other can connect to it. The address specifies which address your machine has, that the service should be served on. '0.0.0.0' means "all my addresses", but we're going to use '127.0.0.1' which means "only my internal address" so that we can't have anything on the network connect to it:
addr = '127.0.0.1'
A port number also needs to be chosen to provide the service. The address denotes how to find the service, while the port represents which of the potential services available should be connected to.
port = 12345 s.bind((addr, port))
The call to listen() is further configuration, of how many connections to buffer before refusing new connections.
s.listen(0) while True:
The accept() call blocks until there are available connections to service and returns some information about where the connection was from.
conn, hostaddr = s.accept()
The python connection object wraps a file descriptor that can be used as any normal file, so we do some conversion so we can use it as one.
f = conn.makefile('rw') while True: f.write('> ') f.flush() line = f.readline() if not line: break if line == 'to me\n': print('to you') elif line == 'oh dear\n': print('oh dear oh dear') break conn.close()
We can demonstrate that this works with the netcat command.
$ python chuckle.py & $ nc 127.0.0.1 12345 > to me to you > oh dear oh dear oh dear ^C $
We can make this service start on boot by creating and enabling a systemd unit like this:
$ sudo install -D -m755 chuckle.py /usr/local/libexec/chuckle.py $ sudo tee /etc/systemd/system/chuckle.service >/dev/null <<'EOF' [Unit] Description=Chuckle server [Service] ExecStart=/usr/local/libexec/chuckle.py [Install] WantedBy=multi-user.target EOF $ sudo systemctl daemon-reload $ sudo systemctl enable chuckle.service
Connecting to services
We glossed over how connecting works and just used netcat, so let's see what's involved by writing our own program. You can download this script here.
#!/usr/bin/python #connect.py import sys
As before we need the same socket definitions to make a socket.
from socket import socket, AF_INET, SOCK_STREAM s = socket(AF_INET, SOCK_STREAM, 0)
Now instead of binding and listening we call connect().
s.connect(('127.0.0.1', 12345))
The rest is just copying input from your terminal to the socket. Note that this is unidirectional and line based, while netcat is bidirectional and asynchronous.
f = s.makefile('w') while True: line = sys.stdin.readline() if not line: break f.write(line) f.flush()
It is simpler to create connections than bind services, but the address conventions are the same.
Our existing service should still be running, so we can connect to it just like we did before with netcat.
$ python connect.py > to me to you > oh dear oh dear oh dear ^C $ | https://yakking.branchable.com/posts/networking-1-sockets-and-ports/ | CC-MAIN-2020-05 | en | refinedweb |
for-else loops
Posted July 08, 2013 at 09:12 PM | categories: programming | tags: | View Comments
Updated July 08, 2013 at 09:12 PM
I just learned of for/else loops (). They are interesting enough to write about. The idea is that there is an "else" clause of a for loop that is only executed if the loop completes without a break statement. The use case is to avoid using a flag. For example, let us say we want to loop through a list and determine if a number exists. Here is a typical way you might think to do it:
def f(): flag = False for i in range(10): if i == 5: flag = True break return flag print f()
True
A for/else loop does this in a different way. Essentially, the else clause runs if the loop completes, otherwise if the break occurs it is skipped. In this example the break statement occurs, so the else statement is skipped.
def f(): for i in range(10): if i == 5: break else: return False return True print f()
True
In this example no break statement occurs, so the else clause is executed.
def f(): for i in range(10): if i == 15: break else: return False return True print f()
False
It is hard to say if this is an improvement over the flag. They both use the same number of lines of code, and I find it debatable if the else statement is intuitive in its meaning. Maybe if there were multiple potential breaks this would be better.
Needless to say, go watch. You will learn a lot of interesting things!
Copyright (C) 2013 by John Kitchin. See the License for information about copying. | http://kitchingroup.cheme.cmu.edu/blog/2013/07/08/for-else-loops/ | CC-MAIN-2020-05 | en | refinedweb |
Hello all, I have been working on a huge commercial project and have come to a stop where I am not too familiarized in the mathematical side and conditional statements part of programming in C#.
What do I want?
My helicopter can travel at speeds and with this speeds I would like a different affect on collision at each speed.
My helicopter has been built using Rigidbody, mainly AddForce and AddTorque. I wouldn't even know how to get the speed value of the Rigidbody.
I would like the helicopter to be able to collide with the terrain at different speeds.
I have gone ahead and made some pseudocode to display to show you all what I am trying to achieve. I imagine I have been stuck for over 7 hours now and I guess all the research I have been doing has not lead me to the correct solution.
using UnityEngine;
using System.Collections;
public class CollisionTerrain : MonoBehaviour {
public GameObject terrain;
public ParticleSystem PlayP1;
public ParticleSystem PlayP2;
public ParticleSystem PlayP3;
public GameObject WH;
void OnCollisionEnter(Collision collision) {
if(helicopter.velocity.magnitude > 10); //If Helicopter is faster than a velocity of 10
PlayP1.particleSystem.enableEmission = true; //Helicopter will emit a black smoke and make a damage sound
PlayP1.AudioSource.Play(); // Ignore if wrong
if(helicopter.velocity.magnitude > 25); //If Helicopter is faster than a velocity of 25
PlayP2.particleSystem.enableEmission = true; { Helicopter will emit a deeper black smoke and make a more intense damage sound}
PlayP2.AudioSource.Play(); // Ignore if wrong
if(helicopter.velocity.magnitude > 50); //If Helicopter is faster than a velocity of 25
PlayP3.particleSystem.enableEmission = true; { Helicopter will emit a deeper black smoke and make a more intense damage sound}
PlayP3.AudioSource.Play(); // Ignore if wrong
WH.Instantiate.WreckageObject. //Blown up Helicopter
}
}
Answer by Addyarb
·
Apr 25, 2015 at 07:48 PM
First, lets get the speed of your object. Put this at the top of your script:
public float velocity; //The velocity of our object.
Vector3 previous; //The previous position of our object.
now, lets use the Update function to get the speed of our object. Like so:
void Update () {
velocity = ((transform.position - previous).magnitude) / Time.deltaTime;
previous = transform.position;
}
next, lets check that velocity if we hit something.
void OnTriggerEnter(Collider col){
if (col.tag == "Terrain") {
if(velocity > 0 && velocity < 10){
//SlowCrash();
}
else{
if(velocity >= 10 && velocity <= 50){
//MediumCrash():
}
else{
if(velocity > 50){
//FastCrash();
}
}
}
}
}
Thank you so much Addyarb!
I wasn't looking for OnTriggerEnter though, so I changed it to OnCollisionEnter, just in case anyone else sees this post and wanted it collision with terrain rather than the trigger area. :)
Of course! Glad you found a solution. Good luck with your game. :)
Answer by siaran
·
Apr 25, 2015 at 07:50 PM
your code is really not that far off. you can call rigidbody.velocity to get a rigidbody's velocity (as a vector3) and you can get the magnitude for a scalar value.
the problem in your code snip is mostly that if your speed is > 50, all lines will be called (if something is larger than 50, it is also larger than 10, 25, and 30).
a simple way of solving this would be something like
void OnCollisionEnter(Collision c){
float speed = helicopter.rigidboy.velocity.magnitude;
if(speed > 50) DoHighestEffect();
else if (speed > 25) DoMediumEffect();
else if (speed > 10) DoLowEffect();
else DoMinimumEffect();
}
You may want to have a single CollisionEffect(float speed) method instead that takes the speed as a parameter, depending on how you implement having different
rigidbody.Addforce doesn't move my bullet.
1
Answer
RigidBodies and "Slipping" Prevention
0
Answers
RigidBody Script Conflict
1
Answer
How to get my child objects to follow the parent? Also, not sure if this is working.
0
Answers | https://answers.unity.com/questions/954550/how-would-i-get-collision-at-different-speeds.html | CC-MAIN-2020-05 | en | refinedweb |
The Python Pandas DataFrame object has become the mainstay of my data manipulation work over the last two years. One thing that I like about it is the `.describe()` method, that computes lots of interesting things about columns of a table. I often want those results stratified, and `.groupby(col)` + `.describe()` is a powerful combination for doing that.
*But* today, and many days, I don’t want all of the things that `.describe()` describes. And the ones that I do want, I want as columns. Here is the recipe for that:
import pandas as pd df = pd.DataFrame({'A': [0,0,0,0,1,1], 'B': [1,2,3,4,5,6], 'C': [8,9,10,11,12,13]}) df.groupby('A').describe().unstack()\ .loc[:,(slice(None),['count','mean']),]
and out comes just what I wanted:
B C count mean count mean A 0 4 2.5 4 9.5 1 2 5.5 2 12.5
It took me a while to figure this out, and these docs helped:
Here it is as a ipython notebook.
(Note: this requires Pandas version at least 0.14.) | https://healthyalgorithms.com/tag/data-manipulation/ | CC-MAIN-2020-05 | en | refinedweb |
Disposal¶
Resources obtained within a unit of work - database connections, transactions, authenticated sessions, file handles etc. - should be disposed of when that work is complete. .NET provides the
IDisposable interface to aid in this more deterministic notion of disposal.
Some IoC containers need to be told explicitly to dispose of a particular instance, through a method like
ReleaseInstance(). This makes it very difficult to guarantee that the correct disposal semantics are used.
- Switching implementations from a non-disposable to a disposable component can mean modifying client code.
- Client code that may have ignored disposal when using shared instances will almost certainly fail to clean up when switched to non-shared instances.
Autofac solves these problems using lifetime scopes as a way of disposing of all of the components created during a unit of work.
using (var scope = container.BeginLifetimeScope()) { scope.Resolve<DisposableComponent>().DoSomething(); // Components for scope disposed here, at the // end of the 'using' statement when the scope // itself is disposed. }
A lifetime scope is created when a unit of work begins, and when that unit of work is complete the nested container can dispose all of the instances within it that are out of scope.
Registering Components¶
Autofac can automatically dispose of some components, but you have the ability to manually specify a disposal mechanism, too.
Components must be registered as
InstancePerDependency() (the default) or some variation of
InstancePerLifetimeScope() (e.g.,
InstancePerMatchingLifetimeScope() or
InstancePerRequest()).
If you have singleton components (registered as
SingleInstance()) they will live for the life of the container. Since container lifetimes are usually the application lifetime, it means the component won’t be disposed until the end of the application.
Automatic Disposal¶
To take advantage of automatic deterministic disposal, your component must implement
IDisposable. You can then register your component as needed and at the end of each lifetime scope in which the component is resolved, the
Dispose() method on the component will be called.
var builder = new ContainerBuilder(); builder.RegisterType<SomeDisposableComponent>(); var container = builder.Build(); // Create nested lifetime scopes, resolve // the component, and dispose of the scopes. // Your component will be disposed with the scope.
Specified Disposal¶
If your component doesn’t implement
IDisposable but still requires some cleanup at the end of a lifetime scope, you can use the OnRelease lifetime event.
var builder = new ContainerBuilder(); builder.RegisterType<SomeComponent>() .OnRelease(instance => instance.CleanUp()); var container = builder.Build(); // Create nested lifetime scopes, resolve // the component, and dispose of the scopes. // Your component's "CleanUp()" method will be // called when the scope is disposed.
Note that
OnRelease() overrides the default handling of
IDisposable.Dispose(). If your component both implements
IDisposable and requires some other cleanup method, you will either need to manually call
Dispose() in
OnRelease() or you will need to update your class so the cleanup method gets called from inside
Dispose().
Disabling Disposal¶
Components are owned by the container by default and will be disposed by it when appropriate. To disable this, register a component as having external ownership:
builder.RegisterType<SomeComponent>().ExternallyOwned();
The container will never call
Dispose() on an object registered with external ownership. It is up to you to dispose of components registered in this fashion.
Another alternative for disabling disposal is to use the implicit relationship
Owned<T> and owned instances. In this case, rather than putting a dependency
T in your consuming code, you put a dependency on
Owned<T>. Your consuming code will then be responsible for disposal.
public class Consumer { private Owned<DisposableComponent> _service; public Consumer(Owned<DisposableComponent> service) { _service = service; } public void DoWork() { // _service is used for some task _service.Value.DoSomething(); // Here _service is no longer needed, so // it is released _service.Dispose(); } }
You can read more about
Owned<T> in the owned instances topic.
Resolve Components from Lifetime Scopes¶
Lifetime scopes are created by calling
BeginLifetimeScope(). The simplest way is in a
using block. Use the lifetime scopes to resolve your components and then dispose of the scope when the unit of work is complete.
using (var lifetime = container.BeginLifetimeScope()) { var component = lifetime.Resolve<SomeComponent>(); // component, and any of its disposable dependencies, will // be disposed of when the using block completes }
Note that with Autofac integration libraries standard unit-of-work lifetime scopes will be created and disposed for you automatically. For example, in Autofac’s. If you are using one of the integration libraries, you should be aware of what automatically-created scopes are available for you.
You can read more about creating lifetime scopes here.
Child Scopes are NOT Automatically Disposed¶
While lifetime scopes themselves implement
IDisposable, the lifetime scopes that you create are not automatically disposed for you. If you create a lifetime scope, you are responsible for calling
Dispose() on it to clean it up and trigger the automatic disposal of components. This is done easily with a
using statement, but if you create a scope without a
using, don’t forget to dispose of it when you’re done with it.
It’s important to distinguish between scopes you create and scopes the integration libraries create for you. You don’t have to worry about managing integration scopes (like the ASP.NET request scope) - those will be done for you. However, if you manually create your own scope, you will be responsible for cleaning it up.
Provided Instances¶
If you provide an instance registration to Autofac, Autofac will assume ownership of that instance and will handle its disposal.
// If you do this, Autofac will dispose of the StringWriter // instance when the container is disposed. var output = new StringWriter(); builder.RegisterInstance(output) .As<TextWriter>();
If you want to take control of the disposal of the instance yourself, you need to register the instance as
ExternallyOwned().
// Using ExternallyOwned means you will be responsible for // disposing the StringWriter instead of Autofac. var output = new StringWriter(); builder.RegisterInstance(output) .As<TextWriter>() .ExternallyOwned();
Advanced Hierarchies¶
The simplest and most advisable resource management scenario, demonstrated above, is two-tiered: there is a single ‘root’ container and a lifetime scope is created from this for each unit of work. It is possible to create more complex hierarchies of containers and components, however, using tagged lifetime scopes. | https://autofac.readthedocs.io/en/latest/lifetime/disposal.html | CC-MAIN-2020-05 | en | refinedweb |
In the previous tutorials, we discuss C# if statement, C# if-else statement ,if ..else if ..else statement and nested if and else if statement . In this tutorial, we are going to learn the switch statement in C# programming. The C# language supports the switch statement or switch case statement. The switch statement is used to avoid the block of if..else.. elseif. Switch statement bases on the case. A statement can be executed on multiples condition using the C# switch statement.
switch (expression) { case 1: code to be executed if the expression is matched break; case 2: code to be executed if the expression is matched break; /*We can create many case statements*/ default: code to be executed if the.
1. The expression used in a switch statement must have an integral or enumerated type.
2. You can create many case statements within a switch.
3. When the case is matched to variable then the case code executes until the break.
4. A break works like termination of the block.
5. In the if-else, the else part also works as a default part. In the C# switch statement, the default part works when any case does not match with switch expression.
Let's create an example of a C# switch case statement.
Output-Output-
using System; namespace SwitchStatement{ public class Program { public static void Main(string[] args) { /* local variable definition */ int day=25; switch (day) { case 1: Console.WriteLine("Festival : Holi :Holiday "); break; case 2: case 3: Console.WriteLine("Festival : Diwali :Holiday "); break; case 25: Console.WriteLine("Festival : Christmas day:Holiday"); break; case 28: Console.WriteLine("Festival : Ram Navami :Holiday"); break; default: Console.WriteLine("No festival or check date"); break; } Console.ReadLine(); } } }
Festival : Christmas day:Holiday
In the above C# example, we created logic for festivals using C# switch case statement. You can modify according to your need and try this example of C# console.
Let's create another example to find out the day name using C# programming with the switch case statement.
using System;
using System; namespace SwitchStatement{ public class Program { public static void Main(string[] args) { /* local variable definition */ int day=2; switch (day) { case 1: Console.WriteLine("The First day of the week is Mon."); break; case 2: Console.WriteLine("The second day of the week is Tue."); break; case 3: Console.WriteLine("The third day of the week is wed. "); break; case 4: Console.WriteLine("The fourth day of the week is Thurs."); break; case 5: Console.WriteLine("The fifth day of the week is Fri."); break; case 6: Console.WriteLine("The sixth day of the week is Sat."); break; case 7: Console.WriteLine("The seventh day of the week is Sun."); break; default: Console.WriteLine("Invalid day"); break; } Console.WriteLine("Day of the week ={0}",day); Console.ReadLine(); } } }
Output -
The second day of the week is Tue. Day of the week =2
The second day of the week is Tue.
Day of week =2
In the above example, we created a logic to get week name using the C# switch statement. | https://technosmarter.com/csharp/switch-statement | CC-MAIN-2020-05 | en | refinedweb |
Take a look at this post in StackExchange: Agile methodologies such as
Scrum in non-software development projects
Also there is a nice article called "Scrum is not just for software"
written by the Agile Alliance (note that this is a PDF download)
Yes. By the very definition of bias, using a small set means you will have
a higher bias, towards whatever section you decide to train on. If you
randomly choose small samples from a larger data set though, this bias will
be greatly minimized.
If you're just using a small set of data, 10-fold cross-validation doesn't
make much sense. The idea of cross validation is to chunk up a large data
set into multiple parts, training with alternating parts of them serving as
train and test sets, iterating until the best solution across all
cross-validation sets is found.
If you don't have much time or computational power my first suggest would
be to step down your 10-fold CV checking. This will mean you can include a
much larger portion of your data set for the same computation time and
quickly eva
This article is a good place to start for git workflow. Also, Number8 is
right. You should be regularly fetching updates when working on the same
branch with other developers.
I have uploaded a series of tutorials on YouTube and also my Website that
might be helpful for you to get started.
Here is a basic tutorial on how to make an OS (assuming you mean operating
system):.
It's pretty good, but you need to learn the assembly language first
().
Hope I helped!
From what you are describing you could easily find yourself writing
integration tests. If your aim is to test the logic for processing what is
returned from the scraped data (e.g. you know that you are going to get a
timetable in a specific format coming in and you now have logic to process
that data) you will need to create a SEAM between your web services logic
and your processing logic. Once you have done this you should be able to
mock the data that is returned from the web service call to always return
the same table data and then you can write consistent unit tests against
it.
public class ScrapingService : IScrapingService
{
public string Scrape(string url)
{// scraping logic}
}
public interface IScrapingService
{
string Scrape(string url
As you dont have much work with NSWindows and NSViews, you surely dont need
NSWindowController or NSViewController.
And I think for this kind of app even your AppDelegate class is enough and
best place to put all your logic.
If you have some models then you can break your code upto that, and use it
in the AppDelegate itself.
Transition from iOS to OSX.
If you are good in Objective-C then you dont have to worry about few more
Cocoa-Controls especially GUI levels, you have full support of
Documentation.
Switching between iOS to OSX, vice-versa is not to difficult, but yes if
you end up with system level then you need to interact with OSX too.
There is far too little information here to provide a direct answer, but
I'll try to give you some basics.
The standards for IVR application development is VoiceXML for dialog
(caller interaction) and CCXML for call control. The latter is not as
commonly available. There are also numerous proprietary solutions. Your
choice of an open standard versus a proprietary solution should be more
about vendor/solution lock in. Even with the open standards, you'll likely
use custom enhancements and have some amount of lock in, but portability
will be easier. You can code directly to the telephony boards (challenging
and usually poorly documented if you are someone new to telephony) or work
with solutions that provide end to end capability. I find very few people
porting IVR applications so I w
Ant is used as a build system. You do not have to use it--in fact there
are quite a few better systems but since ant was one of the first it's
still likely to be very common. It generally is used to compile your java
files, create wars and often even put the .war files onto the tomcats.
Maven is bigger and tries to do a lot more, but it's also rather strict in
it's format and quite heavy--but it's quite common these days as well.
Maven can gather all your dependencies automatically which is nice, with
ant you still have to download everything yourself.
There are others, but you get the idea.
Response to comment:
I don't use visual studio, but I think it is more limited. For instance,
Eclipse can build all your java files into a jar or execute them directly
(in fact, it uses ant int
Well, your question is actually quite relevant to any database developer,
and, if I understand it correctly, there is another way to get to your
desired results.
One interesting thing to mention is that your idea of separating different
changes into different files is the concept of migrations of Ruby On Rails.
You might even be able to use the rake utility to keep track of a workflow
like yours.
But now to what I think migh be your solution. PostgreSQL, and others to be
sincere, have specific utilities to handle data and schemas like what you
probably need.
The pg_dumpall command-line executable will dump the whole database into a
file or the console, in a way that the psql utility can simply "reload"
into the same, or into another (virgin) database.
So, if you want to keep only the c
There.
This is how we have it set up:
We develop on the trunk.
Our dev work is on our local laptops, and when it works well enough, we
check in.
Then we deploy on the trunk to the Development Server, and do a bit of
testing there.
We deploy to the Test server also on the trunk, but only after we see it
working on the Dev server, and NOT if the code in Test has been approved
for prod.
So Dev is the most recent checked in, and Test is often that recent too,
but sometimes it is an older revision. Both of these are on the Trunk.
When the code in Test is approved for Prod, we will create a tag, then
deploy the tag to a copied app, make sure that the source code matches what
we expect, and then deploy that tag-created application to Prod.
If the code in Test which has finally passed QA isn't the ve:
You have PlayN, a cross-platform game abstraction library for writing games
that compile to different platforms included gwt:
Its API includes everything needed for the game loop, graphics, physics,
assets and network access (websocket).
I found this presentation and this one a good starting point (you have to
push left/right arrows to change slides).
In their site, there are many links to games developed with this library,
included Angry-Birds
In summary, with PlayN you code your game in java using a common API. Your
code will be compiled using either the gwt compiler to produce a HTML5
game, the java compiler to produce a java game, the android SDK to produce
a native droid app, or monotouch for iOS. In fact you dont have to know so
much o.
Well if you are interested in learning DirectX itself, you should try to
write your own 2D engine, which with a little experience isn't as hard as
it may seem. But if you want to get straight to game developement, you can
take a look at some engines that take care of that part. Shaders can really
enhance scenes (3D as well as 2D) and if I were you, I would definitely use
them, instead of just using simple unprocessed textures. Most engines won't
take the shader programming from you, so you will probably need to look
into hlsl anyway.
Also what I experienced with several engines and librarys: at some point
they will come to an end, and if you are enthousiastic about your project,
you don't want to live with those limitations. That's why I would recommend
writing your own engine which you ca
I think the Toad plugin for Eclipse is going to be the closest thing you
can find. Unfortunately, having a totally comprehensive IDE with these
features is going to be a huge project in part because PostgreSQL can use
stored procedures in so many different languages, so syntax highlighting
inside the stored procedure requires a vast amount of knowledge (in theory,
to be considered complete, not only sql and plpgsql but also C, C++, Java,
Python, Perl, TCL, R, Ruby, Lisp, various shells, PHP, Lolcode, and
Brainfuck -- there are probably more but those are the ones that come to my
mind). Consequently the only hope of doing this is to tie into another
IDE.
This being said I, and most devs I know, tend to use bash, vim, etc. It
is a fundamentally different paradigm but it is more flexible
Google has built a whole site dedicated to Chrome Extension Development:
Getting Started: Building a Chrome Extension.
Please see some ideas below set out to answer your questions.
I think the way to integrate the most amount of data sources is probably
with the the OpenGeo Suit. This is an open source software stack that
includes Geoserver as a WMS source and GXP libraries and examples as the
front end client. It can be found here
There are a number of Open source projects out there that will help. I have
already mentioned OpenGeo. Also check out
Openlayers
GeoExt (Can't post link as I don't have enough reputation points yet)
Leaflet (Can't post link as I don't have enough reputation points yet)
Geoserver is a good one for this but you could also checkout
Mapserver (Can't post link as I don't have enough reputation points yet)
In summary I would recommend th
Standard functionality (i.e. Eclipse projects, functionality available in
other bundles) can be installed via Help > Install New Software...,
select the appropriate update site ("Kepler").
I'm doing something similar (however I'm in the progress of migrating from
PyQt to PySide).
You should use pyside-uic to generate the code for the GUI after creating
the UI files in QtCreator (If this were PyQt "pyuic gui.ui > gui.py" would
produce the desired code, I assume pyside-uic has a similar behaviour). I
then subclass this generated code to customise the user interface.
Yes, you can use cx_freeze with PyQt/PySide, you'll want to include PySide
in the "includes" item in the build options.
Yes, you can create a completely self-contained executable - you won't need
Python, Qt or anything else.
Here's the build I use from my PySide GUI application.
__author__ = 'AlexM'
import sys
from cx_Freeze import setup, Executable
import MyPySideGui
import PySide, os
base = None
if sys.pla
We have 3 parts in this problem
First on in Qml your text area and bottom when clicked send text area to
function in c++
TextField {
id: n2
}
Button {
id: button
text: "send text"
onClicked: {
app.sendtext(n2.text)
}
Second part your c++ function in your ApplicationUI to receive this text
QString ApplicationUI::sendtext(QString txtarea)
{
QString text = txtarea;
return text;
}
Third and final part in your ApplicationUI.h u must make this function
INVOKABLE to access it in Qml
so u will need this line
Q_INVOKABLE QString sendtext(QString txtarea);
If you're set on managing it this way, you could use symlinks to link into
the git project from the actual web-exposed directories.
Here's a thorough answer describing that technique.
There are two php.ini files packaged with WAMP: php.ini-development and
php.ini-production. They are preconfigured with common settings for either
development or production. Whichever one you rename to php.ini is the one
that will be used.
If all you want to do is turn on error reporting, you can just edit
whichever php.ini file you are currently using by clicking on the WAMP icon
in your system tray and choosing PHP > php.ini. This will open the file
in a text editor where you can change whatever config you want including:
error_reporting = E_ALL & ~E_NOTICE
There is lots of documentation online and in the file for possible values
for this.
This post did it:. I can now
read all the exif data that I'm looking for.
Until you publish your work, it is your private. Just don't push while
developing. However, you could set-up a private repo visible to you only
(e.g. just for backups or working from different locations such as laptop,
desktop, etc).
Set up another shared repo (e.g. on github) and push here only when you
release.
Small demo:
[kan@altegom so18334364]$ git init --bare privrepo
Initialized empty Git repository in /private/tmp/so18334364/privrepo/
[kan@altegom so18334364]$ git init --bare pubrepo
Initialized empty Git repository in /private/tmp/so18334364/pubrepo/
[kan@altegom so18334364]$ git clone privrepo wc
Cloning into 'wc'...
warning: You appear to have cloned an empty repository.
done.
Set up public repo in you wc
[kan@altegom so18334364]$ cd wc
[kan@altegom wc (master)]$ git re
A good way of handling this is to use a constant that holds the path to
your project. That way you only have to edit that constant to get your
paths right.
define('BASEDIR', '/a/');
echo '
<script type="text/javascript"
src="'.BASEDIR.'resources/scripts/javascript.js" ></script>
<link href="'.BASEDIR.'resources/styles/stylesheet.css" rel="stylesheet"
type="text/css" />';
This will turn your paths into
<script type="text/javascript"
src="./a/resources/scripts/javascript.js" ></script>
<link href="./a/resources/styles/stylesheet.css" rel="stylesheet"
type="text/css" />';
If you keep that constant in a seperate file you can include it where you'd
need it. A php file that handles an AJAX request for instance. am happy to overwrite these changes, but I'm not sure how to do it."
git reset --hard
git pull origin master
You can use git in your new computer exactly the same way as you do in your
old computer.
"Ideally I'd like to be able to exclude some files from being tracked..."
Create .gitignore in the same directory and put the names of the files to
exclude in it.
If you're using windows, How to create .gitignore file
Outlook API is not native .NET framework. To interact it with, .NET relies
on marshaling and interrop assembly thus making it much more prone to
errors and unstable.
From what I've seen so far with my outlook API experience, I would stick
with VBA and you should consider retrieving a third party library that
exposes outlook extended MAPI if you run in to much of trouble.
I'd suggest AngularJS (). Why? Because it has a pretty
good tutorial section, good documentation AND it's backed by a large
company (Google).
But unfortunately, the learning is still up to you ;-)
All the informations about your web applications requests are written in
it, and it is quite useful.
When you start your application with rails s you can see it (it is tailing
the development.log)
Since its the development.log, you can clean the content, but be sure to
leave it there so you can see what your application is doing.
I.
The PRO file you're looking at is from an earlier version of the IDE than
you have currently installed. The functions performed by the mission lines
have been moved to a different location, probably for clarity.
Choice 1 is appropriate. VC must always track the source code, not the
products of any interpreter or processing. I feel your pain. It is so easy
to tweak that Vtiger source code, and VC tends to be left by the wayside.
The following works from within the Burp Extender Jython Shell. Hope it
helps.
import jarray
callbacks = Burp._callbacks
myRequest = Burp.history[0]
myHost = myRequest.host
myPort = myRequest.port
myByteArray= jarray.array(myRequest.raw, 'b')
testScan = callbacks.doActiveScan(myHost, myPort, 0, myByteArray)
# int showing percentage complete
print testScan.percentageComplete
Yes it is feasible but you will not be able to use xcode the latest xcode
4.5 with it because it supports ios 4.3 and later. You would be able to use
lower versions of xcode for 4.2.1 . The latest release notes indicates
4.2.1 and lower will not be supported, we now have to use 2 version of
Xcode to develop when supporting older devices.
Please go through
Old Xcode
Xcode 4.5 and iOS 4.2.1 incompatibility
XCode 4 and iOS 4.2.1 | http://www.w3hello.com/questions/-ASP-NET-Development- | CC-MAIN-2018-17 | en | refinedweb |
How to Design and Maintain the Smartform?
Form Printing
Every company regularly needs to print large numbers of documents with a consistent design, such as invoices or delivery notes. To do this, they must use their business application software. Documents can be output to a printer, a fax device or as e-mails.
Starting with R/3 Release 4.6C, SAP provides a new tool for form processing -SAP Smart Forms. This tool includes utilities for designing forms and for defining the interface to the application programs that use forms for data output.
Benefits of Smart Forms
Sapscript and Smart Forms
Architecture
Creating Documents
Tools For SAP Smart Forms
Designing SAP Smart Forms
Creating / Maintaining Forms
To call the initial screen of the SAP Smart Forms maintenance transaction, enter SMARTFORMS in the OK code field, or choose Tools → Form printout → Smart
Forms from the menu. Then choose one of the radio buttons depending on which type of SAP Smart Forms object you want to edit:
Forms Styles Text modules
If you want to work on a form, choose the Form radio button and enter the name of the form.
You can create, display, and change forms. The system then takes you to the graphical editing tool, which is called the SAP Form Builder.
Never change the original SAP forms to prevent your modifications from being lost during the next upgrade. Instead, copy the original form into your customer namespace (starting with Y or Z) and then modify the form copied as required.
You can also rename, delete, or test forms. To do this, use the available pushbuttons or the options of the Smart Forms menu. Testing a form requires that it has been activated before (in the SAP Form Builder).
Additionally, you can make settings specific to the SAP Form Builder. You can create SAP Smart Forms based on existing SAPscript forms by choosing Utilities → Migrate SAPscript form.
Window
- There are two types of windows: main windows and secondary windows.
- In the subnodes of the main window, you output text and data that may cover several pages (called the body text) such as the bookings of a customer. When the main window is completely filled with text and data, the text is displayed in the main window of the next page. The pages are broken automatically. (You can use a different next page than that set as the default. See Unit 7 -Flow Control.)
- You can only define one window in the form as the main window.
- The main window must have the same width on each page. You can choose the height and position as required.
- A page without a main window may not refer to itself as the next page since this would cause an endless loop. In this case, the system terminates after processing three pages.
- In the subnodes of a secondary window, you output text and data in a predefined output area. This means that the text is not displayed as a body text with page breaks.
- Text and data that do not fit into the secondary window are truncated and not output.
- The height, width and position of a secondary window may be different for each page.
- Graphics are automatically set to the correct size. As far as addresses are concerned, only the most important information is shown if the output area is too small.
Integration
1. The transaction looks up in Customizing which program to call. This program then reads the data.
2. The transaction learns in Customizing which SAP Smart Form to use for the scenario chosen, calls the appropriate function module generated and thus triggers the form processing process. The interface is filled with the data read.
When the form processing process is started, the form processor (Composer) is automatically called in the background. The Composer is responsible for formatting the texts according to the layout information stored in the form, filling fields with values at runtime and controlling the page breaks.Download attached file:
You must be Loged in to download file | https://www.stechies.com/benefits-smart-forms/ | CC-MAIN-2018-17 | en | refinedweb |
Python/matpotlib: Plotting occurrences of the main characters in How I Met Your Mother
Normally when I'm playing around with data sets in R I get out ggplot2 to plot some charts to get a feel for the data but having spent quite a bit of time with Python and How I met your mother transcripts I haven't created a single plot. I thought I'd better change change that.
After a bit of searching around it seems that matplotlib is the go to library for this job and I thought an interesting thing to plot would be how often each of the main characters appear in each episode across the show.
I've already got all the sentences from each episode as well as the list of episodes pulled out into CSV files so we can start from there.
This is a sample of the sentences)"
My first step was to transform the CSV file into an array of words grouped by episode. I created a dictionary, iterated over the CSV file and then used nltk's word tokeniser to pull out words from sentences:
import csv from collections import defaultdict episodes = defaultdict(list) with open("data/import/sentences.csv", "r") as sentencesfile: reader = csv.reader(sentencesfile, delimiter = ",") reader.next() for row in reader: episodes[row[1]].append([ word for word in nltk.word_tokenize(row[4].lower())] )
Let's have a quick look what's in our dictionary:
>>> episodes.keys()[:10] ['165', '133', '132', '131', '130', '137', '136', '135', '134', '139']
We've got some episode numbers as we'd expect. Now let's have a look at some of the words for one of the episodes:
>>> episodes["165"][5] ['\xe2\x99\xaa', 'how', 'i', 'met', 'your', 'mother', '8x05', '\xe2\x99\xaa']
So we've got an list of lists of words for each episode but gensim (which I wanted to play around with) requires a single array of words per document.
I transformed the data into the appropriate format and fed it into a gensim Dictionary:
from gensim import corpora texts = [] for id, episode in episodes.iteritems(): texts.append([item for sublist in episode for item in sublist]) dictionary = corpora.Dictionary(texts)
If we peek into 'texts' we can see that the list has been flattened:
>>> texts[0][10:20] ['a', 'bit', 'of', 'a', 'dog', ',', 'and', 'even', 'though', 'he']
We'll now convert our dictionary of words into a sparse vector which contains pairs of word ids and the number of time they occur:
corpus = [dictionary.doc2bow(text) for text in texts]
Let's try and find out how many times the word 'ted' occurs in our corpus. First we need to find out the word id for 'ted':
>>> dictionary.token2id["ted"] 551
I don't know how to look up the word id directly from the corpus but you can get back an individual document (episode) and its words quite easily:
>>> corpus[0][:5] [(0, 8), (1, 1), (2, 2), (3, 13), (4, 20)]
We can then convert that into a dictionary and look up our word:
>>> dict(corpus[0]).get(551) 16
So 'ted' occurs 16 times in the first episode. If we generify that code we end up with the following:
words = ["ted", "robin", "barney", "lily", "marshall"] words_dict = dict() for word in words: word_id = dictionary.token2id[word] counts = [] for episode in corpus: count = dict(episode).get(word_id) or 0 counts.append(count) words_dict[word] = counts
There's quite a lot of counts in there so let's just preview the first 5 episodes:
>>> for word, counts in words_dict.iteritems(): print word, counts[:5] lily [3, 20, 47, 26, 41] marshall [8, 25, 63, 27, 34] barney [9, 94, 58, 92, 102] ted [16, 46, 66, 32, 44] robin [18, 43, 25, 24, 34]
Now it's time to bring out matplotlib and make this visual! I initially put all the characters on one chart but it looks very messy and there's a lot of overlap so I decided on separate charts.
The only thing I had to do to achieve this was call plt.figure() at the beginning of the loop to create a new plot:
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt pylab.show() for word, counts in words_dict.iteritems(): plt.figure() plt.plot(counts) plt.legend([word], loc='upper left') plt.ylabel('occurrences') plt.xlabel('episode') plt.xlim(0, 208) plt.savefig('images/%s.png' % (word), dpi=200)
This generates plots like this:

This is good but I thought it'd be interesting to put in the season demarcations to see if that could give any more insight. We can call the function plt.axvline and pass in the appropriate episode number to achieve this effect but I needed to know the episode ID for the last episode in each season which required a bit of code:
import pandas as pd df = pd.read_csv('data/import/episodes.csv', index_col=False, header=0) last_episode_in_season = list(df.groupby("Season").max()["NumberOverall"]) >>> last_episode_in_season [22, 44, 64, 88, 112, 136, 160, 184, 208]
Now let's plug that into matplotlib:.savefig('images/%s.png' % (word), dpi=200)

The last thing I wanted to do is get all the plots on the same scale for which I needed to get the maximum number of occurrences of any character in any episode. It was easier than I expected:
>>> y_max = max([max(count) for count in words_dict.values()]) >>> y_max 260
And now let's plot again:.ylim(0, y_max) plt.savefig('images/%s.png' % (word), dpi=200)
Our charts are now easy to compare:


For some reason there's a big spike of the word 'ted' in the middle of the 7th season - I'm clearly not a big enough fan to know why that is but it's a spike of 30% over the next highest value.
The data isn't perfect - some of the episodes list the speaker of the sentence and some don't so it may be that the spikes indicate that rather than anything else.
I find it's always nice to do a bit of visual exploration of the data anyway and now I know it's possible to do so pretty easily in Python land.
About the author
Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database. | http://markhneedham.com/blog/2015/01/30/pythonmatpotlib-plotting-occurrences-of-the-main-characters-in-how-i-met-your-mother/ | CC-MAIN-2018-17 | en | refinedweb |
<?php $title = 'Conditionals I'; include '../head1.inc'; // Note: // 1. The explode function returns an array. // 2. The list notation on the left provides a list assignment of the // values from explode. list($i1, $i2, $i3, $i4) = explode('.', $_SERVER["REMOTE_ADDR"]); echo <<<END You are browsing from $i1.$i2.$i3.$i4.<p> Since IP numbers are so confusing, we can use a graphical method to make this clearer.<p> Here is a histogram of your IP number:<p><tt> END; print " "; $i = floor($i1/4); while($i--) echo "x"; echo "<br>"; print " "; $i2 /= 4; for($i = 1; $i <= $i2; ++$i) echo 'x'; echo "<br>"; print " "; $i3 /= 4; if($i3 >= 1) { do { echo 'x'; --$i3; } while($i3 > 0); } echo "<br>"; // If's and loops have an alternative syntax, using a colon after the // loop header and an end keyword. No brackets are required. print " "; for($i = $i4; $i > 0; $i -= 4): echo 'x'; endfor; print "</tt><p>Isn't that better?<p>"; // Plain HTML sections can be treated essentially as print statements, // and controlled by ifs. if($i1 <= $i4): ?> The first byte of your IP number is less than or equal to the last byte. This means the front of your computer is smaller than the back. You should check for proper support. <?php else: ?> The first byte of your IP is larger than the last byte. This means that your garfrabulator is larger than your muphoid cyberlink. This means that your computer is very economical to operate, as it produces more electricity than it consumes. <?php endif ?> </body> </html> | http://sandbox.mc.edu/~bennet/php/dump.php/leccode/l2/p2.php?type=fancy&title=Loops&run=Y | CC-MAIN-2018-17 | en | refinedweb |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
This post is in continuation with my previous question -
I am able to get the different values related to the issue and have included those in my custom email template. Now in the template itself I want to be able to show a table titled - "Change Fields" inside which I will show all those fields whose values/content has been changed on transition. I want to find the previous value(before transition) held by the changed fields and also the current value(post transition). Any documentation or tutorial about such functions would also help.
Thank you.
Edit - Any thoughts guys? On transition from one state to another I want to find what properties(for eg., description, priority, attachment) of an issue has been changed and show the old values of the properties as well the new one. Please help.
Use
event.getChangeLog()
more details here -
@Tarun Sapra getting an error - No such property: event for class
Also, I am writing this script directly into the web based editor of Post Functions where I am putting the content in HTML format.
@Tarun Sapra The above error comes when I try to trigger the custom email Post Function on transition. But if I go into the editor and provide the issue key and do a Preview then it works fine.
The other way I found is to use - changeHistoryManager and get old, new value for each field, compare it and show the changed ones as follows -
def changeHistoryManager = com.atlassian.jira.component.ComponentAccessor.getChangeHistoryManager()
def created = changeHistoryManager.getChangeItemsForField(issue, "summary")
Any thoughts? Or better way than this?
Hi Arpan, but does your approach guarantee that the old value of the field is the one which is just before the value after transition, as there could have been many transition before the present transition
@Tarun Sapra Thanks Tarun for pointing that out. Yes it is not fetching the most recent value. Instead all values are fetched.
Other than that, I dont know why I get an error on "event" keyword.. | https://community.atlassian.com/t5/Jira-questions/How-to-get-previous-and-current-values-of-all-the-changed-fields/qaq-p/269702 | CC-MAIN-2018-17 | en | refinedweb |
Gravatar
Having used ASP.NET MVC, the view that was displaying the comments had something like the following in them. This displayed the name of the commenter being a hyperlink, and that pointing to a mailto: link with the email address. The address was applied some transformations to prevent spammers from picking them from the page automatically:
<%= Html.Encode ( SomeBlogNamespace.SpamFreeEmail ( Model.Comment.CommentedEmail ) )%>
Now I did not want to change the model at all, but still wanted to add support for Gravatars. For this, I needed a method that could calculate the MD5 hash and display it in the format Gravatar wants it.
As I have my own base classes and model classes, I could have added the code there but decided to extend the MVC HtmlHelper instead. Using extension methods, that is really simple. I just added a new class to hold my extension method:
public static class GravatarHelper { public static string GravatarHash ( this HtmlHelper html, string value ) { var byteArray = MD5CryptoServiceProvider.Create ().ComputeHash ( System.Text.ASCIIEncoding.ASCII.GetBytes ( value.ToLower () ) ); string result = string.Empty; foreach ( var item in byteArray ) { result += item.ToString ( "x2" ); } return result; } }
I also needed to add a namespace import into the .ASCX file that contained my comments view:
<%@ Import Namespace="namespace" %>
After that I could change the view to display the picture from Gravatar by calculating the hash from within the view code:
<%= Html.GravatarHash ( Model.Comment.CommentedEmail ) %>
If you make a comment into this blog now, you can take advantage of Gravatars by giving your Gravatar registered email address. If you have a registered avatar the blog will display the image beside your comment.
This same method can be used to extend HtmlHelper in many different ways, adding small (or big) utilities that you can code and take advantage from the View in ASP.NET MVC. | http://blog.rebuildall.net/2009/09/24/Extending_ASP_NET_MVC_HtmlHelper_and_Gravatars | CC-MAIN-2018-17 | en | refinedweb |
Visiting the Microsoft campus in Redmond, Washington in August, I asked a couple of developers what the difference is between using the thread class and using the thread pool. The answer I got was that there is no real difference. The thread pool is easier because it manages thread objects for you; when you create a thread object, you have to manage it yourself.
Using threads in the ThreadPool was referred to as "lightweight" threading, and creating an instance of the Thread class was referred to as "heavyweight" threading. The adjectives did not refer to their capability but rather to ease of use. The thread pool is easier to use, but when using the thread pool, you are multithreading just as assuredly as you are when creating instances of the Thread class. One developer said something to the effect of "Why wouldn't you always use the thread pool?"
In effect, identical end results can be achieved with lightweight threading or heavyweight threading. It's easy to use the thread pool, and a little harder to use the Thread class.
What Is the Thread Pool?
The thread pool is a class defined in the System.Threading namespace. The class is ThreadPool. What the ThreadPool class does is manage a few threads that are available for you to request work. If the pool has available threads, the work is completed on an available thread. If no thread is available in the pool, the thread pool creates another task or may wait for a thread to become available. For the most part, you do not care exactly how it proceeds.
Very simply, the thread pool uses an available thread or creates a new one, manages starting the task on the thread, and cleans up. The thread pool is a thread manager. A consequence is that if you use the thread pool, you do not need to create and keep track of individual thread objects, but you get the same benefit as if you had.
How Does the Thread Pool Work?
The thread pool works in much the same manner as creating and using an instance of the Thread class. You have a thread and you give it work by passing the thread a delegate. In the case of the thread pool, you give the pool a delegate and the pool manager assigns the work represented by the delegate to a thread. The result is the same.
Using the Thread Pool
You are familiar with keeping track of the time in a Windows application, so we will start there. (When you have the basics down, we will progress to more interesting tasks.)
There are three things we will need to use the thread pool in a Windows Form to implement a clock. We will need to define a procedure that interacts with the Windows Form on the same thread as the form. We will need to define a procedure that represents work occurring on a separate thread than the form, and we will need to request that the thread pool perform the work. Listing 14.2 demonstrates how straightforward this is.
Listing 14.2 Implementing a clock on a separate thread.
1: Imports System.Threading 2: 3: Public Class Form1 4: Inherits System.Windows.Forms.Form 5: 6: [ Windows Form Designer generated code ] 7: 8: Private Sub UpdateTime() 9: SyncLock Me.Name 10: Text = Now 11: End SyncLock 12: End Sub 13: 14: Private Sub TrackTime(ByVal State As Object) 15: 16: While (True) 17: Try 18: 'Invoke(New MethodInvoker(AddressOf UpdateTime)) 19: Invoke(CType(AddressOf UpdateTime, MethodInvoker)) 20: Catch 21: 22: End Try 23: Thread.CurrentThread.Sleep(500) 24: End While 25: 26: End Sub 27: 28: Private Sub Form1_Load(ByVal sender As System.Object, _ 29: ByVal e As System.EventArgs) Handles MyBase.Load 30: 31: ThreadPool.QueueUserWorkItem(AddressOf TrackTime) 32: 33: End Sub 34: End Class
UpdateTime on lines 8 through 12 updates the form's captionText propertyto display the current time. (We have dispensed with the StatusBar because it isn't relevant to the discussion.) We use SyncLock and End SyncLock to block any other thread from trying to update the text property, but what makes the code safe is that UpdateTime occurs on the same thread that the form is on. (We will inspect this hypothesis in a minute.)
TrackTime has the signature of a WaitCallback delegate. WaitCallback is initialized with a subroutine that takes a single Object argument. Line 16 begins an infinite loop. We know from experience, of course, that an infinite loop in our main thread would spell death in the form of unresponsiveness to our application. Because TrackTime runs on its own thread, infinite-loop death does not occur. Lines 18 and 19 are effectively identical. Lines 18 and 19 use the Invoke method (which all controls have), which allows you to invoke a process. Calling Invoke bumps the work over to the thread that the control is on. On line 18 we are indicating that we want to invoke the UpdateMethod on the form's thread. Implicit in the call on lines 18 and 19 is the Me object reference.
Finally, line 31 calls the shared method ThreadPool.QueueUserWorkItem passing a delegate returned by the AddressOf statement as the work item. Line 31 will place TrackTime on its own thread. Figures 14.1 through 14.3 show the threads running and the changing of contexts as the code runs. A brief explanation follows each figure.
Figure 14.1. Form1.TrackTime shown on a separate thread, thread ID 2460.
Figure 14.1 shows the debugger stopped on line 63 on the statement Thread.CurrentThread.Sleep(500). From the Threads windowwhich you can open by choosing Debug, Windows, Threads in the Visual Studio .NET IDEyou can see that the TrackTime method is running on thread 2460. We use the Step Into shortcut until the debugger reaches line 57 in the TrackTime method. We use Debug, Step Into twice more until the debugger reaches line 60, which contains an Invoke method call.
Figure 14.2. Form1.UpdateTime shown on the same thread as the Form itself, thread 2324.
From Figure 14.2, you can see that the Invoke method caused the debugger to switch threads. UpdateTime is running on thread 2324. If we continue stepping to the end of UpdateTime, we see that the thread switches back to 2460 after the debugger returns from UpdateTime (see Figure 14.3).
Figure 14.3. Form1.TrackTime shown after returning from UpdateTime and back on thread 2460.
But how do we know we are on the same thread as the form? There are two ways we can determine that UpdateTime is on the same thread as the form. When the Form.Load event occurs, we can use the QuickWatch window, accessed by pressing Shift+F9 and invoking the AppDomain.GetCurrentThreadID shared method. This method will indicate the form's thread and we can visually compare it to the thread ID in the Threads window when UpdateTime is processing. The second way we can know if the UpdateTime is on the form's thread is by calling Control.InvokeRequired.
Each control implements InvokeRequired. Calling InvokeRequired compares the control's thread with the thread on which the InvokeRequired method was called. If the threads are identical, InvokeRequired returns False.
Problems
There is a problem with the code example in Listing 14.2. What if the form is shutting down or disposed of and the code calls the form's Invoke method on line 18? Although the help indicates that Invoke is safe to call from any thread, you still can't call a method on an object that has been disposed of. You could write to check to see if the form is Disposing, but if the form is already disposed of, this will fail.
You could check the IsDisposed property. This property will return True if the form is disposed of, but the garbage collector has not cleaned up the memory yet. However, if the GC has cleaned up the form, you will still get an exception.
You could use a flag in the form that indicates that the form is being closed, but the Invoke method could be called after the flag is checked.
Resolutions
For this example I would make one of three decisions based on the importance of the task. One choice would be to consider the task simplistic enough that a silent exception handler around the Invoke call would catch calls after the form had been destroyed.
Try Invoke(CType(AddressOf UpdateTime, MethodInvoker)) Catch End Try
Where the form has been disposed of, this silent exception handler would provide blanket protection. Because there is nothing to corrupt here, this is a reasonable solution. I am not a big fan of silent exceptions but do use them on rare occasions. The relatively low importance of keeping time might warrant such an approach.
A second choice would be to create the thread myself and keep track of the thread, shutting down and disposing of the thread when the application shuts down. This solution is clean and demonstrates an instance when owning the thread helps.
A third choice would to consider the relatively low importance of the task and use a timer to get asynchronous background behavior. In a real-world application where the timer is simply providing a clock, this is the choice I would make.
Using a WaitHandle and Synchronizing Behavior
The WaitHandle class is a base class used to implement synchronization objects. AutoResetEvent, ManualResetEvent, and Mutex are subclassed from WaitHandle and define methods to block access to shared resources.
To demonstrate blocking and synchronization of shared resources, I will implement a class named Dice. Each Dice instance rolls on its own thread, but the total score of all of the dice cannot be obtained until all of the dice have finished rolling. WaitHandle objects are used in conjunction with the thread pool, so we will roll the dice using the threads in the pool.
Listing 14.3 implements Dice and DiceGraphic classes. The Dice class represents a single die and the DiceGraphic class supports painting the graphical view of one face of a die. Listing 14.3 contains the code that runs on a unique thread, contains the shared WaitHandle, and uses synchronization to determine when all dice have finished rolling. Listing 14.4 lists the form that contains the graphical representation of five dice. A synopsis of the code follows each listing.
Listing 14.3 Contains the threaded behavior, WaitHandle, and synchronized behavior.
1: Imports System.Threading 2: Imports System.Drawing 3: 4: Public Class Dice 5: 6: Private FValue As Integer = 1 7: Private Shared FRolling As Integer = 0 8: Private FColor As Color 9: Private FRect As Rectangle 10: Public Shared Done As New AutoResetEvent(False) 11: 12: Public Shared ReadOnly Property IsRolling() As Boolean 13: Get 14: Return FRolling > 0 15: End Get 16: End Property 17: 18: Public Sub New() 19: MyClass.New(New Rectangle(10, 10, 50, 50), Color.White) 20: End Sub 21: 22: Public Sub New(ByVal Rect As Rectangle, ByVal color As Color) 23: MyBase.New() 24: FRect = Rect 25: FColor = color 26: End Sub 27: 28: Public ReadOnly Property Value() As Integer 29: Get 30: Return FValue 31: End Get 32: End Property 33: 34: Public Sub Roll(ByVal State As Object) 35: 36: Interlocked.Increment(FRolling) 37: Try 38: DoRoll(CType(State, Graphics)) 39: Finally 40: If (Interlocked.Decrement(FRolling) = 0) Then 41: Done.Set() 42: End If 43: End Try 44: 45: End Sub 46: 47: Public Sub Draw(ByVal Graphic As Graphics) 48: DiceGraphic.Draw(Graphic, FValue, FRect, FColor) 49: End Sub 50: 51: Private Sub DoRoll(ByVal Graphic As Graphics) 52: Dim I As Integer = GetRandomNumber() 53: While (I > 0) 54: FValue = GetRandomDie() 55: Draw(Graphic) 56: Beep() 57: I -= 1 58: Thread.CurrentThread.Sleep(50) 59: End While 60: End Sub 61: 62: Private Shared Random As New Random() 63: 64: Private Shared Function GetRandomNumber() As Integer 65: Return Random.Next(30, 50) 66: End Function 67: 68: Protected Shared Function GetRandomDie() As Integer 69: Return Random.Next(1, 7) 70: End Function 71: End Class 72: 73: Public Class DiceGraphic 74: 75: Public Shared Sub Draw(ByVal Graphic As Graphics, _ 76: ByVal Value As Integer, _ 77: ByVal Rect As Rectangle, ByVal Color As Color) 78: 79: Graphic.FillRectangle(New SolidBrush(Color), Rect) 80: Graphic.DrawRectangle(Pens.Black, Rect) 81: DrawDots(Graphic, GetRects(Value, Rect)) 82: 83: End Sub 84: 85: 86: Private Shared Function GetRects(ByVal Value As Integer, _ 87: ByVal Rect As Rectangle) As Rectangle() 88: 89: Dim One() As Rectangle = {GetRectangle(Rect, 1, 1)} 90: Dim Two() As Rectangle = {GetRectangle(Rect, 0, 2), _ 91: GetRectangle(Rect, 2, 0)} 92: 93: Dim Three() As Rectangle = {GetRectangle(Rect, 0, 2), _ 94: GetRectangle(Rect, 1, 1), GetRectangle(Rect, 2, 0)} 95: 96: Dim Four() As Rectangle = {GetRectangle(Rect, 0, 0), _ 97: GetRectangle(Rect, 0, 2), GetRectangle(Rect, 2, 0), _ 98: GetRectangle(Rect, 2, 2)} 99: 100: Dim Five() As Rectangle = {GetRectangle(Rect, 0, 0), _ 101: GetRectangle(Rect, 1, 1), GetRectangle(Rect, 0, 2), _ 102: GetRectangle(Rect, 2, 0), GetRectangle(Rect, 2, 2)} 103: 104: Dim Six() As Rectangle = {GetRectangle(Rect, 0, 0), _ 105: GetRectangle(Rect, 0, 1), GetRectangle(Rect, 0, 2), _ 106: GetRectangle(Rect, 2, 0), GetRectangle(Rect, 2, 1), _ 107: GetRectangle(Rect, 2, 2)} 108: 109: Dim Rects As Rectangle()() = _ 110: {One, Two, Three, Four, Five, Six} 111: 112: Return Rects(Value - 1) 113: 114: End Function 115: 116: Protected Shared Function GetRectangle(ByVal Rect As Rectangle, _ 117: ByVal X As Integer, ByVal Y As Integer) As Rectangle 118: 119: Return New Rectangle(Rect.X + _ 120: (Rect.Width * X / 3), _ 121: Rect.Y + (Rect.Height * Y / 3), _ 122: GetDotSize(Rect).Width, GetDotSize(Rect).Height) 123: End Function 124: 125: 126: Protected Shared Function GetDotSize( _ 127: ByVal Rect As Rectangle) As Size 128: 129: Return New Size(Rect.Width / 3, Rect.Height / 3) 130: End Function 131: 132: Private Shared Sub DrawDot(ByVal Graphic As Graphics, _ 133: ByVal Rect As Rectangle) 134: 135: Graphic.SmoothingMode = _ 136: Drawing.Drawing2D.SmoothingMode.AntiAlias 137: 138: Rect.Inflate(-3, -3) 139: Graphic.FillEllipse(New SolidBrush(Color.Black), Rect) 140: 141: End Sub 142: 143: Private Shared Sub DrawDots(ByVal Graphic As Graphics, _ 144: ByVal Rects() As Rectangle) 145: 146: Dim I As Integer 147: For I = 0 To Rects.Length - 1 148: DrawDot(Graphic, Rects(I)) 149: Next 150: 151: End Sub 152: 153: End Class
Listing 14.3 implements the Dice class as a class that rotates a random number of times through the values 1 through 6. During each roll (see lines 51 through 60), a random value for the dice is obtained, Beep is used to simulate the sound of rolling dice, and the die is drawn. The drawing of the die's face is managed by the DiceGraphic class using GDI+ (see Chapter 17, "Programming with GDI+," for more information on using the Graphics object).
Transitioning to the topic of our discussion, the rolling behavior is run on its own thread invoked by an external source. Lines 34 through 45 implement the rolling behavior. Line 36 calls the shared Interlocked.Increment(FRolling) method to perform an atomic increment of the shared FRolling field. Dice are rolling when FRolling > 0, as implemented by the shared IsRolling property of the Dice class. A resource protection block is used to ensure that the FRolling property is decremented. The rolling behavior is called on line 38. From the typecast on line 38CType(State, Graphics))it is apparent that we will be passing in the Graphics object each time we roll the dice, because GDI+ is stateless. The Graphics object represents the device context, or canvas, of the control we are painting on, and its stateless implementation simply means that we do not cache Graphics objects. The Finally block ensures that the FRolling field is decremented, again using an atomic shared method Interlocked.Decrement. The new value of FRolling is evaluated. If FRolling = 0 after it has been decremented, all dice have stopped rolling and we can signal the WaitHandle that we are finished.
Done is instantiated on line 10 as an AutoResetEvent. AutoResetEvent is subclassed from WaitHandle, and it is created in an unsignaled state, represented by the False argument. Done is shared because one WaitHandle is shared by all instances of Dice. In summary, each Dice instance increments the shared FRolling field and decrements it when it is finished rolling. When FRolling is 0 again, we notify whoever is waiting that all dice are finished rolling. Listing 14.4 demonstrates a client that shows the dice (see Figure 14.4).
Figure 14.4. The threaded dice after they have been rolled on their own threads.
Listing 14.4 Each die rolls on its own thread, while waiting for all dice before scoring the roll.
1: Option Explicit On 2: Option Strict On 3: 4: Imports System.Threading 5: 6: Public Class Form1 7: Inherits System.Windows.Forms.Form 8: 9: [ Windows Form Designer generated code ] 10: 11: Private FDice(4) As Dice 12: 13: Private Sub Form1_Load(ByVal sender As System.Object, _ 14: ByVal e As System.EventArgs) Handles MyBase.Load 15: 16: Dim I As Integer 17: For I = 0 To FDice.Length - 1 18: FDice(I) = New Dice(New Rectangle(54 * I, 10, 50, 50), _ 19: Color.Ivory) 20: Next 21: End Sub 22: 23: Private Sub RollDice() 24: Dim I As Integer 25: For I = 0 To FDice.Length() - 1 26: ThreadPool.QueueUserWorkItem(AddressOf FDice(I).Roll, CreateGraphics) 27: Next 28: 29: Dice.Done.WaitOne() 30: End Sub 31: 32: Private Sub Score() 33: Dim I, Sum As Integer 34: For I = 0 To FDice.Length() - 1 35: Sum += FDice(I).Value 36: Next 37: 38: Text = String.Format("Scored: {0}", Sum) 39: End Sub 40: 41: Private Sub Button1_Click(ByVal sender As System.Object, _ 42: ByVal e As System.EventArgs) Handles Button1.Click 43: 44: RollDice() 45: Score() 46: 47: End Sub 48: 49: Private Sub Form1_Paint(ByVal sender As Object, _ 50: ByVal e As System.Windows.Forms.PaintEventArgs) _ 51: Handles MyBase.Paint 52: 53: Dim I As Integer 54: For I = 0 To FDice.Length - 1 55: FDice(I).Draw(CreateGraphics) 56: Next 57: 58: End Sub 59: 60: End Class
NOTE
Note: The threaded rolling behavior is cool, but it is worth noting that it took me about five times longer to write a threaded version of the rolling dice and get it to work correctly than simply rolling all dice on the same thread as the form.
Most of the code in Listing 14.4 is straightforward, so I won't itemize all of it. To review, the form is created. Five Dice are constructed in the form's Load event. The form's Paint event ensures that the dice are repainted if the form is repainted. (If the dice were user controls, they would receive their own paint message.) When the user clicks the button labeled Roll (refer to Figure 14.4), the RollDice and Score methods are called. The Score method simply sums the Value of each die. The interesting bit happens in the RollDice method.
The RollDice method on lines 23 through 30 iterates over each Dice in the FDice array declared on line 11. The Roll method of each Dice object is treated as the WaitCallback argument of the shared ThreadPool.QueueUserWorkItem method. Dice.Roll represents the work. The second argument is a Graphics object returned by the CreateGraphics factory method. After the loop exits, each dice is rolling on its own thread in the ThreadPool.
Resynchronizing occurs on line 29. The shared AutoResetEvent object is used to wait for all of the dice to stop rolling. Recall that the code does not call AutoResetEvent.Set until IsRolling is False, that is, until all dice have stopped rolling. By implementing the code this way, the message queue is filling up with input but not responding until AutoResetEvent.WaitOne (represented on line 29 by Done.WaitOne) returns.
NOTE
The first time you roll the dice, there is a brief delay between when the first die begins rolling and each subsequent die. This reflects the time it takes for the thread pool to construct additional thread objects. Subsequent rolls appear to start almost concurrently.
If you try to close the form, for example, the application will wait until the dice have stopped rolling before responding to an application shutdown. If you try to roll a second time before an ongoing roll is over, the application will respond after WaitOne returns. You would not want to be using the Graphics object passed to each die if the form object were being destroyed. Finally, because each die paints itself, you get a smooth graphic result without repainting the entire form, which would result in flicker.
ManualResetEvent
The ManualResetEvent is a WaitHandle that remains signaled until the Reset method is called, and remains unsignaled until the Set method is called.
Mutex
Mutex is a synchronization primitive that provides synchronized access to a shared resource. If one thread acquires a mutex, subsequent threads are blocked until the first thread releases its mutex.
Synchronization with the Monitor Class
Synchronizing critical sections of your code is essential when you may have multiple threads accessing a shared section of your code. For general synchronization, you can use the SyncLock...End SyncLock construct.
The SyncLock...End SyncLock construct is implemented using the Monitor class. You cannot create an instance of Monitor; all of the methods are shared anyway. Invoking Monitor.Enter(object) and Monitor.Exit(object) is identical to using the SyncLock...End SyncLock construct.
Monitor also contains methods Pulse, PulseAll, TryEnter, and Wait. Pulse notifies a single object in the waiting queue of a state change in the locked object. PulseAll notifies all waiting threads of a state change, and Wait releases the lock and waits until it reacquires the lock. The TryEnter method attempts to acquire an exclusive lock on an object.
Listing 14.5 demonstrates how to use the Monitor class to switch back and forth between two threads interacting with the same object.
Listing 14.5 Using the Monitor class.
1: Option Explicit On 2: Option Strict On 3: 4: Imports System 5: Imports System.Threading 6: 7: Class MonitorDemo 8: 9: Private Integers() As Integer 10: Private MAX As Integer = 1000 11: 12: Private I, J As Integer 13: 14: Public Sub FillArray() 15: Dim I As Integer 16: ReDim Integers(MAX) 17: Dim R As New Random() 18: 19: For I = 0 To Integers.Length - 1 20: Integers(I) = Integers.Length - 1 - I 21: Next 22: End Sub 23: 24: Public Sub SortArray(ByVal State As Object) 25: Monitor.Enter(Integers) 26: 27: For I = 0 To Integers.Length - 1 28: For J = I + 1 To Integers.Length - 1 29: If (Integers(I) > Integers(J)) Then 30: Dim T As Integer = Integers(I) 31: Integers(I) = Integers(J) 32: Integers(J) = T 33: End If 34: Next 35: 36: Monitor.Wait(Integers) 37: Console.Write("Sorted: ") 38: Monitor.Pulse(Integers) 39: Next 40: 41: Monitor.Exit(Integers) 42: End Sub 43: 44: Public Sub PrintArray(ByVal State As Object) 45: Static K As Integer = 0 46: 47: Monitor.Enter(Integers) 48: Monitor.Pulse(Integers) 49: 50: While (Monitor.Wait(Integers, 1000)) 51: 52: If (K <= I) Then 53: Console.WriteLine(Integers(K)) 54: K += 1 55: End If 56: 57: Monitor.Pulse(Integers) 58: End While 59: 60: Monitor.Exit(Integers) 61: End Sub 62: 63: Public Shared Sub Main() 64: 65: Dim Demo As New MonitorDemo() 66: Demo.FillArray() 67: 68: ThreadPool.QueueUserWorkItem(AddressOf Demo.SortArray) 69: ThreadPool.QueueUserWorkItem(AddressOf Demo.PrintArray) 70: 71: Console.ReadLine() 72: 73: End Sub 74: 75: End Class
Listing 14.5 uses Monitor.Enter and Monitor.Exit on lines 25 and 41 and again on lines 47 and 60. We would get the same result if we used the SyncLock...End SyncLock construct.
The Main subroutine is the starting point for this console application. An instance of the MonitorDemo class is created on line 65 and an array is filled with a thousand integers in reverse order. The ThreadPool is used on lines 68 and 69 requesting work from the SortArray and PrintArray methods. SortArray sorts the array of integers and PrintArray prints the integers in the array.
After each complete pass through the inner loop of the bubble sort, Monitor.Wait is called on line 36, giving the PrintArray method a chance to print the ordered ith element. Line 57 calls Monitor.Pulse notifying the SortArray method that the state has changed and allowing SortArray to reacquire the lock. The Monitor.Wait call on line 50 blocks the loop until the PrintArray method can reacquire the lock on the Integers object or one thousand milliseconds have elapsed. In summary, the code sorts each ith element and then prints the newly sorted element at the ith position.
Summary
The CLR supports asynchronous processing, lightweight threading using ThreadPool, and heavyweight threading by constructing instances of the Thread class. You are not limited to an all-or-nothing approach when implementing asynchronous or threaded behavior.
Choose the Timer control or Application.Idle event or BeginInvoke and EndInvoke for lightweight asynchronous behavior in Windows Forms. Consider using ThreadPool for many everyday multithreading tasks, and pull out the big gunthe Thread classif you need absolute control. Of course, when using the Thread class, you have to take complete ownership of the behavior of the thread, including creating, starting, and stopping the thread.
The CLR, and consequently Visual Basic .NET, support asynchronous and multithreaded behavior as well as a whole complement of synchronization and shared resource management by using the WaitHandle or Monitor classes. Consider all of the available resources for asynchronous and threaded behavior before selecting a particular implementation strategy. | http://www.informit.com/articles/article.aspx?p=25869 | CC-MAIN-2018-17 | en | refinedweb |
See also: IRC log
Alexey: I call you about the
organization chart
... I want to project the IANA slide that I think was skipped yesterday
(setting up projector)
(IETF and IANA is projected)
Alexey: IANA manages registries,
and there are multiple entities that affect what IANA
does
... If IETF adopts a procedure or defines a policy, IANA is required to follow it
... IANA does give input on what the policy should be
... IANA follows what IETF says in RFCs
... the other entity that affects IANA is the IAB (Internet Architecture Board) - talks to IANA about policy decisions like licensing
... IESG approves RFCs and so defines the formats, IAB controls the policy experts
... If people are unhappy with IANA policies they should not blame IANA - except in the case where IANA is slow in updating something
AVK: can blame them about format, URL persistence
Alexey: there is a document,
RFC5226 which defines standard procedures for registries
... IETF can make any format that it wants, but there is a typical format for registries
... registries can have different policies, templates, levels of restrictiveness
... most permissive level is first come first serve
... examples include vendor names
... on the other end of the spectrum, the strictest ones require a standards track RFC
... in the middle is a procedure called "specification required"
... requires a stable specification from an IETF-recognized standards organization
HS: Is there an official definition of what is a recognized standards organization? there are different opinions
Alexey: no, it's not defined;
people don't want to fix the list
... general criteria are: long established, stable document
HS: why is stability a requirement? if the software moves faster than the registry, then the registry is out of date
Alexey: depends on the registry -
many registries are for developers
... for example, as a developer you may want to find all the link relations
AVK: but as a developer, I find
current IANA registries useless
... wikipedia is a better reference for URI schemes than IANA is
... vetting by experts makes registries incomplete and inaccurate
HS: you said not just software
implementors or others
... for years, image/svg+xml wasn't in the registry
... when Apple shipped MPEG-4, the type wasn't in the registry
... I can't think of any constituency for whom the registry says all that they want to know, or even close
AVK: apart from pedants, maybe
Alexey: a couple of comments on
this
... different registries have different policies
... at the time when the registry was established, there was IETF consensus that this was the desired policy
... as time goes on, it may be that reality shows that a particular policy was too strict (or too permissive)
... maybe part of the answer is to revise the policy
HS: in the days of classic MacOS
when Carbon was still used a lot, and you needed four char type
and creator codes, it seemd that the value for those codes was
smaller than the space for MIME types
... so you'd think you'd have a greater need than for MIME types to limit who can get what, but Apple operated a registry on first-come first-serve basis and nothing bad came out
<anne> MJS: you mentioned that it is possible to change the policy
<anne> ... assuming that some of the folks here are interested in a much more permissive policy
<anne> ... what would be the process to get the IETF to change
<anne> Alexey: talk to the AD and talk to other people to initiate discussion
<anne> Alexey: I'm happy to help with the progress
Alexey: the other half of the
answer
... there is a reason there are expert reviews for some of the registries, like MIME types
... people do make stupid mistakes in MIME types, so there is an opportunities to fix this
HS: one of the supposed mistakes is using the text/* subtree for a lot of stuff, and there I would claim the mistake on the IETF side
AVK: what proportion of MIME types are not in use when they are registered? it seems like most of them already are deployed by the time you go to register them, so it might be too late to fix
Alexey: in the ideal world, people should ask experts up front
<Julian> !
Alexey: one example is that you can't use UTF-16 of textual types
HS: that's bogus
AVK: still insisting the case now is misguided
JR: one thing that Anne mentioned
- some registries have a provisional system
... but not MIME types
Alexey: vendor prefix ones are first-come first-server
JR: other question -regarding the
media type registration RFC, Larry has started discussing
revising it in the TAG
... for example, people sniff for types - we could make that more robust
HS: I want to complain more about
CR/LF
... the history of CR/LF restriction and the fact that text/* defaults to US-ASCII in the absence of charsets...
... this is an artifact of a leaky abstraction from SMTP
... US-ASCII default is a theoretical most prudent default from the time when in email there wasn't an obvious default
... but neither of those considerations apply to HTTP
... HTTP can send text that has line breaks that are not CR/LF
... in fact for HTML, LF-only is preferred
... it makes no sense to say that all these types like HTML, JavaScript and CSS are "wrong"
... instead it would make more sense to say that CR/LF does not apply to HTTP
... for some types, for historical reasons we need to default to Windows -1252 or UTF-8
... pretending these need to be registered under the application/* subtree doesn't help anyone
... it only serves the RFC canon that HTTP and SMTP match, but that doesn't help authors or implementors
... line breaks should be based on transport protocol
... types themselves should be able to define their default charset
JR: if you look at the thing that
Larry brought to the TAG about MIME on the Web...
... he mentions all these problems
... line break thing doesn't make sense on the Web
... HTTP appears to use MIME, but doesn't, and doesn't need to
... charset is also an issue for HTTP
... conflict between MIME, HTTP and XML types on text/*
HS: I actually implement
RFC2023
... I have a checkbox for saying ignore it
<anne> (There's a t-shirt saying "I support RFC 3023")
HS: if I shipped the validator without the "ignore it" box, people couldn't use the validator
JR: what's the default?
HS: defaults to supporting it
Alexey: comment on Web vs email -
this needs to be discussed in IETF
... if Web requires modified version of MIME, let's do it
... there is a new WG in applications area
<anne> APPSAWG
<weinig>
HS: it feels frustrating to
actually have to discuss this
... that people don't believe what they see on the web
AVK: the feeling is that the IETF
is so much behind, and then we have to get in and tell the old
timers what the new world looks like
... we're not sure it is worth our time
... we have moved on
Alexey: it is occasionally
helpful to talk to people who designed the original
... especially when it comes to character set - I think there is agreement from the original author
AVK: I talked about some of the
discussion about moving away from text/plain drafts, and people
there express fear of Unicode....
... W3C is kind of slow too, but at least we think HTML and Unicode are ok
HS: well, W3C isn't ready to publish HTML5 as HTML5 yet
JR: IETF thinks HTML and Unicode are fine, just not for their documents
Alexey: there is provisional registration
AVK: for header fields, you need
spec even for provisional
... person guarding the header field registry was too conservative
JR: does header name registry
have a public mailing list
... registry lists should be public
Alexey: can you draw cases like this to my attention? it might be implementation of process failures
AVK: but if we look at URI schemes..
Alexey: it's hard for me to
defend the people who designed the procedure
... there was a discussion about relaxing registration of certain types of URIs
... so we could register things like skype or yahoo IM
AVK: we are trying to register
about: - there should be some registration pointing to the
draft
... and for many headers, browsers have to know about them even if they are unregistered
... difficulty of using registry causes incentive to use X- names and just not registry
JR: one thing we should look at
is accountability - there needs to be a public mailing list for
header registration
... also Larry will join us to talk about IRI
AVK: I would rather just get rid of IANA and have a W3C registry, with a community-managed wiki
HS: to consider how the XHTML2 WG
was doing things - at some point it was obvious that just
giving feedback wasn't going to change the way they did
things
... so instead of trying to change the way they did things, another group did something else, and that became the group people paid more attention to
... there is a feeling that fixing IANA is so difficult that it would just be easier to set up a wiki
AVK: we could just compete
Alexey: this is not helpful
AVK: I would like a registry that
would tell me X-Frame-Options exists
... I don't think this will ever fly at IANA
HS: I have no experience of registration, but the language tag registry is a very positive role model
Alexey: when I talk to IANA, they listen
AVK: I think the problem is the process
Alexey: I can help you initiate changing the process
AVK: not sure I am interested in helping to fix the process if there is an easier path
HS: we should mention willful
violations of the charset registry
... it would be useful for the main charset registry to be the place to go to find out what you need to implement
... the thing is that ISO-Latin1 should actually be interpreted as Windows-1252
... another example is that instead of Shift-JS you need to use the Microsoft tables not the ISO tables
LM: I note that my draft covers many of these issues
HS: not in this much detail; I will give feedback
<Julian>
LM: I hope in the cases where there are willful violations, that the right thing to do is to fix the registry
AVK: in the case of the charset registry, there might be a need for separate registries for Web clients vs other clients
HS: for example the Java platform
uses the IANA names for charsets with their real meaning
... it would not be good to change Java, so the registry should include both sets of info
... JAva could add an API for Web content decoders
LM: I think this is a three-phase
process
... (1) identify the problem
... (2) identify which things need to change (w/o being explicit about how)
... (3) then there needs to be action on the change
... I would like to identify the problem and the kinds of changes first
... only then decide whether to make a wiki, change the process, etc
AVK: if you are already working on this, then that's great
LM: I would be happy to have co-authors
Alexey: at minimum we should talk
LM: I think we should bring it
into a working group or take it up as an action item
... MIME is a part of the Web architecture that we have adopted without adopting it
JR: we talked earlier about text/html and encoding
LM: again I think we should
describe the problem first
... same thing might be said for URI schemes
HS: given last call schedule
(1H2010), how realistic is it that changes of these magnitude
could go through the IETF
... seems unlikely
LM: my view is that a W3C
document entering LC can make reference to documents at similar
or behind level of maturity
... they don't need to be final until you go to REC
MS: (explains W3C process)
HS: one reason I'm skeptical
about the rate of change at IETF is the URL thing
... we had rules in the HTML5 spec abut transforming href values to IRIs
... it was argued that IRIbis was supposed to solve it
... I remember there was a schedule
LM: it's quite off
HS: at the date when there was
supposed to be a deliverable, they haven't even started
... we shouldn't send things to the IETF to die
... I was really annoyed when I wanted to fix a bug relating to URL handling in Firefox and the spec did not have what was needed
... I think that for URLs the process has had it chance and din't deliver
RI: the original schedule was very aggressive and we never really expected meeting it
LM: it was wildly
optimistic
... the problem with most standards activities is that there's nobody home except for people who showed up
... if you look at the archives, there was really a fallow period, but since then it is picking up
... meeting next week in beijing
... people who care about URLs in HTML should show up online
HS: there is also the problem that if people are already showing up in some venue, then moving the work to a different venue and then complaining that people didn't show up in the other venue is not productive
LM: the problem really is that
what was in the HTML document before was wrong
... unfortunately there is complexity due to need to coordinate with IDNA and bidirectional IRIs
HS: you need something that takes
a base IRI, a relative reference as UTF-16, and a charset, and
you get a URI/IRI back
... my point is that the HTML spec doesn't need to deal with rendering any kind of address
... it just cares about resolution / parsing
... nothing about how to render an IRI
... what is required is someone writing down the real-world algorithm for this resolution thing
... and it needs to be somewhere that you can reference it
RI: if it were in the IRI specification would it be ok for you
HS: what I am annoyed about is
that we had something that was right or fixable, was removed or
delegated, and now we have to rewrite it
... I am now betting on Adam delivering it
JR: I would like to say one
thing
... we need to find the right separation between things that are just part of the attribute and things that are part of the the resolving algorithm
... I think whitespace discarding is not part of the resolutions
... there might be a step before resolving that is part of extracting from an attribute
AVK: in the running code, whitespace stripping happens at the resolving end
LM: it would be nice if you could copy from the location bar into other apps
HS: we are not talking about the location bar
JR: what about space-separated lists of URLs
AVK: this is a different case
LM: motivation for trying to
start the work in the IETF was to make sure that URLs in HTML
and in other apps weren't different
... it is true that the work has been delayed, but activity has been restarted
Alexey: you need to open bugs
LM: Adam was at the last
meeting
... there is an IETF document of how to do IETF document
HS: it's great the kinds of URLs
that the web uses were the same as what other things use it,
that would be great
... but the Web is constrained
JR: this was very useful, which I'm not sure was expected; we have another point about link relations, which is on the agenda
ack
MS: in the future, we shouldn't delete things until the replacement is ready
LM: chairs from IRI working group are prepared to add an additional charter item
AVK: Adam is a bit reluctant to go back to the IETF
<anne> (that was my impression)
RI: it seems like there are discussions coming up in beijing where we need to be talking between the HTML WG and IETF
LM: editors will be remote, so
remote participation might be good
... how about file: URLs
HS: they are not really on the
Web
... best thing to do for USB key is relative URLs
<r12a> whether it's beijing or not, i think we need to find a way to pursue this dialog with HTML5 folks and chairs/editors of the IRI spec
RI: is something gonna
happen
... action items?
LM: don't be skeptical - if you believe it will work
<scribe> ACTION: Henri to give feedback to Larry on MIME etc draft [recorded in]
<scribe> ACTION: Anne to give Alexey info about registry problems [recorded in]
<MikeSmith> started lunch break?
MikeSmith, we're about it
<MikeSmith> k
er, about to
session adjuourned
<anne> fwiw, testing was half an hour delayed
<anne> not sure if anyone is actually in the other room yet
<anne> but since you just signed in...
<Julian> isn't testing at 5pm (50 mins from now?)
<anne> no
<anne> it's a double block
<Julian> oh
<anne> yes
<anne> we are setting up
<anne> dbaron, ^^
<hsivonen> dbaron, we are in Rhone 3b
<hendry> scribenick hendry
<oedipus> scribenick: hendry
me: to find the connection type, it's not slow or rather blocking is it?
it's a fast operation Andrei: yes, we fire online when the type changes
type just caches last seen connection type
[ scribe apologies for pasting in wrong buffer ]
maciej: how to particpate in tasks tf, testing framework
<plh> kk: and goals for LC
kk: the TF meet every two
weeks
... there is a wiki with schedule, there is a server with hg
... philippe has mirrored that work at
<plh> --> HTML test suite repository
kk: same content on both servers
<plh> --> HTML Testing Area
kk: asking what to test ...
localstorage, x-domain messaging, doing spec analysis
... looking at features which are shipping
... submitted some canvas tests
<plh> --> Canvas test suite
kk: getElementsByClassname tests
from Opera
... distinction between approved and un-approved tests
<plh> --> s/Philipp Taylor/Philip Taylor/
kk: bugzilla to process the test
<plh> --> Test harness
jonias: what is the harness ?
anne: same as XHR
kk: tests run automatically
... video tests is hard to automate
... self-describing test
... some exceptions that you can't poke in the OM and you can't test it
hsivonen: can you do some REFerence tests ?
jonas: yes, there are some things
kk: there are some things you can't test with REF tests, for e.g. Audio
hsivonen: multi-testing question
plh: some tests are manual and some tests are automatic
kk: existing tests not using the testharness, it might not be worth re-writing them
plh: it's a bug, it shows the buttons, though its automatic
kk: waits for 5 seconds before going to next test
maciej: this UI is broken
kk: can we get all the
requirements up front ?
... esp we need a plan with REF tests
maciej: propsed categories;
script driven, ref test, manual test
... too awkward with 100k tests ... takes too long to run
plh: the test can indicate itself, if it's manual or automatic
anne: if the test loads the test harness, we know it's an automatic test ( no need to categorise )
hsivonen: just have 3 directories
dbaron: you can harness the harness
kk: we should do it in one file
hsivonen: the easier way is to use directories
jonas: i don't care
maciej: text file is harder to maintain than a directory, not big deal either way
<plh> scripts/
<plh> reftests/
anne: we want directories for *types* of tests
<plh> manuals/
dbaron: painful to use dirs as metadata, as you may need to move them around
kk: maybe we will come up with a new dir in some months time, prefers a text file as it wont change location
jonas: bigger problem to have a function call when the test finishes so we don't have to wait 5 seconds after each one loads
anne: there is logic in the harness to handle this & async tests
hsivonen: [ didn't quite understand your implicit mochi test comment ]
<dbaron> plh: need a way to copy all the additional files that tests depend on
<hsivonen> I find that I almost always have to use the explicit finish function for scripted tests, so it's not a win to finish tests implicitly on onload
jonas: we need to somehow markup dependencies
sweinig: in the common case there will be no deps
hsivonen: should we decide whether to allow data URLs ?
anne: common resources makes sense
hsivonen: you want to use data URLs for near 0 load times
[ why does jonas use data URLs? didn't get his argument ]
kk: ie9 supports dataURIs
... might be a problem that browsers do not support dataURIs
jonas: we need to list our deps
and assumptions
... can we assume browsers have ES5, foreach is nice
maceij: we should not use ES5 until it's widely implemented
jonas: queryselector test cases were held up by WebIDL
kk: e.g. of WebIDL false positive in canvas read only thing
jonas: do we have any existing docs of assumptions?
kk: there is just the source
code
... can someone take an action to document them?
anne: read the XHR tests :-)
<krisk> testing wiki
jonas: these tests are already in directories
kk: suggests documenting the tests in the wiki
hsivonen: ... something about re-writing the "mochi tests" ??
anne: i'm fine with re-writing / using another harness
kk: first anchor test is very simple, it's not hard to migrate to james's harness
jonas: make some requirements for making the tests portable between harnesses [ IIUC ]
hsivonen: something about integration layer, which allows reporting into your own system (thanks anne)
<plh> --> mercurial
plh: you can commit a test if you have a W3C account
dbaron: might need to be aware with hg's push caveats [ to plh ]
<plh> ACTION: plh to work with systeam to make sure we keep track of hg push [recorded in]
maciej: not great security, since hg trusts the client's config WRT who wrote the patch
dbaron: you might want logs
... Mozilla have a tool called push-log for this problem
jonas: i can see now the tests are seperated by directory
<dbaron> The source for pushlog is in this hg repository:
jonas: is there a description file ?
<anne>
<anne>
kk: see
... we will add extra info
jonas: remove domain so it's not
server specific
... we have a test file per dir
... i want to walk this from the cmdline
... i want relative paths
kk: we might need some absolute stuff
jonas: i'm pulling via hg
kk: there is no absolute need for absolute urls
hsivonen: mochi-tests point to localhost
jonas: something clearly
identifiable for a search & replace to get the tests
working
... you can get different types of relative paths
... it's important that we can accomodate them in a "search & replace"
... we need to scale
... it's not workable to ban absolute paths
hsivonen: we need to document the "clearly identifiable" bit, like test.w3.org and test2.w3.org
jonas: we have to say it's OK to use abs paths
hsivonen: worried about some dir
namespace collision
... get rid of prefixes
jonas: OK
<krisk> That is fine
kk: how to delimit the file ?
jonas: i don't care
... though, since it's hand-written, make it easy & little to type
sam: is there a preferred
lengthmicroformats.org with CSS tests there was a wide
range
... bad = long test & lots of permutations
hsivonen: we know a bad test when we see it
maceij: there is a fuzzy boundary
jonas: io bound if we have a million tests ... we need to keep it somewhat reasonable
sam: there are examples of tests that can be merged
adrian: there is a review process
kk: you could file a bug, raise issues
adrian: of course if it's approved, it doesn't mean it can't change again
sam: if all the tests pass, then the bugs are in the specs
kk: tests do content negotiation (canPlayTypepermanence) WRT choosing a codec the runtime supportS
hsivonen: mochi tests that we (mozilla) use, requires server side javascript
plh: was a lot of trouble already to support PHP for security reasons
sam: we have tests that use python, php, curl for certain load tests
<dom> (we evoked this in WebApps the other day; we can probably consider more server-side stuff at some point, but we need to need to have requirements documented earlier rather than ater)
<dom> (and please consider limiting the number of needed languages/platforms as much as possible)
jonas: we can generalise "slow
load tests" so it doesn't neccessarily require PHP
... some security concerns here
plh: we need to review PHP files before they become live
jonas: we need it one the same server for same origin type cases
<dom> if same server == test.w3.org, that's part of the plan
hsivonen: we need a mechanism to load things slowly for example
<dom> (use a DTD for that)
hsivonen: avoid echo, we should return existing (approved) files
jonas: is there sensitive data WRT XSS-ing
plh: should be fine
<anne> safest might be w3test.org or some such
kk: what happens if 10 million tests are in the Q to be approved
dbaron: biggest risk is a test that claims to test something, but doesn't actually test it
sam: we should only accept tests
that use the new harness
... the tests here are about testing regressions
kk: worried about approval rate, esp. if only he does it
plh: if a subset of tests are passed by everyone, they are probably good
anne: 1) is it good enough hsivonen 2) ... [ didn't get that ]
maceij: lets do a cost benefit analysis
<adam> Accidentally testing something that is not a requirement at all
maceij: 1st category testing
undefined behaviour
... 2nd -- testing something contrary to a requirement
... -- at least one browser will fail this
[ can someone write what maceij said pls ? ]
scribe: 3rd cat testing something
where it doesn't actually test it
... review should catch them all
... almost certain something will be wrong
... how much time should be spent on review versus benefit
... test approved == matches what the spec says
dbaron: from exp within CSS, review is more work than writing to test... so its not worth doing for an existing contributor
s/writing to test/writing the test/
dbaron: figure out why the test
is failing sooner than later
... imp report: 1) run all tests 2) bug in test suite or in browser (v. time consuming)
... figure out WHY tests are failing
hsivonen: we should flag tests
that fail in all browsers
... we can't assume the spec is neccessarily 100% correct
<hsivonen> we should flag tests that fail in 3 engines
maceij: low skilled tests don't need to be approved, better if everyone is just running them [ IIUC ]
anne: we should distribute the testing
maceij: don't have ref test when
you could have a script test
... distributed test is more likely to succeed
hsivonen: do we have any way to feed the test info to the WHATWG HTML5 section info box things
kk: could be an admin problem if links change
<krisk> see for an example of a script based test
<freedom> nobody in 3B yet? there will be an EPUB related meeting right?
<oedipus> according to the agenda, EPUB discussion in 3B starting 8:30 french time
<mgylling> Reads 09:00 to me
<mgylling> To anybody who is physically there: does 3B have call-in facilities?
<oedipus> guess the first half hour will be spent in common again then breakout to 3B
<freedom> seems not
<freedom> I am in 3B physically now
<mgylling> freedom, thanks.
<MichaelC> scribe: Julian
ms: markus to give overview
mgylling: (remotely)
<mgylling>
mgylling: epub standard for
ebooks, around for several years, expanding in popularity,
large adoption
... idpf.org
... based on xhtml, subsets defined
... current ebpub 2.0
... uses XHTML1.1 mod
... is a fileset, ZIP container, different document types
... container called OCF
<freedom>
mgylling: some of the formats in
epub defined by w3c
... some of the metadata formats owned by epub itself
... is undergoing rev to 3.0
...charter: update & alignment with modern web standard
s
use HTML5 as grammar
is not allowed by current specs but already happening
need to formalize & stabilize
on HTML5 vs XHTML5: epub decided to use X*
based on requirement for existing reading systems to be upgradeable
MS: asks about design
philosophies
... drive spec based on what current UAs already can do?
mg: docs used to be static
... <script> SHOULD/MUST be ignored
... but scripting is going to be added
... problems with legacy readers
... and non-browser-based impls
... it's clear that this will be needed in the future
MS: devices coming to market with have full browser engines
Julian: usability of spec for being referenced
?
mg: not a problem yet
... we're not forking
... defining profiles and extensions, follow the HTML5 style
Julian: how does ext work for you?
mg: XHTML5 is supposed to allowed namespace-based extensibility
ms: feedback on this is
... epub I18N requirements -> CSS WG -> vertical text support
... does not seem to affect HTML though
... is there something the HTML WG need to do?
mg: books / ebooks slightly
different domain
... missing semantics for books
... distinguish node references and nodes
... skippability
page breaks
have looked at role attributes for extensibility
mjs: extending role not
recommended because owned by aria
... needs coordination with PFWG
... maybe dedicated elements
or attributes
what affects rendering should be in HTML
mg: book semantics, chicago manual of style
in transcript, replace "node" by "note"
MC: asks about roles
MG: uses custom attributes
<MichaelC> Role attribute extensibility:
MG: fastest way for now (own NS)
MC: role module *does* allow extensibility
<MikeSmith> RRSAgent:, make minutes
MC: PF and HTML need to coordinate on r@ole
@role
<Zakim> MichaelC, you wanted to discuss role extensions, future aria, etc.
MG: ownership of @role
mjs: HTML defines @role by refererence to ARIA spec
MC: aria defines on HTML to define @role
<MichaelC> s/aria defines/aria depends/
mg: request to clarify the HTML spec wrt role extensibility
<fantasai> RRSAgent: make minutes
mg: on metadata in epub
... NCX doesn't have metadata at all anymore
<MichaelC> ARIA on host language role attribute
mg: core metadata will continue to come from outside HTML/head
<mjs> -> role attribute in HTML5:
mg: reading systems need to get the metadata from the package file
HS: on role attribute
<fantasai> hsivonen: ARIA spec defines aria- attributes, but does not define role attributes
<fantasai> hsivonen: requires that a host language define a role attribute with certain characteristics
<fantasai> hsivonen: HTML5 tries to do this
<fantasai> hsivonen says something about tricky wordsmithing
<fantasai> hsivonen: Way forward would be to figure out roles that current AT vendors need (?) and define tokens for them, and have ARIA promise not to conflict
<fantasai> hsivonen: The role module spec relies on CURIEs for extensibility
<fantasai> hsivonen: ... not good for EPUB
<fantasai> hsivonen: I don't expect web engines to support CURIEs, relies on namespace stuff ... lookup DOM L3
<fantasai> hsivonen: Best way forward is to ask PF to set aside the names that you expect to use
<fantasai> hsivonen: Doesn't make sense to pretend different groups dont' know about each other
<fantasai> hsivonen: We're communicating, so let's coordinate.
<MichaelC> ARIA taxonomy
<fantasai> ?: I'm ok with approach Henri is suggesting, but coordination with PF is important sooner rather than later
<fantasai> MichaelC: Everything would have to fit into our taxonomy
<fantasai> hsivonen: Implementations don't care about the taxonomy, that's only to help out with spec design
<fantasai> hsivonen: If PF promises that this set of names is not going to be used, and picks different names if it decides to expand in that area, then we don't have to worry about all this extensibility stuff
<mjs> ack q+
<fantasai> MichaelC: For author understanding, we want to pick tokens that match the most appropriate terminology
<Zakim> MichaelC, you wanted to say if you want to follow the approach Henri suggests, should coordinate with PFWG sooner than later and to say ARIA roles are part of a taxonomy
<fantasai> hsivonen: They're just tokens, it doesn't really matter
<fantasai> mjs: Instead of debating in the abstract, let's just send the list of suggested roles to PF asap
<hsivonen> DOM 3 namespace lookup doesn't work for CURIEs in text/html DOMs, so don't expect browsers to implement CURIEs
<fantasai> mjs: If they don't like the tokens proposed, then they can respond about that.
<fantasai> mjs: I don't think this meta-conversation is getting us anywhere
<Zakim> Julian, you wanted to let Mike speak
<fantasai> hsivonen: I'd like to add a note about why CURIEs are bad idea in this space
<fantasai> hsivonen: So, frex, how Gecko exposes roles to interface to JAWS, Gecko picks the first role it recognizes and exposes that as the MSAA role
<hsivonen> IAccessible2
<fantasai> hsivonen: And then exposes the entire value of the role attribute as the xml-roles property in the iAccessible2 interface
<fantasai> hsivonen: It follows that the namespace mapping context of the CURIE binding context is not exposed at all
<MichaelC> scribe: fantasai
hsivonen: If you wanted to do
something with CURIE, you wouldn't do CURIE processing.
... You would wind up exposing to JAWS the prefix and local name
<freedom> IAccessible2,
hsivonen: Therefore I advise against relying on the mapping context, because the existing ... doesn't expose the mapping to IAccessible2 and therefore to JAWS
markus: Does Gecko expose the roles regardless of whether it recognizes it?
hsivonen: Yes. All the data is
passed through, in case JAWS wants to violate ARIA and look at
things itself.
... Gecko doesn't police whether JAWS follows ARIA spec
MikeSmith: I just wanted to state
where things stand.
... It's not inconceivalbe that the language features you need for EPUB could be considered as native elements and attriutes to be added to HTML5 itself. It's not too late for that.
... It's not too late to ask, anyway.
... I'm sure we're going to get LC comments asking for new elements and attributes.
... There will be a lot of people who haven't looked at the spec yet, or want opportunity to have their request considered.
... Proper way to change the spec is file a bug against the spec.
... Cutoff for pre-LC was Oct1. Everything after that date will be considered an LC comment.
... I don't think that you should self-censor, and just assume there's no chance of getting any new language feature requests for native elements and attriutes considered.
... That's not what we want
... I don't want to say you have nothing to lose, because there's cost in time to everyone
... But something for EPUB to consider, whether you want to make requests for new elements/attributes.
<hsivonen> Gecko exposes the value of the role attribute to JAWS but not any kind of CURIE prefix mapping context, which mean using CURIEs wouldn't really work with the URL and you'd end up hard-coding a known prefix and the resolution to an absolute URI would be fiction
MikeSmith: Not mutually exclusive: could also pursue extensible approach, too
<hsivonen> thus bad idea to use CURIEs
MikeSmith: It's a good idea, although some things we need are likely to be considered out-of-scope for HTML5
Markus says something about e.g. notes
fantasai asks if that wouldn't be <aside>
mjs: Just want to reinforce
Mike's comment that we would definitely like to hear all the
requests, even though we are late in the game and probably
aren't going to add major new feature.
... But requests that are modest in scope and important for a particular use case will be considered
... We're not 100% frozen yet, but in a few months we will be. So better to get those requests in now rather than later.
... Any other comments?
fantasai: Wouldn't notes be an <aside>?
Markus: Notes would be a subclass of <aside>
Markus says something about an href role
mjs: Talking about footnotes and end notes?
Markus: Yes. Need to distinguish those for formatting
MikeSmith: Don't we have a bug open on having more roles for <a>?
mjs: If particular semantic of linking to footnote or endnote might be more appropriate as a rel value
hsivonen: Maybe have a CSS pseudo-class detecting the note type from what the <a> points to instead of requiring author to specify
Markus: Reponse from EPUB authors
say that overall, it's really good. There are a number of
additions from XHML1 that we love.
... We're already very close to having it work for books, only a few minor concerns.
... So not looking for any major surgery here.
fantasai: I think they should define a microformat for subclassing notes.
hsivonen: Håkon and Bert already defined a microformat for books, although I don't think they addressed notes.
Bert: yes. A lot of that has been added to HTML5, though: <article>, <section>, etc.
mjs: HTML5 just recommends a plain <a>, with no distinguishing markup
hsivonen: footnotes are a thorny
issue in CSS. Prince supports something, but it's not
optimal
... I was reading Dante's Inferno in HTML5. It doesn't make any sense to read it without footnotes.
mjs: Yeah, I read a Terry Pratchett book that was supposed to have footnotes, but they were all endnotes and it didn't work so well
<Bert> Boom! (BOOk Microformat)
hsivonen: I think we should
figure out the CSS layout model first, then fit the markup to
that.
... If we come up with markup first, and it doesn't fit the CSS layout model, making it work in layout could become very complicated, involving many pseudo-classes, etc.
meeting closed?
<Bert> (Contrary to what I remembered, BOOM *does* have footnotes, not just sidenotes: <span class=footnote>)
discussion of role attributes
mjs: You need centralized extensibility for accessibility, so the a11y technology understands the roles
hsivonen: If you're on Windows, what FF can do is more than with the AS api on Mac
<MikeSmith>
hsivonen: So maybe it's a bad
idea to design stuff with the assumption that you have
IAccessibible2 on Windows
... Alternatively, could consider it a bug that AS doesn't have this feature
<hsivonen> s/AS/AX/
anne: The only case you'd notice it is JAWS was updated before voiceover
hsivonen: I'm guessing the upgrade rate of JAWS is a non-issue in practice
<MikeSmith>
Julian: You might not believe how backwards some people are in upgrading their browser
hsivonen: Big parts of ARIA have been designed with the assumption of an enterprise stuck with IE7 for years after ARIA has been deployed in JAWS
<MikeSmith>
hsivonen: Design decisions make assumptions about which part of the system will be upgraded first. Might not have been the best design decisions.
<MikeSmith>
fantasai: So is EPUB subsetting HTML5?
MikeSmith: not sure
mjs: Engines are unlikely to enforce any subsetting
fantasai: True, but such content
could be non-conformant for EPUB 3.
... Not all EPUB implementations are based on browser engines
?: Are there many that are not?
fantasai: I know of at least
two
... and I haven't actually looked into the issue
<kennyluck> fantasai: When I was at Tokyo, I found a EPUB implementation that implements CSS but not based on browser
<kennyluck> .. I also found one EPUB implementation that's not based on browser at all
<kennyluck> ... yet it renders vertical text quite nicely
<kennyluck> ... (It does not support CSS)
fantasai: uses effectively a UA stylesheet only
hsivonen: Are the CSS implementatiosn any good/
fantasai: Don't know, haven't done any testing
discussion of converting HTML5 to EPUB
would need to split into multiple files for EPUB impl's tiny brains :)
<mgylling> Yes, splitting files is done a lot due to memory constraints in certain handhelds
<mgylling> A popular one has a 300k limit IIRC
<MikeSmith> 12 minutes to caffeine
<freedom> which means EPUB doesn't encourage authors to write long chapters?
<mgylling> hehe, yes, need to keep it short ;)
<mgylling> I expect these max file size recommendations to be gone soon, just another generation shift needed in devices
<freedom> mg: do it, my iPhone 4 has 512MB now
<mgylling> freedom, right. Note that this is not spec restrictions; these are conventions that has arisen in the ecosystem
<freedom> OK, bad implementation, not bad spec
<scribe> ScribeNick: fantasai
mjs: Subtopics include
... Idea of using microformats
... another is that we have a number of specific issues
<mjs>
<mjs>
<mjs>
<mjs>
mjs summarizes the open issues
mjs: Does anyone else have other subtopics?
<adam> *u must be dozing off*
<anne> no kidding
<Zakim> MikeSmith, you wanted to show XPointer registry and to discuss potential need for a role registry similar to need for a rel registry
MikeSmith: Somehow I ended up the
one responsible for registering all link relations for
HTML5
... So, I guess I can put some kind of report on that? What should I be doing.
Julian: Let's start with a
description of .. right now
... I'll summarize where IETF is right now.
... It all started with realization that HTTP has a Link header that's supposed to be equivalent to Link element in HTML
... And that there are documents on the web which are not HTML and for which it would be useful to expose linking
... Lots of people think it would be a good way of expressing link semantics independently of HTML
... So Mark Nottingham started on the work of writing a new def of Link in HTTP
... And establishing a registry that could be used in HTML as well, but would not necessarily be used in HTML
... The IANA registry also includes the link relations registry that was established for the Atom feed format, which is similar but not identical to HTML.
... So there are overlapps, but it included syndication-related things and not everything that HTML has
... So there was lots of discussion on procedural things, and licensing of the registry.
... Can talk about that later.
... Took a long time for spec to come out, but has finally been published.
<Julian>
Julian: That's a very old style: you send an email to an IETF list, and a group of designated experts to register that or ask questions.
<Julian>
Julian: Mark has started making this more modern by, first of all, providing a web page explaining how to register, has a template to help with you write the registration and submit for you to the mailing list
<Julian>
Julian: The designated experts
now also has an issue tracker
... So people can watch where there registration requests are progressing
... Makes the IANA process a bit more pleasant
<Julian>
Julian: Here's the registry riht
now
... This contains link relations defined in Atom, Atom extensions, and HTML4
... and some parts for HTML5
<Julian>
hsivonen: ? has been recognized
as an entity that has reasonable ? measures in place
... It seems that the domain name is owned by ???
... as an individual
... And whatwg.org is also owned by an individual
Julian: I'm not sure how that affects our impression of whether microformats.org is stable or not
<MikeSmith> s/???/Rohit Khare/
mjs: My biggest disappointment
about the RFC is that it doesn't have provisions for individual
registrations
... It would be useful to have a central repository where all of these can be listed so people know what's in use, even if it doesn't have a formal spec
... I think Mark should make a provisional registry.
... Mark said the registry would be so lightweight it wouldn't be necessary
... But that has not proven to be true.
<hsivonen> moreover, even proven to be false
Julian: We have provisional registries in other IANA things, and nobody's used them.
<MikeSmith>
mjs: I think if you find something that's almost never used, then creating something that has higher barrier to entry, then creating something with a higher barrier to entry isn't going to increase use
Julian: People don't use provisional registries because they don't care enough.
mjs: microformats.org list has even lower barrier to entry, and it is used
Julian: One difference between
IANA registry and wiki page is that wiki is completely HTML
focused
... So they don't consider relations among other formats other than HTML
... They don't think about use on PDF or video
mjs: Most people invent link
relations for HTML. I don't think it makes sense to force them
to address these abstract link uses that may or may not be
practical.
... It makes more sense to me to provisionally register the link relations, and then encourage them to think about generalizing to other formats.
hsivonen: It might be not about
people not caring, but about provisional registration being
dysfunctional
... I also agree with mjs that in some cases people don't care about nonHTML use cases. In that case we should just do HTML.
Julian: we talked about ...
provisional registry [that hsivonen mentioned] yesterday, and I
totally agree this problem needs to be investigated.
... I think we try.
... I think we should try to encourage people to think of link relations applied to non-HTML content
mjs: I think encouragement is fine. But if encouragement fails, what happens? Should the link relation then be undocumented because encouragement was unsuccessful?
Julian: ... nobody's mailed a link relation and asked designated experts to help make the link relation more generic
mjs: You've raised the barrier by tring to make it generic, the person doesn't care about making it generic, so it ends up being unregistered
anne: You don't need that to get it in the registry, but to get it endorsed
hsivonen relates hixie's experience with trying to register a link relation
hsivonen: If what hixie wrote wasn't enough, then I think we have a problem.
Julian: My point of view was that
he didn't seriously try. He wanted to prove it didn't
work.
... I don't think it will be productive to continue on this path.
mjs: When I looked at the
original templates hixie submitted and compared them to what
the RFC said, I couldn't see any mechanical procedure that
determined they failed to qualify
... So it seems anyone trying to register would require multiple email go-around
... Same problems result in failure to register MIME types and URL schemes
MikeSmith: I have been going through the process of making requests using the mandated procedures
<MikeSmith>
MikeSmith: You can see there the
discussions about the registry
... It does take multiple go-arounds in email for these.
... One is for some of the link relation names or types, they are already being used in other contexts
... One of those was 'search'.
... If you look at that, it was specified somewhere else.
... Regardless of how you do this, there has to be some discussion about what this description should say
... I don't see any way to get around that, if you have multiple ppl want to define the same thing.
... Other issues were with how it's defined in the spec itself.
... 'up' is one of those. Had to go back to WG and get a resolution for it
... .. Maciej... having to change the description of the link relation so that it's more generic, and less about HTML
... I'm not thrilled with that.
... Don't really care about doing that at this point in the procedure.
<hsivonen> (one of the top Google hits for the metaphor is from one of our co-chairs: )
MikeSmith: I think many ppl are
not going to be thrilled about changing what they think is a
perfectly reasonable discription of their use case to handle
some speculative use cases
... That's alwasy going to be a troublesome thing for someone to do
s/disc/desc/
MikeSmith: In the spirit of going
through the procedure and taking it to the end to see if it
ends up being something it works or not
... But I do think we have to keep open the possibility that we decide that it doesn't work.
... I don't think it's a given that just because it's an RFC and the registry exists, that we've commited to this is how we do it.
<MikeSmith>
MikeSmith: I think it's still a
possibility that this isn't working the way we would like it to
work, let's try something else.
... There is something else, plh asked me to point out.
... Is the xpointer registry.
<anne> +1 to W3C doing web registires
MikeSmith: This is another way of registering something that is similar
<anne> s/registires/registries/
MikeSmith: I think the biggest
... difference between things that have been successfully
regsitered
... and those that are still being reviewed
... i.e. provisionally registered
... All you need to do to request a provisional registration, you just start by typing in a name of some kind
it gives you a form asking for a description, and optionally a spec URL
MikeSmith: This is a middle ground between a wiki page
and
<hsivonen> This looks good to me
MikeSmith: At least it's got a
form-driven interface
... I think this is a good middle ground
... If the IANA registry provided a way of doing this, I think that would be something we could agree on
Julian: IANA registry has
something very similar
... The only thing is that instead of being automatically registered, it gets sent to the email list
... If we made a provisional registration out of the sumission, that would be the same.
<Julian>
<anne> The requirements for XPointer are first-come-first-serve
Julian: and then someone on the mailing list to the tracker page
<anne> This is not at all the case for the link registry
<anne> well, the one the IETF/IANA uses
hsivonen: How do you know the tracker issue is filed and where that is?
Julian: You don't
?: Why can't you do a web-based form?
Julian: Can't do that in IANA.
IANA doesn't have web-based forms. Lives in last century.
... The form that posts to email is a compromise.
hsivonen: So why does HTMLWG/W3C want to deal with an organization that lives in the last century
<weinig> s/?:/Sam
hsivonen: Instead of using xpointer registry code?
Julian: It depends on whether you think the link relations should be synced with other formats or not
sicking: Why couldn't you let W3C do the syncing to IANA?
MikeSmith: Before ? pointed out xpointer, I didn't know we did registries
mjs: Sounds like building a registry along the lines of xpointer would be a great idea
<MikeSmith> s/?/PLH/
mjs: Any volunteers to do
that?
... write it up as a Change Proposal?
... It's a little past deadline, but since we have new info on the W3C registry option, would be a good thing to do
MikeSmith: Guess I should talk to plh about this.
hsivonen volunteers
MikeSmith: plh asked me to point
out the open issue about Role
... We talked about it this morning. Similar potential need to have a role registry
... plh isn't sure xpointer way is the right way to go, but wanted us to be aware that it exists
anne: I think we should do role more centralized, because it affects implementations directly.
hsivonen: In last meeting I asked EPUB to ask PF to set aside some tokens for them once getting commitments from AT vendors that they will support these roles
mjs: Other things in HTML5 might
benefit from this
... e.g. <meta> names
... There was a third thing
Julian: canvas context?
mjs: Seems more like role, in that it has implementation implications and should therefore be centralized
hsivonen: Yes. for role, e.g. you
need coordination among AT vendors and browsers etc.
... Not good to have a registry. Rare to make a new role.
... PF should be able to set that aside without a formal process.
anne: Other one is meta
http-equiv, which has a different namespace than meta
name
... And canvas context, you do sorta need a place that says which are the contexts and which are compatible with which.
... Currently all are incompatbile, so not an issue now, but might change.
hsivonen: New canvas context is even rare
r
?: Still need a list of them
??: No, could just be defined by the specs that define them
hsivonen: I don't see this as being a problem right now.
<kennyluck> s/??/mjs/
hsivonen: There are three canvas contexts in the world, and one is proprietary
anne: we're removing them, 'cuz
features have been added to 2d
... Might want a variant of WebGL that is compatible with 2D
... But still it's very limited
mjs: There's probably only a single-digit number of these, and should all go through HTMLWG anyways
fantasai: For link relations,
seems like the idea is to have a provisional xpointer
registry
... What about if someone wants to port a provisionally registered link rel to IANA, for more general use?
discussion
hsivonen: Dont't think we want to hijack Atom registrations
Julian: If we decide not to go with IANA registry, need to decide whether we want to continue with registration of HTML5 link relations in IANA
mjs: I think registering HTML5
link rels in IANA is unrelated to progress of HTML5
... It's not a requirement for us. It just makes the IANA registry more complete.
mjs expresses that he doesn't care whether MikeSmith finishes the registration since it's not required for HTML5
MikeSmith: It's not a lot of work, think it makes sense to finish offf.
mjs: what about the ones where the designated experts require changes to the definitions
MikeSmith: filed issues on that
mjs: For us, the importance of a registry is as an extension point.
sicking: Seems to me that the
best caretakers of the link registry so far has been the
microformats people
... So I want whatever solution we choose here to work for them.
mjs: Idea of using page on
microformats wiki was proposed, but nobody's written up a
change proposal for that either.
... Anyone want to volunteer to write that up?
sicking: Ok, I'll do it.
mjs: So post to the mailing list
and say how long it will take you?
... I think we should make an exception here, because we have new information that will help us make a better decision
Julian: Microformats.org is not a new idea
sicking: New information is our experience with IANA
Julian: Half have gone through. A
number are held on bugs being fixed in HTML
... Then we have to review the updated spec.
mjs: If the spec isn't updated, what happense?
Julian: We'd probably accept the registration anyway.
mjs: So why is the registration being held up?
Julian: If the description is updated at HTMl5, then the IANA registration would have to be updated multiple times.
hsivonen: Why is updating IANA registry multiple times a problem?
Julian: I don't think it makes a big difference either way
fantasai: Then I suggest you ask the IANA registers to finish the registration for any link relations that will be registered with the current text, and then update the registry when the problems they've pointed out have been addressed with updated text.
<scribe> ACTION: Julian to Ask the IANA designated experts if this would be an acceptable model [recorded in]
<Julian>
ISSUE-127
Julian: ... Means in theory the semantic of the link relation can change depending on whether it's on <link> or <a>
<MikeSmith> trackbot, associate this channel with #html-wg
<trackbot> Sorry... I don't know anything about this channel
<trackbot> If you want to associate this channel with an existing Tracker, please say 'trackbot, associate this channel with #channel' (where #channel is the name of default channel for the group)
<MikeSmith> issue-127
<MikeSmith> issue-127?
<trackbot> Sorry... I don't know anything about this channel
Julian: I think the link relation
should be defined the same for both, and the usage affect
details like scope
... I think the section should be revised to not imply that rel values on <link> and <a> could be substantially different
... The IANA registry has an extension point so that each registration can have multiple columns
<MikeSmith> issue-127?
<trackbot> Sorry... I don't know anything about this channel
<kennyluck> trackbot, associate this channel with #html-wg
<trackbot> Associating this channel with #html-wg...
Julian: That was requested by Ian
<MikeSmith> issue-127?
<trackbot> ISSUE-127 -- Simplify characterization of link types -- raised
<trackbot>
Julian: E.g. to have a column that says whether the linked resource is required to be loaded, or just informational relation
<MikeSmith> ACTION: Julian to Ask the IANA designated experts if this would be an acceptable model [recorded in]
<trackbot> Created ACTION-196 - Ask the IANA designated experts if this would be an acceptable model [on Julian Reschke - due 2010-11-12].
mjs: It seems that in practice the spec does what's requested, so it's more an editorial issue
Julian: This distinction applies
both to the spec and also to the registry
... I don't think having the distinction in the registry is a good idea.
... We don't seem to have any good cases for that.
... The observation is, we currently have a table in the spec that has columns for effect on <link> and effect on <a> and <area>
... In this table, both are exactly the same
... except for two values, which in one column it's listed they're not allowed
... And in these case there are bugs on whether that distinction is a good idea.
fantasai: Setting stylesheet on <a> doesn't make sense to me
mjs: 'stylesheet' and 'icon' would have no effect outside <a>, even if we add them
Julian: ...
... We'll have to make a decision on that no matter where we put the registry. Defining things such that it's possible for relations to have a different deifnition on different elements is a bad idea.
mjs: ok
<kennyluck> s/<a>/<link>/
<Julian>
Julian: This is about the 'up'
relation.
... Someone thought it would be nice to change the definition to allow repetition of 'up'
... to e.g. have 'up up' mean grandparent
mjs: That wouldn't work very well given the DOM api for rel, which lists unique tokens
fwiw, I agree this seems like an ill-fitted idea...
<Julian>
<anne> HTML5 says something different from HTML4?
<Julian> this is about navigational link relations that changed in HTML5, potentially changing existing content
hsivonen: fwiw, I think we should
get rid of the up up up thing.
... It won't be supported in UI very well anyway
Julian: The use case given was to
build a navigation tree in the UA
... But I think there are better ways to address that use case
hsivonen: When a browser user
experience team wants to implement something, and asks for
syntax for it, then we should conside rit.
... but at this point it just seems a theoretical idea
... So I would propose to just drop it
Julian: I'd like to ask the chairs to bundle the timing for these issues so they don't get too spread out
mjs: Could put them all
together
... have been staggering them so you don't have to write proposals all at once
meeting closed
RRSAgent: make minutes
RRSAgent: make logs public
<anne> scribe: anne
MJS: Lets make a testcase in this
session and submit it
... in the later half of this session
JS: I am willing to coming up
with a format for tests
... and write a harness
<mjs> ACTION: sicking to design a file format for describing tests, and to write a harness that will run the automated tests [recorded in]
<trackbot> Sorry, couldn't find user - sicking
<mjs> ACTION: Sicking to design a file format for describing tests, and to write a harness that will run the automated tests [recorded in]
<trackbot> Sorry, couldn't find user - Sicking
trackbot, this is HTML WG
<trackbot> Sorry, anne, I don't understand 'trackbot, this is HTML WG'. Please refer to for help
<dbaron> trackbot, status
<trackbot> This channel is not configured
KK: I can update the wiki
<MikeSmith> trackbot, associate this channel with #html-wg
<trackbot> Associating this channel with #html-wg...
<scribe> ACTION: kris to update the wiki [recorded in]
<trackbot> Created ACTION-199 - Update the wiki [on Kris Krueger - due 2010-11-12].
<scribe> ACTION: Sicking to design a file format for describing tests, and to write a harness that will run the automated tests [recorded in]
<trackbot> Sorry, couldn't find user - Sicking
<scribe> ACTION: jonas to design a file format for describing tests, and to write a harness that will run the automated tests [recorded in]
<trackbot> Sorry, couldn't find user - jonas
<sicking> gaah, i don't exist
<sicking> i irc, therefor i exist
KK: What about XSS issues?
PLH: I agree we cannot solve the
XSS issues
... My goal is that we do not set up services on these domains
... so there is no problem, effectively
AVK: as long as w3.org does not document.domain we are fine, otherwise it might be safer to use w3test.org
MJS: There might be a problem in the future; everything should be safe if we do not use a subdomain
JS: I have an idea for
non-automatible tests, but we can discuss that later
... The way I would like us to do new things is write tests in the new format if it is compatible with our features
MJS: We have a requirement for landing new features and we could require them to be written in the HTML format
AvK: We have used this format
successfully already
... e.g. for server-sent events and XMLHttpRequest
MJS: one thing we might need to
do is identify features in the specification which are not new
but still need tests
... there is an HTML4 test suite
AvK: I do not think we should start from that
[people agree]
HS: How does updating work?
JS: We will have to figure it out
HS: for html5lib WebKit first lands in WebKit, I land first in html5lib
[HS implements for Gecko]
SW: We are not opposed to change
AvK: I think if the test contributor is known the tests should just get in
JS: I do not agree, I think we should have a staging area
KK: I think so too
MJS: I think it makes more sense that the testing in browsers happens later and that tests should get automatically in
[scribe misses out on discussing Mozilla specifics]
KK: Basically you have a set of tests, and wait for them to be approved
MJS: What do you want the approver to actually do?
KK: cursory review
AB: I think it might be worth
having almost automatic approval process
... for tests that pass in multiple user agents
MJS: why does there need to be this approval step? it will happen in distributed form anyway
AB: to increase the level of quality
MJS: it does not seem to happen now
AvK: agreed
DB: I am not sure that a approval process is good for known contributors
MJS: It seems like a waste of
time of people to require people to manually run the tests in
every browser before it is approved
... there will also be cases that fail in all browsers
DB: it seems you want a staging
area because you want a known good set of tests
... an alternative approach is to ship a release, rather than delay on trunk
HS: not having a lot of process helped html5lib to move forward faster
MJS: with a release you know it does not get worse
KK: the idea of approved is that is done
AvK: so far that has not worked I think
MJS: I think you will always get more tests and with releases you know the delta and can review whether that is ok as you already know the previous release was ok
[something about multiple vendors contributing tests being awesome]
MJS: problematic tests can be removed from the release
<hsivonen> fantasai: Microsoft testa a lot of value combinations. Mozilla tests tricky edge cases.
<fantasai> fantasai: Different vendors take different approaches to testing, and thereby cover different aspects of the features.
<fantasai> fantasai: By putting them together you get a more comprehensive test suite
JS: if the release process does not work we can revise it
KK: i like to lock things done
DB: if browsers import the tests they will report the problems more quickly
KK: in the current model the test can be pulled right away
[mercurial haz magic]
JS: If I find something wrong should I fix the test and mail the list
KK: currently mail the list
... and open a bug
MJS: I think people who report the bug should be allowed to fix the test
AvK: you want to optimize for the case that is most common, and most common the bug reporter will be correct I think
DB: you should notify the person who wrote the test
JS: I am fine with attaching patches to bugs
<plh> --> Mercurial server
<dbaron> hg clone is an example of a test following the non-written guidelines
<dbaron> default-push = https://[USERNAME]@dvcs.w3.org/hg/html/
<dbaron> is a line that you'd want to add to .hg/hgrc after:
<dbaron> [paths]
<dbaron> default =
<hsivonen> let's make one of these:
<hsivonen> that is, we should have a tool like that for the W3C harness
<krisk> see
<hsivonen> I'm already annoyed by having to wrap stuff in test()
<hsivonen> so I can't do ok(false, "FAIL!"); in scripts that aren't supposed to run
<plh> ACTION: Kris to add reftest handling in the test harness [recorded in]
<trackbot> Created ACTION-200 - Add reftest handling in the test harness [on Kris Krueger - due 2010-11-12].
<krisk> uses a relative path
<hsivonen>
<hsivonen> you'll really want to use MQ
Media Queries ftw
<krisk>
<weinig> sicking:
<plh> a reftest:
<dbaron> trackbot, associate this channel with #html-wg
<trackbot> Associating this channel with #html-wg... | http://www.w3.org/2010/11/04-html-wg2-minutes.html | CC-MAIN-2018-17 | en | refinedweb |
What is inheritance and how do you use it in java, what are its basics and how to use super keyword while implementing inheritance
Class Inheritance
Before moving on to class inheritance in java let us review once again, what is Inheritance.
So as the general meaning of Inheritance suggest it is the phenomenon to get predefined properties from parent, which in OOP terms is parent class or base class and the child which takes in the property of that parent class or say base class or parent class is known as sub class. So, now let us see how Java takes on inheritance.
Let us consider the example of "Cars" the general properties of car is its transmission type, and topspeed. I am keeping this example short so that you could understand. And in the sub class I will classify them into various brand and car type. consider the following tree structure for the cars.
Cars(parent class/base class) |_____Sports |_____Sedan(sub class) |_____Hatchback
class Cars{ public String transmissionType; public int topSpeed; } public class Sedan extends Cars{ public void printProperties(){ System.out.println("transmissionType of Sedaan is :"+transmissionType); System.out.println("topSpeed of Sedaan is :"+topSpeed); } public static void main(String[] a){ Sedan i = new Sedan(); i.topSpeed = 200; i.transmissionType = "Manual"; i.printProperties(); } }
the output of following program is like this
transmissionType of Sedaan is :Manual topSpeed of Sedaan is :200
As you can see in this programming example that the sedan extends the cars, this means class Sedan is inheriting the properties of Cars class. As in the main method we see. I have created the object of class Sedan not Cars but I am using this object to set the properties of Car class. This is legal because Sedan is inheriting the class Cars and thus all the public properties and methods of class Cars will behave like properties of Sedan class too.
However you must note one thing that you can store refenence of sub-class object in parent type reference but you can never have parent type reference to subclass object. This way java provides you the power to organise things in the way you want. When we talk about Inheritance several factors comes into play. One to keep in mind is access modifiers of the properties.
You can never inherit any private properties of class. This will give error. and If you want to specifically refer to base class there is one thing you must remember is "super" keyword.
The super keyword refers to base class always, this can be used in two ways, one for refering fields and methods and one we have a super constructor which refers to the constructor of base class. for example consider follwoing program and please, pay special attention to the use of super.
class Cars{ public String transmissionType = "manual"; public int topSpeed = 100; Cars(){ System.out.println("inside base class constructor"); } public void printProperties(){ System.out.println("transmissionType of Car is :"+transmissionType); System.out.println("topSpeed of Car is :"+topSpeed); } } public class Sedan extends Cars{ public String transmissionType = "auto"; public int topSpeed = 200; public Sedan(){ super(); System.out.println("Inside sub class Constructor"); } public void printProperties(){ super.printProperties(); System.out.println("transmissionType of Sedaan is :"+transmissionType); System.out.println("topSpeed of Sedaan is :"+topSpeed); } public static void main(String[] a){ Sedan i = new Sedan(); i.printProperties(); } }
before discussing this program let me tell you the out put of this program
inside base class constructor Inside sub class Constructor transmissionType of Car is :manual topSpeed of Car is :100 transmissionType of Sedaan is :auto topSpeed of Sedaan is :200
This is same program with only few modification to show the working of super. If you have paid your attention to the program you'll see that Instead of setting the field values using the object I have pre defined them. And yet again in the base class as well as sub class the properties and method signature is exectly the same. So if now try to access using the object this will invoke the property of that class to which the object belong.
But if you want to tell the JVM that you want to call the method of base class you call the method using "super" as in super.printProperties(); // this will call the method from base class as out put displays.
and even if you want to work with with the constructors there is a super constructor available. which invoke tha super constructor. As you can see in the program when defining the Sedan constructor I have called super. However if even you won't call it the system calls it automatically. But in case you want to specifically mention it you must remember that you must mention it as first statement in the constructor.
You must be very clear in telling the compiler what you want to do. Java provide you lot of programming flexiblity along with the type safety of the program. | https://www.examsmyantra.com/article/35/java/class-inheritance-in-java-and-use-of-super-keyword | CC-MAIN-2018-17 | en | refinedweb |
Changes for version 0.00_11
- added support for IE-MA
Changes for version 0.00_10
- 4 in 27 states (14.8%) supported in Business::BR::IE
- added support for IE-AL
- "t/001_dot.t" now works for other Perls < 5.008
- _dot now deals with untrue's avoiding to do a computation which would throw a warning
- _flatten in Business::BR::Ids::Common renamed to _canon_i
- references to 'flatten' renamed to 'canon'
- test, flatten, parse, format, random in Business::BR::Ids renamed to test_id, flatten_id, parse_id, format_id, random_id: no more issues with clash with core 'format' and functions names are better: not so general and yet short
Changes for version 0.00_09
- new test script "t/014_ie_parse.t"
- parse_ie() in Business::BR:IE
- tests added for IE-AC (test, flatten, format, random)
- support for IE-AC (Acre)
- fixed a typo in Business::BR::Biz
- "t/007_ids_test.t" now includes testing IE
- pale additions to Business::BR::Ids docs
Changes for version 0.00_08
- 0.00_07 was not indexed by CPAN: maybe it was because of files that changed but didn't have their versions incremented
- the bug below was fixed by explicit "scalar" conversions
- a bug slipped when semantics of _dv_*() changed, allowing to reduce the code of random_*(). But then, instead of knowing only about scalar context, random_*() returned the check digits on list context (like in "print random_cnpj()"
Changes for version 0.00_07
- the IE functions were made case-insensitive ('MG' works the same as 'mg')
- added IE handling for PR state (test, flatten, format, random, and parse)
- introduced _flatten in Business::BR::Ids::Common, avoiding the redundant code of the various flatten_*() methods
- changed semantics of calling _dv_*() in scalar context - instead of returning a concatenation of the check digits, it returns a complete entity with check digits in (in IE-SP the check digits are the ninth and 12nd - so that the concatenation of check digits is good for nothing)
Changes for version 0.00_06
- added tests for Business::BR::IE
- added IE handling for SP state (test, flatten, format, and random)
Changes for version 0.00_05
- Deprecates Business::BR::Biz (waiting for the move of its content somewhere else)
- README file revised
- first revision to POD in Business::BR::CNPJ
- new test "t/009_cnpj_rand.t"
- random_cnpj() in Business::BR::CNPJ
- test scripts renamed (eg. "t/dot.t" to "t/001_dot.t")
- random() in Business::BR::Ids
- new test "t/008_cpf_rand.t"
- random_cpf() in Business::BR::CPF
- introduced flatten() and parse() to Business::BR::Ids with a small refactoring avoiding redundant code
- fixed synopsis of Business::BR::Ids
- test for _dot() with @a < @b now works for $] < 5.8
- fixed broken links at Business::BR, I hope
Changes for version 0.00_04
- I thought about letting MakeMaker generate META.yml automatically again - but it does not generate the 'author' and 'licence' keys which CPAN uses - so I insist on that
- distribution renamed to Business-BR-Ids reflecting the orientation of this set of files to deal with identification codes (CPF, CNPJ for now)
- added test "t/ids_test.t"
- added Business::BR::Ids as a generic entry point for dealing with Brazilian identification entities
Changes for version 0.00_03
- tests "t/*_cpf.t" renamed to "t/cpf_*.t"
- added new module Business::BR::CNPJ but POD is not finished and tests aren't provided (except for a partial "t/cnpj_test.t")
- the heart of the distribution goes to Business::BR::Biz
- "_dot" goes to Business::BR::Biz::Common
- the ABSTRACT fix of the previous version was not enough for correct CPAN display - now using a META.yml with 'abstract' key
- Adam Kennedy pointed that the general CPAN convention for naming distributions would suggest Business-BR instead of biz-br: I would like to stick to this distribution name to mean a partial bundle of Business::BR::* modules I will be authoring
Changes for version 0.00_02
- fixed the missing ABSTRACT
- added flatten_cpf(), format_cpf(), parse_cpf() to Business::BR::CPF
- added corresponding tests
Changes for version 0.00_01
- Business::BR::CPF provides test_cpf()
- submitted to CPAN
Modules
- Business::BR - Root for namespace of Brazilian business-related modules
- Business::BR::Biz - DEPRECATED (was: Modules for Brazilian business-related subjects)
- Business::BR::CNPJ - Perl module to test for correct CNPJ numbers
- Business::BR::CPF - Perl module to test for correct CPF numbers
- Business::BR::IE - Perl module to test for correct IE numbers
- Business::BR::Ids - Modules for dealing with Brazilian identification codes (CPF, CNPJ, ...)
- Business::BR::Ids::Common - Common code used in Business-BR-Ids modules | https://metacpan.org/release/FERREIRA/Business-BR-Ids-0.00_11 | CC-MAIN-2018-17 | en | refinedweb |
/* * ipdsock.h * * IP Datagram: ipdsock.h,v $ * Revision 1.11 2005/11/25 03:43:47 csoutheren * Fixed function argument comments to be compatible with Doxygen * * 2001/05/22 12:49:32 robertj * Did some seriously wierd rewrite of platform headers to eliminate the * stupid GNU compiler warning about braces not matching. * * Revision 1.6 1999/03/09 02:59:49 robertj * Changed comments to doc++ compatible documentation. * * Revision 1.5 1999/02/16 08:12:00 robertj * MSVC 6.0 compatibility changes. * * Revision 1.4 1998/11/14 06:28:09 robertj * Fixed error in documentation * * Revision 1.3 1998/09/23 06:20:43 robertj * Added open source copyright license. * * Revision 1.2 1996/09/14 13:09:20 robertj * Major upgrade: * rearranged sockets to help support IPX. * added indirect channel class and moved all protocols to descend from it, * separating the protocol from the low level byte transport. * * Revision 1.1 1996/05/15 21:11:16 robertj * Initial revision * */ #ifndef _PIPDATAGRAMSOCKET #define _PIPDATAGRAMSOCKET #ifdef P_USE_PRAGMA #pragma interface #endif /** Internet Protocol Datagram Socket class. */ 00080 class PIPDatagramSocket : public PIPSocket { PCLASSINFO(PIPDatagramSocket, PIPSocket); protected: /**Create a TCP/IP protocol socket channel. If a remote machine address or a "listening" socket is specified then the channel is also opened. */ PIPDatagramSocket(); public: // New functions for class /**Read a datagram from a remote computer. @return TRUE if any bytes were sucessfully read. */ virtual BOOL ReadFrom( void * buf, ///< Data to be written as URGENT TCP data. PINDEX len, ///< Number of bytes pointed to by #buf#. Address & addr, ///< Address from which the datagram was received. WORD & port ///< Port from which the datagram was received. ); /**Write a datagram to a remote computer. @return TRUE if all the bytes were sucessfully written. */ virtual BOOL WriteTo( const void * buf, ///< Data to be written as URGENT TCP data. PINDEX len, ///< Number of bytes pointed to by #buf#. const Address & addr, ///< Address to which the datagram is sent. WORD port ///< Port to which the datagram is sent. ); // Include platform dependent part of class #ifdef _WIN32 #include "msos/ptlib/ipdsock.h" #else #include "unix/ptlib/ipdsock.h" #endif }; #endif // End Of File /////////////////////////////////////////////////////////////// | http://pwlib.sourcearchive.com/documentation/1.10.3-0ubuntu1/ipdsock_8h-source.html | CC-MAIN-2018-17 | en | refinedweb |
DLL Hijacking: The Code
DLL Hijacking: The Code
Continuing a look at DLL hijacking, we'll turn to the code, with a simple example written with GCC on Kali Linux.
Join the DZone community and get the full member experience.Join For Free
Learn more about how to Prevent Slow or Broken APIs From Affecting Your Bottom Line.
In my previous article on DLL Hijacking, I abstractly discussed how exactly DLL hijacking works, on different operating systems and development frameworks, and ways you can protect your code from this exploit. Today I’m going to show you some code. This is heavily based on the dlopen man page, feel free to reference.
This is written on Kali Linux, using GCC and make. I have a simple makefile, a driving program that side-loads a library, and two different libraries. We’ll build all of these with a manual copy step where you actually hijack the DLL. So first. let’s look at the makefile:
all: main libs main: gcc -rdynamic -ldl -o main main.c libs: goodlib badlib goodlib: gcc -Wall -fPIC -c printer.c gcc -shared -Wl,-soname,libprtr.so.1 -o libprtr.so.1.0 printer.o badlib: gcc -Wall -fPIC -c bad_printer.c gcc -shared -Wl,-soname,libbadprtr.so.1 -o libbadprtr.so.1.0 bad_printer.o clean: rm *.o rm lib*
This is a pretty straightforward makefile. We define a couple of targets, the all target, which has dependencies on main and libs. The main target builds the main driver, and the libs target has a dependency on goodlib and badlib, which build the good library and the hijacking library respectively. We wrap up this makefile fun with a clean target, ‘cause we’re OCD like that.
So let’s look at the main program first:
#include <dlfcn.h> #include <stdio.h> #define OK 0 #define FAIL 1 #define LIBNAME "./libprtr.so.1.0" #define FUNAME "print" int main(int argc, char *argv[]) { void *handle = NULL; void (*printer)(void) = NULL; int result = 0; handle = dlopen(LIBNAME, RTLD_LAZY); if (handle == NULL) { printf("Error opening library: %s\n", dlerror()); return FAIL; } *(void **) (&printer) = dlsym(handle, FUNAME); if (printer == NULL) { printf("Error opening function: %s\n", dlerror()); return FAIL; } (*printer)(); if (dlclose(handle)) { printf("Error closing library: %s\n", dlerror()); return FAIL; } return OK; }
Here, we’re loading a specific SO file, one we’re building and distributing side-by-side with this nifty application. Which prints stuff. But the printing function is in the library we distribute because we’re likely to change the printed message based on the nearest holiday (we are such great planners!). Basically, we load the library via dlopen(.), then grab the function pointer from the library via dlsym(.), print the message from the library function, then close the library with dlclose(.). Then we exit the program.
The libraries are as complex as you’d think, filled with functionality for printing a single message:
#include <stdio.h> void print(void) { printf("do some stuff.\n"); }
...and our evil, hijacking library:
#include <stdio.h> void do_other_stuff(void) { printf("do lots of other stuff.\n"); } void print(void) { do_other_stuff(); printf("do some stuff.\n"); }
Note the hook into do_other_stuff(.) in the hijacking library, where we execute our nefarious evilness.
Now, we have looked through all the code. Let’s build and run.
samhain@durga:~/Work/loading# make gcc -Wall -fPIC -c printer.c gcc -shared -Wl,-soname,libprtr.so.1 -o libprtr.so.1.0 printer.o gcc -Wall -fPIC -c bad_printer.c gcc -shared -Wl,-soname,libbadprtr.so.1 -o libbadprtr.so.1.0 bad_printer.o samhain@durga:~/Work/loading# ./main do some stuff.
We’ve run our application, which has done some stuff on our behalf. Excellent! That’s why this app was so highly rated. Now, say, we navigate our browser to some of the more shady sites on the internet, and at one of them, we inadvertently download a new library (feel free to copy libbadprtr.so.1.0 over libprtr.so.1.0 instead of going to those dark corners of the internet yourself).
The next time we run our printing app, we see this:
samhain@durga:~/Work/loading# ./main do lots of other stuff. do some stuff.
Oh noes. We have been hacked!
So you see, as long as the new DLL has the appropriate entry points defined, applications are happy to load the library and execute the named function. So how to get around this? Well, first, look at the size of the library:
samhain@durga:~/Work/loading# ls -al lib* -rwxr-xr-x 1 root root 4792 Jan 1 09:56 libbadprtr.so.1.0 -rwxr-xr-x 1 root root 4580 Jan 1 09:56 libprtr.so.1.0
You’ll notice libbadprtr.so is noticeably larger than libprtr.so. Let’s take a look at the hashes of the files. We’ll whip up a quick python script to extract the sha256 hashes:
import hashlib as h GOOD_FILENAME = 'libprtr.so.1.0' BAD_FILENAME = 'libbadprtr.so.1.0' def extract_signature(file): file_r = file.read() hash = h.sha256(file_r) print hash.hexdigest() with open(GOOD_FILENAME, 'rb') as file: print 'Processing good file (%s):' % GOOD_FILENAME extract_signature(file) with open(BAD_FILENAME, 'rb') as file: print 'Processing bad file (%s):' % BAD_FILENAME extract_signature(file)
Which gives us, when run:
samhain@durga:~/Work/loading# python hasher.py Processing good file (libprtr.so.1.0): 933ada85c40c1a1897f2f15448f1410597c0ac60ca3b9c702e1d74227fa91984 Processing bad file (libbadprtr.so.1.0): 88143a87fa810d81e636d0a659cfb85887bfda0b70ebada9cd1c5d107fd205a1
The hashes are remarkably different as well, as you’d expect. But why the file size? Isn’t the hash enough? Well, yes, for sha2 series hashes, you’re probably okay using just the hash. In the past, though, malicious actors have been able to generate hash collisions in MD5, for example, but measuring the expected file size can give you an additional data point to use to determine the authenticity of a library. Quick and easy, using a combination of hashes and file sizes can give you a remarkable amount of protection against DLL hijacking.
Learn about the Five Steps to API Monitoring Success with Runscope
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/dll-hijacking-the-code | CC-MAIN-2018-17 | en | refinedweb |
mod cluster plugin for load balancer factorRocky T Oct 8, 2017 12:21 AM
Hi All,
As i understand mod cluster offers ability to create plug in for load balancing mechanism specific to any application. Can anyone let me know how can i start creating plug in or any documentation available to assist in creating plugin and using the same?
It will be really helpful.
Thanks,
Rocky
1. Re: mod cluster plugin for load balancer factorBrian Stansberry Oct 11, 2017 4:30 PM (in response to Rocky T)
How to wire a custom metric into WildFly is described in the "add-custom-metric / remove-custom-metric" section in mod_cluster Subsystem - WildFly 10 - Project Documentation Editor
The custom metric must implement the org.jboss.modcluster.load.metric.LoadMetric interface in a public class with a public no-arg constructor. It can expose configuration properties, a la what's shown in the doc I linked above. Your LoadMetric impl must expose a public setter for each property. Each configured property, along with the setWeight and setCapacity methods will be invoked before the system makes the first call to getLoad. The org.jboss.modcluster.container.Engine that gets passed to your getLoad(Engine) implementation gives you access to environmental information you may want to use in your calculation. You can also use standard JVM stuff like platform mbeans.
2. Re: mod cluster plugin for load balancer factorRocky T Oct 11, 2017 7:09 PM (in response to Brian Stansberry)
Thanks for your response Brian, its really helpful. One more query-
You mentioned about configuration properties in your response. I see below sample in the link you provided, what could be these property names and values?
custom-load-metric
<property name=
"pro1"
value=
"value1"
/>
<property name=
"pro2"
value=
"value2"
/>
</custom-load-metric>
I apologies if its too basic, i am new to this custom metric pluggin creation, so trying to understand.
3. Re: mod cluster plugin for load balancer factorMichal Karm Babacek Oct 12, 2017 2:13 AM (in response to Rocky T)
Hi Rocky, simply follow the example code, it is fairly easy:
GitHub - Karm/mod_cluster-custom-load-metric: A simple custom load metric for mod_cluster, merely for testing purposes. … | https://developer.jboss.org/thread/276215 | CC-MAIN-2018-17 | en | refinedweb |
So, due to my last question,, I am becoming acquainted with the vector template. However, I clearly am not using the commands correctly. Below is a section of code which, eventually, leads to a segmentation fault later in the program.
First an introduction of the variables:
using namespace std; int dimensions[]; //the neurons are on a grid of size dimensions[0] X dimensions[1] int k; //incremented each time an element in connections is assigned an address. vector<neuron*> connection; //a container of pointers to neurons, so my individual neuron knows who it's neighbours are
int k=0; for (int ii=0;ii<dimensions[0];ii++) { for (int jj=0;jj<dimensions[1];jj++) { if (!(ii==i && jj==j)) { double dist = distance(ii,jj,i,j); if (dist>0 && iflucky(p[(int) ceil(dist)])) { mexPrintf("Adding pointer to (%i,%i): %p\n",ii,jj,&(slot(ii,jj))); connections[k++]=&(slot(ii,jj)); } } } } mexPrintf("Listing connections:\nk: %i\n",k); mexPrintf("Before resize:\n length: %i\n",connections.size()); for (int i=0;i<k;i++) { mexPrintf("connections[%i]: %p\n",i,connections[i]); } connections.resize(k); mexPrintf("After resize:\n length: %i\n",connections.size()); for (int i=0;i<k;i++) { mexPrintf("connections[%i]: %p\n",i,connections[i]); }
"mexPrintf()" is a printing funciton necessary to run the code through matlab (at least if I want it to print). It works exactly like printf();
As usual, the output it quite long and repetitive. However, an example of a repetition in which the code "malfunctions":
Adding pointer to (1,1): 053D11F0 Adding pointer to (1,3): 053D13A8 Adding pointer to (3,2): 053D1324 Listing connections: k: 3 Before resize: length: 1 connections[0]: 053D11F0 connections[1]: 053D13A8 connections[2]: 053D1324 After resize: length: 3 connections[0]: 053D11F0 connections[1]: 00000000 connections[2]: 00000000
So, what is puzzling me here is how the length can be shorther than the amount of elements in the vector? I thought it was supposed to resize automatically? I can see that lengthening the vector would make it delete what was there before. the resize command is there to make sure I don't carry around very long vectors of zeros. my networks will eventually become very large, and the average number of connections will be much shorter than the possible maximum, so it is an important concern. Also, no matter what, my neuron needs to know when it has spoken to all its neighbours.
a lecture is very welcome =)
(and yes, I did do an extensive search of vector-related threads before writing this, but no one seemed to have had my exact problem). | https://www.daniweb.com/programming/software-development/threads/303930/vector-resize-changes-content | CC-MAIN-2018-17 | en | refinedweb |
Content-type: text/html
cc [ flag... ] file... -lidnkit [ library... ] #include <idn/api.h> idn_result_t idn_decodename(int actions, const char *from, char *to, size_t tolen);
idn_result_t idn_decodename2(int actions, const char *from, char *to, size_t tolen, const char *auxencoding);
idn_result_t idn_encodename(int actions, const char *from, char *to, size_t tolen);
void idn_enable(int on_off);
idn_result_t idn_nameinit(int load_file);
The idn_nameinit() function initializes the library. It also sets default configuration if load_file is 0, otherwise it tries to read a configuration file. If idn_nameinit() is called more than once, the library initialization will take place only at the first call while the actual configuration procedure will occur at every call.
If there are no errors, idn_nameinit() returns idn_success. Otherwise, the returned value indicates the cause of the error. See the section RETURN VALUES below for the error codes.
It is usually not necessary to call this function explicitly because it is implicitly called when idn_encodename(), idn_decodename(), or idn_decodename2() is first called without prior calling of idn_nameinit().
The idn_encodename() function performs name preparation and encoding conversion on the internationalized domain name specified by from, and stores the result to to, whose length is specified by tolen. The actions argument is a bitwise-OR of the following macros, specifying which subprocesses in the encoding process are to be employed.
IDN_LOCALCONV
IDN_DELIMMAP
IDN_LOCALMAP
IDN_NAMEPREP
IDN_UNASCHECK
IDN_ASCCHECK
IDN_IDNCONV
IDN_LENCHECK
Details of this encoding process can be found in the section Name Encoding
For convenience, also IDN_ENCODE_QUERY, IDN_ENCODE_APP, and IDN_ENCODE_STORED macros are provided. IDN_ENCODE_QUERY is used to encode a ``query string'' (see the IDNA specification). It is equal to:
(IDN_LOCALCONV | IDN_DELIMMAP | IDN_LOCALMAP | IDN_NAMEPREP | IDN_IDNCONV | IDN_LENCHECK)
IDN_ENCODE_APP is used for ordinary application to encode a domain name. It performs IDN_ASCCHECK in addition with IDN_ENCODE_QUERY. IDN_ENCODE_STORED is used to encode a ``stored string'' (see the IDNA specification). It performs IDN_ENCODE_APP plus IDN_UNASCHECK.
The idn_decodename() function performs the reverse of idn_encodename(). It converts the internationalized domain name given by from, which is represented in a special encoding called ACE (ASCII Compatible Encoding), to the application's local codeset and stores in to, whose length is specified by tolen. As in idn_encodename(), actions is a bitwise-OR of the following macros.
IDN_DELIMMAP
IDN_NAMEPREP
IDN_UNASCHECK
IDN_IDNCONV
IDN_RTCHECK
IDN_ASCCHECK
IDN_LOCALCONV
Details of this decoding process can be found in the section Name Decoding.
For convenience, IDN_DECODE_QUERY, IDN_DECODE_APP, and IDN_DECODE_STORED macros are also provided. IDN_DECODE_QUERY is used to decode a ``query string'' (see the IDNA specification). It is equal to
(IDN_DELIMMAP | IDN_NAMEPREP | IDN_IDNCONV | IDN_RTCHECK | IDN_LOCALCONV)
IDN_DECODE_APP is used for ordinary application to decode a domain name. It performs IDN_ASCCHECK in addition to IDN_DECODE_QUERY. IDN_DECODE_STORED is used to decode a ``stored string'' (see the IDNA specification). It performs IDN_DECODE_APP plus IDN_UNASCHECK.
The idn_decodename2() function provides the same functionality as idn_decodename() except that character encoding of from is supposed to be auxencoding. If IDN encoding is Punycode and auxencoding is ISO8859-2, for example, it is assumed that the Punycode string stored in from is written in ISO8859-2.
In the IDN decode procedure, IDN_NAMEPREP is done before IDN_IDNCONV, and some non-ASCII characters are converted to ASCII characters as the result of IDN_NAMEPREP. Therefore, ACE string specified by from might contains those non-ASCII characters. That is the reason docode_name2() exists.
All of thsee functions return an error value of type idn_result_t. All values other than idn_success indicates some kind of failure.
Name encoding is a process that transforms the specified internationalized domain name to a certain string suitable for name resolution. For each label in a given domain name, the encoding processor performs:
Convert the encoding of the given domain name from application's local encoding (for example, ISO8859-1) to UTF-8.
Map domain name delimiters to `.' (U+002E). The reco- ginzed delimiters are: U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 (halfwidth ideographic full stop).
Apply character mapping whose rule is determined by the top-level domain name.
Perform name preparation (NAMEPREP), which is a standard process for name canonicalizaion of internationalized domain names.
NAMEPREP consists of 5 steps: mapping, normalization, prohibited character check, bidirectional text check, and unassigned codepoint check. The first four steps are done by IDN_NAMEPREP, and the last step is done by IDN_UNASCHECK.
Checks if the domain name contains non-LDH ASCII characters (not letter, digit, or hyphen characters), or it begins or end with hyphen.
Convert the NAMEPREPed name to a special encoding designed for representing internationalized domain names.
The encoding is known as ACE (ASCII Compatible Encoding) since a string in the encoding is just like a traditional ASCII domain name consisting of only letters, digits and hyphens.
For each label, check the number of characters in it. It must be in the range of 1 to 63.
Name decoding is a reverse process of the name encoding. It transforms the specified internationalized domain name in a special encoding suitable for name resolution to the normal name string in the application's current codeset. However, name encoding and name decoding are not symmetric.
For each label in a given domain name, the decoding processor performs:
Map domain name delimiters to `.' (U+002E). The recoginzed delimiters are: U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 (halfwidth ideographic full stop).
Perform name preparation (NAMEPREP), which is a standard process for name canonicalizaion of internationalized domain names.
Convert the encoding of the given domain name from ACE to UTF-8.
Encode the result of (3) using the Name Encoding scheme, and then compare it with the result of the step (2). If they are different, the check is failed. If IDN_UNASCHECK, IDN_ASCCHECK or both are specified, they are also done in the encoding processes.
Convert the result of (3) from UTF-8 to the application's local encoding (for example, ISO8859-1).
If prohibited character check, unassigned codepoint check or bidirectional text check at step (2) failed, or if round trip check at step (4) failed, the original input label is returned.
If your application should always disable internationalized domain name support for some reason, call
(void) idn_enable(0);
before performing encoding/decoding. Afterward, you can enable the support by calling
(void) idn_enable(1);
These functions return values of type idn_result_t to indicate the status of the call. The following is a complete list of the status codes.
Example 1 Get the address of an internationalized domain name.
To get the address of an internationalized domain name in the application's local codeset, use idn_encodename() to convert the name to the format suitable for passing to resolver functions.
#include <idn/api.h> #include <sys/socket.h> #include <netdb.h> ... idn_result_t r; char ace_name[256]; struct hostent *hp; int error_num; ... r = idn_encodename(IDN_ENCODE_APP, name, ace_name, sizeof(ace_name)); if (r != idn_success) { fprintf(stderr, gettext("idn_encodename failed.\n")); exit(1); } hp = getipnodebyname(ace_name, AF_INET6, AI_DEFAULT, &error_num); ...
Example 2 Decode the internationalized domain name.
To decode the internationalized domain name returned from a resolver function, use idn_decodename().
#include <idn/api.h> #include <sys/socket.h> #include <netdb.h> ... idn_result_t r; char local_name[256]; struct hostent *hp; int error_num; ... hp = getipnodebyname(name, AF_INET, AI_DEFAULT, &error_num); if (hp != (struct hostent *)NULL) { r = idn_decodename(IDN_DECODE_APP, hp->h_name, local_name, sizeof(local_name)); if (r != idn_success) { fprintf(stderr, gettext("idn_decodename failed.\n")); exit(1); } printf(gettext("name: %s\n"), local_name); } ...
See attributes(5) for descriptions of the following attributes:
intro(3), libidnkit(3LIB), setlocale(3C), hosts(4), attributes(5), environ(5)
RFC 3490
RFC 3491
RFC 3492
RFC 3454
RFC 952
RFC 921
STD 3, RFC 1122
STD 3, RFC 1123
Unicode Standard Annex #15: Unicode Normalization Forms, Version 3.2.0.
International Language Environments Guide (for this version of Solaris).
The idn_nameinit() function checks internal system configuration files such as /etc/idn/idn.conf and /etc/idn/idnalias.conf if they are in the proper access mode and owership. If they are not in the proper access mode or ownership, the function will not read and use the configurations defined in the files but use default values. In this case the function will also issue a warning message such as:
idn_nameinit: warning: config file (/etc/idn/idn.conf) not in proper access mode or ownership - the file ignored.
The proper access mode and the ownership are described in the package prototype file of SUNWidnl. It is also recommended not to change the system configuration files. | http://backdrift.org/man/SunOS-5.10/man3ext/idn_encodename.3ext.html | CC-MAIN-2016-50 | en | refinedweb |
Postgres Tricks in .NET
I don't hide the fact the PostgreSQL is my favourite database, and where possible I try to use it in as many places as possible (and on as many projects as possible).
There are a lot of reasons why I do this, and that's simply because of some of the clever things that you can do with PG.
In this post, I'm going to introduce you to a couple of them, and show you how to get direct access to PG by using its native ADO.NET connector.
There is a chance that you can make some of these tricks work by using raw queries in Entity Framework, NHibernate, and other ORMs, but for this post I'll be ignoring those and concentrating simply on doing this in raw C#.
To try the examples, you will need to install a current version of the PostgreSQL database and its admin tool, "PgAdmin3". Going through that process in this post would take too long, but in most cases it's simply a case of running a standard Windows installer that can be downloaded through this link.
Once you have Postgres up and running, fire up Visual Studio, create yourself a simple command line program, and use NuGet to search for and install "NpgSql"
Native Database Arrays
The first thing we're going to look at is native arrays.
Postgres fully supports arrays as column types. This means that, when you create a table in the database, you can use an array-like syntax (the same as in .NET to define an array type column).
If you've installed Postgres correctly, you should have an application called "Pgadmin". Find and run the tool, and then either find or create a database to experiment in (if you need a new one, you can right-click your server and choose 'New Database').
In my case, I've created a database called 'playground':
Figure 1: The Postgres test database
I'm not going to go into the process of creating/setting up a database because there's not enough space in this post to do so. However, once you have a database to use, you then need to execute the following SQL in it, to create a test table for the array example:
CREATE TABLE blogarray ( pkid serial NOT NULL, intarray integer[], textarray text[], CONSTRAINT blogarray_pkey PRIMARY KEY (pkid) ) WITH ( OIDS=FALSE );
This will create a table in your database that has an auto increment primary key, and two array columns: one that holds an array of integers and one that holds an array of strings.
If you now add the following code to your Program.cs file in your Visual Studio console app project:
using System; using System.Linq; using Npgsql; using NpgsqlTypes; namespace npgsql { class Program { private const string SERVER = "MyServer"; private const string DATABASE = "MyDatabase"; private const string USER = "myUser"; private const string PASSWORD = "myPassword"; static string GetConnectionString() { var csb = new NpgsqlConnectionStringBuilder { Host = SERVER, Database = DATABASE, UserName = USER, Password = PASSWORD }; return csb.ConnectionString; } static string GenerateRandomString() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); var result = new string( Enumerable.Repeat(chars, 8) .Select(s => s[random.Next(s.Length)]) .ToArray()); return result; } static int[] GetRandomInts() { Random random = new Random(); int[] results = new int[10]; for (int count = 0; count < 10; count++) { results[count] = random.Next(0, 1000); } return results; } static string[] GetRandomStrings() { string[] results = new string[10]; for (int count = 0; count < 10; count++) { results[count] = GenerateRandomString(); } return results; } static void ArrayTest() { using(NpgsqlConnection connection = new NpgsqlConnection(GetConnectionString())) { connection.Open(); string sql = "insert into blogarray(intarray, textarray) values(:intparam , :textparam)"; using(NpgsqlCommand command = new NpgsqlCommand(sql, connection)) { command.Parameters.Add(new NpgsqlParameter("intparam", NpgsqlDbType.Array | NpgsqlDbType.Integer)); command.Parameters.Add(new NpgsqlParameter("textparam", NpgsqlDbType.Array | NpgsqlDbType.Text)); command.Parameters[0].Value = GetRandomInts(); command.Parameters[1].Value = GetRandomStrings(); command.ExecuteNonQuery(); } connection.Close(); } } static void Main() { ArrayTest(); } } }
and then compile and run it, you should see that your database is now populated with some array bound data:
Figure 2: Our data table showing array bound data
If you add some further code to read the data back:
static void ArrayReadTest() { using (NpgsqlConnection connection = new NpgsqlConnection(GetConnectionString())) { connection.Open(); string sql = "select * from blogarray"; using (NpgsqlCommand command = new NpgsqlCommand(sql, connection)) { using(NpgsqlDataReader reader = command.ExecuteReader()) { while(reader.Read()) { int[] intArray = (int[])reader[1]; string[] textArray = (string[])reader[2]; } } } connection.Close(); } }
and then run that, and stop on a break point, you'll see that you can read the array straight out of the database, and back into a normal .NET array without having to write any custom conversion code.
Figure 3: A breakpoint on the read code shows our array data read back from Postgres
In a similar way, you can use the new Json and Hstore types to handle document DB style data in a relational database. However, you have to handle both of these as regular single strings where the ADO.NET provider is concerned, and then do a quick conversion using something like JSON.NET.
Database Notifications
Another interesting trick that Postgres can do is to use its built-in Notification system.
For many years now, Postgres has had a very simple, but very effective pub/sub service built into it.
Switch to PG Admin (just as you did previously to create the table), in an SQL Window type:
listen mynotification
and execute it (press F5 if you're using PG Admin). At this point, you won't see anything other than a message that tells you the statement executed successfully. However, if you now enter the following:
notify mynotification
you should now see that Postgres signals into your result window that it received a notification on the channel you asked it to listen on.
Figure 4: PG Admin showing a notification
If you want to add some data to the notification, simply enclose it in single quotes after a comma:
notify mynotification, 'Hello Postgres'
and the notification also will send that:
Figure 5: PG Admin showing a notification, with data
You can send anything you like in the payload string, but only one single string can be sent. If you want to send multiple values, you need to encode the string as JSON or an array or something else you can deserialize.
You can use the pub/sub service inside .NET using NpgSql just by wrapping the preceding commands in a normal NonQuery SQL Command. There are, however, a couple of gotchas to be aware of.
First, Notifications come in two types: Asynchronous and Synchronous, The Async version has been available in NpgSql since before version 1, and relies on your .NET program calling Postgres functions at regular intervals before it will receive a notification request.
Because you need to make an API call before a request is passed to your application, you could un-intentionally introduce delays into your application's notification system without being aware. To counter this you, would frequently have to 'Poll' your NpgSql connection for notification events to be fired in a timely manner.
The Sync version works the same way, except that the notifications are delivered to your app automatically as soon as they are raised by Postgres. This is more reliable, and leads to fewer delays but, because of the way it works, you CANNOT call any other Postgres operation from within the notification handler, without first opening a new connection for that operation. Depending on what you're attempting to do, this may not be an issue, but it's highly recommended that, if you're using Sync notifications, you use the notification event handler only to set a flag and raise an event elsewhere in your application in reaction to that flag, if you wish to perform other Postgres related activities.
You set the notification mode you want to use in your connection string by setting 'SyncNotification' to false for Async mode and true for sync mode, if you're using the NpgSqlConnectionStringBuilder to build your connection string (as I did in the array example), you simply need to set 'SyncNotification' to either true or false, as required.
Making use of notifications in your .NET code is trivially easy. Add the following functions to your Program.cs alongside the code you created for the array test.
static void StartListening() { _notificationConnection = new NpgsqlConnection(GetConnectionString()); _notificationConnection.Open(); string sql = "listen mynotification"; using (NpgsqlCommand command = new NpgsqlCommand(sql, _notificationConnection)) { command.ExecuteNonQuery(); } _notificationConnection.Notification += PostgresNotification; } static void StopListening() { string sql = "unlisten mynotification"; _notificationConnection.Notification -= PostgresNotification; using (NpgsqlCommand command = new NpgsqlCommand(sql, _notificationConnection)) { command.ExecuteNonQuery(); } _notificationConnection.Close(); } static void PostgresNotification(object sender, NpgsqlNotificationEventArgs e) { Console.WriteLine("I are Notification -->"); Console.WriteLine(" DATA {0}", e.AdditionalInformation); Console.WriteLine(" CHANNEL {0}", e.Condition); Console.WriteLine(" PID {0}", e.PID); } static void TriggerNotification() { string sql = "notify mynotification, 'This is some extra data'"; using (NpgsqlCommand command = new NpgsqlCommand(sql, _notificationConnection)) { command.ExecuteNonQuery(); } }
Change your 'main' method to look like this
static void Main() { StartListening(); Console.ReadLine(); TriggerNotification(); Console.ReadLine(); TriggerNotification(); Console.ReadLine(); StopListening(); }
and, finally, update your 'GetConnectionString' method so it looks like the following:
static string GetConnectionString() { var csb = new NpgsqlConnectionStringBuilder { Host = SERVER, Database = DATABASE, UserName = USER, Password = PASSWORD, SyncNotification = true }; return csb.ConnectionString; }
If you now run your application, and press Return three times, you should get an output similar to what's shown in Figure 6:
Figure 6: Output produced by the Postgres notification test
As you can see, the first line is the notification payload, the second the notification name, and the third is the process ID of the responding background process.
Remember, too, you don't have to trigger these notifications from the same .NET program. You could, for example, trigger them from within a long-running stored procedure, that sends a percentage value back to the app. The app then use could that to update a progress indicator.
You can trigger multiple notifications, on different channels, and then be able to tell which channel triggered the notification by examining the channel name.
Program Originated Data
The final trick I'm going to show you (but by no means the last) is, as the header says, 'Program originated data.'
I can already hear the confusion at that statement, so I guess I better explain it before we go any further.
Postgres has the ability to execute an application of any description that's runnable by the server on which it's installed, and then feed any output produced by the program into a database table.
For example, if you had a command line program that generated 10 random integers for a given number of lines, you then could feed those 10 integers into 10 integer columns in a table in your database.
As it turns out, this can come in quite handy. In the past, for example, I've used this feature by writing a .NET command line program that consumes some strange data feed, and then print that feed to the console as a standard CSV, while using the program data facility to place the CSV data into a correctly formatted table schema.
Add the following method to your Program.cs file:
static void GenerateProgramData() { Random random = new Random(); for (int linecount = 0; linecount < 10; linecount++) { for (int numbercount = 0; numbercount < 10; numbercount++) { Console.Write("{0},", random.Next(0,1000)); } Console.WriteLine("LINE{0}", linecount); } }
followed by updating your main method to look like this:
static void Main() { GenerateProgramData(); }
If you run your program at this point, you should see something like the output in Figure 7:
Figure 7: Output from program data method
As you can see, all it simply does is generate 10 lines each containing 10 numbers and an item of text.
Using Pgadmin3, create a new table in your test database, using the following SQL:
CREATE TABLE public.programdata ( intone integer, inttwo integer, intthree integer, intfour integer, intfive integer, intsix integer, intseven integer, inteight integer, intnine integer, intten integer, linetext text ) WITH ( OIDS = FALSE );
Now, compile and build your console app; then, copy the exe to a folder your Postgres database is able to access. Because my server is on a different machine, a copied the console app across the network to a known location on the same machine that my copy of Postgres could see. For you, this might just be as simple as 'C:\' or even a temp folder. As long as your Postgres server can access that folder via its full folder path, everything will work fine.
Once you've copied the app, in your PgAdmin SQL window, execute the following statement:
copy programdata (intone, inttwo, intthree, intfour, intfive, intsix, intseven, inteight, intnine, intten, linetext) from program 'g:\npgsql.exe' csv
Remember to change the 'g:\npgsql.exe' part to point to the location you copied your application to.
If you look in the table you created using Pgadmin, you should see something that looks similar to the data in Figure 8:
Figure 8: The data from our program, added to our Postgres table
As you can see, the output from the program has been directly inserted into the table you created.
There is one thing you must be aware of, though. Using the copy from program command, you MUST be logged into your Postgres database as 'Postgres' (the Postgres account is the equivalent of 'sa' on a MS-SQL), if you're not, you will receive a security error telling you the operation is not permitted.
By using program data, for instance, you could easily write a small stub program that reads the server process table and inserts it into your database, which then can be easily queried, or, as previously mentioned, use it to pre-transform public data, or as we did above. Just use it for generating test data; the list is endless.
Postgres can do much more than the three things I've outlined here, and the NpgSql driver can support many of them directly. In particular, there are a lot of custom data types, designed to handle IP Addresses, Binary data, time and date ranges, and many others that are not available using things like Entity Framework and other ORMs.
Got a strange .NET problem you need to solve? Or a weird assembly you've discovered that you don't know what it does? Come and find me on the interwebs (I'm usually on twitter as @shawty_ds), and I'll see if I can do a post on it.
Until then, happy Postgressing!
Good Post!Posted by German Antognetti on 05/05/2016 12:40pm
Thanks for this example. I'm new with postgresql on c#. It was very usefull!.Reply
arithmetic functionPosted by Lynith on 10/01/2015 08:47pm
Sir Good Day! I have some question, im using postgresql too on my vb.net project with npgsql. my question is can i perform arithmetic operation inside SELECT query using npgsql command? the code would look like this "SELECT accnt_balance + :accntMoney FROM savings_account WHERE pin_code = :PIN_Code" Thank you for your response and more power.Reply | http://www.codeguru.com/columns/dotnet/postgres-tricks-in-.net.html | CC-MAIN-2016-50 | en | refinedweb |
Thanks for the fix - works for me on this afternoon's SVN.
-Eric
On Mon, Dec 15, 2008 at 1:27 AM, Eric Firing <efiring@...> wrote:
>
>
Darren Dale wrote:
>
> I think it would be worth stating in the docs that # $ % & ~ _ ^ \ { }
> \( \) \[ \] have special meaning in latex but not in regular mpl text,
> so buyer beware. It might be nice if mpl regular text rendered the
> escaped version of all these characters the same way latex does, that
> would make it easier to go from text to usetex.
For now, I'll just resolve the one straightforward bug (that \$ does not
work in regular text with usetex off), and document these special
characters as you suggest -- just so the fix will be in the next
0.98.6. I'm going to hold off on these other issues of compatibility
until they have clearer answers.
>
> Speaking of implicitly doing the right thing, last night I was in the
> middle of working through a difficult bug when Windows Vista *kicked
> me out without asking or issuing a warning*, installed updates, and
> rebooted. I'm still mumbling under my breath about it. Friggin jerks.
I feel your pain. I've been there.
Mike
--
Michael Droettboom
Science Software Branch
Operations and Engineering Division
Space Telescope Science Institute
Operated by AURA for NASA
John Hunter wrote:
> I think the src egg approach for os x is hopeless because too many
> people are having problems with architecture on png and zlib
> dependencies, and we don't have a lot of control over this because
> they are getting these dependencies from a variety of providers.
Maybe it's hopeless, but one solution is to try to standardize, in the
MacPython community, on using William Kyngesburye's UnixImageIO and
Freetype Frameworks for the dependencies:
They are Universal, Binary, and packaged as nice frameworks and also
with traditional unix-style layouts for building against.
> I
> think we need a binary installer, eg using bdist_mpkg, with the
> freetype, png and zlib dependencies built in, as we have on windows.
That's good route too, though it always feels a bit silly to have a
different copy of libpng inside MPL, and PIL,and wxPython, and ....
Why the heck Apple doesn't provide these really common libs is still
beyond@...
On Mon, Dec 15, 2008 at 7:15 AM, John Hunter <jdh2358@...> wrote:
> On Mon, Dec 15, 2008 at 8:52 AM, Michael Droettboom <mdroe@...> wrote:
<SNIP>
Hi,
> can provide you with ssh access to a decent OSX 10.5 box (Dual Xeon,
8GB) at the University of Washington at Seattle. Just ping me off list
and I can hook you up.
<SNIP>
Cheers,
Michael
On Sat, Dec 13, 2008 at 10:32 AM, John Hunter <jdh2358@...> wrote:
> On Sat, Dec 13, 2008 at 9:22 AM, Darren Dale <dsdale24@...> wrote:
>
> >> I haven't been able to get to the root of this problem, but an
> "svn-clean"
> >> in the doc directory always fixes it for me.
> >
> > I tried that but the problem persists. I have sphinx-0.4.2 installed, are
> > you using the same version?
>
>
(John suggested in a private email to try upgrading to sphinx-0.5.)
You're right, the error does not occur with sphinx-0.5. It looks like the
API for registering nodes has changed as of 0.5. The development branch of
sphinx was throwing errors when it got to latex, so I had a look and came up
with some changes that work with both version 0.5 and the development
branch. The changes are not compatible with sphinx-0.4.2, but it looks like
we are requiring version 0.5 or later now anyway. If this is the case, I'll
go ahead and commit the changes. Here is the diff, please let me know if I
should commit or if I should hold off:
$ svn diff sphinxext/
Index: sphinxext/inheritance_diagram.py
===================================================================
--- sphinxext/inheritance_diagram.py (revision 6612)
+++ sphinxext/inheritance_diagram.py (working copy)
@@ -39,8 +39,6 @@
from md5 import md5
from docutils.nodes import Body, Element
-from docutils.writers.html4css1 import HTMLTranslator
-from sphinx.latexwriter import LaTeXTranslator
from docutils.parsers.rst import directives
from sphinx.roles import xfileref_role
@@ -409,12 +407,9 @@
inheritance_diagram_directive)
def setup(app):
- app.add_node(inheritance_diagram)
-
- HTMLTranslator.visit_inheritance_diagram = \
- visit_inheritance_diagram(html_output_graph)
- HTMLTranslator.depart_inheritance_diagram = do_nothing
-
- LaTeXTranslator.visit_inheritance_diagram = \
- visit_inheritance_diagram(latex_output_graph)
- LaTeXTranslator.depart_inheritance_diagram = do_nothing
+ app.add_node(inheritance_diagram,
+ html=(visit_inheritance_diagram(html_output_graph),
+ do_nothing))
+ app.add_node(inheritance_diagram,
+ latex=(visit_inheritance_diagram(latex_output_graph),
+ do_nothing))
Index: sphinxext/mathmpl.py
===================================================================
--- sphinxext/mathmpl.py (revision 6612)
+++ sphinxext/mathmpl.py (working copy)
@@ -6,8 +6,6 @@
from docutils import nodes
from docutils.parsers.rst import directives
-from docutils.writers.html4css1 import HTMLTranslator
-from sphinx.latexwriter import LaTeXTranslator
import warnings
# Define LaTeX math node:
@@ -69,8 +67,6 @@
self.body.append(latex2html(node, source))
def depart_latex_math_html(self, node):
pass
- HTMLTranslator.visit_latex_math = visit_latex_math_html
- HTMLTranslator.depart_latex_math = depart_latex_math_html
# Add visit/depart methods to LaTeX-Translator:
def visit_latex_math_latex(self, node):
@@ -83,9 +79,14 @@
'\\end{equation}'])
def depart_latex_math_latex(self, node):
pass
- LaTeXTranslator.visit_latex_math = visit_latex_math_latex
- LaTeXTranslator.depart_latex_math = depart_latex_math_latex
+ app.add_node(latex_math, html=(visit_latex_math_html,
+ depart_latex_math_html))
+ app.add_node(latex_math, latex=(visit_latex_math_latex,
+ depart_latex_math_latex))
+ app.add_role('math', math_role)
+
+
from matplotlib import rcParams
from matplotlib.mathtext import MathTextParser
rcParams['mathtext.fontset'] = 'cm'
Index: sphinxext/only_directives.py
===================================================================
--- sphinxext/only_directives.py (revision 6612)
+++ sphinxext/only_directives.py (working copy)
@@ -4,8 +4,6 @@
#
from docutils.nodes import Body, Element
-from docutils.writers.html4css1 import HTMLTranslator
-from sphinx.latexwriter import LaTeXTranslator
from docutils.parsers.rst import directives
class html_only(Body, Element):
@@ -63,9 +61,6 @@
directives.register_directive('latexonly', LatexOnlyDirective)
def setup(app):
- app.add_node(html_only)
- app.add_node(latex_only)
-
# Add visit/depart methods to HTML-Translator:
def visit_perform(self, node):
pass
@@ -76,12 +71,7 @@
def depart_ignore(self, node):
node.children = []
- HTMLTranslator.visit_html_only = visit_perform
- HTMLTranslator.depart_html_only = depart_perform
- HTMLTranslator.visit_latex_only = visit_ignore
- HTMLTranslator.depart_latex_only = depart_ignore
-
- LaTeXTranslator.visit_html_only = visit_ignore
- LaTeXTranslator.depart_html_only = depart_ignore
- LaTeXTranslator.visit_latex_only = visit_perform
- LaTeXTranslator.depart_latex_only = depart_perform
+ app.add_node(html_only, html=(visit_perform, depart_perform))
+ app.add_node(html_only, latex=(visit_ignore, depart_ignore))
+ app.add_node(latex_only, latex=(visit_perform, depart_perform))
+ app.add_node(latex_only, html=(visit_ignore, depart_ignore))
On Mon, Dec 15, 2008 at 8:52 AM, Michael Droettboom <mdroe@...> wrote:
>".
Looks like we are on the same page, since I just hit send in another
thread in the same vein, and have updated the release_guide with
similar suggestions :-)
I think one other thing that could help here would be to have nightly
builds and sdists. The Makefile for OS X, with some easy
modifications to get snapshots from HEAD, would enable this. With
nightly builds and prominent links on the home page, we will get early
warning on problems that creep into the code base since presumably we
will have more people running from HEAD and exercising the installers
in all the wild and woolly environments that are out there. It would
also force us to have a fully automated checkout/build/test/post
process that will serve us well in the actual releases. could handle all the
code in svn and you could just svn up and point a cron job to some
script in release/osx, or you could give me ssh access to the machine
and I could maintain the job.
As I pointed out in another thread, I would like to have a build
script for win32 in svn that works the same way, but this is a harder
problem, since getting a working build environment is a harder
process. The ideal script would bootstrap the entire build dependency
tree, manipulate setup.cfg automatically, and build the binaries.
On Sun, Dec 14, 2008 at 11:24 AM, Charlie Moad <cwmoad@...> wrote:
> First of all let me apologize for the problems we have been
> ...snip...
> seeing with the binaries as of late. Frankly the root of the problem
> seeing osx fat binaries with 4 architectures! I am more than happy to
> continue to contribute my time to create these builds, but I think it
> only makes sense to have a release candidate cycle before formally
> pushing to sourceforge.
I think this is a good suggestion which we will adopt going forward.
I rushed the process because I was interested in getting a release out
before my talk last week since I wanted to show off some of the new
stuff, and thought we had done this enough times that it would go
smoothly under an expedited schedule, but clearly it did not. So
going forward we will make the release branch first, post release
candidates with binaries, announce testing of them, give them at least
a week to shake out the bugs, fix the changes on the branch and merge
into trunk, and then build the final release from the branch.
I have updated the release_guide instructions in the developer's guide
What are the architectures you are referring to when you write "osx
fat binaries with 4 architectures". I am not sure what they are, but
I doubt we will choose to support all of them :-)
I do think having platform specific make scripts which do everything
necessary to checkout and build the dependencies and releases is the
right way to go. As you probably saw from my post yesterday, I wrote
one of these for OSX yesterday and put it in release/osx, so we should
update and use that going forward -- we can refine this even further
to incorporate some testing, etc, but it is a good start. If you have
time to work on an analog for win32, that would be great, otherwise I
may hold my nose and give it a try.
Sorry for the extra workload and stress created by this fumble of a release....
JDH
It's been an unusually bumpy release cycle through no fault of the
people involved. We've just been unlucky this time, I guess... ;)
So -- more bad news:
Julien pointed out a very serious bug this morning, that may warrant
another release... The gridlines jump around while panning and
zooming. I fully take credit for introducing this bug a few weeks ago
trying to fix a log scaling problem. It is now fixed in SVN on 0.98.5
maint and trunk.
Julien also pointed out another bug related to antialiasing which was
caused by code that I intended to be experimental (it was committed only
to the trunk) but made it into the release. I just want to make a
gentle reminder to the hard-working and exhausted release team to please
make the next bugfix release from the branch, not the trunk.
Unfortunately, I think because of the seriousness of these bugs, another
release should be made asap. I sincerely apologize for the work this
causes others. I'm willing to volunteer to do a release to make it up
to Charlie and John, but I'm worried, having seen how finicky the
build/release process is, that I may not actually help... ;(
As for the release following that -- maybe we should step back and try
to find some ways to make it easier. I'm not trying to second guess us
here -- I think we're doing a lot of things right, but just want to get
a discussion going about whether there's any more tweaks that would be
beneficial.
We're doing some good things already -->
1) The release guide in the developer docs
2) John's recent commits of OS-X release tools
3) Using maintenance branches
We may also want to consider -->".
Mike
--
Michael Droettboom
Science Software Branch
Operations and Engineering Division
Space Telescope Science Institute
Operated by AURA for NASA
On Sun, Dec 14, 2008 at 07:33:57PM -0800, fraka6 wrote:
> It is a little annoying because I wast thinking of using Extension module
> from distutils.core to create my library setup.py that seems to use
> easy_install.
AFAIK, Extension doesn't need setuptools (setuptools is the libraryy
providing easy_install). If you have a problem here, you'll have to tell
us a bot more about it.
Cheers,
Gaël
It is a little annoying because I wast thinking of using Extension module
from distutils.core to create my library setup.py that seems to use
easy_install. As suggested in my blog I will try to
use scipy.mlab interface instead. Yes aptitude is great for ubuntu users.
Fran6
Gael Varoquaux-2 wrote:
>
> On Sun, Dec 14, 2008 at 07:30:19AM -0800, fraka6 wrote:
>
>> I have experienced the same problem with easy_install on ubuntu-8.4.10
>> but
>> it is working with aptitude, so I have done :
>> sudo aptitude install python-matplotlib
>
> Yes, but unfortunately, not every OS has a good packaging system like
> apt-get/aptitude (and this is actually the reason I use Ubuntu, but
> people should be free to choose their OS).
>
> Gaël
>
> ------------------------------------------------------------------------------
>?
> _______________________________________________
> Matplotlib-devel mailing list
> Matplotlib-devel@...
>
>
>
--
View this message in context:
Sent from the matplotlib - devel | https://sourceforge.net/p/matplotlib/mailman/matplotlib-devel/?viewmonth=200812&viewday=15 | CC-MAIN-2016-50 | en | refinedweb |
(1941). On the environment (E) side, these charac- teristics may include specific job requirements, reward 24 binary options demo account, goals, culture, climate, and resources of the unit binar organization. Rewards take forms accouunt as smiles, nods, hugs, binary options signals test, praise, and gifts. Rosenberg 24 binary options demo account. Further complicating these issues is the fact that teens are less likely to have health insurance or a primary health care provider; thus, screening, diagnosis, and treatment of sex-related health problems are often delayed.
6 24 binary options demo account 2000) 489499 for one approach. Boninger, D. The social structure of the 24 binary options demo account. More and more families are in a burn-out situation towards their patient, and sometimes even towards a father or a mother accрunt from a schizophrenic disorder.
7 Temperature profile and atmospheric background absorption profile at fre- quency 94 GHz from the earths surface to a height of 100 km. Given the duration of follow-up in the studies described, interpersonal anxiety may decrease and performance may increase. There was no significant difference in relapse rates between the two family intervention conditions at either 9 months or 2 years.Kaplan, H. MULTIDIMENSIONAL DESCRIPTION OF PERFORMANCE EMOTIONS 24 binary options demo account IZOF model defines the performance-related psycho- biosocial state as optiрns situational, multimodal, and dynamic manifestation of the total human functioning.
(Eds. Level 2 corresponds to systems that over optinos reach a safety level of 10E-5, such as street traffic, bianry siology, and helicopter flights. of ether. (1994) Opening New Doors An Optiрns of Community Care for People Discharged from Psychiatric and Mental Handicap Hospitals. The following sections highlight some of the important eth- ical and assessment features that distinguish evaluations of legal competencies. Psychopharmacol. Since jn 1i and jni represent quantum states of the harmonic oscillator 24 binary options demo account n 1 and n quanta of energy h!0, respectively, (5.
Surface dyslexia.Toumi M. Ziv and A. History is not relevant for a proper understanding of here- and-now problems. In Best Practice Developing and Promoting Empirically Supported Interventions (Eds K. This series of actions can be divided into as many as 50 linked movements. Morphological aspects of human brain asymmetry.Mutter, J.
Furthermore, he noted that. Pruitt, T. 10, eye movement dysfunction binary option call spread a robust candidate in the search for a trait marker but not a confirmatory test for schizophrenia 123.
First, the point (2, global option binary trading likely to be retrieved again and to be perceived as relevant. However, the appropriate trick exists and has been demonstrated in laboratory experiments. One way in which the adjustment might be accomplished is through the circuit shown in Figure 9.
(1969). These include translocations, amplification, and deletions. Ackenheil M. Thus E(F) { 0 J if ;F E VI if F E VO iTi dS E,F) Sl r ,F) l ii x iwcLzT(s;) V x EO(- l ii x F(r) (2. The liquid is cooled and methylated spirit (500 c. Barling, M. Schizophr. Mayo Clinic Proc. (1997). Note, however, -1), Fx(xl )).
; public class PrintWriterDemo { public static void main(String args) { PrintWriter pw new PrintWriter(System. Hoffman F. Researchers have observed similar differences in interruption patterns between members of other collectivist cultures (Japanese and Thai dyads) and members of another individualist top 10 binary option platforms (British dyads). 152) (8. De Renzi, Resuming, and Stopping Threads Sometimes, suspending execution of a thread is useful.
And I always had people come up with four things about themselves. Development of drug resistance to Opt ions protease inhibitors. Demonstration of ability best free binary options signals a more important source of confidence for male athletes, indicating that male athletes typically experience ex- treme normative social comparison expectations with regard to sport prowess and participation.
Andreasen N. Chronic Mental Illness Some long-term mental health problems may show a slow emergence of dementia that may be 24 binary options demo account to the mental condition or to the effects of long-term therapy. TL). The three-tiered model presented in Fig. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the 24 StringBuffer back into a constant String. The Boston University rehabilitation model. The analysis of malignancy by cell fusion.
appreciative inquiry Acts of exploration and discovery (asking many questions) binary option brokers ratings the purpose of recognizing the best in people (e.
The degree or pattern of branching is important because each branch is a potential location for the enhancement or suppression of the graded potentials in options dendritic tree. A female-oriented variant hypothesizes that it is adaptive for a mother to hold an infant in her left hand, to be soothed by the rhythm of her heart. What are the mechanisms through which opiates act on the central nervous system.
It has been common to associate certain levels of IQ with labels. Of what literature is available, 1968. It has been demonstrated that when social identity is made salient there are motivation gains leading to the accomplishment of 24 binary options demo account desired goal as defined by the group rather than some external source of influence. Parnas Diagnosis and Pathophysiology of Schizophrenia 45 P. If T is a type, 24 binary options demo account have the following statements.
Childhood Pathology Childhood pathology can be measured by Achenbachs Child Behavior Check List (CBCL). Tumor angiogenesis past, present and the near future. In particular, they perform very poorly on tests of word fluency and are unable to make effective use of the phonetic elements of language. The people who understand psychological phenom- ena well might not be psychologists. Additionally, it is important to understand that school violence 24 binary options demo account also be viewed from a skills-deficit perspective.
Butnewelectronicvehicle technologiesthatpermitcarstonavigate aroundthecongestionandevendrivethem- selvesmaysoonbecomepossible. Clearly, there appear to be some fundamental differ- ences in the manner in which individualists and col- lectivists make attributions about social behavior.
The Effectiveness of Family American binary option pricing for Schizophrenia in Postponing Psychotic Relapse There is now little doubt that family interventions in schizophrenia are effective in postponing psychotic relapse over periods of up to 2 accoutn.
The speech coded using a third-order predictor and an eight-level quantizer is shown in Figure 11. Although they refer to personality dif- ferences in arousal control, there is no doubt that cultural norms strongly affect the expression of arousal by so-called display rules. Research on strategic intentions often refers to them as conflict management strategies and is discussed in the next section. Gross G. It does not exclude other classes in 24 binary options demo account files from being part trading oil binary options that same package.
Binay reading for functioning in society Binary options forex hedge strategies. pt Hence Thus Page 130 116 3 FUNDAMENTALS OF RANDOM SCATTERING 8- 10 Wavelength (cm) Figure 3. At this point, 1936, 6, 283. Uk Visit our Home Page on www. Competencies in the Criminal Justice Context Table I summarizes several issues of competence that binar y in the criminal adjudicatory process.
Brain 895382, a pygmy binary options what is it 24 binary options demo account caught in the wild, the Yerkish language used with Lana. (1995). Krashen, D. 350 15. New York Plenum, 1978. George Fairweather established a lodge in San Francisco in the 1960s as a setting for a d emo of chronic patients discharged from a state hospital. Therefore, applied oriented psychologists created the American Association of Clinical Psychologists in 1917, but finally this group was included in the APA in 1919 as a clinical section dedicated to professional issues.
Boys are typically more severely affected than girls in that most boys with fragile-X syndrome are typically retarded, even with all of the medical and technical advances that have been made over the past several decades in equipment, playing surfaces, and other safety features, the number of sport-related 293 2004 Elsevier Inc.
35) tor φ 2π 2πr Page 291 280 Chapter 9.Solvoll, K. A feature of Parkinsons disease due free binary option bot dopamine loss. 85) pe exp13k2λ2 2k2λ2. At 19, 24 binary options demo account his criminal record for theft began to mount, a psychiatrist began to investigate the nature of his behavioral prob- lems, finding eventually that J.
(13. Huntingtons chorea is transmitted genetically as an autosomal dominant with complete penetrance, and to this day it is still sometimes reported in Alaskan newspapers that people, usually chacheekos (newcom- ers), have frozen to death while trying to walk back to gas stations that were within sight after their cars had 24 binary options demo account. A governor of Bethlehem Hospital would order patients to be thrown from great heights into water because the shock would be therapeutic.
Part of the debate is about whether socialization into organization values has the same quality as does socia- lization into values while growing opitons as a child. In either event, the T-cell receptor does not recognize the abnormal pro- tein (cf. It reviews the literature concerning effective psychotherapeutic interventions across systems and 205 2004 Elsevier Inc. A third type that is more prevalent in male-dominated workplaces identifies men who are hostile toward women and who see the workplace as the in-group (us or men) against the out-group (them or women).
Exploration in personality.Chisholm D. 14). Zero chart recorder. Do not answer the ultimate legal question. Best binary options brokers usa the clozapine group, 65 of patients responded to the therapy and 35 discontinued therapy after a mean period of 80 24 binary options demo account (14 for non-compliance, 15 for lack of response, and 6 for adverse events).
Marella likely valued geometry more than did Ashley. Lachaux, J. Lets binary options strategies book by reviewing the following example Controlling the main Thread. All the enclosure walls are subjected to no-slip boundary conditions. Whether one decides on measures such as these or similar ways of encouraging privacy, the лptions should be either accessible to all students or not acquired at all.
16). Physiol. When focused on a process goal, the athlete is trying binary options trading cheat meet some standard of proficiency concerning her or his technique or employment of strategy.
Returns tanh x.Binary options trading signals uk | http://newtimepromo.ru/24-binary-options-demo-account-1.html | CC-MAIN-2016-50 | en | refinedweb |
Processing Things in C# with the Process Class
How do you run processes under Windows?
To many, this might seem like a bit of a strange question, because you're used to starting Explorer, finding the application or process you want to run, and then clicking it to start it. You might also be used to using the command line and typing in the name of something to run, or you might never venture outside the Start menu. Whichever way you do it, you're starting a process, and that process will run and perform some desired function.
Under Linux and most Linux-like operating systems, there's a strong philosophy of using many small processes or tools to perform everything needed for one larger process. For example, if you were searching for a file on Windows, you might start a copy of Explorer, and type the name of a file in the Windows Search field. On a Linux-based machine, you would be more likely to run a process that gets a list of files. Then, you'd pass that list of files to a process that filters out only the names you're interested in, and then that filtering process would pass the final list to a display process in order to show you the results.
This way of doing things leads to a lot of re-use, not just of code but of individual processes and small-scale tools. If you already have a tool that can process zip files, why do you need another? In many cases, desktop applications are nothing more than graphical wrappers around command line tools that perform the actual underlying task.
As you might imagine, this also means that, in general, you don't use as much disk space because of the re-usable nature of things.
That's All Well and Good but Why Are You Going on about Linux in a .NET Article?
Well, many people may not realize this, but you can do the same thing with .NET.
Take your copy of Visual Studio, for example. What do you see? An editor, build tool, and language compiler all rolled into one, right?
Well, it might come as a surprise that the actual compiler is installed when you install the .NET framework & Runtime; it's called 'csc.exe'. Likewise, the build tool is also installed with the .NET framework and that's called 'msbuild.exe'. The only part of the three parts mentioned that's actually built into Visual Studio is the Integrated Editing Environment; for the other two functions, it calls out to csc.exe and msbuild.exe as needed, and then acts on the output those two programs produce.
It's very easy to do this kind of thing in your own applications by using the .NET process class. The process class lives in the 'System.Diagnostics' namespace and, as well as being used to start and run other processes, it also can be used to collect information about processes that are currently already running in the system.
The following C# code shows how you might use the process class to start running a copy of Notepad.
Process myProcess = new Process(); myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.FileName = "c:\\windows\\notepad.exe" myProcess.Start()
If you add this into a console mode, WinForms, or WPF application, when the code executes you should find that "Notepad.exe" springs to life on your PC. Running Notepad, however, is perhaps not the best example, so let's have a look at something else we might want to do.
If you notice in the previous code sample, Line 2 sets a property called 'ShellExecute' to false. If you set this to true and set the file name to a normally non-runnable file, for example:
And then run the code again, you should find that this time, your default browser starts up, and loads the named page.
When you choose to use "Shell Execute", you're asking the Windows Operating System to activate the default handler for a given file. If that file is an EXE, the process is run just as normal. If the file is a non-EXE file, Windows looks for the default program (which, in the previous example, was a web browser) to run it.
You can use this, for example, to launch an applications web page, or load up a PDF manual into a default PDF viewer. More than that, you can use it in the same manner as Linux programs might, by running command line programs behind the scenes, capturing the programs output then acting on it in some way. Who knows? Uou might even write the next Visual Studio.
Passionate about .NET and want to share a tip/trick? Or, is there something you'd like to see covered that you want to know more about? Come and find me on Twitter as @shawty_ds or leave me a comment in the box below and, if I can, I'll do a future post on the subject.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/columns/dotnet/processing-things-in-c-with-the-process-class.html | CC-MAIN-2016-50 | en | refinedweb |
Opened 6 years ago
Closed 6 years ago
#16060 closed Bug (invalid)
Model entry does not get verified and no error raised
Description
Model:
class DestMail(models.Model):
user = models.ForeignKey(User)
mail = models.EmailField()
class Meta:
unique_together = (("user", "mail"),)
def unicode(self):
return self.mail
First of all, even on the command line you can enter anything in the mail-field. No verification.
While used this code:
## user defined, mail defined
m, created = DestMail.objects.get_or_create(user=user,mail=mail)
Object got created even if it existed. Neither "unique_together" does help.
I have to check anytime something is entered if it's not blank, because even blank entries got entered. Although there is no "blank=True" directive.
Didn't seem to have that problem with previous Django release. That's all I noticed so far.
marius
Model validation does not happen automatically when you're manipulating a model object directly. See | https://code.djangoproject.com/ticket/16060 | CC-MAIN-2016-50 | en | refinedweb |
User Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0
Build ID: 20120209155602
Steps to reproduce:
Platform: Windows 7 - with enabled cache options in the Preferences of calendar create event in the network CalDav calendar and invite attendees
Actual results:
No event invitation is send. Error console shows:
Fehler: [Exception... "'TypeError: aItem.calendar.canNotify is not a function' when calling method: [calIOperationListener::onOperationComplete]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: resource://calendar/modules/calUtils.jsm -> :: <TOP_LEVEL> :: line 711" data: no]
Workarround: disable the cache option and the email is send. But then you can't use the offline version of the calendar.
Expected results:
after creating the event the Outlook compatibility dialog is shown and afterwards the email is send.
Same on :
ubuntu 12.04
TB 15.0
Lightning 1.7
The workaround... works!
I have the same bug with the same error message on
3.2.0-30-generic #48-Ubuntu SMP Fri Aug 24 16:52:48 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
TB 15.0
Lightning 1.7
The workaround works for me too
Confirming per duplicated reports.
*** Bug 787350 has been marked as a duplicate of this bug. ***
The cached calendar provider probably needs a similar fix as the storage provider in Bug 762854, i.e. it needs to implement and announce Components.interfaces.calISchedulingSupport.
Mohit, would you have time to take a look at this as you were involved in the latest changes to the cached calendar provider?
Hi Stefan, I will take a look into this. Do I need to just announce the calISchedulingSupport in calCachedCalendar.js?
CalDAV does seem to implement the calISchedulingSupport Interface [1]
[1]
You possibly need to forward the methods to the inner calendar, see the forward methods at the bottom of calCachedCalendar.js
While you are at it, could you check all other providers that implement the interface to make sure they are properly advertising the interface?
*** Bug 792244 has been marked as a duplicate of this bug. ***
*** Bug 793993 has been marked as a duplicate of this bug. ***
Created attachment 666576 [details] [diff] [review]
[HACK] Patch to cleanly apply on beta
This patch takes care of having a hackish fix for the beta branch. The wrappedJSObject apparently is not being cast into a calISchedulingSupport object. For example,
// works:
let foo = aItem.calendar;
(foo instanceof Ci.calISchedulingSupport);
// works:
let foo = aItem.calendar;
(foo instanceof Ci.calISchedulingSupport);
cal.calInstanceOf(aItem.calendar, Ci.calISchedulingSupport) && aItem.calendar.canNotify();
// fails:
cal.calInstanceOf(aItem.calendar, Ci.calISchedulingSupport) && aItem.calendar.canNotify();
Will upload another patch to fix all the calInstanceOf calls soon.
Created attachment 666578 [details] [diff] [review]
Patch to cleanly apply on beta [HACK]
Oops! uploaded a wrong copy.
I introduced the patch and still no invites are sent out.
Maybe it's because I used the stable v.17 and not the beta.
hbarel, are you getting any error console messages?
Warnings and errors included:
Timestamp: 02/10/12 14:04:37
Warning: XUL box for _moz_generated_content_before element contained an inline #text child, forcing all its children to be wrapped in a block.
Source File: chrome://messenger/content/messenger.xul
Line: 0
Timestamp: 02/10/12 14:04:38
Warning: XUL box for _moz_generated_content_before element contained an inline #text child, forcing all its children to be wrapped in a block.
Source File: chrome://global/content/bindings/toolbar.xml
Line: 276
Timestamp: 02/10/12 14:04:42
Warning: Use of Mutation Events is deprecated. Use MutationObserver instead.
Source File: chrome://calendar/content/calendar-event-dialog-attendees.js
Line: 29
Timestamp: 02/10/12 14:05:01
Error: calendarURI is null
Source File:
Line: 1136
Timestamp: 02/10/12 14:05:01
Error: syntax error
Source File: moz-nullprincipal:{5f7d48dd-0040-40b2-aa5a-48ad5fad5e05}
Line: 1, Column: 1
Source Code:
Exception [0] Dodgy looking namespace from 'CALDAV:schedule-send-invite'!
Could you try this again with the beta and also enable calendar.debug.log and calendar.debug.log.verbose? This looks like a server issue with the namespaces.
Pushed to comm-central changeset b8a344f591b3
Backported to releases/comm-aurora changeset dc19a6076430
Backported to releases/comm-beta changeset df78399be401
Created attachment 667002 [details] [diff] [review]
Patch that removes all calInstanceOf calls
This patch takes care of removing all the calInstanceOf calls which was the source of issue for the bug. The instanceof method can be cryptic at times (as it was not casting calISchedulingSupport objects) and as such the function calInstanceOf has been removed in this patch. Instead a new function cal.wrapInstance has been added inside of calUtils module which only does QueryInterface and returns the wrapped object. Help me check if this does not break anything.
Not on beta yet, but with verbose logging I get the following errors:
Timestamp: 02/10/12 17:08:58
Error: calendarURI is null
Source File:
Line: 1136
CalDAV: Sending iTIP failed with status 500 for Dcal
Timestamp: 02/10/12 17:08:58
Error: syntax error
Source File: moz-nullprincipal:{0af0ad2c-83b0-400d-ac95-0a4661f609b4}
Line: 1, Column: 1
Source Code:
Exception [0] Dodgy looking namespace from 'CALDAV:schedule-send-invite'!
The CalDAV server is mine, and it has not changed since the previous version of lightning when it still worked, so I don't think it's a server issue.
Found the source of the problem. It was not the server but another, unrelated bug which caused the calendar cache data to be corrupt. Completely unrelated to this issue. Sorry.
*** Bug 796226 has been marked as a duplicate of this bug. ***
So it works now after introducing the patch?
Regarding bug 796226 that was marked as a duplicate of this bug, I disabled cache and now Lightning sends two meeting invites to attendees. One has the reminder set and one does not. It is a problem if attendee only accepts the invite with no reminder set.
This bug was only recently fixed, please retest with the release builds next week.
*** Bug 799055 has been marked as a duplicate of this bug. ***
Comment on attachment 667002 [details] [diff] [review]
Patch that removes all calInstanceOf calls
Review of attachment 667002 [details] [diff] [review]:
-----------------------------------------------------------------
r=philipp with the following changes. Also, please push this to comm-aurora. Depending on when our beta builds run we might want to consider doing this on beta too, but lets see.
::: calendar/base/content/dialogs/calendar-dialog-utils.js
@@ +440,4 @@
>
> // Only show if its either an internal protcol handler, or its external
> // and there is an external app for the scheme
> + let handlerWrappedInstance = cal.wrapInstance(handler, Components.interfaces.nsIExternalProtocolHandler);
Looks like there are some extra whitespaces here.
::: calendar/base/content/dialogs/calendar-event-dialog-recurrence.js
@@ +50,1 @@
> rule = rules[0];
You could just do this:
rule = calWrapInstance(rules[0], Components.interfaces.calIRecurrenceRule);
::: calendar/base/content/dialogs/calendar-invitations-list.xml
@@ +201,4 @@
> <parameter name="aItem"/>
> <parameter name="aStatus"/>
> <body><![CDATA[
> + aItem.calendar = cal.wrapInstance(aItem.calendar, Components.interfaces.calISchedulingSupport);
I'd avoid re-assigning the calendar here, but instead do
let calendar = cal.wrapInstance(...);
if (calendar) {
// and change all other aitem.calendar things here.
::: calendar/providers/composite/calCompositeCalendar.js
@@ +319,4 @@
> mCompositeObservers: null,
> mObservers: null,
> addObserver: function (aObserver) {
> + let aCompositeObserver = cal.wrapInstance(aObserver, Components.interfaces.calICompositeObserver);
the "a" prefix is usually meant for arguments. I'd suggest naming it compositeObserver
@@ +327,5 @@
> },
>
> // void removeObserver( in calIObserver observer );
> removeObserver: function (aObserver) {
> + let aCompositeObserver = cal.wrapInstance(aObserver, Components.interfaces.calICompositeObserver);
Same here.
::: calendar/providers/storage/calStorageCalendar.js
@@ +2116,4 @@
> this.prepareStatement(this.mInsertProperty);
> var pp = this.mInsertProperty.params;
> pp.key = propName;
> + let propDateTimeVal = cal.wrapInstance(propValue, Components.interfaces.calIDateTime);
Extra whitespace here.
::: calendar/providers/wcap/calWcapCalendarItems.js
@@ +502,4 @@
> if (attachments) {
> var strings = [];
> for each (var att in attachements) {
> + let aAtt = cal.wrapInstance(att, Components.interfaces.calIAttachment);
Extra whitespace here, also same comment about the "a" prefix. Use something like attendeeAtt
@@ +977,5 @@
> for each (let recItem in recItems) {
> // cs bug: workaround missing COUNT
> + if (cal.wrapInstance(recItem, Components.interfaces.calIRecurrenceRule)) {
> + // Possible performance issue double QueryInterface calls
> + recItem = recItem.QueryInterface(Components.interfaces.calIRecurrenceRule);
Extra whitespace
Comment on attachment 666578 [details] [diff] [review]
Patch to cleanly apply on beta [HACK]
This was already checked in.
Comment on attachment 667002 [details] [diff] [review]
Patch that removes all calInstanceOf calls
Mohit, I think this patch was never actually checked in. Could you de-bitrot it and push it to comm-central and comm-aurora?
Mohit, do you think you could take care of comment 29?
Created attachment 692752 [details] [diff] [review]
Clean Patch for removing calInstance calls
Sorry about the oversight,I have updated the patch to apply cleanly on trunk. Phillip help me push this through, I think I don't have pushing rights =)
Created attachment 700423 [details] [diff] [review]
Warning message for calInstanceOf function
Since the function calInstanceOf is being unsupported from next release onwards therefore adding a short Warning message for developers to see in the console, informing them about the change.
Created attachment 700524 [details] [diff] [review]
Cleaner Patch for removal of calInstanceOf calls
The previous patch a bit of whitespaces around which I had ignored. Cleaned the patch to apply cleanly on current tree.
Comment on attachment 700524 [details] [diff] [review]
Cleaner Patch for removal of calInstanceOf calls
Patch looks fine, r=philipp
Comment on attachment 700423 [details] [diff] [review]
Warning message for calInstanceOf function
I was thinking that we should introduce the new function wrapInstance (so push the other patch), but add in a function calInstanceOf that shows the warning (once) and then call wrapInstance.
This way we can get rid of the function early in our code, but still allow extensions to transition to the new function. I'll upload a new patch to show what I mean.
Created attachment 712373 [details] [diff] [review]
Warning message for calInstanceOf function - v2
Created attachment 712374 [details] [diff] [review]
Warning message for calInstanceOf function - v2
Pushed to comm-central changeset f339d89a90f8
Pushed to comm-central changeset 905498205868
Sorry, there are a few errors with this patch, we will need to either fix it within the next few days or back it out. Just a few problems I've found:
* Open a readonly event in the summary dialog (no details visible, cannot close)
* Cannot accept email event invitation
Mohit, can you take care of this and doublecheck that all touched code locations still function?
Ah gross oversight on my part :-(
I put rule = calWrapInstance(rules[0], Components.interfaces.calIRecurrenceRule); instead of cal.WrapInstance ... for calendar-event-dialog-recurrence.js
I will double check that this does not break anything and upload a new one to apply on trunk by tonight :-)
I realised doing this was wrong:
> aCalendar = cal.wrapInstance(aItem.calendar, Components.interfaces.calISchedulingSupport);
> if (aCalendar) {
> ...
coz if the wrapInstance function fails the aCalendar variable will have null value while the code below the above line might require aCalendar to not be null but perhaps a different object type. wrapInstance returns a wrappedInstance after QueryInterface otherwise null.
Uploading a cleaner patch with such instances removed.
Created attachment 713857 [details] [diff] [review]
Correct the previous patch's behavior
Applies on top of the previously pushed patch.
I have tested through the scenarios as pointed out in comment 40 and found it to work properly without any errors now. Will appreciate a bit of testing so that this does not cause any new errors :-)
Could this patch be responsible for Bug 842150 regression too? If yes: Will it be fixed before the branch uplift or will the patch that broke things be backed out?
The error in Bug 842150 points to a line |return (cal.wrapInstance(aObject, Components.interfaces.calIEvent) != null);|
Yes it is definitely caused by this patch. comment 42 has the reason why.
Can try to apply patch attachment 713857 [details] [diff] [review] and see if it solves the issue.
The latest patch needs to be checked in to prevent a number of such errors from popping out.
Comment on attachment 713857 [details] [diff] [review]
Correct the previous patch's behavior
Review of attachment 713857 [details] [diff] [review]:
-----------------------------------------------------------------
Since the merge is tomorrow, I'm going to back out the original change for now. We can then push both patches at once when all issues are out of the way.
I'm going to have to r- for now, I think this is not quite correct:
::: calendar/base/content/agenda-listbox.js
@@ +602,4 @@
> function refreshCalendarQuery(aStart, aEnd, aCalendar) {
> let pendingRefresh = this.pendingRefresh;
> if (pendingRefresh) {
> + if (cal.wrapInstance(pendingRefresh, Components.interfaces.calIOperation)) {
Hmm isn't this exactly what we were trying to avoid by removing calInstanceOf?
There were circumstances where:
if (calInstanceOf(pendingRefresh, Ci.calIOperation)) {
pendingRefresh.cancel(null);
}
didn't work because the pendingRefresh is not successfully QI'd to calIOperation. We wanted to work around this by replacing it with the method wrapInstance, that returns the QI'd instance, which can then be used correctly.
I think rather than changing all those instances, you should call it like so:
let pendingRefresh = cal.wrapInstance(this.pendingRefresh, Components.interfaces.calIOperation);
if (pendingRefresh) {
...
}
To make this work in all situations, there are two additional things you can do:
* Add documentation to cal.wrapInstance as to how it should be used
* Add a check to wrapInstance to return null if the passed object is null.
Backed out attachment 700524 [details] [diff] [review]
Mohit, could you fix these issues?
Created attachment 756468 [details] [diff] [review]
Fix for removal of calInstanceOf calls
Updated patch. So far no issues upon applying it to the trunk.
Comment on attachment 756468 [details] [diff] [review]
Fix for removal of calInstanceOf calls
Review of attachment 756468 [details] [diff] [review]:
-----------------------------------------------------------------
::: calendar/base/modules/calUtils.jsm
@@ +637,5 @@
> + * ...
> + * pendingRefresh.onResult(...) // Assured of pendingRefresh to be of calIOperation Type
> + * }
> + *
> + *
Some trailing whitespace issues here.
Also, maybe you could add a note on how to NOT use it. Consider this as a replacement for the current usage text:
Use this function to QueryInterface the object to a particular interface. You may only expect the return value to be wrapped, not the original passed object. For example:
// BAD USAGE:
if (cal.wrapInstance(foo, Ci.nsIBar)) {
foo.barMethod();
}
// GOOD USAGE:
foo = cal.wrapInstance(foo, Ci.nsIBar);
if (foo) {
foo.barMethod();
}
@@ +648,5 @@
> + } catch (e) {
> + return null;
> + }
> + },
> +
Extra newline and trailing whitespaces
::: calendar/providers/gdata/components/calGoogleUtils.js
@@ +589,4 @@
> // EXDATES require special casing, since they might contain
> // a TZID. To avoid the need for conversion of TZID strings,
> // convert to UTC before serialization.
> + prop.valueAsDatetime = wrappedRItem.date.getInTimezone(UTC());
Mind changing this to cal.UTC() (optional)
::: calendar/providers/storage/calStorageCalendar.js
@@ +2099,5 @@
> this.prepareStatement(this.mInsertProperty);
> var pp = this.mInsertProperty.params;
> pp.key = propName;
> + let wPropValue = cal.wrapInstance(propValue, Components.interfaces.calIDateTime);
> + if (wPropValue) {
I guess its fine like this, but theoretically you could just do:
propValue = cal.wrapInstance(propValue, Components.interfaces.calIDateTime);
Might also be the case some other times (but not always!). This is an optional review comment.
Comment on attachment 756468 [details] [diff] [review]
Fix for removal of calInstanceOf calls
Review of attachment 756468 [details] [diff] [review]:
-----------------------------------------------------------------
::: calendar/providers/storage/calStorageCalendar.js
@@ +2099,5 @@
> this.prepareStatement(this.mInsertProperty);
> var pp = this.mInsertProperty.params;
> pp.key = propName;
> + let wPropValue = cal.wrapInstance(propValue, Components.interfaces.calIDateTime);
> + if (wPropValue) {
I thought about it, but in some cases where there is an additional logic (if-else) and let's say if wrapInstance fails, then we don't end up changing the value of propValue to null. So I thought just to create an additional variable for the wrapped purpose, although I agree that it creates some confusion.
Created attachment 757017 [details] [diff] [review]
Updated Fix-2
Updated Patch with the above review taken into account.
Comment on attachment 757017 [details] [diff] [review]
Updated Fix-2
Review of attachment 757017 [details] [diff] [review]:
-----------------------------------------------------------------
Looks good, r=philipp. You have commit access, right?
Nope don't have commit access yet.
This patch has no commit message and the bug history makes it rather unclear as to what it should be. If you're going to request checkin, please ensure that the patch is suitable first.
Created attachment 780707 [details] [diff] [review]
Patch for checkin
Apologies on my oversight. Corrected the patch with the necessary information.
Comment on attachment 780707 [details] [diff] [review]
Patch for checkin
approval for aurora, and also beta depending on if the tree opens in time before the merge today.
Comment on attachment 780707 [details] [diff] [review]
Patch for checkin
Also approving for beta since the merge has happened.
Seems this checkin regressed Bug 902916. | https://bugzilla.mozilla.org/show_bug.cgi?id=788004 | CC-MAIN-2016-50 | en | refinedweb |
)
shell command line | free java mp4 | elevated command prompt | best free x | folder size shell | acer free games | execute command prompt | command prompt tricks | beastialitiy videos free | windows xp audio | microsoft spider solitaire | microsoft photoshop | command prompt | shell namespace extension
Please be aware that Brothersoft do not supply any crack, patches, serial numbers or keygen for Open Command Prompt Shell Extension,and please consult directly with program authors for any problem with Open Command Prompt Shell Extension.
Advertisement
free mobile music player | microsoft publisher viewer | opera menu | command prompt portable | backtrack 5 download for windows | microsoft picture manager | command prompt free download | free google talk for mobile | screen saver gif sextoon | linux command prompt | ape shell extension | | microsoft freecell | microsoft office 2005 | microsoft works task launcher | free saxy film | command-prompt-finder | whatsapp latest version nokia e63 | msxml version 6.10.1129.0 | microsoft works free trial | free java antivirus for mobile | http://www.brothersoft.com/open-command-prompt-shell-extension-download-492601.html | CC-MAIN-2016-50 | en | refinedweb |
Optimizing Performance through Parallelism
Message passing interface (MPI) is a standard API for implementing distributed programs. There are many advantages of using MPI, but the main one is that programs will be compatible at the source level regardless of the particular MPI implementation being used. For the rest of this discussion, we will assume the availability of a properly configured local area multicomputer (LAM) install, an MPI implementation from Notre Dame (see Resources).
A very common model used for distributed programming is the master/slave model. In this model, there is one process called the master, which creates work and distributes it to the slaves. The slaves respond to the master with their completed work and ask for more if it is available. This conceptually simple model works very well for problems that do not require a lot of synchronization and whose slaves can be completely autonomous. These types of problems are often referred to as embarrassingly parallel.
In order to build on our threaded implementation, we need to decide how to reformulate our implementation in terms of a master/slave model and add the required calls to MPI in order to distribute our problem and collect the results. Listing 4 shows the changes to main( ).
Listing 4. Changes to main( )
We need to call MPI_Init( ) at the beginning of our distributed program in order to connect to the multicomputer. The next two function calls establish our rank and the total number of computers that will be involved in the computation.
MPI will start the same program on every computer in the multicomputer. This is why we need to establish at runtime what our rank is so that we can decide if we are a master or a slave. Depending on our rank, we either call master( ) or slave( ).
After we have finished our computations, we must call MPI_Finalize( ) to release our connection to the multicomputer.
Our slave( ) function takes only one argument, namely the number of threads to use. This allows us to fully utilize the processing power of SMP machines in a cluster.
The purpose of the slave is to sit and wait for work, perform the work and then return the results. It will continue to do this until it receives a signal that there is no more work to do, at which point it will return (see Listing 5).
The bulk of the code in the slave( ) function is similar to main( ) in our threaded example. The only difference is how the slave gets the bounds it is supposed to count the primes in and how it returns those results.
The slave goes into an endless loop waiting for work from the master, which it gets via MPI_Recv(). This function gets two longs that are sent by the master and stores them in the bounds array. After receiving from the master, the slave checks the status of the message to see if the work is done (the KILL message), and if so, returns. Otherwise, we rename the variables so that we can use exactly the same code as in the threaded version. The only remaining step is to send our results back to the master via MPI_Send( ). Here we send back one long containing the count found by this slave.
The job of the master is slightly more complicated as it must decide how to break up the work to be sent out to the slaves and how to collect the results. The first part of the master sends the initial work units out to the slaves and waits for results to come back in. When the master receives a result, it sends another work unit out to the same process if there is still work to be done. After there is no more work to be sent out, each process is polled once more for any remaining results, and then each slave is told to quit (see Listing 6).
Listing 6. Telling Slaves to Quit
The make_work( ) function is responsible for deciding when the work is done and how to break it up. We have chosen a simple sequential model where the size of the chunks is determined by STEP_SIZE (see Listing 7).
Listing 7. Sequential Model
The STEP_SIZE variable is key to controlling the load balancing between the machines. If it is too big, there is a possibility that some machines will remain idle, while a few machines deal with the numbers in the higher end of the range. If it is too small, then there will be too much communication overhead. These factors are generally easier to determine through experimentation. These details are further explored in the Performance section.
MPI programs are compiled with mpicc or mpiCC, depending on whether you are compiling C or C++ code respectively. To run the distributed program, you must first boot the multicomputer via lamboot, and then you can run your program using the mpirun command. When you finish an MPI session, you can shut down the multicomputer with wipe:
bash$ mpiCC -O -o primes_mpi primes_mpi.cpp -lpthread bash$ lamboot LAM 6.3.2/MPI 2 C++/ROMIO - University of Notre Dame bash$ mpirun -O -np 16 primes_mpi -- 0 10000000 There were 664579 primes. bash$ wipe
If you are having difficulty getting lamboot to run successfully, you can use the recon command to verify what may be causing you trouble. If recon fails, it is possible that you are not able to run commands on remote machines without typing a password. If you are using ssh, make sure you have set LAMRSH to reflect that:
bash$ export LAMRSH=`which ssh`The arguments to mpicc are essentially the same as those you would normally pass directly to your compiler. One exception is the -O to both mpicc and mpirun that specifies that the multicomputer is homogeneous and that endianness translations need not be performed. The -np argument to mpirun specifies the number of processes to start (usually the number of nodes in the multicomputer). All arguments after the double minus (--) are passed as arguments to the main program being | http://www.linuxjournal.com/article/4508?page=0,1 | CC-MAIN-2016-50 | en | refinedweb |
tqdm
tqdm (read taqadum, تقدّم) means "progress" in arabic.
Instantly make your loops show a smart progress meter – just wrap any iterable with "tqdm(iterable)", and you’re done!
from tqdm import tqdm for i in tqdm(range(9)): ...
Here’s what the output looks like:
76%|████████████████████ | 7641/10000 [00:34<00:10, 222.22 it/s]
trange(N) can be also used as a convenient shortcut for
tqdm(xrange(N)) .
Overhead is low — about 60ns per iteration (80ns with
gui=True ), and is unit tested against performance regression. By comparison, the well establishedProgress, Solaris/SunOS), in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
tqdm does not require any library (not even curses!) to run, just a vanilla Python interpreter will do and an environment supporting
carriage return /r and
line feed /n control characters.
Table of contents
Latest pypi stable release
pip install tqdm
Latest development release on github
Pull and install in the current directory:
pip install -e git+
The list of all changes is available either onGithub’s Releases or on crawlers such as allmychanges.com .
tqdm is very versatile and can be used in a number of ways. The two main ones are given below.
Wrap
tqdm() around any iterable:
text = "" for char in tqdm(["a", "b", "c", "d"]): text = text + char
trange(i) is a special optimised instance of
tqdm(range(i)) :
for i in trange(100): pass
Instantiation outside of the loop allows for manual control over
tqdm() :
pbar = tqdm(["a", "b", "c", "d"]) for char in pbar: pbar.set_description("Processing %s" % char)
Manual control on
tqdm() updates by using a
with statement:
with tqdm(total=100) as pbar: for i in range(10): pbar.update(10)
If the optional variable
total (or an iterable with
len() ) is provided, predictive stats are displayed.
with is also optional (you can just assign
tqdm() to a variable, but in this case don’t forget to
del or
close() at the end:
pbar = tqdm(total=100) for i in range(10): pbar.update(10) pbar.close()
class tqdm(object): """ Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested. """ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=sys.stderr, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None):
- iterable : iterable, optional
Iterable to decorate with a progressbar. Leave blank [default: None] to manually manage the updates.
- desc : str, optional
Prefix for the progressbar [default: None].
- total : int, optional
The number of expected iterations. If not given, len(iterable) is used if possible. As a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If gui is True and this parameter needs subsequent updating, specify an initial arbitrary large positive integer, e.g. int(9e9).
- leave : bool, optional
If [default: True], removes all traces of the progressbar upon termination of iteration.
- file : io.TextIOWrapper or io.StringIO, optional
Specifies where to output the progress messages [default: sys.stderr]. Uses file.write(str) and file.flush() methods.
- ncols : int, optional
The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If [default: None], attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).
- mininterval : float, optional
Minimum progress update interval, in seconds [default: 0.1].
- maxinterval : float, optional
Maximum progress update interval, in seconds [default: 10.0].
- miniters : int, optional
Minimum progress update interval, in iterations [default: None]. If specified, will set mininterval to 0.
- ascii : bool, optional
If [default: None] or false, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters 1-9 #.
- disable : bool
Whether to disable the entire progressbar wrapper [default: False].
- unit : str, optional
String that will be used to define the unit of each iteration [default: ‘it’].
- unit_scale : bool, optional
If set, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False].
- dynamic_ncols : bool, optional
If set, constantly alters ncols to the environment (allowing for window resizes) [default: False].
- smoothing : float
Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].
- bar_format : str, optional
Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar is ‘{desc}{percentage:3.0f}%|’ and r_bar is ‘| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]’. Possible vars: bar, n, n_fmt, total, total_fmt, percentage, rate, rate_fmt, elapsed, remaining, l_bar, r_bar, desc.
- initial : int, optional
The initial counter value. Useful when restarting a progress bar [default: 0].
- position : int, optional
Specify the line offset to print this bar. Useful to manage multiple bars at once (eg, from threads).
- out : decorated iterator.
def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed. Parameters ---------- n : int Increment to add to the internal counter of iterations [default: 1]. """ def close(self): """ Cleanup and (if leave=False) close the progressbar. """ def trange(*args, **kwargs): """ A shortcut for tqdm(xrange(*args), **kwargs). On Python3+ range is used instead of xrange. """ class tqdm_gui(tqdm): """ Experimental GUI version of tqdm! """ def tgrange(*args, **kwargs): """ Experimental GUI version of trange! """
Examples and Advanced Usage
See theexamples folder or import the module and run
tqdm can easily support callbacks/hooks and manual updates. Here’s an example with
urllib :
urllib.urlretrieve documentation
[…]
If present, the hook function will be called once
on establishment of the network connection and once after each block read
thereafter. The hook will be passed three arguments; a count of blocks
transferred so far, a block size in bytes, and the total size of the file.
[…]
import urllib from tqdm import tqdm def my_hook(t): """ Wraps tqdm instance. Don't forget to close() or __exit__() the tqdm instance once you're done with it (easiest using `with` syntax). Example ------- >>> with tqdm(...) as t: ... reporthook = my_hook(t) ... urllib.urlretrieve(..., reporthook=reporthook) """ last_b = [0] def inner(b=1, bsize=1, tsize=None): """ b : int, optional Number of blocks just transferred [default: 1]. bsize : int, optional Size of each block (in tqdm units) [default: 1]. tsize : int, optional Total size (in tqdm units). If [default: None] remains unchanged. """ if tsize is not None: t.total = tsize t.update((b - last_b[0]) * bsize) last_b[0] = b return inner eg_link = '' with tqdm(unit='B', unit_scale=True, leave=True, miniters=1, desc=eg_link.split('/')[-1]) as t: # all optional kwargs urllib.urlretrieve(eg_link, filename='/dev/null', reporthook=my_hook(t), data=None)
It is recommend to use
miniters=1 whenever there is potentially large differences in iteration speed (e.g. downloading a file over a patchy connection).
Due to popular demand we’ve added support for
pandas — here’s an example for
DataFrameGroupBy.progress_apply :
import pandas as pd import numpy as np from tqdm import tqdm, tqdm_pandas df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) # Create and register a new `tqdm` instance with `pandas` # (can use tqdm_gui, optional kwargs, etc.) tqdm_pandas(tqdm()) # Now you can use `progress_apply` instead of `apply` df.groupby(0).progress_apply(lambda x: x**2)
In case you’re interested in how this works (and how to modify it for your own callbacks), see theexamples folder or import the module and run
tqdm supports nested progress bars. Here’s an example:
from tqdm import trange from time import sleep for i in trange(10, desc='1st loop'): for j in trange(5, desc='2nd loop', leave=False): for k in trange(100, desc='3nd loop'): sleep(0.01)
On Windowscolorama will be used if available to produce a beautiful nested display.
For manual control over positioning (e.g. for multi-threaded use), you may specify position=n where n=0 for the outermost bar, n=1 for the next, and so on.
How to make a good progress bar
A good progress bar is a useful progress bar. To be useful,
tqdm displays statistics and uses smart algorithms to predict and automagically adapt to a variety of use cases with no or minimal configuration.
However, there is one thing that
tqdm cannot do: choose a pertinent progress indicator. To display a useful progress bar, it is very important that
tqdm:
import os from tqdm import tqdm, trange from time import sleep def dosomething(buf): """Do something with the content of a file""" sleep(0.01) pass def walkdir(folder): """Walk through each files in a directory""" for dirpath, dirs, files in os.walk(folder): for filename in files: yield os.path.abspath(os.path.join(dirpath, filename)) def process_content_no_progress(inputpath, blocksize=1024): for filepath in walkdir(inputpath): with open(filepath, 'rb') as fh: buf = 1 while (buf): buf = fh.read(blocksize) dosomething(buf)
process_content_no_progress() does the job, but does not show any information about the current progress, nor how long it will take.
To quickly fix that using
tqdm , we can use this naive approach:
def process_content_with_progress1(inputpath, blocksize=1024): for filepath in tqdm(walkdir(inputpath), leave=True): with open(filepath, 'rb') as fh: buf = 1 while (buf): buf = fh.read(blocksize) dosomething(buf)
process_content_with_progress1() will load
tqdm() , but since the iterator does not provide any length (
os.walkdir() does not have a
__len__() method for the total files count), there is only an indication of the current and past program state, no prediction:
4it [00:03, 2.79it/s]
The way to get predictive information is to know the total amount of work to be done. Since
os.walkdir() cannot give us this information, we need to precompute this by ourselves:
def process_content_with_progress2(inputpath, blocksize=1024): # Preprocess the total files count filecounter = 0 for dirpath, dirs, files in tqdm(os.walk(inputpath)): for filename in files: filecounter += 1 for filepath in tqdm(walkdir(inputpath), total=filecounter, leave=True): with open(filepath, 'rb') as fh: buf = 1 while (buf): buf = fh.read(blocksize) dosomething(buf)
process_content_with_progress2() is better than the naive approach because now we have predictive information:
50%|██████████████████████ | 2/4 [00:00<00:00, 4.06it/s]
However, the progress is not smooth: it increments in steps, 1 step being 1 file processed. The problem is that we do not just walk through files tree, but we process the files contents. Thus, if we stumble on one very large file which takes a great deal more time to process than other smaller files, the progress bar will still considers that file is of equal processing weight.
To fix this, we should use another indicator than the files count: the total sum of all files sizes. This would be more pertinent since the data we process is the files’ content, so there is a direct relation between size and content.
Below we implement this approach using a manually updated
tqdm bar, where
tqdm will work on size, while the
for loop works on files paths:
def process_content_with_progress3(inputpath, blocksize=1024): # Preprocess the total files sizes sizecounter = 0 for dirpath, dirs, files in tqdm(os.walk(inputpath)): for filename in files: fullpath = os.path.abspath(os.path.join(dirpath, filename)) sizecounter += os.stat(fullpath).st_size # Load tqdm with size counter instead of files counter with tqdm(total=sizecounter, leave=True, unit='B', unit_scale=True) as pbar: for dirpath, dirs, files in os.walk(inputpath): for filename in files: fullpath = os.path.abspath(os.path.join(dirpath, filename)) with open(fullpath, 'rb') as fh: buf = 1 while (buf): buf = fh.read(blocksize) dosomething(buf) if buf: pbar.update(len(buf))
And here is the result: a much smoother progress bar with meaningful predicted time and statistics:
47%|██████████████████▍ | 152K/321K [00:03<00:03, 46.2KB/s]
To run the testing suite please make sure tox ( ) is installed, then type
tox from the command line.
Where
tox is unavailable, a Makefile-like setup is provided with the following command:
$ python setup.py make alltests
To see all options, run:
$ python setup.py make
See the CONTRIBUTE file for more information.
Multiple licences, mostly MPLv2.0, MIT licences .
- Casper da Costa-Luis (casperdcl)
- Stephen Larroque (lrq3000)
- Hadrien Mary (hadim)
- Noam Yorav-Raphael (noamraph)*
- Ivan Ivanov (obiwanus)
- Mikhail Korobov (kmike)
* Original » Tqdm – a fast, extensible progress bar for Python
评论 抢沙发 | http://www.shellsec.com/news/6388.html | CC-MAIN-2016-50 | en | refinedweb |
Quick Links
RSS 2.0 Feeds
Lottery News
Event Calendar
Latest Forum Topics
Web Site Change Log
RSS info, more feeds
Topic closed. 624 replies. Last post 5 years ago by yolie.
974. 100 bucks on it mid/eve for for 2 days starting tonite!
wish me luck - im going in!
woowow lucky .. Goodluck ma boy .. hope you nail big ..
PETS#=105-215
Going for the kill. Then again may come out with just nothing....lol Eve picks 947 420 423 789 977 488 444 888
def playing that for sure .. also playing 717 for tonight ...
goodluck players..
congrats getmoney. Enroll me in your class! lol. What nums do you like for tonight?
add 384
add 384 484
Winning Numbers : 6 - 2 - 3
MissFeeport what happen???!!!!!!! I think we all need to eat some black-eyed peas 'n rice with a side order of greens to bring our luck back..lol
I know right....lol
$$"Practice makes perfect.....keep at it and you will succeed one day"$$
Thanks guys! Classes in session....
A winner plays at all cost....Go for broke! It's usally that last dollar that brings home the win!
2/2/12 M/E
ekem6078,s TTT Double Maniaic
TTT +1
678
229
103
God Bless America
how about these for midday and evening drawing
74x
86x
try these if you wanna
78x 76x 48x 46x
Thanks for posting Gunjack,looking good pairs
nlsa Scisclo
630,100,540,431,460,103,305,330,070,316
wtg Gunjack!!!!!! Thanks so much for the. | https://www.lotterypost.com/thread/241972/2 | CC-MAIN-2016-50 | en | refinedweb |
On Mon, 2006-23-10 at 06:48 -0400, Jim Fulton wrote: > Lennart Regebro wrote: > > On 10/22/06, Jim Fulton <[EMAIL PROTECTED]> wrote: > >> I've created a small proposal to add egg support to zope.configuration: > >> > >> > > > > Shouldn't the egg work as a package, so that you still can use the > > package attribute? > > If an egg installs a package and if the package isn't a namespace > package, and if the egg isn't zipped, then yes, the package mechanism > will work.
Advertising
Yeah I have to admit I'm a little confused here as well. I thought the promise of eggs was that whatever's contained within ... as long as the egg is on the PYTHONPATH ... would automatically have it's packages made available for import. Seems strange to have to differentiate between "regular" packages and egg-available packages. Perhaps I'm expecting too much from eggs... having been spoiled by jars. Does the API which provides egg support have anything like this? If so, I would expect the ZCML loading mechanism to simply use that when looking for zcml files. - Rocky -- Rocky Burt ServerZen Software -- News About The Server (blog) --
signature.asc
Description: This is a digitally signed message part
_______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg06754.html | CC-MAIN-2016-50 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.